repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
ktisha/Crucible4IDEA
src/com/jetbrains/crucible/ui/toolWindow/details/CommentForm.java
[ "@State(name = \"CrucibleSettings\",\n storages = {\n @Storage(file = \"$APP_CONFIG$\" + \"/crucibleConnector.xml\")\n }\n)\npublic class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {\n public String SERVER_URL = \"\";\n public String USERNAME = \"\";\n\n @Override\n public CrucibleSettings getState() {\n return this;\n }\n\n @Override\n public void loadState(CrucibleSettings state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n\n public static CrucibleSettings getInstance() {\n return ServiceManager.getService(CrucibleSettings.class);\n }\n\n public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = \"CRUCIBLE_SETTINGS_PASSWORD_KEY\";\n private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());\n\n public void savePassword(String pass) {\n PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));\n }\n\n @Nullable\n public String getPassword() {\n final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));\n\n return credentials != null ? credentials.getPasswordAsString() : null;\n }\n}", "public class CrucibleManager {\n private final Project myProject;\n private final Map<String, CrucibleSession> mySessions = new HashMap<String, CrucibleSession>();\n\n private static final Logger LOG = Logger.getInstance(CrucibleManager.class.getName());\n\n // implicitly constructed by pico container\n @SuppressWarnings(\"UnusedDeclaration\")\n private CrucibleManager(@NotNull final Project project) {\n myProject = project;\n }\n\n public static CrucibleManager getInstance(@NotNull final Project project) {\n return ServiceManager.getService(project, CrucibleManager.class);\n }\n\n @Nullable\n public List<BasicReview> getReviewsForFilter(@NotNull final CrucibleFilter filter) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getReviewsForFilter(filter);\n }\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n @Nullable\n public Review getDetailsForReview(@NotNull final String permId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getDetailsForReview(permId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n @Nullable\n public Comment postComment(@NotNull final Comment comment, boolean isGeneral, String reviewId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.postComment(comment, isGeneral, reviewId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n public void completeReview(String reviewId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n session.completeReview(reviewId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n }\n\n @Nullable\n public CrucibleSession getSession() throws CrucibleApiException {\n final CrucibleSettings crucibleSettings = CrucibleSettings.getInstance();\n final String serverUrl = crucibleSettings.SERVER_URL;\n final String username = crucibleSettings.USERNAME;\n if (StringUtil.isEmptyOrSpaces(serverUrl) || StringUtil.isEmptyOrSpaces(username)) {\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.define.host.username\"), MessageType.ERROR);\n return null;\n }\n try {\n new URL(serverUrl);\n }\n catch (MalformedURLException e) {\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.wrong.host\"), MessageType.ERROR);\n return null;\n }\n String key = serverUrl + username + crucibleSettings.getPassword();\n CrucibleSession session = mySessions.get(key);\n if (session == null) {\n session = new CrucibleSessionImpl(myProject);\n session.login();\n mySessions.put(key, session);\n try {\n session.fillRepoHash();\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n }\n }\n return session;\n }\n\n public Map<String,VirtualFile> getRepoHash() {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getRepoHash();\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n }\n return Collections.emptyMap();\n }\n\n public void publishComment(@NotNull Review review, @NotNull Comment comment) throws IOException, CrucibleApiException {\n CrucibleSession session = getSession();\n if (session != null) {\n session.publishComment(review, comment);\n }\n }\n}", "public class Comment {\n\n @NotNull private final User myAuthor;\n @NotNull private final String myMessage;\n private boolean myDraft;\n\n private String myLine;\n private String myReviewItemId;\n private String myPermId;\n private String myRevision;\n private Date myCreateDate = new Date();\n private final List<Comment> myReplies = new ArrayList<Comment>();\n private String myParentCommentId;\n\n public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {\n myAuthor = commentAuthor;\n myMessage = message;\n myDraft = draft;\n }\n\n @NotNull\n public String getMessage() {\n return myMessage;\n }\n\n @NotNull\n public User getAuthor() {\n return myAuthor;\n }\n\n public Date getCreateDate() {\n return new Date(myCreateDate.getTime());\n }\n\n public void setCreateDate(Date createDate) {\n if (createDate != null) {\n myCreateDate = new Date(createDate.getTime());\n }\n }\n\n @Override\n public String toString() {\n return getMessage();\n }\n\n public String getLine() {\n return myLine;\n }\n\n public void setLine(String line) {\n myLine = line;\n }\n\n public String getReviewItemId() {\n return myReviewItemId;\n }\n\n public void setReviewItemId(String reviewItemId) {\n myReviewItemId = reviewItemId;\n }\n\n public String getRevision() {\n return myRevision;\n }\n\n public void setRevision(String revision) {\n myRevision = revision;\n }\n\n public void addReply(Comment reply) {\n myReplies.add(reply);\n }\n\n public List<Comment> getReplies() {\n return myReplies;\n }\n\n public void setParentCommentId(String parentCommentId) {\n myParentCommentId = parentCommentId;\n }\n\n public String getParentCommentId() {\n return myParentCommentId;\n }\n\n public String getPermId() {\n return myPermId;\n }\n\n public void setPermId(String id) {\n myPermId = id;\n }\n\n public boolean isDraft() {\n return myDraft;\n }\n\n public void setDraft(boolean draft) {\n myDraft = draft;\n }\n}", "public class Review extends BasicReview {\n private final List<Comment> myGeneralComments = new ArrayList<Comment>();\n private final List<Comment> myComments = new ArrayList<Comment>();\n\n private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();\n\n public Review(@NotNull final String id, @NotNull final User author,\n @Nullable final User moderator) {\n super(id, author, moderator);\n }\n\n public void addGeneralComment(@NotNull Comment generalComment) {\n myGeneralComments.add(generalComment);\n }\n\n public void addComment(@NotNull Comment comment) {\n myComments.add(comment);\n }\n\n @NotNull\n public List<Comment> getGeneralComments() {\n return myGeneralComments;\n }\n\n @NotNull\n public List<Comment> getComments() {\n return myComments;\n }\n\n @NotNull\n public Set<ReviewItem> getReviewItems() {\n return myItems;\n }\n\n public void addReviewItem(@NotNull final ReviewItem item) {\n myItems.add(item);\n }\n\n @Nullable\n public String getPathById(@NotNull final String id) {\n for (ReviewItem item : myItems) {\n if (item.getId().equals(id))\n return item.getPath();\n }\n return null;\n }\n\n @Nullable\n public String getIdByPath(@NotNull final String path, Project project) {\n final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();\n\n for (ReviewItem item : myItems) {\n final String repo = item.getRepo();\n final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();\n String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));\n if (FileUtil.pathsEqual(relativePath, item.getPath())) {\n return item.getId();\n }\n }\n return null;\n }\n\n public boolean isInPatch(@NotNull Comment comment) {\n final String reviewItemId = comment.getReviewItemId();\n return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {\n @Override\n public boolean value(ReviewItem item) {\n return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();\n }\n });\n }\n}", "public class User {\n\n @NotNull protected final String myUserName;\n @Nullable private final String myAvatar;\n\n public User(@NotNull String userName) {\n this(userName, null);\n }\n\n public User(@NotNull final String userName, @Nullable String avatar) {\n myUserName = userName;\n myAvatar = avatar;\n }\n\n @NotNull\n public String getUserName() {\n return myUserName;\n }\n\n @Override\n public String toString() {\n return \"User [[\" + myUserName+ \"]]\";\n }\n\n @Override\n public int hashCode() {\n return myUserName.toLowerCase().hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof User)\n return myUserName.equalsIgnoreCase(((User)obj).getUserName());\n return super.equals(obj);\n }\n\n @Nullable\n public String getAvatar() {\n return myAvatar;\n }\n}" ]
import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.*; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.crucible.configuration.CrucibleSettings; import com.jetbrains.crucible.connection.CrucibleManager; import com.jetbrains.crucible.model.Comment; import com.jetbrains.crucible.model.Review; import com.jetbrains.crucible.model.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Set;
package com.jetbrains.crucible.ui.toolWindow.details; /** * User: ktisha */ public class CommentForm extends JPanel { private static final int ourBalloonWidth = 350; private static final int ourBalloonHeight = 200; private final EditorTextField myReviewTextField; private JBPopup myBalloon; private Editor myEditor; @NotNull private final Project myProject; private final boolean myGeneral; private final boolean myReply; @Nullable private FilePath myFilePath; private boolean myOK; public Review getReview() { return myReview; } private Review myReview; private Comment myParentComment; public CommentForm(@NotNull Project project, boolean isGeneral, boolean isReply, @Nullable FilePath filePath) { super(new BorderLayout()); myProject = project; myGeneral = isGeneral; myReply = isReply; myFilePath = filePath; final EditorTextFieldProvider service = ServiceManager.getService(project, EditorTextFieldProvider.class); final Set<EditorCustomization> editorFeatures = ContainerUtil.newHashSet(SoftWrapsEditorCustomization.ENABLED, SpellCheckingEditorCustomizationProvider.getInstance().getEnabledCustomization()); myReviewTextField = service.getEditorField(PlainTextLanguage.INSTANCE, project, editorFeatures); final JScrollPane pane = ScrollPaneFactory.createScrollPane(myReviewTextField); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(pane); myReviewTextField.setPreferredSize(new Dimension(ourBalloonWidth, ourBalloonHeight)); myReviewTextField.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "postComment"); myReviewTextField.getActionMap().put("postComment", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myOK = true; if (myBalloon != null) { myBalloon.dispose(); } } }); } @Nullable public Comment postComment() {
final Comment comment = new Comment(new User(CrucibleSettings.getInstance().USERNAME), getText(), !myOK);
4
orekyuu/Riho
src/net/orekyuu/riho/events/TestListener.java
[ "public enum FacePattern {\n NORMAL, SMILE1, SMILE2, AWAWA, FUN, JITO, SURPRISE, SYUN;\n}", "public class Loop {\n private final int loopCount;\n private static final Loop INFINITE = new Loop(-1);\n private static final Loop ONCE = Loop.of(1);\n\n private Loop(int count) {\n this.loopCount = count;\n }\n\n public static Loop of(int loopCount) {\n if (loopCount < 0) {\n throw new IllegalArgumentException();\n }\n return new Loop(loopCount);\n }\n\n public boolean isInfinite() {\n return this == INFINITE;\n }\n\n public int getLoopCount() {\n return loopCount;\n }\n\n public static Loop infinite() {\n return INFINITE;\n }\n\n public static Loop once() {\n return ONCE;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Loop loop = (Loop) o;\n return loopCount == loop.loopCount;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(loopCount);\n }\n}", "public class Reaction {\n private final Emotion emotion;\n private final Loop emotionLoop;\n private final Duration duration ;\n private final FacePattern facePattern;\n\n public Reaction(FacePattern facePattern, Duration duration, Emotion emotion, Loop emotionLoop) {\n this.emotion = emotion;\n this.emotionLoop = emotionLoop;\n this.duration = duration;\n this.facePattern = facePattern;\n }\n\n public static Reaction of(FacePattern facePattern, Duration duration) {\n return of(facePattern, duration, Emotion.NONE, Loop.once());\n }\n\n public static Reaction of(FacePattern facePattern, Duration duration, Emotion emotion, Loop emotionLoop) {\n return new Reaction(facePattern, duration, emotion, emotionLoop);\n }\n\n public Emotion getEmotion() {\n return emotion;\n }\n\n public Loop getEmotionLoop() {\n return emotionLoop;\n }\n\n public Duration getDuration() {\n return duration;\n }\n\n public FacePattern getFacePattern() {\n return facePattern;\n }\n}", "public enum Emotion {\n NONE, QUESTION, DROP, MOJYA, SWEAT, SURPRISED, ANGER, SAD\n}", "public interface RihoReactionNotifier {\n\n Topic<RihoReactionNotifier> REACTION_NOTIFIER = Topic.create(\"riho reaction\", RihoReactionNotifier.class);\n\n void reaction(Reaction reaction);\n}" ]
import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.TestStatusListener; import com.intellij.openapi.project.Project; import net.orekyuu.riho.character.FacePattern; import net.orekyuu.riho.character.Loop; import net.orekyuu.riho.character.Reaction; import net.orekyuu.riho.emotion.Emotion; import net.orekyuu.riho.topics.RihoReactionNotifier; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.Random;
package net.orekyuu.riho.events; public class TestListener extends TestStatusListener { private int failedCount = 0; private static final Random rand = new Random(); @Override public void testSuiteFinished(@Nullable AbstractTestProxy abstractTestProxy) { } @Override public void testSuiteFinished(@Nullable AbstractTestProxy abstractTestProxy, Project project) { super.testSuiteFinished(abstractTestProxy, project); if (abstractTestProxy == null) { return; } RihoReactionNotifier notifier = project.getMessageBus().syncPublisher(RihoReactionNotifier.REACTION_NOTIFIER); if (abstractTestProxy.isPassed() || abstractTestProxy.isIgnored()) { if (failedCount == 0) { notifier.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(5))); } else {
notifier.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(5), Emotion.SURPRISED, Loop.once()));
1
TomGrill/gdx-twitter
gdx-twitter-core-tests/src/de/tomgrill/gdxtwitter/core/tests/TwitterSystemUnitTests.java
[ "public class TwitterConfig {\n\n\t/**\n\t * Put your Consumer Key (API Key) here. Get it at <a\n\t * href=\"https://apps.twitter.com/\">https://apps.twitter.com/</a>\n\t * \n\t */\n\tpublic String TWITTER_CONSUMER_KEY = \"\";\n\n\t/**\n\t * Put your Consumer Secret (API Secret) here. Get it at <a\n\t * href=\"https://apps.twitter.com/\">https://apps.twitter.com/</a>\n\t * \n\t */\n\tpublic String TWITTER_CONSUMER_SECRET = \"\";\n\n\t/**\n\t * \n\t */\n\tpublic String TWITTER_CALLBACK_URL = \"https://github.com/TomGrill/gdx-twitter\";\n\n\tpublic int TWITTER_REQUEST_TIMEOUT = 3000;\t// in ms\n\n\t/*\n\t * ##########################################################################\n\t * \n\t * \n\t * Only edit settings below this line if you know what you do. Expert usage\n\t * only\n\t * \n\t * ##########################################################################\n\t */\n\n\t/**\n\t * It is NOT recommended to change this value. If you do so you have to edit\n\t * your AndroidManifest.xml as well.\n\t * \n\t */\n\tpublic String TWITTER_ANDROID_SCHEME = \"gdx-twitter\";\n\tpublic String TWITTER_ANDROID_HOST = \"twitter\";\n\n\t/**\n\t * Prefix for variable names.\n\t */\n\tpublic String PREFERECES_VARIABLE_PREFIX = \"gdx-twitter.\";\n\n\t/**\n\t * Filename where session data is stored.\n\t */\n\tpublic String TWITTER_SESSION_FILENAME = \".gdx-twitter-session\";\n\n\t/**\n\t * Class which manages the Twitter session. Default is\n\t * {@link PreferencesTwitterSession}. You can write your own session manager\n\t * class. For example if you want to store the tokens in a database. Must\n\t * implement {@link TwitterSession}.\n\t */\n\n\tpublic TwitterSession TWITTER_SESSION = new PreferencesTwitterSession(Gdx.app.getPreferences(TWITTER_SESSION_FILENAME), PREFERECES_VARIABLE_PREFIX);\n\n}", "public class TwitterSystem {\n\n\tprivate static final String TAG = \"gdx-twitter\";\n\n\tprivate TwitterAPI twitterAPI;\n\tprivate TwitterConfig config;\n\n\tprivate Class<?> gdxClazz = null;\n\tprivate Object gdxAppObject = null;\n\n\tprivate Class<?> gdxLifecycleListenerClazz = null;\n\tprivate Method gdxAppAddLifecycleListenerMethod = null;\n\n\tpublic TwitterSystem(TwitterConfig config) {\n\t\tthis.config = config;\n\n\t\tloadGdxReflections();\n\t\ttryLoadAndroidTwitterAPI();\n\t\ttryLoadDesktopTwitterAPI();\n\t\ttryLoadHTMLTwitterAPI();\n\t\ttryLoadIOSTWitterAPI();\n\t}\n\n\tprivate void loadGdxReflections() {\n\n\t\ttry {\n\t\t\tgdxClazz = ClassReflection.forName(\"com.badlogic.gdx.Gdx\");\n\t\t\tgdxAppObject = ClassReflection.getField(gdxClazz, \"app\").get(null);\n\t\t\tgdxLifecycleListenerClazz = ClassReflection.forName(\"com.badlogic.gdx.LifecycleListener\");\n\t\t\tgdxAppAddLifecycleListenerMethod = ClassReflection.getMethod(gdxAppObject.getClass(), \"addLifecycleListener\", gdxLifecycleListenerClazz);\n\n\t\t} catch (ReflectionException e) {\n\t\t\tthrow new RuntimeException(\"No libGDX environment. \\n\");\n\t\t}\n\n\t}\n\n\tprivate void tryLoadAndroidTwitterAPI() {\n\n\t\tif (Gdx.app.getType() != ApplicationType.Android) {\n\t\t\tGdx.app.debug(TAG, \"Skip loading Twitter API for Android. Not running Android. \\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (Gdx.app.getType() == ApplicationType.Android) {\n\t\t\ttry {\n\n\t\t\t\tClass<?> activityClazz = ClassReflection.forName(\"android.app.Activity\");\n\n\t\t\t\tClass<?> twitterClazz = ClassReflection.forName(\"de.tomgrill.gdxtwitter.android.AndroidTwitterAPI\");\n\n\t\t\t\tObject activity = null;\n\n\t\t\t\tif (ClassReflection.isAssignableFrom(activityClazz, gdxAppObject.getClass())) {\n\n\t\t\t\t\tactivity = gdxAppObject;\n\t\t\t\t} else {\n\n\t\t\t\t\tClass<?> supportFragmentClass = findClass(\"android.support.v4.app.Fragment\");\n\t\t\t\t\t// {\n\t\t\t\t\tif (supportFragmentClass != null && ClassReflection.isAssignableFrom(supportFragmentClass, gdxAppObject.getClass())) {\n\n\t\t\t\t\t\tactivity = ClassReflection.getMethod(supportFragmentClass, \"getActivity\").invoke(gdxAppObject);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tClass<?> fragmentClass = findClass(\"android.app.Fragment\");\n\t\t\t\t\t\tif (fragmentClass != null && ClassReflection.isAssignableFrom(fragmentClass, gdxAppObject.getClass())) {\n\t\t\t\t\t\t\tactivity = ClassReflection.getMethod(fragmentClass, \"getActivity\").invoke(gdxAppObject);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif (activity == null) {\n\t\t\t\t\tthrow new RuntimeException(\"Can't find your gdx activity to instantiate gdx-twitter. \" + \"Looks like you have implemented AndroidApplication without using \"\n\t\t\t\t\t\t\t+ \"Activity or Fragment classes or Activity is not available at the moment\");\n\t\t\t\t}\n\n\t\t\t\tObject twitter = ClassReflection.getConstructor(twitterClazz, activityClazz, TwitterConfig.class).newInstance(activity, config);\n\n\t\t\t\tgdxAppAddLifecycleListenerMethod.invoke(gdxAppObject, twitter);\n\n\t\t\t\ttwitterAPI = (TwitterAPI) twitter;\n\n\t\t\t\tGdx.app.debug(TAG, \"gdx-twitter for Android loaded successfully.\");\n\n\t\t\t} catch (Exception e) {\n\t\t\t\tGdx.app.debug(TAG, \"Error creating gdx-twitter for Android (are the gdx-twitter **.jar files installed?). \\n\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void tryLoadDesktopTwitterAPI() {\n\t\tif (Gdx.app.getType() != ApplicationType.Desktop) {\n\t\t\tGdx.app.debug(TAG, \"Skip loading Twitter API for Desktop. Not running Desktop. \\n\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\n\t\t\tfinal Class<?> twitterClazz = ClassReflection.forName(\"de.tomgrill.gdxtwitter.desktop.DesktopTwitterAPI\");\n\t\t\tObject twitter = ClassReflection.getConstructor(twitterClazz, TwitterConfig.class).newInstance(config);\n\n\t\t\ttwitterAPI = (TwitterAPI) twitter;\n\n\t\t\tGdx.app.debug(TAG, \"gdx-twitter for Desktop loaded successfully.\");\n\n\t\t} catch (ReflectionException e) {\n\t\t\tGdx.app.debug(TAG, \"Error creating gdx-twitter for Desktop (are the gdx-twitter **.jar files installed?). \\n\");\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\tprivate void tryLoadHTMLTwitterAPI() {\n\t\tif (Gdx.app.getType() != ApplicationType.WebGL) {\n\t\t\tGdx.app.debug(TAG, \"Skip loading gdx-twitter for HTML. Not running HTML. \\n\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\n\t\t\tfinal Class<?> twitterClazz = ClassReflection.forName(\"de.tomgrill.gdxtwitter.html.HTMLTwitterAPI\");\n\t\t\tObject twitter = ClassReflection.getConstructor(twitterClazz, TwitterConfig.class).newInstance(config);\n\n\t\t\ttwitterAPI = (TwitterAPI) twitter;\n\n\t\t\tGdx.app.debug(TAG, \"gdx-twitter for HTML loaded successfully.\");\n\n\t\t} catch (ReflectionException e) {\n\t\t\tGdx.app.debug(TAG, \"Error creating gdx-twitter for HTML (are the gdx-twitter **.jar files installed?). \\n\");\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\tprivate void tryLoadIOSTWitterAPI() {\n\n\t\tif (Gdx.app.getType() != ApplicationType.iOS) {\n\t\t\tGdx.app.debug(TAG, \"Skip loading gdx-twitter for iOS. Not running iOS. \\n\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\n\t\t\t// Class<?> activityClazz =\n\t\t\t// ClassReflection.forName(\"com.badlogic.gdx.backends.iosrobovm.IOSApplication\");\n\t\t\tfinal Class<?> twitterClazz = ClassReflection.forName(\"de.tomgrill.gdxtwitter.ios.IOSTwitterAPI\");\n\n\t\t\tObject twitter = ClassReflection.getConstructor(twitterClazz, TwitterConfig.class).newInstance(config);\n\n\t\t\ttwitterAPI = (TwitterAPI) twitter;\n\n\t\t\tGdx.app.debug(TAG, \"gdx-twitter for iOS loaded successfully.\");\n\n\t\t} catch (ReflectionException e) {\n\t\t\tGdx.app.debug(TAG, \"Error creating gdx-twitter for iOS (are the gdx-twitter **.jar files installed?). \\n\");\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\tpublic TwitterAPI getTwitterAPI() {\n\t\treturn twitterAPI;\n\t}\n\n\t/** @return null if class is not available in runtime */\n\tprivate static Class<?> findClass(String name) {\n\t\ttry {\n\t\t\treturn ClassReflection.forName(name);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public class ActivityStub {\n\n}", "public class FragmentStub {\n\n}", "public class GdxLifecycleListenerStub {\n\n}", "public class GdxStub {\n\n}", "public class PreferencesStub implements Preferences {\n\n\t@Override\n\tpublic Preferences putBoolean(String key, boolean val) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Preferences putInteger(String key, int val) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Preferences putLong(String key, long val) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Preferences putFloat(String key, float val) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Preferences putString(String key, String val) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Preferences put(Map<String, ?> vals) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean getBoolean(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getInteger(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic long getLong(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic float getFloat(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic String getString(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean getBoolean(String key, boolean defValue) {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getInteger(String key, int defValue) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic long getLong(String key, long defValue) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic float getFloat(String key, float defValue) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic String getString(String key, String defValue) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Map<String, ?> get() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean contains(String key) {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void remove(String key) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void flush() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n}", "public class SupportFragmentStub {\n\n}", "public class TwitterAPIStub extends TwitterAPI {\n\n\tpublic TwitterAPIStub(TwitterConfig config) {\n\t\tsuper(config);\n\t}\n\n\t@Override\n\tpublic void signin(boolean allowGUI, TwitterResponseListener reponseListener) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n}" ]
import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.headless.HeadlessApplication; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Constructor; import com.badlogic.gdx.utils.reflect.Field; import com.badlogic.gdx.utils.reflect.Method; import com.badlogic.gdx.utils.reflect.ReflectionException; import de.tomgrill.gdxtwitter.core.TwitterConfig; import de.tomgrill.gdxtwitter.core.TwitterSystem; import de.tomgrill.gdxtwitter.core.tests.stubs.ActivityStub; import de.tomgrill.gdxtwitter.core.tests.stubs.FragmentStub; import de.tomgrill.gdxtwitter.core.tests.stubs.GdxLifecycleListenerStub; import de.tomgrill.gdxtwitter.core.tests.stubs.GdxStub; import de.tomgrill.gdxtwitter.core.tests.stubs.PreferencesStub; import de.tomgrill.gdxtwitter.core.tests.stubs.SupportFragmentStub; import de.tomgrill.gdxtwitter.core.tests.stubs.TwitterAPIStub;
/******************************************************************************* * Copyright 2015 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tomgrill.gdxtwitter.core.tests; @RunWith(PowerMockRunner.class) @PrepareForTest({ ClassReflection.class, Field.class, Constructor.class, Method.class }) public class TwitterSystemUnitTests { private TwitterConfig config; private ClassReflection classReflectionMock; private Field fieldMock; private Constructor constructorMock; private Method methodMock; private ActivityStub activityStub; private TwitterAPIStub twitterAPIStub;
private GdxStub gdxStub;
5
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/api/dao/CongressmanDao.java
[ "public class DatabaseHelper extends SQLiteOpenHelper {\n\t\n\tprivate static final String dbName = \"AKAN.db\";\n\t\n\tprivate static final String congressmanTable = \"CREATE TABLE [CONGRESSMAN] \"\n\t + \"([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, \"\n\t + \"[NAME_CONGRESSMAN] VARCHAR(40), [PARTY] VARCHAR(10), \"\n\t + \"[UF_CONGRESSMAN] VARCHAR (2), [TOTAL_SPENT_CONGRESSMAN] DOUBLE, \"\n\t + \"[STATUS_CONGRESSMAN] BOOLEAN, [PHOTO_CONGRESSMAN] VARCHAR(255), \"\n\t + \"[RANKING_CONGRESSMAN] INT);\";\n\t\n\tprivate static final String quotaTable = \"CREATE TABLE [QUOTA] \"\n\t + \"([ID_QUOTA] VARCHAR(10) unique, [ID_CONGRESSMAN] VARCHAR(10), \"\n\t + \"[ID_UPDATE] INT, [TYPE_QUOTA] INT(10), [DESCRIPTION_QUOTA] \"\n\t + \"VARCHAR (40), [MONTH_QUOTA] INT, [YEAR_QUOTA] INT, \"\n\t + \"[VALUE_QUOTA] DOUBLE);\";\n\t\n\tprivate static final String urlTable = \"CREATE TABLE [URL] \"\n\t + \"([UPDATE_VERIFIER_URL] VARCHAR(10), \"\n\t + \"[ID_UPDATE_URL] VARCHAR(255), [DEFAULT_URL] VARCHAR (255), \"\n\t + \"[FIRST_URL] VARCHAR (255), [SECOND_URL] VARCHAR (255));\";\n\t\n\tprivate static final String statisticTable = \"CREATE TABLE [STATISTIC] \"\n\t + \"([ID_STATISTIC] VARCHAR(10) unique, [MONTH_STATISTIC] INT, \"\n\t + \"[STD_DEVIATION] DOUBLE, [AVERAGE_STATISTIC] DOUBLE, \"\n\t + \"[MAX_VALUE_STATISTIC] DOUBLE, [YEAR_STATISTIC] INT,\"\n\t + \"ID_SUBQUOTA INT(10));\";\n\t\n\tprivate static final String versionTable = \"CREATE TABLE [VERSION] \"\n\t + \"([ID_VERSION] VARCHAR(10) unique, [NUM_VERSION] INT);\";\n\t\n\tpublic DatabaseHelper( Context context ) {\n\t\tsuper( context, dbName, null, 1 );\n\t}\n\t\n\tpublic DatabaseHelper( Context context, String name, CursorFactory factory,\n\t int version ) {\n\t\t\n\t\tsuper( context, name, factory, version );\n\t}\n\t\n\t/**\n\t * Describes the actions that will be made when creating the database.\n\t * Creates the tables.\n\t */\n\t@Override\n\tpublic void onCreate( SQLiteDatabase db ) {\n\t\tdb.execSQL( congressmanTable );\n\t\tdb.execSQL( quotaTable );\n\t\tdb.execSQL( urlTable );\n\t\tdb.execSQL( statisticTable );\n\t\tdb.execSQL( versionTable );\n\t}\n\t\n\t/**\n\t * Describes the actions that will be made if there is a update in the\n\t * database.\n\t */\n\t@Override\n\tpublic void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {\n\t\t/* ! Empty Method. */\n\t}\n}", "public enum Order {\n\tRANKING( 0, \"RANKING_CONGRESSMAN\" ),\n\tALPHABETIC( 1, \"NAME_CONGRESSMAN\" ),\n\tSTATE( 2, \"UF_CONGRESSMAN\" ),\n\tPARTY( 3, \"PARTY\" );\n\t\n\tprivate int valueOrder;\n\tprivate String representativeName;\n\t\n\tOrder( int value, String name ) {\n\t\tthis.valueOrder = value;\n\t\tthis.representativeName = name;\n\t}\n\t\n\t/**\n\t * Return the numerical value of the ordenation.\n\t * \n\t * @return The numerical value of the ordenation.\n\t */\n\tpublic int getValueOrder() {\n\t\treturn valueOrder;\n\t}\n\t\n\t/**\n\t * Return a name that represent the ordenation.\n\t * \n\t * @return The name that represent this ordenation.\n\t */\n\tpublic String getOrderName() {\n\t\treturn representativeName; \n\t}\n\n}", "public class DatabaseInvalidOperationException extends Exception {\n private static final long serialVersionUID = 380307236047507820L;\n}", "public class NullCongressmanException extends Exception {\n\tprivate static final long serialVersionUID = -652180129137381807L;\n\t\n\tpublic NullCongressmanException() {\n\t\t/*! Empty Constructor. */\n\t}\n\t\n\tpublic NullCongressmanException( String message ) {\n\t\tsuper( message );\n\t}\n}", "public class Congressman {\n\tstatic final boolean FOLLOWED = true;\n\tstatic final boolean NOT_FOLLOWED = false;\n\t\n\tprotected int id = 0;\n\tprotected int idUpdateCongressman = 0;\n\tprotected boolean statusCogressman = NOT_FOLLOWED;\n\tprotected byte[] photoCongressman = null;\n\t\n\tprotected String nameCongressman = \"\";\n\tprotected String partyCongressman = \"\";\n\tprotected String ufCongressman = \"\";\n\tprotected int ranking = 0;\n\tprotected List<Quota> quotasCongressman = null;\n\tprotected double totalSpentCongressman = 0;\n\tprotected String typeCongressman = \"\";\n\t\n\tpublic String getTypeCongressman() {\n\t\treturn typeCongressman;\n\t}\n\t\n\tpublic void setTypeCongressman( String typeCongressman ) {\n\t\tthis.typeCongressman = typeCongressman;\t\n\t}\n\t\n\tpublic int getIdCongressman() {\n\t\treturn id;\n\t}\n\t\n\tpublic void setIdCongressman( int idCongressman ) {\n\t\tthis.id = idCongressman;\n\t}\n\t\n\tpublic int getIdUpdateCongressman() {\n\t\treturn idUpdateCongressman;\n\t}\n\t\n\tpublic void setIdUpdateCongressman( int idUpdateCongressman ) {\n\t\tthis.idUpdateCongressman = idUpdateCongressman;\n\t}\n\t\n\tpublic boolean isStatusCogressman() {\n\t\treturn statusCogressman;\n\t}\n\t\n\tpublic void setStatusCogressman( boolean statusCogressman ) {\n\t\tthis.statusCogressman = statusCogressman;\n\t}\n\t\n\tpublic byte[] getPhotoCongressman() {\n\t\treturn photoCongressman;\n\t}\n\t\n\tpublic void setPhotoCongressman( byte[] photoCongressman ) {\n\t\tthis.photoCongressman = photoCongressman;\n\t}\n\t\n\tpublic String getNameCongressman() {\n\t\treturn nameCongressman;\n\t}\n\t\n\tpublic void setNameCongressman( String nameCongressman ) {\n\t\tthis.nameCongressman = nameCongressman;\n\t}\n\t\n\tpublic String getPartyCongressman() {\n\t\treturn partyCongressman;\n\t}\n\t\n\tpublic void setPartyCongressman( String partyCongressman ) {\n\t\tthis.partyCongressman = partyCongressman;\n\t}\n\t\n\tpublic String getUfCongressman() {\n\t\treturn ufCongressman;\n\t}\n\t\n\tpublic void setUfCongressman( String ufCongressman ) {\n\t\tthis.ufCongressman = ufCongressman;\n\t}\n\t\n\tpublic List<Quota> getQuotasCongressman() {\n\t\treturn quotasCongressman;\n\t}\n\t\n\tpublic void setQuotasCongressman( List<Quota> quotasCongressman ) {\n\t\tthis.quotasCongressman = quotasCongressman;\n\t}\n\t\n\tpublic double getTotalSpentCongressman() {\n\t\treturn totalSpentCongressman;\n\t}\n\t\n\tpublic void setTotalSpentCongressman( double totalSpentCongressman ) {\n\t\tthis.totalSpentCongressman = totalSpentCongressman;\n\t}\n\t\n\tpublic int getRankingCongressman() {\n\t\treturn ranking;\n\t}\n\t\n\tpublic void setRankingCongressman( int rankingCongressman ) {\n\t\tthis.ranking = rankingCongressman;\n\t}\n}" ]
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import br.com.visualize.akan.api.helper.DatabaseHelper; import br.com.visualize.akan.domain.enumeration.Order; import br.com.visualize.akan.domain.exception.DatabaseInvalidOperationException; import br.com.visualize.akan.domain.exception.NullCongressmanException; import br.com.visualize.akan.domain.model.Congressman;
/* * File: CongressmanDao.java Purpose: Brings the implementation of class * CongressmanDao. */ package br.com.visualize.akan.api.dao; /** * This class represents the Data Access Object for the Congressman, responsible * for all data base operations like selections, insertions and updates. */ public class CongressmanDao extends Dao { private static final boolean EMPTY = true; private static final boolean NOT_EMPTY = false; private static CongressmanDao instance; private static String tableName = "CONGRESSMAN"; private static String tableColumns[ ] = { "ID_CONGRESSMAN", "ID_UPDATE", "NAME_CONGRESSMAN", "PARTY", "UF_CONGRESSMAN", "TOTAL_SPENT_CONGRESSMAN", "STATUS_CONGRESSMAN", "PHOTO_CONGRESSMAN", "RANKING_CONGRESSMAN" }; private CongressmanDao( Context context ) { CongressmanDao.database = new DatabaseHelper( context ); } /** * Return the unique instance of CongressmanDao active in the project. * <p> * * @return The unique instance of CongressmanDao. */ public static CongressmanDao getInstance( Context context ) { if( CongressmanDao.instance != null ) { /* !Nothing To Do. */ } else { CongressmanDao.instance = new CongressmanDao( context ); } return CongressmanDao.instance; } /** * Checks if database is empty. */ public boolean checkEmptyLocalDb() { sqliteDatabase = database.getReadableDatabase(); String query = "SELECT 1 FROM " + tableName; Cursor cursor = sqliteDatabase.rawQuery( query, null ); boolean isEmpty = NOT_EMPTY; if( cursor != null ) { if( cursor.getCount() <= 0 ) { cursor.moveToFirst(); isEmpty = EMPTY; } else { /* ! Nothing To Do */ } } else { isEmpty = EMPTY; } return isEmpty; } /** * Checks database version. */ public boolean checkDbVersion(int remoteVersion) { sqliteDatabase = database.getReadableDatabase(); String query = "SELECT * FROM VERSION"; Cursor cursor = sqliteDatabase.rawQuery( query, null ); cursor.moveToFirst(); int currentVersion = cursor.getInt( cursor.getColumnIndex("NUM_VERSION") ); boolean isLastVersion = currentVersion < remoteVersion; return isLastVersion; } /** * Inserts in the database a version of remote * database. * * @param int version of remote database. * * @return Result if the operation was successful or not. */ public boolean insertDbVersion( int version ) { boolean result = false; sqliteDatabase = database.getWritableDatabase(); sqliteDatabase.delete( "VERSION",null, null); ContentValues content = new ContentValues(); content.put( "NUM_VERSION", version ); result = (insertAndClose( sqliteDatabase, "VERSION", content ) > 0 ); return result; } /** * Up * * @param congressman * @return * @throws NullCongressmanException */
public boolean setFollowedCongressman( Congressman congressman )
4
BurstProject/burstcoin
src/java/nxt/http/EscrowSign.java
[ "public final class Account {\n\n public static enum Event {\n BALANCE, UNCONFIRMED_BALANCE, ASSET_BALANCE, UNCONFIRMED_ASSET_BALANCE,\n LEASE_SCHEDULED, LEASE_STARTED, LEASE_ENDED\n }\n\n public static class AccountAsset {\n\n private final long accountId;\n private final long assetId;\n private final DbKey dbKey;\n private long quantityQNT;\n private long unconfirmedQuantityQNT;\n\n private AccountAsset(long accountId, long assetId, long quantityQNT, long unconfirmedQuantityQNT) {\n this.accountId = accountId;\n this.assetId = assetId;\n this.dbKey = accountAssetDbKeyFactory.newKey(this.accountId, this.assetId);\n this.quantityQNT = quantityQNT;\n this.unconfirmedQuantityQNT = unconfirmedQuantityQNT;\n }\n\n private AccountAsset(ResultSet rs) throws SQLException {\n this.accountId = rs.getLong(\"account_id\");\n this.assetId = rs.getLong(\"asset_id\");\n this.dbKey = accountAssetDbKeyFactory.newKey(this.accountId, this.assetId);\n this.quantityQNT = rs.getLong(\"quantity\");\n this.unconfirmedQuantityQNT = rs.getLong(\"unconfirmed_quantity\");\n }\n\n private void save(Connection con) throws SQLException {\n try (PreparedStatement pstmt = con.prepareStatement(\"MERGE INTO account_asset \"\n + \"(account_id, asset_id, quantity, unconfirmed_quantity, height, latest) \"\n + \"KEY (account_id, asset_id, height) VALUES (?, ?, ?, ?, ?, TRUE)\")) {\n int i = 0;\n pstmt.setLong(++i, this.accountId);\n pstmt.setLong(++i, this.assetId);\n pstmt.setLong(++i, this.quantityQNT);\n pstmt.setLong(++i, this.unconfirmedQuantityQNT);\n pstmt.setInt(++i, Nxt.getBlockchain().getHeight());\n pstmt.executeUpdate();\n }\n }\n\n public long getAccountId() {\n return accountId;\n }\n\n public long getAssetId() {\n return assetId;\n }\n\n public long getQuantityQNT() {\n return quantityQNT;\n }\n\n public long getUnconfirmedQuantityQNT() {\n return unconfirmedQuantityQNT;\n }\n\n private void save() {\n checkBalance(this.accountId, this.quantityQNT, this.unconfirmedQuantityQNT);\n if (this.quantityQNT > 0 || this.unconfirmedQuantityQNT > 0) {\n accountAssetTable.insert(this);\n } else {\n accountAssetTable.delete(this);\n }\n }\n\n @Override\n public String toString() {\n return \"AccountAsset account_id: \" + Convert.toUnsignedLong(accountId) + \" asset_id: \" + Convert.toUnsignedLong(assetId)\n + \" quantity: \" + quantityQNT + \" unconfirmedQuantity: \" + unconfirmedQuantityQNT;\n }\n\n }\n\n public static class AccountLease {\n\n public final long lessorId;\n public final long lesseeId;\n public final int fromHeight;\n public final int toHeight;\n\n private AccountLease(long lessorId, long lesseeId, int fromHeight, int toHeight) {\n this.lessorId = lessorId;\n this.lesseeId = lesseeId;\n this.fromHeight = fromHeight;\n this.toHeight = toHeight;\n }\n\n }\n \n public static class RewardRecipientAssignment {\n \t\n \tpublic final Long accountId;\n \tprivate Long prevRecipientId;\n \tprivate Long recipientId;\n \tprivate int fromHeight;\n \tprivate final DbKey dbKey;\n \t\n \tprivate RewardRecipientAssignment(Long accountId, Long prevRecipientId, Long recipientId, int fromHeight) {\n \t\tthis.accountId = accountId;\n \t\tthis.prevRecipientId = prevRecipientId;\n \t\tthis.recipientId = recipientId;\n \t\tthis.fromHeight = fromHeight;\n \t\tthis.dbKey = rewardRecipientAssignmentDbKeyFactory.newKey(this.accountId);\n \t}\n \t\n \tprivate RewardRecipientAssignment(ResultSet rs) throws SQLException {\n \t\tthis.accountId = rs.getLong(\"account_id\");\n \t\tthis.dbKey = rewardRecipientAssignmentDbKeyFactory.newKey(this.accountId);\n \t\tthis.prevRecipientId = rs.getLong(\"prev_recip_id\");\n \t\tthis.recipientId = rs.getLong(\"recip_id\");\n \t\tthis.fromHeight = (int) rs.getLong(\"from_height\");\n \t}\n \t\n \tprivate void save(Connection con) throws SQLException {\n \t\ttry (PreparedStatement pstmt = con.prepareStatement(\"MERGE INTO reward_recip_assign \"\n \t\t\t\t+ \"(account_id, prev_recip_id, recip_id, from_height, height, latest) KEY (account_id, height) VALUES (?, ?, ?, ?, ?, TRUE)\")) {\n \t\t\tint i = 0;\n \t\t\tpstmt.setLong(++i, this.accountId);\n \t\t\tpstmt.setLong(++i, this.prevRecipientId);\n \t\t\tpstmt.setLong(++i, this.recipientId);\n \t\t\tpstmt.setInt(++i, this.fromHeight);\n \t\t\tpstmt.setInt(++i, Nxt.getBlockchain().getHeight());\n \t\t\tpstmt.executeUpdate();\n \t\t}\n \t}\n \t\n \tpublic long getAccountId() {\n \t\treturn accountId;\n \t}\n \t\n \tpublic long getPrevRecipientId() {\n \t\treturn prevRecipientId;\n \t}\n \t\n \tpublic long getRecipientId() {\n \t\treturn recipientId;\n \t}\n \t\n \tpublic int getFromHeight() {\n \t\treturn fromHeight;\n \t}\n \t\n \tpublic void setRecipient(long newRecipientId, int fromHeight) {\n \t\tprevRecipientId = recipientId;\n \t\trecipientId = newRecipientId;\n \t\tthis.fromHeight = fromHeight;\n \t}\n }\n\n static class DoubleSpendingException extends RuntimeException {\n\n DoubleSpendingException(String message) {\n super(message);\n }\n\n }\n\n static {\n\n Nxt.getBlockchainProcessor().addListener(new Listener<Block>() {\n @Override\n public void notify(Block block) {\n int height = block.getHeight();\n try (DbIterator<Account> leasingAccounts = getLeasingAccounts()) {\n while (leasingAccounts.hasNext()) {\n Account account = leasingAccounts.next();\n if (height == account.currentLeasingHeightFrom) {\n leaseListeners.notify(\n new AccountLease(account.getId(), account.currentLesseeId, height, account.currentLeasingHeightTo),\n Event.LEASE_STARTED);\n } else if (height == account.currentLeasingHeightTo) {\n leaseListeners.notify(\n new AccountLease(account.getId(), account.currentLesseeId, account.currentLeasingHeightFrom, height),\n Event.LEASE_ENDED);\n if (account.nextLeasingHeightFrom == Integer.MAX_VALUE) {\n account.currentLeasingHeightFrom = Integer.MAX_VALUE;\n account.currentLesseeId = 0;\n accountTable.insert(account);\n } else {\n account.currentLeasingHeightFrom = account.nextLeasingHeightFrom;\n account.currentLeasingHeightTo = account.nextLeasingHeightTo;\n account.currentLesseeId = account.nextLesseeId;\n account.nextLeasingHeightFrom = Integer.MAX_VALUE;\n account.nextLesseeId = 0;\n accountTable.insert(account);\n if (height == account.currentLeasingHeightFrom) {\n leaseListeners.notify(\n new AccountLease(account.getId(), account.currentLesseeId, height, account.currentLeasingHeightTo),\n Event.LEASE_STARTED);\n }\n }\n }\n }\n }\n }\n }, BlockchainProcessor.Event.AFTER_BLOCK_APPLY);\n\n }\n\n private static final DbKey.LongKeyFactory<Account> accountDbKeyFactory = new DbKey.LongKeyFactory<Account>(\"id\") {\n\n @Override\n public DbKey newKey(Account account) {\n return account.dbKey;\n }\n\n };\n\n private static final VersionedEntityDbTable<Account> accountTable = new VersionedEntityDbTable<Account>(\"account\", accountDbKeyFactory) {\n\n @Override\n protected Account load(Connection con, ResultSet rs) throws SQLException {\n return new Account(rs);\n }\n\n @Override\n protected void save(Connection con, Account account) throws SQLException {\n account.save(con);\n }\n\n };\n\n private static final DbKey.LinkKeyFactory<AccountAsset> accountAssetDbKeyFactory = new DbKey.LinkKeyFactory<AccountAsset>(\"account_id\", \"asset_id\") {\n\n @Override\n public DbKey newKey(AccountAsset accountAsset) {\n return accountAsset.dbKey;\n }\n\n };\n\n private static final VersionedEntityDbTable<AccountAsset> accountAssetTable = new VersionedEntityDbTable<AccountAsset>(\"account_asset\", accountAssetDbKeyFactory) {\n\n @Override\n protected AccountAsset load(Connection con, ResultSet rs) throws SQLException {\n return new AccountAsset(rs);\n }\n\n @Override\n protected void save(Connection con, AccountAsset accountAsset) throws SQLException {\n accountAsset.save(con);\n }\n\n @Override\n protected String defaultSort() {\n return \" ORDER BY quantity DESC, account_id, asset_id \";\n }\n\n };\n\n private static final DerivedDbTable accountGuaranteedBalanceTable = new DerivedDbTable(\"account_guaranteed_balance\") {\n\n @Override\n public void trim(int height) {\n try (Connection con = Db.getConnection();\n PreparedStatement pstmtDelete = con.prepareStatement(\"DELETE FROM account_guaranteed_balance \"\n + \"WHERE height < ?\")) {\n pstmtDelete.setInt(1, height - 1440);\n pstmtDelete.executeUpdate();\n } catch (SQLException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n };\n \n private static final DbKey.LongKeyFactory<RewardRecipientAssignment> rewardRecipientAssignmentDbKeyFactory = new DbKey.LongKeyFactory<RewardRecipientAssignment>(\"account_id\") {\n \t\n \t@Override\n \tpublic DbKey newKey(RewardRecipientAssignment assignment) {\n \t\treturn assignment.dbKey;\n \t}\n\t};\n\t\n\tprivate static final VersionedEntityDbTable<RewardRecipientAssignment> rewardRecipientAssignmentTable = new VersionedEntityDbTable<RewardRecipientAssignment>(\"reward_recip_assign\", rewardRecipientAssignmentDbKeyFactory) {\n\t\t\n\t\t@Override\n\t\tprotected RewardRecipientAssignment load(Connection con, ResultSet rs) throws SQLException {\n\t\t\treturn new RewardRecipientAssignment(rs);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void save(Connection con, RewardRecipientAssignment assignment) throws SQLException {\n\t\t\tassignment.save(con);\n\t\t}\n\t};\n\n private static final Listeners<Account,Event> listeners = new Listeners<>();\n\n private static final Listeners<AccountAsset,Event> assetListeners = new Listeners<>();\n\n private static final Listeners<AccountLease,Event> leaseListeners = new Listeners<>();\n\n public static boolean addListener(Listener<Account> listener, Event eventType) {\n return listeners.addListener(listener, eventType);\n }\n\n public static boolean removeListener(Listener<Account> listener, Event eventType) {\n return listeners.removeListener(listener, eventType);\n }\n\n public static boolean addAssetListener(Listener<AccountAsset> listener, Event eventType) {\n return assetListeners.addListener(listener, eventType);\n }\n\n public static boolean removeAssetListener(Listener<AccountAsset> listener, Event eventType) {\n return assetListeners.removeListener(listener, eventType);\n }\n\n public static boolean addLeaseListener(Listener<AccountLease> listener, Event eventType) {\n return leaseListeners.addListener(listener, eventType);\n }\n\n public static boolean removeLeaseListener(Listener<AccountLease> listener, Event eventType) {\n return leaseListeners.removeListener(listener, eventType);\n }\n\n public static DbIterator<Account> getAllAccounts(int from, int to) {\n return accountTable.getAll(from, to);\n }\n\n public static int getCount() {\n return accountTable.getCount();\n }\n\n public static int getAssetAccountsCount(long assetId) {\n try (Connection con = Db.getConnection();\n PreparedStatement pstmt = con.prepareStatement(\"SELECT COUNT(*) FROM account_asset WHERE asset_id = ? AND latest = TRUE\")) {\n pstmt.setLong(1, assetId);\n try (ResultSet rs = pstmt.executeQuery()) {\n rs.next();\n return rs.getInt(1);\n }\n } catch (SQLException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n public static Account getAccount(long id) {\n return id == 0 ? null : accountTable.get(accountDbKeyFactory.newKey(id));\n }\n \n public static Account getAccount(long id, int height) {\n return id == 0 ? null : accountTable.get(accountDbKeyFactory.newKey(id), height);\n }\n\n public static Account getAccount(byte[] publicKey) {\n Account account = accountTable.get(accountDbKeyFactory.newKey(getId(publicKey)));\n if (account == null) {\n return null;\n }\n if (account.getPublicKey() == null || Arrays.equals(account.getPublicKey(), publicKey)) {\n return account;\n }\n throw new RuntimeException(\"DUPLICATE KEY for account \" + Convert.toUnsignedLong(account.getId())\n + \" existing key \" + Convert.toHexString(account.getPublicKey()) + \" new key \" + Convert.toHexString(publicKey));\n }\n\n public static long getId(byte[] publicKey) {\n byte[] publicKeyHash = Crypto.sha256().digest(publicKey);\n return Convert.fullHashToId(publicKeyHash);\n }\n\n static Account addOrGetAccount(long id) {\n Account account = accountTable.get(accountDbKeyFactory.newKey(id));\n if (account == null) {\n account = new Account(id);\n accountTable.insert(account);\n }\n return account;\n }\n\n private static final DbClause leasingAccountsClause = new DbClause(\" current_lessee_id >= ? \") {\n @Override\n public int set(PreparedStatement pstmt, int index) throws SQLException {\n pstmt.setLong(index++, Long.MIN_VALUE);\n return index;\n }\n };\n\n public static DbIterator<Account> getLeasingAccounts() {\n return accountTable.getManyBy(leasingAccountsClause, 0, -1);\n }\n\n public static DbIterator<AccountAsset> getAssetAccounts(long assetId, int from, int to) {\n return accountAssetTable.getManyBy(new DbClause.LongClause(\"asset_id\", assetId), from, to, \" ORDER BY quantity DESC, account_id \");\n }\n\n public static DbIterator<AccountAsset> getAssetAccounts(long assetId, int height, int from, int to) {\n if (height < 0) {\n return getAssetAccounts(assetId, from, to);\n }\n return accountAssetTable.getManyBy(new DbClause.LongClause(\"asset_id\", assetId), height, from, to, \" ORDER BY quantity DESC, account_id \");\n }\n\n static void init() {}\n\n\n private final long id;\n private final DbKey dbKey;\n private final int creationHeight;\n private byte[] publicKey;\n private int keyHeight;\n private long balanceNQT;\n private long unconfirmedBalanceNQT;\n private long forgedBalanceNQT;\n\n private int currentLeasingHeightFrom;\n private int currentLeasingHeightTo;\n private long currentLesseeId;\n private int nextLeasingHeightFrom;\n private int nextLeasingHeightTo;\n private long nextLesseeId;\n private String name;\n private String description;\n\n private Account(long id) {\n if (id != Crypto.rsDecode(Crypto.rsEncode(id))) {\n Logger.logMessage(\"CRITICAL ERROR: Reed-Solomon encoding fails for \" + id);\n }\n this.id = id;\n this.dbKey = accountDbKeyFactory.newKey(this.id);\n this.creationHeight = Nxt.getBlockchain().getHeight();\n currentLeasingHeightFrom = Integer.MAX_VALUE;\n }\n\n private Account(ResultSet rs) throws SQLException {\n this.id = rs.getLong(\"id\");\n this.dbKey = accountDbKeyFactory.newKey(this.id);\n this.creationHeight = rs.getInt(\"creation_height\");\n this.publicKey = rs.getBytes(\"public_key\");\n this.keyHeight = rs.getInt(\"key_height\");\n this.balanceNQT = rs.getLong(\"balance\");\n this.unconfirmedBalanceNQT = rs.getLong(\"unconfirmed_balance\");\n this.forgedBalanceNQT = rs.getLong(\"forged_balance\");\n this.name = rs.getString(\"name\");\n this.description = rs.getString(\"description\");\n this.currentLeasingHeightFrom = rs.getInt(\"current_leasing_height_from\");\n this.currentLeasingHeightTo = rs.getInt(\"current_leasing_height_to\");\n this.currentLesseeId = rs.getLong(\"current_lessee_id\");\n this.nextLeasingHeightFrom = rs.getInt(\"next_leasing_height_from\");\n this.nextLeasingHeightTo = rs.getInt(\"next_leasing_height_to\");\n this.nextLesseeId = rs.getLong(\"next_lessee_id\");\n }\n\n private void save(Connection con) throws SQLException {\n try (PreparedStatement pstmt = con.prepareStatement(\"MERGE INTO account (id, creation_height, public_key, \"\n + \"key_height, balance, unconfirmed_balance, forged_balance, name, description, \"\n + \"current_leasing_height_from, current_leasing_height_to, current_lessee_id, \"\n + \"next_leasing_height_from, next_leasing_height_to, next_lessee_id, \"\n + \"height, latest) \"\n + \"KEY (id, height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)\")) {\n int i = 0;\n pstmt.setLong(++i, this.getId());\n pstmt.setInt(++i, this.getCreationHeight());\n DbUtils.setBytes(pstmt, ++i, this.getPublicKey());\n pstmt.setInt(++i, this.getKeyHeight());\n pstmt.setLong(++i, this.getBalanceNQT());\n pstmt.setLong(++i, this.getUnconfirmedBalanceNQT());\n pstmt.setLong(++i, this.getForgedBalanceNQT());\n DbUtils.setString(pstmt, ++i, this.getName());\n DbUtils.setString(pstmt, ++i, this.getDescription());\n DbUtils.setIntZeroToNull(pstmt, ++i, this.getCurrentLeasingHeightFrom());\n DbUtils.setIntZeroToNull(pstmt, ++i, this.getCurrentLeasingHeightTo());\n DbUtils.setLongZeroToNull(pstmt, ++i, this.getCurrentLesseeId());\n DbUtils.setIntZeroToNull(pstmt, ++i, this.getNextLeasingHeightFrom());\n DbUtils.setIntZeroToNull(pstmt, ++i, this.getNextLeasingHeightTo());\n DbUtils.setLongZeroToNull(pstmt, ++i, this.getNextLesseeId());\n pstmt.setInt(++i, Nxt.getBlockchain().getHeight());\n pstmt.executeUpdate();\n }\n }\n\n public long getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n void setAccountInfo(String name, String description) {\n this.name = Convert.emptyToNull(name.trim());\n this.description = Convert.emptyToNull(description.trim());\n accountTable.insert(this);\n }\n\n public byte[] getPublicKey() {\n if (this.keyHeight == -1) {\n return null;\n }\n return publicKey;\n }\n\n private int getCreationHeight() {\n return creationHeight;\n }\n\n private int getKeyHeight() {\n return keyHeight;\n }\n\n public EncryptedData encryptTo(byte[] data, String senderSecretPhrase) {\n if (getPublicKey() == null) {\n throw new IllegalArgumentException(\"Recipient account doesn't have a public key set\");\n }\n return EncryptedData.encrypt(data, Crypto.getPrivateKey(senderSecretPhrase), publicKey);\n }\n\n public byte[] decryptFrom(EncryptedData encryptedData, String recipientSecretPhrase) {\n if (getPublicKey() == null) {\n throw new IllegalArgumentException(\"Sender account doesn't have a public key set\");\n }\n return encryptedData.decrypt(Crypto.getPrivateKey(recipientSecretPhrase), publicKey);\n }\n\n public long getBalanceNQT() {\n return balanceNQT;\n }\n\n public long getUnconfirmedBalanceNQT() {\n return unconfirmedBalanceNQT;\n }\n\n public long getForgedBalanceNQT() {\n return forgedBalanceNQT;\n }\n\n public long getEffectiveBalanceNXT() {\n\n Block lastBlock = Nxt.getBlockchain().getLastBlock();\n if (lastBlock.getHeight() >= Constants.TRANSPARENT_FORGING_BLOCK_6\n && (getPublicKey() == null || lastBlock.getHeight() - keyHeight <= 1440)) {\n return 0; // cfb: Accounts with the public key revealed less than 1440 blocks ago are not allowed to generate blocks\n }\n if (lastBlock.getHeight() < Constants.TRANSPARENT_FORGING_BLOCK_3\n && this.creationHeight < Constants.TRANSPARENT_FORGING_BLOCK_2) {\n if (this.creationHeight == 0) {\n return getBalanceNQT() / Constants.ONE_NXT;\n }\n if (lastBlock.getHeight() - this.creationHeight < 1440) {\n return 0;\n }\n long receivedInlastBlock = 0;\n for (Transaction transaction : lastBlock.getTransactions()) {\n if (id == transaction.getRecipientId()) {\n receivedInlastBlock += transaction.getAmountNQT();\n }\n }\n return (getBalanceNQT() - receivedInlastBlock) / Constants.ONE_NXT;\n }\n if (lastBlock.getHeight() < currentLeasingHeightFrom) {\n return (getGuaranteedBalanceNQT(1440) + getLessorsGuaranteedBalanceNQT()) / Constants.ONE_NXT;\n }\n return getLessorsGuaranteedBalanceNQT() / Constants.ONE_NXT;\n }\n\n private long getLessorsGuaranteedBalanceNQT() {\n long lessorsGuaranteedBalanceNQT = 0;\n try (DbIterator<Account> lessors = getLessors()) {\n while (lessors.hasNext()) {\n lessorsGuaranteedBalanceNQT += lessors.next().getGuaranteedBalanceNQT(1440);\n }\n }\n return lessorsGuaranteedBalanceNQT;\n }\n\n private DbClause getLessorsClause(final int height) {\n return new DbClause(\" current_lessee_id = ? AND current_leasing_height_from <= ? AND current_leasing_height_to > ? \") {\n @Override\n public int set(PreparedStatement pstmt, int index) throws SQLException {\n pstmt.setLong(index++, getId());\n pstmt.setInt(index++, height);\n pstmt.setInt(index++, height);\n return index;\n }\n };\n }\n\n public DbIterator<Account> getLessors() {\n return accountTable.getManyBy(getLessorsClause(Nxt.getBlockchain().getHeight()), 0, -1);\n }\n\n public DbIterator<Account> getLessors(int height) {\n if (height < 0) {\n return getLessors();\n }\n return accountTable.getManyBy(getLessorsClause(height), height, 0, -1);\n }\n \n public long getGuaranteedBalanceNQT(final int numberOfConfirmations) {\n return getGuaranteedBalanceNQT(numberOfConfirmations, Nxt.getBlockchain().getHeight());\n }\n\n public long getGuaranteedBalanceNQT(final int numberOfConfirmations, final int currentHeight) {\n if (numberOfConfirmations >= Nxt.getBlockchain().getHeight()) {\n return 0;\n }\n if (numberOfConfirmations > 2880 || numberOfConfirmations < 0) {\n throw new IllegalArgumentException(\"Number of required confirmations must be between 0 and \" + 2880);\n }\n int height = currentHeight - numberOfConfirmations;\n try (Connection con = Db.getConnection();\n PreparedStatement pstmt = con.prepareStatement(\"SELECT SUM (additions) AS additions \"\n \t\t + \"FROM account_guaranteed_balance WHERE account_id = ? AND height > ? AND height <= ?\")) {\n pstmt.setLong(1, this.id);\n pstmt.setInt(2, height);\n pstmt.setInt(3, currentHeight);\n try (ResultSet rs = pstmt.executeQuery()) {\n if (!rs.next()) {\n return balanceNQT;\n }\n return Math.max(Convert.safeSubtract(balanceNQT, rs.getLong(\"additions\")), 0);\n }\n } catch (SQLException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n public DbIterator<AccountAsset> getAssets(int from, int to) {\n return accountAssetTable.getManyBy(new DbClause.LongClause(\"account_id\", this.id), from, to);\n }\n\n public DbIterator<Trade> getTrades(int from, int to) {\n return Trade.getAccountTrades(this.id, from, to);\n }\n\n public DbIterator<AssetTransfer> getAssetTransfers(int from, int to) {\n return AssetTransfer.getAccountAssetTransfers(this.id, from, to);\n }\n\n public long getAssetBalanceQNT(long assetId) {\n AccountAsset accountAsset = accountAssetTable.get(accountAssetDbKeyFactory.newKey(this.id, assetId));\n return accountAsset == null ? 0 : accountAsset.quantityQNT;\n }\n\n public long getUnconfirmedAssetBalanceQNT(long assetId) {\n AccountAsset accountAsset = accountAssetTable.get(accountAssetDbKeyFactory.newKey(this.id, assetId));\n return accountAsset == null ? 0 : accountAsset.unconfirmedQuantityQNT;\n }\n \n public RewardRecipientAssignment getRewardRecipientAssignment() {\n \treturn getRewardRecipientAssignment(id);\n }\n \n public static RewardRecipientAssignment getRewardRecipientAssignment(Long id) {\n \treturn rewardRecipientAssignmentTable.get(rewardRecipientAssignmentDbKeyFactory.newKey(id));\n }\n \n public void setRewardRecipientAssignment(Long recipient) {\n \tsetRewardRecipientAssignment(id, recipient);\n }\n \n public static void setRewardRecipientAssignment(Long id, Long recipient) {\n \tint currentHeight = Nxt.getBlockchain().getLastBlock().getHeight();\n \tRewardRecipientAssignment assignment = getRewardRecipientAssignment(id);\n \tif(assignment == null) {\n \t\tassignment = new RewardRecipientAssignment(id, id, recipient, (int) (currentHeight + Constants.BURST_REWARD_RECIPIENT_ASSIGNMENT_WAIT_TIME));\n \t}\n \telse {\n \t\tassignment.setRecipient(recipient, (int) (currentHeight + Constants.BURST_REWARD_RECIPIENT_ASSIGNMENT_WAIT_TIME));\n \t}\n \trewardRecipientAssignmentTable.insert(assignment);\n }\n \n private static DbClause getAccountsWithRewardRecipientClause(final long id, final int height) {\n \treturn new DbClause(\" recip_id = ? AND from_height <= ? \") {\n \t\t@Override\n \t\tpublic int set(PreparedStatement pstmt, int index) throws SQLException {\n \t\t\tpstmt.setLong(index++, id);\n \t\t\tpstmt.setInt(index++, height);\n \t\t\treturn index;\n \t\t}\n \t};\n }\n \n public static DbIterator<RewardRecipientAssignment> getAccountsWithRewardRecipient(Long recipientId) {\n \treturn rewardRecipientAssignmentTable.getManyBy(getAccountsWithRewardRecipientClause(recipientId, Nxt.getBlockchain().getHeight() + 1), 0, -1);\n }\n\n public long getCurrentLesseeId() {\n return currentLesseeId;\n }\n\n public long getNextLesseeId() {\n return nextLesseeId;\n }\n\n public int getCurrentLeasingHeightFrom() {\n return currentLeasingHeightFrom;\n }\n\n public int getCurrentLeasingHeightTo() {\n return currentLeasingHeightTo;\n }\n\n public int getNextLeasingHeightFrom() {\n return nextLeasingHeightFrom;\n }\n\n public int getNextLeasingHeightTo() {\n return nextLeasingHeightTo;\n }\n\n void leaseEffectiveBalance(long lesseeId, short period) {\n Account lessee = Account.getAccount(lesseeId);\n if (lessee != null && lessee.getPublicKey() != null) {\n int height = Nxt.getBlockchain().getHeight();\n if (currentLeasingHeightFrom == Integer.MAX_VALUE) {\n currentLeasingHeightFrom = height + 1440;\n currentLeasingHeightTo = currentLeasingHeightFrom + period;\n currentLesseeId = lesseeId;\n nextLeasingHeightFrom = Integer.MAX_VALUE;\n accountTable.insert(this);\n leaseListeners.notify(\n new AccountLease(this.getId(), lesseeId, currentLeasingHeightFrom, currentLeasingHeightTo),\n Event.LEASE_SCHEDULED);\n } else {\n nextLeasingHeightFrom = height + 1440;\n if (nextLeasingHeightFrom < currentLeasingHeightTo) {\n nextLeasingHeightFrom = currentLeasingHeightTo;\n }\n nextLeasingHeightTo = nextLeasingHeightFrom + period;\n nextLesseeId = lesseeId;\n accountTable.insert(this);\n leaseListeners.notify(\n new AccountLease(this.getId(), lesseeId, nextLeasingHeightFrom, nextLeasingHeightTo),\n Event.LEASE_SCHEDULED);\n\n }\n }\n }\n\n // returns true iff:\n // this.publicKey is set to null (in which case this.publicKey also gets set to key)\n // or\n // this.publicKey is already set to an array equal to key\n boolean setOrVerify(byte[] key, int height) {\n if (this.publicKey == null) {\n \tif (Db.isInTransaction()) {\n \t\tthis.publicKey = key;\n this.keyHeight = -1;\n accountTable.insert(this);\n \t}\n return true;\n } else if (Arrays.equals(this.publicKey, key)) {\n return true;\n } else if (this.keyHeight == -1) {\n Logger.logMessage(\"DUPLICATE KEY!!!\");\n Logger.logMessage(\"Account key for \" + Convert.toUnsignedLong(id) + \" was already set to a different one at the same height \"\n + \", current height is \" + height + \", rejecting new key\");\n return false;\n } else if (this.keyHeight >= height) {\n Logger.logMessage(\"DUPLICATE KEY!!!\");\n if (Db.isInTransaction()) {\n \tLogger.logMessage(\"Changing key for account \" + Convert.toUnsignedLong(id) + \" at height \" + height\n + \", was previously set to a different one at height \" + keyHeight);\n this.publicKey = key;\n this.keyHeight = height;\n accountTable.insert(this);\n }\n return true;\n }\n Logger.logMessage(\"DUPLICATE KEY!!!\");\n Logger.logMessage(\"Invalid key for account \" + Convert.toUnsignedLong(id) + \" at height \" + height\n + \", was already set to a different one at height \" + keyHeight);\n return false;\n }\n\n void apply(byte[] key, int height) {\n if (! setOrVerify(key, this.creationHeight)) {\n throw new IllegalStateException(\"Public key mismatch\");\n }\n if (this.publicKey == null) {\n throw new IllegalStateException(\"Public key has not been set for account \" + Convert.toUnsignedLong(id)\n +\" at height \" + height + \", key height is \" + keyHeight);\n }\n if (this.keyHeight == -1 || this.keyHeight > height) {\n this.keyHeight = height;\n accountTable.insert(this);\n }\n }\n\n void addToAssetBalanceQNT(long assetId, long quantityQNT) {\n if (quantityQNT == 0) {\n return;\n }\n AccountAsset accountAsset;\n accountAsset = accountAssetTable.get(accountAssetDbKeyFactory.newKey(this.id, assetId));\n long assetBalance = accountAsset == null ? 0 : accountAsset.quantityQNT;\n assetBalance = Convert.safeAdd(assetBalance, quantityQNT);\n if (accountAsset == null) {\n accountAsset = new AccountAsset(this.id, assetId, assetBalance, 0);\n } else {\n accountAsset.quantityQNT = assetBalance;\n }\n accountAsset.save();\n listeners.notify(this, Event.ASSET_BALANCE);\n assetListeners.notify(accountAsset, Event.ASSET_BALANCE);\n }\n\n void addToUnconfirmedAssetBalanceQNT(long assetId, long quantityQNT) {\n if (quantityQNT == 0) {\n return;\n }\n AccountAsset accountAsset;\n accountAsset = accountAssetTable.get(accountAssetDbKeyFactory.newKey(this.id, assetId));\n long unconfirmedAssetBalance = accountAsset == null ? 0 : accountAsset.unconfirmedQuantityQNT;\n unconfirmedAssetBalance = Convert.safeAdd(unconfirmedAssetBalance, quantityQNT);\n if (accountAsset == null) {\n accountAsset = new AccountAsset(this.id, assetId, 0, unconfirmedAssetBalance);\n } else {\n accountAsset.unconfirmedQuantityQNT = unconfirmedAssetBalance;\n }\n accountAsset.save();\n listeners.notify(this, Event.UNCONFIRMED_ASSET_BALANCE);\n assetListeners.notify(accountAsset, Event.UNCONFIRMED_ASSET_BALANCE);\n }\n\n void addToAssetAndUnconfirmedAssetBalanceQNT(long assetId, long quantityQNT) {\n if (quantityQNT == 0) {\n return;\n }\n AccountAsset accountAsset;\n accountAsset = accountAssetTable.get(accountAssetDbKeyFactory.newKey(this.id, assetId));\n long assetBalance = accountAsset == null ? 0 : accountAsset.quantityQNT;\n assetBalance = Convert.safeAdd(assetBalance, quantityQNT);\n long unconfirmedAssetBalance = accountAsset == null ? 0 : accountAsset.unconfirmedQuantityQNT;\n unconfirmedAssetBalance = Convert.safeAdd(unconfirmedAssetBalance, quantityQNT);\n if (accountAsset == null) {\n accountAsset = new AccountAsset(this.id, assetId, assetBalance, unconfirmedAssetBalance);\n } else {\n accountAsset.quantityQNT = assetBalance;\n accountAsset.unconfirmedQuantityQNT = unconfirmedAssetBalance;\n }\n accountAsset.save();\n listeners.notify(this, Event.ASSET_BALANCE);\n listeners.notify(this, Event.UNCONFIRMED_ASSET_BALANCE);\n assetListeners.notify(accountAsset, Event.ASSET_BALANCE);\n assetListeners.notify(accountAsset, Event.UNCONFIRMED_ASSET_BALANCE);\n }\n\n void addToBalanceNQT(long amountNQT) {\n if (amountNQT == 0) {\n return;\n }\n this.balanceNQT = Convert.safeAdd(this.balanceNQT, amountNQT);\n addToGuaranteedBalanceNQT(amountNQT);\n checkBalance(this.id, this.balanceNQT, this.unconfirmedBalanceNQT);\n accountTable.insert(this);\n listeners.notify(this, Event.BALANCE);\n }\n\n void addToUnconfirmedBalanceNQT(long amountNQT) {\n if (amountNQT == 0) {\n return;\n }\n this.unconfirmedBalanceNQT = Convert.safeAdd(this.unconfirmedBalanceNQT, amountNQT);\n checkBalance(this.id, this.balanceNQT, this.unconfirmedBalanceNQT);\n accountTable.insert(this);\n listeners.notify(this, Event.UNCONFIRMED_BALANCE);\n }\n\n void addToBalanceAndUnconfirmedBalanceNQT(long amountNQT) {\n if (amountNQT == 0) {\n return;\n }\n this.balanceNQT = Convert.safeAdd(this.balanceNQT, amountNQT);\n this.unconfirmedBalanceNQT = Convert.safeAdd(this.unconfirmedBalanceNQT, amountNQT);\n addToGuaranteedBalanceNQT(amountNQT);\n checkBalance(this.id, this.balanceNQT, this.unconfirmedBalanceNQT);\n accountTable.insert(this);\n listeners.notify(this, Event.BALANCE);\n listeners.notify(this, Event.UNCONFIRMED_BALANCE);\n }\n\n void addToForgedBalanceNQT(long amountNQT) {\n if (amountNQT == 0) {\n return;\n }\n this.forgedBalanceNQT = Convert.safeAdd(this.forgedBalanceNQT, amountNQT);\n accountTable.insert(this);\n }\n\n private static void checkBalance(long accountId, long confirmed, long unconfirmed) {\n if (confirmed < 0) {\n throw new DoubleSpendingException(\"Negative balance or quantity for account \" + Convert.toUnsignedLong(accountId));\n }\n if (unconfirmed < 0) {\n throw new DoubleSpendingException(\"Negative unconfirmed balance or quantity for account \" + Convert.toUnsignedLong(accountId));\n }\n if (unconfirmed > confirmed) {\n throw new DoubleSpendingException(\"Unconfirmed exceeds confirmed balance or quantity for account \" + Convert.toUnsignedLong(accountId));\n }\n }\n\n private void addToGuaranteedBalanceNQT(long amountNQT) {\n if (amountNQT <= 0) {\n return;\n }\n int blockchainHeight = Nxt.getBlockchain().getHeight();\n try (Connection con = Db.getConnection();\n PreparedStatement pstmtSelect = con.prepareStatement(\"SELECT additions FROM account_guaranteed_balance \"\n + \"WHERE account_id = ? and height = ?\");\n PreparedStatement pstmtUpdate = con.prepareStatement(\"MERGE INTO account_guaranteed_balance (account_id, \"\n + \" additions, height) KEY (account_id, height) VALUES(?, ?, ?)\")) {\n pstmtSelect.setLong(1, this.id);\n pstmtSelect.setInt(2, blockchainHeight);\n try (ResultSet rs = pstmtSelect.executeQuery()) {\n long additions = amountNQT;\n if (rs.next()) {\n additions = Convert.safeAdd(additions, rs.getLong(\"additions\"));\n }\n pstmtUpdate.setLong(1, this.id);\n pstmtUpdate.setLong(2, additions);\n pstmtUpdate.setInt(3, blockchainHeight);\n pstmtUpdate.executeUpdate();\n }\n } catch (SQLException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n}", "public interface Attachment extends Appendix {\n\n TransactionType getTransactionType();\n\n abstract static class AbstractAttachment extends AbstractAppendix implements Attachment {\n\n private AbstractAttachment(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n }\n\n private AbstractAttachment(JSONObject attachmentData) {\n super(attachmentData);\n }\n\n private AbstractAttachment(int version) {\n super(version);\n }\n\n private AbstractAttachment() {}\n\n @Override\n final void validate(Transaction transaction) throws NxtException.ValidationException {\n getTransactionType().validateAttachment(transaction);\n }\n\n @Override\n final void apply(Transaction transaction, Account senderAccount, Account recipientAccount) {\n getTransactionType().apply(transaction, senderAccount, recipientAccount);\n }\n\n }\n\n abstract static class EmptyAttachment extends AbstractAttachment {\n\n private EmptyAttachment() {\n super(0);\n }\n\n @Override\n final int getMySize() {\n return 0;\n }\n\n @Override\n final void putMyBytes(ByteBuffer buffer) {\n }\n\n @Override\n final void putMyJSON(JSONObject json) {\n }\n\n @Override\n final boolean verifyVersion(byte transactionVersion) {\n return true;\n }\n\n }\n\n public final static EmptyAttachment ORDINARY_PAYMENT = new EmptyAttachment() {\n\n @Override\n String getAppendixName() {\n return \"OrdinaryPayment\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Payment.ORDINARY;\n }\n\n };\n\n // the message payload is in the Appendix\n public final static EmptyAttachment ARBITRARY_MESSAGE = new EmptyAttachment() {\n\n @Override\n String getAppendixName() {\n return \"ArbitraryMessage\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.ARBITRARY_MESSAGE;\n }\n\n };\n\n public static final EmptyAttachment AT_PAYMENT = new EmptyAttachment() {\n\n\t\t@Override\n\t\tpublic TransactionType getTransactionType() {\n\t\t\treturn TransactionType.AutomatedTransactions.AT_PAYMENT; \n\t\t}\n\n\t\t@Override\n\t\tString getAppendixName() {\n\t\t\treturn \"AT Payment\";\n\t\t}\n\t\t\n\t\t\n\t};\n \n public final static class MessagingAliasAssignment extends AbstractAttachment {\n\n private final String aliasName;\n private final String aliasURI;\n\n MessagingAliasAssignment(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n aliasName = Convert.readString(buffer, buffer.get(), Constants.MAX_ALIAS_LENGTH).trim();\n aliasURI = Convert.readString(buffer, buffer.getShort(), Constants.MAX_ALIAS_URI_LENGTH).trim();\n }\n\n MessagingAliasAssignment(JSONObject attachmentData) {\n super(attachmentData);\n aliasName = (Convert.nullToEmpty((String) attachmentData.get(\"alias\"))).trim();\n aliasURI = (Convert.nullToEmpty((String) attachmentData.get(\"uri\"))).trim();\n }\n\n public MessagingAliasAssignment(String aliasName, String aliasURI) {\n this.aliasName = aliasName.trim();\n this.aliasURI = aliasURI.trim();\n }\n\n @Override\n String getAppendixName() {\n return \"AliasAssignment\";\n }\n\n @Override\n int getMySize() {\n return 1 + Convert.toBytes(aliasName).length + 2 + Convert.toBytes(aliasURI).length;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] alias = Convert.toBytes(this.aliasName);\n byte[] uri = Convert.toBytes(this.aliasURI);\n buffer.put((byte)alias.length);\n buffer.put(alias);\n buffer.putShort((short) uri.length);\n buffer.put(uri);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"alias\", aliasName);\n attachment.put(\"uri\", aliasURI);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.ALIAS_ASSIGNMENT;\n }\n\n public String getAliasName() {\n return aliasName;\n }\n\n public String getAliasURI() {\n return aliasURI;\n }\n }\n\n public final static class MessagingAliasSell extends AbstractAttachment {\n\n private final String aliasName;\n private final long priceNQT;\n\n MessagingAliasSell(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.aliasName = Convert.readString(buffer, buffer.get(), Constants.MAX_ALIAS_LENGTH);\n this.priceNQT = buffer.getLong();\n }\n\n MessagingAliasSell(JSONObject attachmentData) {\n super(attachmentData);\n this.aliasName = Convert.nullToEmpty((String) attachmentData.get(\"alias\"));\n this.priceNQT = Convert.parseLong(attachmentData.get(\"priceNQT\"));\n }\n\n public MessagingAliasSell(String aliasName, long priceNQT) {\n this.aliasName = aliasName;\n this.priceNQT = priceNQT;\n }\n\n @Override\n String getAppendixName() {\n return \"AliasSell\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.ALIAS_SELL;\n }\n\n @Override\n int getMySize() {\n return 1 + Convert.toBytes(aliasName).length + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] aliasBytes = Convert.toBytes(aliasName);\n buffer.put((byte)aliasBytes.length);\n buffer.put(aliasBytes);\n buffer.putLong(priceNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"alias\", aliasName);\n attachment.put(\"priceNQT\", priceNQT);\n }\n\n public String getAliasName(){\n return aliasName;\n }\n\n public long getPriceNQT(){\n return priceNQT;\n }\n }\n\n public final static class MessagingAliasBuy extends AbstractAttachment {\n\n private final String aliasName;\n\n MessagingAliasBuy(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.aliasName = Convert.readString(buffer, buffer.get(), Constants.MAX_ALIAS_LENGTH);\n }\n\n MessagingAliasBuy(JSONObject attachmentData) {\n super(attachmentData);\n this.aliasName = Convert.nullToEmpty((String) attachmentData.get(\"alias\"));\n }\n\n public MessagingAliasBuy(String aliasName) {\n this.aliasName = aliasName;\n }\n\n @Override\n String getAppendixName() {\n return \"AliasBuy\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.ALIAS_BUY;\n }\n\n @Override\n int getMySize() {\n return 1 + Convert.toBytes(aliasName).length;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] aliasBytes = Convert.toBytes(aliasName);\n buffer.put((byte)aliasBytes.length);\n buffer.put(aliasBytes);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"alias\", aliasName);\n }\n\n public String getAliasName(){\n return aliasName;\n }\n }\n\n public final static class MessagingPollCreation extends AbstractAttachment {\n\n private final String pollName;\n private final String pollDescription;\n private final String[] pollOptions;\n private final byte minNumberOfOptions, maxNumberOfOptions;\n private final boolean optionsAreBinary;\n\n MessagingPollCreation(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.pollName = Convert.readString(buffer, buffer.getShort(), Constants.MAX_POLL_NAME_LENGTH);\n this.pollDescription = Convert.readString(buffer, buffer.getShort(), Constants.MAX_POLL_DESCRIPTION_LENGTH);\n int numberOfOptions = buffer.get();\n if (numberOfOptions > Constants.MAX_POLL_OPTION_COUNT) {\n throw new NxtException.NotValidException(\"Invalid number of poll options: \" + numberOfOptions);\n }\n this.pollOptions = new String[numberOfOptions];\n for (int i = 0; i < numberOfOptions; i++) {\n pollOptions[i] = Convert.readString(buffer, buffer.getShort(), Constants.MAX_POLL_OPTION_LENGTH);\n }\n this.minNumberOfOptions = buffer.get();\n this.maxNumberOfOptions = buffer.get();\n this.optionsAreBinary = buffer.get() != 0;\n }\n\n MessagingPollCreation(JSONObject attachmentData) {\n super(attachmentData);\n this.pollName = ((String) attachmentData.get(\"name\")).trim();\n this.pollDescription = ((String) attachmentData.get(\"description\")).trim();\n JSONArray options = (JSONArray) attachmentData.get(\"options\");\n this.pollOptions = new String[options.size()];\n for (int i = 0; i < pollOptions.length; i++) {\n pollOptions[i] = ((String) options.get(i)).trim();\n }\n this.minNumberOfOptions = ((Long) attachmentData.get(\"minNumberOfOptions\")).byteValue();\n this.maxNumberOfOptions = ((Long) attachmentData.get(\"maxNumberOfOptions\")).byteValue();\n this.optionsAreBinary = (Boolean) attachmentData.get(\"optionsAreBinary\");\n }\n\n public MessagingPollCreation(String pollName, String pollDescription, String[] pollOptions, byte minNumberOfOptions,\n byte maxNumberOfOptions, boolean optionsAreBinary) {\n this.pollName = pollName;\n this.pollDescription = pollDescription;\n this.pollOptions = pollOptions;\n this.minNumberOfOptions = minNumberOfOptions;\n this.maxNumberOfOptions = maxNumberOfOptions;\n this.optionsAreBinary = optionsAreBinary;\n }\n\n @Override\n String getAppendixName() {\n return \"PollCreation\";\n }\n\n @Override\n int getMySize() {\n int size = 2 + Convert.toBytes(pollName).length + 2 + Convert.toBytes(pollDescription).length + 1;\n for (String pollOption : pollOptions) {\n size += 2 + Convert.toBytes(pollOption).length;\n }\n size += 1 + 1 + 1;\n return size;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] name = Convert.toBytes(this.pollName);\n byte[] description = Convert.toBytes(this.pollDescription);\n byte[][] options = new byte[this.pollOptions.length][];\n for (int i = 0; i < this.pollOptions.length; i++) {\n options[i] = Convert.toBytes(this.pollOptions[i]);\n }\n buffer.putShort((short)name.length);\n buffer.put(name);\n buffer.putShort((short)description.length);\n buffer.put(description);\n buffer.put((byte) options.length);\n for (byte[] option : options) {\n buffer.putShort((short) option.length);\n buffer.put(option);\n }\n buffer.put(this.minNumberOfOptions);\n buffer.put(this.maxNumberOfOptions);\n buffer.put(this.optionsAreBinary ? (byte)1 : (byte)0);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"name\", this.pollName);\n attachment.put(\"description\", this.pollDescription);\n JSONArray options = new JSONArray();\n if (this.pollOptions != null) {\n Collections.addAll(options, this.pollOptions);\n }\n attachment.put(\"options\", options);\n attachment.put(\"minNumberOfOptions\", this.minNumberOfOptions);\n attachment.put(\"maxNumberOfOptions\", this.maxNumberOfOptions);\n attachment.put(\"optionsAreBinary\", this.optionsAreBinary);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.POLL_CREATION;\n }\n\n public String getPollName() { return pollName; }\n\n public String getPollDescription() { return pollDescription; }\n\n public String[] getPollOptions() { return pollOptions; }\n\n public byte getMinNumberOfOptions() { return minNumberOfOptions; }\n\n public byte getMaxNumberOfOptions() { return maxNumberOfOptions; }\n\n public boolean isOptionsAreBinary() { return optionsAreBinary; }\n\n }\n\n public final static class MessagingVoteCasting extends AbstractAttachment {\n\n private final long pollId;\n private final byte[] pollVote;\n\n MessagingVoteCasting(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.pollId = buffer.getLong();\n int numberOfOptions = buffer.get();\n if (numberOfOptions > Constants.MAX_POLL_OPTION_COUNT) {\n throw new NxtException.NotValidException(\"Error parsing vote casting parameters\");\n }\n this.pollVote = new byte[numberOfOptions];\n buffer.get(pollVote);\n }\n\n MessagingVoteCasting(JSONObject attachmentData) {\n super(attachmentData);\n this.pollId = Convert.parseUnsignedLong((String)attachmentData.get(\"pollId\"));\n JSONArray vote = (JSONArray)attachmentData.get(\"vote\");\n this.pollVote = new byte[vote.size()];\n for (int i = 0; i < pollVote.length; i++) {\n pollVote[i] = ((Long) vote.get(i)).byteValue();\n }\n }\n\n public MessagingVoteCasting(long pollId, byte[] pollVote) {\n this.pollId = pollId;\n this.pollVote = pollVote;\n }\n\n @Override\n String getAppendixName() {\n return \"VoteCasting\";\n }\n\n @Override\n int getMySize() {\n return 8 + 1 + this.pollVote.length;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(this.pollId);\n buffer.put((byte) this.pollVote.length);\n buffer.put(this.pollVote);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"pollId\", Convert.toUnsignedLong(this.pollId));\n JSONArray vote = new JSONArray();\n if (this.pollVote != null) {\n for (byte aPollVote : this.pollVote) {\n vote.add(aPollVote);\n }\n }\n attachment.put(\"vote\", vote);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.VOTE_CASTING;\n }\n\n public long getPollId() { return pollId; }\n\n public byte[] getPollVote() { return pollVote; }\n\n }\n\n public final static class MessagingHubAnnouncement extends AbstractAttachment {\n\n private final long minFeePerByteNQT;\n private final String[] uris;\n\n MessagingHubAnnouncement(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.minFeePerByteNQT = buffer.getLong();\n int numberOfUris = buffer.get();\n if (numberOfUris > Constants.MAX_HUB_ANNOUNCEMENT_URIS) {\n throw new NxtException.NotValidException(\"Invalid number of URIs: \" + numberOfUris);\n }\n this.uris = new String[numberOfUris];\n for (int i = 0; i < uris.length; i++) {\n uris[i] = Convert.readString(buffer, buffer.getShort(), Constants.MAX_HUB_ANNOUNCEMENT_URI_LENGTH);\n }\n }\n\n MessagingHubAnnouncement(JSONObject attachmentData) throws NxtException.NotValidException {\n super(attachmentData);\n this.minFeePerByteNQT = (Long) attachmentData.get(\"minFeePerByte\");\n try {\n JSONArray urisData = (JSONArray) attachmentData.get(\"uris\");\n this.uris = new String[urisData.size()];\n for (int i = 0; i < uris.length; i++) {\n uris[i] = (String) urisData.get(i);\n }\n } catch (RuntimeException e) {\n throw new NxtException.NotValidException(\"Error parsing hub terminal announcement parameters\", e);\n }\n }\n\n public MessagingHubAnnouncement(long minFeePerByteNQT, String[] uris) {\n this.minFeePerByteNQT = minFeePerByteNQT;\n this.uris = uris;\n }\n\n @Override\n String getAppendixName() {\n return \"HubAnnouncement\";\n }\n\n @Override\n int getMySize() {\n int size = 8 + 1;\n for (String uri : uris) {\n size += 2 + Convert.toBytes(uri).length;\n }\n return size;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(minFeePerByteNQT);\n buffer.put((byte) uris.length);\n for (String uri : uris) {\n byte[] uriBytes = Convert.toBytes(uri);\n buffer.putShort((short)uriBytes.length);\n buffer.put(uriBytes);\n }\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"minFeePerByteNQT\", minFeePerByteNQT);\n JSONArray uris = new JSONArray();\n Collections.addAll(uris, this.uris);\n attachment.put(\"uris\", uris);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.HUB_ANNOUNCEMENT;\n }\n\n public long getMinFeePerByteNQT() {\n return minFeePerByteNQT;\n }\n\n public String[] getUris() {\n return uris;\n }\n\n }\n\n public final static class MessagingAccountInfo extends AbstractAttachment {\n\n private final String name;\n private final String description;\n\n MessagingAccountInfo(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.name = Convert.readString(buffer, buffer.get(), Constants.MAX_ACCOUNT_NAME_LENGTH);\n this.description = Convert.readString(buffer, buffer.getShort(), Constants.MAX_ACCOUNT_DESCRIPTION_LENGTH);\n }\n\n MessagingAccountInfo(JSONObject attachmentData) {\n super(attachmentData);\n this.name = Convert.nullToEmpty((String) attachmentData.get(\"name\"));\n this.description = Convert.nullToEmpty((String) attachmentData.get(\"description\"));\n }\n\n public MessagingAccountInfo(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n @Override\n String getAppendixName() {\n return \"AccountInfo\";\n }\n\n @Override\n int getMySize() {\n return 1 + Convert.toBytes(name).length + 2 + Convert.toBytes(description).length;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] name = Convert.toBytes(this.name);\n byte[] description = Convert.toBytes(this.description);\n buffer.put((byte)name.length);\n buffer.put(name);\n buffer.putShort((short) description.length);\n buffer.put(description);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"name\", name);\n attachment.put(\"description\", description);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.Messaging.ACCOUNT_INFO;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n }\n\n public final static class ColoredCoinsAssetIssuance extends AbstractAttachment {\n\n private final String name;\n private final String description;\n private final long quantityQNT;\n private final byte decimals;\n\n ColoredCoinsAssetIssuance(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.name = Convert.readString(buffer, buffer.get(), Constants.MAX_ASSET_NAME_LENGTH);\n this.description = Convert.readString(buffer, buffer.getShort(), Constants.MAX_ASSET_DESCRIPTION_LENGTH);\n this.quantityQNT = buffer.getLong();\n this.decimals = buffer.get();\n }\n\n ColoredCoinsAssetIssuance(JSONObject attachmentData) {\n super(attachmentData);\n this.name = (String) attachmentData.get(\"name\");\n this.description = Convert.nullToEmpty((String) attachmentData.get(\"description\"));\n this.quantityQNT = Convert.parseLong(attachmentData.get(\"quantityQNT\"));\n this.decimals = ((Long) attachmentData.get(\"decimals\")).byteValue();\n }\n\n public ColoredCoinsAssetIssuance(String name, String description, long quantityQNT, byte decimals) {\n this.name = name;\n this.description = Convert.nullToEmpty(description);\n this.quantityQNT = quantityQNT;\n this.decimals = decimals;\n }\n\n @Override\n String getAppendixName() {\n return \"AssetIssuance\";\n }\n\n @Override\n int getMySize() {\n return 1 + Convert.toBytes(name).length + 2 + Convert.toBytes(description).length + 8 + 1;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] name = Convert.toBytes(this.name);\n byte[] description = Convert.toBytes(this.description);\n buffer.put((byte)name.length);\n buffer.put(name);\n buffer.putShort((short) description.length);\n buffer.put(description);\n buffer.putLong(quantityQNT);\n buffer.put(decimals);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"name\", name);\n attachment.put(\"description\", description);\n attachment.put(\"quantityQNT\", quantityQNT);\n attachment.put(\"decimals\", decimals);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.ASSET_ISSUANCE;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public long getQuantityQNT() {\n return quantityQNT;\n }\n\n public byte getDecimals() {\n return decimals;\n }\n }\n\n public final static class ColoredCoinsAssetTransfer extends AbstractAttachment {\n\n private final long assetId;\n private final long quantityQNT;\n private final String comment;\n\n ColoredCoinsAssetTransfer(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.assetId = buffer.getLong();\n this.quantityQNT = buffer.getLong();\n this.comment = getVersion() == 0 ? Convert.readString(buffer, buffer.getShort(), Constants.MAX_ASSET_TRANSFER_COMMENT_LENGTH) : null;\n }\n\n ColoredCoinsAssetTransfer(JSONObject attachmentData) {\n super(attachmentData);\n this.assetId = Convert.parseUnsignedLong((String) attachmentData.get(\"asset\"));\n this.quantityQNT = Convert.parseLong(attachmentData.get(\"quantityQNT\"));\n this.comment = getVersion() == 0 ? Convert.nullToEmpty((String) attachmentData.get(\"comment\")) : null;\n }\n\n public ColoredCoinsAssetTransfer(long assetId, long quantityQNT) {\n this.assetId = assetId;\n this.quantityQNT = quantityQNT;\n this.comment = null;\n }\n\n @Override\n String getAppendixName() {\n return \"AssetTransfer\";\n }\n\n @Override\n int getMySize() {\n return 8 + 8 + (getVersion() == 0 ? (2 + Convert.toBytes(comment).length) : 0);\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(assetId);\n buffer.putLong(quantityQNT);\n if (getVersion() == 0 && comment != null) {\n byte[] commentBytes = Convert.toBytes(this.comment);\n buffer.putShort((short) commentBytes.length);\n buffer.put(commentBytes);\n }\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"asset\", Convert.toUnsignedLong(assetId));\n attachment.put(\"quantityQNT\", quantityQNT);\n if (getVersion() == 0) {\n attachment.put(\"comment\", comment);\n }\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.ASSET_TRANSFER;\n }\n\n public long getAssetId() {\n return assetId;\n }\n\n public long getQuantityQNT() {\n return quantityQNT;\n }\n\n public String getComment() {\n return comment;\n }\n\n }\n\n abstract static class ColoredCoinsOrderPlacement extends AbstractAttachment {\n\n private final long assetId;\n private final long quantityQNT;\n private final long priceNQT;\n\n private ColoredCoinsOrderPlacement(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.assetId = buffer.getLong();\n this.quantityQNT = buffer.getLong();\n this.priceNQT = buffer.getLong();\n }\n\n private ColoredCoinsOrderPlacement(JSONObject attachmentData) {\n super(attachmentData);\n this.assetId = Convert.parseUnsignedLong((String) attachmentData.get(\"asset\"));\n this.quantityQNT = Convert.parseLong(attachmentData.get(\"quantityQNT\"));\n this.priceNQT = Convert.parseLong(attachmentData.get(\"priceNQT\"));\n }\n\n private ColoredCoinsOrderPlacement(long assetId, long quantityQNT, long priceNQT) {\n this.assetId = assetId;\n this.quantityQNT = quantityQNT;\n this.priceNQT = priceNQT;\n }\n\n @Override\n int getMySize() {\n return 8 + 8 + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(assetId);\n buffer.putLong(quantityQNT);\n buffer.putLong(priceNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"asset\", Convert.toUnsignedLong(assetId));\n attachment.put(\"quantityQNT\", quantityQNT);\n attachment.put(\"priceNQT\", priceNQT);\n }\n\n public long getAssetId() {\n return assetId;\n }\n\n public long getQuantityQNT() {\n return quantityQNT;\n }\n\n public long getPriceNQT() {\n return priceNQT;\n }\n }\n\n public final static class ColoredCoinsAskOrderPlacement extends ColoredCoinsOrderPlacement {\n\n ColoredCoinsAskOrderPlacement(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n }\n\n ColoredCoinsAskOrderPlacement(JSONObject attachmentData) {\n super(attachmentData);\n }\n\n public ColoredCoinsAskOrderPlacement(long assetId, long quantityQNT, long priceNQT) {\n super(assetId, quantityQNT, priceNQT);\n }\n\n @Override\n String getAppendixName() {\n return \"AskOrderPlacement\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.ASK_ORDER_PLACEMENT;\n }\n\n }\n\n public final static class ColoredCoinsBidOrderPlacement extends ColoredCoinsOrderPlacement {\n\n ColoredCoinsBidOrderPlacement(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n }\n\n ColoredCoinsBidOrderPlacement(JSONObject attachmentData) {\n super(attachmentData);\n }\n\n public ColoredCoinsBidOrderPlacement(long assetId, long quantityQNT, long priceNQT) {\n super(assetId, quantityQNT, priceNQT);\n }\n\n @Override\n String getAppendixName() {\n return \"BidOrderPlacement\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.BID_ORDER_PLACEMENT;\n }\n\n }\n\n abstract static class ColoredCoinsOrderCancellation extends AbstractAttachment {\n\n private final long orderId;\n\n private ColoredCoinsOrderCancellation(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.orderId = buffer.getLong();\n }\n\n private ColoredCoinsOrderCancellation(JSONObject attachmentData) {\n super(attachmentData);\n this.orderId = Convert.parseUnsignedLong((String) attachmentData.get(\"order\"));\n }\n\n private ColoredCoinsOrderCancellation(long orderId) {\n this.orderId = orderId;\n }\n\n @Override\n int getMySize() {\n return 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(orderId);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"order\", Convert.toUnsignedLong(orderId));\n }\n\n public long getOrderId() {\n return orderId;\n }\n }\n\n public final static class ColoredCoinsAskOrderCancellation extends ColoredCoinsOrderCancellation {\n\n ColoredCoinsAskOrderCancellation(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n }\n\n ColoredCoinsAskOrderCancellation(JSONObject attachmentData) {\n super(attachmentData);\n }\n\n public ColoredCoinsAskOrderCancellation(long orderId) {\n super(orderId);\n }\n\n @Override\n String getAppendixName() {\n return \"AskOrderCancellation\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.ASK_ORDER_CANCELLATION;\n }\n\n }\n\n public final static class ColoredCoinsBidOrderCancellation extends ColoredCoinsOrderCancellation {\n\n ColoredCoinsBidOrderCancellation(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n }\n\n ColoredCoinsBidOrderCancellation(JSONObject attachmentData) {\n super(attachmentData);\n }\n\n public ColoredCoinsBidOrderCancellation(long orderId) {\n super(orderId);\n }\n\n @Override\n String getAppendixName() {\n return \"BidOrderCancellation\";\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.ColoredCoins.BID_ORDER_CANCELLATION;\n }\n\n }\n\n public final static class DigitalGoodsListing extends AbstractAttachment {\n\n private final String name;\n private final String description;\n private final String tags;\n private final int quantity;\n private final long priceNQT;\n\n DigitalGoodsListing(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.name = Convert.readString(buffer, buffer.getShort(), Constants.MAX_DGS_LISTING_NAME_LENGTH);\n this.description = Convert.readString(buffer, buffer.getShort(), Constants.MAX_DGS_LISTING_DESCRIPTION_LENGTH);\n this.tags = Convert.readString(buffer, buffer.getShort(), Constants.MAX_DGS_LISTING_TAGS_LENGTH);\n this.quantity = buffer.getInt();\n this.priceNQT = buffer.getLong();\n }\n\n DigitalGoodsListing(JSONObject attachmentData) {\n super(attachmentData);\n this.name = (String) attachmentData.get(\"name\");\n this.description = (String) attachmentData.get(\"description\");\n this.tags = (String) attachmentData.get(\"tags\");\n this.quantity = ((Long) attachmentData.get(\"quantity\")).intValue();\n this.priceNQT = Convert.parseLong(attachmentData.get(\"priceNQT\"));\n }\n\n public DigitalGoodsListing(String name, String description, String tags, int quantity, long priceNQT) {\n this.name = name;\n this.description = description;\n this.tags = tags;\n this.quantity = quantity;\n this.priceNQT = priceNQT;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsListing\";\n }\n\n @Override\n int getMySize() {\n return 2 + Convert.toBytes(name).length + 2 + Convert.toBytes(description).length + 2\n + Convert.toBytes(tags).length + 4 + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n byte[] nameBytes = Convert.toBytes(name);\n buffer.putShort((short) nameBytes.length);\n buffer.put(nameBytes);\n byte[] descriptionBytes = Convert.toBytes(description);\n buffer.putShort((short) descriptionBytes.length);\n buffer.put(descriptionBytes);\n byte[] tagsBytes = Convert.toBytes(tags);\n buffer.putShort((short) tagsBytes.length);\n buffer.put(tagsBytes);\n buffer.putInt(quantity);\n buffer.putLong(priceNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"name\", name);\n attachment.put(\"description\", description);\n attachment.put(\"tags\", tags);\n attachment.put(\"quantity\", quantity);\n attachment.put(\"priceNQT\", priceNQT);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.LISTING;\n }\n\n public String getName() { return name; }\n\n public String getDescription() { return description; }\n\n public String getTags() { return tags; }\n\n public int getQuantity() { return quantity; }\n\n public long getPriceNQT() { return priceNQT; }\n\n }\n\n public final static class DigitalGoodsDelisting extends AbstractAttachment {\n\n private final long goodsId;\n\n DigitalGoodsDelisting(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.goodsId = buffer.getLong();\n }\n\n DigitalGoodsDelisting(JSONObject attachmentData) {\n super(attachmentData);\n this.goodsId = Convert.parseUnsignedLong((String)attachmentData.get(\"goods\"));\n }\n\n public DigitalGoodsDelisting(long goodsId) {\n this.goodsId = goodsId;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsDelisting\";\n }\n\n @Override\n int getMySize() {\n return 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(goodsId);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"goods\", Convert.toUnsignedLong(goodsId));\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.DELISTING;\n }\n\n public long getGoodsId() { return goodsId; }\n\n }\n\n public final static class DigitalGoodsPriceChange extends AbstractAttachment {\n\n private final long goodsId;\n private final long priceNQT;\n\n DigitalGoodsPriceChange(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.goodsId = buffer.getLong();\n this.priceNQT = buffer.getLong();\n }\n\n DigitalGoodsPriceChange(JSONObject attachmentData) {\n super(attachmentData);\n this.goodsId = Convert.parseUnsignedLong((String)attachmentData.get(\"goods\"));\n this.priceNQT = Convert.parseLong(attachmentData.get(\"priceNQT\"));\n }\n\n public DigitalGoodsPriceChange(long goodsId, long priceNQT) {\n this.goodsId = goodsId;\n this.priceNQT = priceNQT;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsPriceChange\";\n }\n\n @Override\n int getMySize() {\n return 8 + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(goodsId);\n buffer.putLong(priceNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"goods\", Convert.toUnsignedLong(goodsId));\n attachment.put(\"priceNQT\", priceNQT);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.PRICE_CHANGE;\n }\n\n public long getGoodsId() { return goodsId; }\n\n public long getPriceNQT() { return priceNQT; }\n\n }\n\n public final static class DigitalGoodsQuantityChange extends AbstractAttachment {\n\n private final long goodsId;\n private final int deltaQuantity;\n\n DigitalGoodsQuantityChange(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.goodsId = buffer.getLong();\n this.deltaQuantity = buffer.getInt();\n }\n\n DigitalGoodsQuantityChange(JSONObject attachmentData) {\n super(attachmentData);\n this.goodsId = Convert.parseUnsignedLong((String)attachmentData.get(\"goods\"));\n this.deltaQuantity = ((Long)attachmentData.get(\"deltaQuantity\")).intValue();\n }\n\n public DigitalGoodsQuantityChange(long goodsId, int deltaQuantity) {\n this.goodsId = goodsId;\n this.deltaQuantity = deltaQuantity;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsQuantityChange\";\n }\n\n @Override\n int getMySize() {\n return 8 + 4;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(goodsId);\n buffer.putInt(deltaQuantity);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"goods\", Convert.toUnsignedLong(goodsId));\n attachment.put(\"deltaQuantity\", deltaQuantity);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.QUANTITY_CHANGE;\n }\n\n public long getGoodsId() { return goodsId; }\n\n public int getDeltaQuantity() { return deltaQuantity; }\n\n }\n\n public final static class DigitalGoodsPurchase extends AbstractAttachment {\n\n private final long goodsId;\n private final int quantity;\n private final long priceNQT;\n private final int deliveryDeadlineTimestamp;\n\n DigitalGoodsPurchase(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.goodsId = buffer.getLong();\n this.quantity = buffer.getInt();\n this.priceNQT = buffer.getLong();\n this.deliveryDeadlineTimestamp = buffer.getInt();\n }\n\n DigitalGoodsPurchase(JSONObject attachmentData) {\n super(attachmentData);\n this.goodsId = Convert.parseUnsignedLong((String)attachmentData.get(\"goods\"));\n this.quantity = ((Long)attachmentData.get(\"quantity\")).intValue();\n this.priceNQT = Convert.parseLong(attachmentData.get(\"priceNQT\"));\n this.deliveryDeadlineTimestamp = ((Long)attachmentData.get(\"deliveryDeadlineTimestamp\")).intValue();\n }\n\n public DigitalGoodsPurchase(long goodsId, int quantity, long priceNQT, int deliveryDeadlineTimestamp) {\n this.goodsId = goodsId;\n this.quantity = quantity;\n this.priceNQT = priceNQT;\n this.deliveryDeadlineTimestamp = deliveryDeadlineTimestamp;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsPurchase\";\n }\n\n @Override\n int getMySize() {\n return 8 + 4 + 8 + 4;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(goodsId);\n buffer.putInt(quantity);\n buffer.putLong(priceNQT);\n buffer.putInt(deliveryDeadlineTimestamp);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"goods\", Convert.toUnsignedLong(goodsId));\n attachment.put(\"quantity\", quantity);\n attachment.put(\"priceNQT\", priceNQT);\n attachment.put(\"deliveryDeadlineTimestamp\", deliveryDeadlineTimestamp);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.PURCHASE;\n }\n\n public long getGoodsId() { return goodsId; }\n\n public int getQuantity() { return quantity; }\n\n public long getPriceNQT() { return priceNQT; }\n\n public int getDeliveryDeadlineTimestamp() { return deliveryDeadlineTimestamp; }\n\n }\n\n public final static class DigitalGoodsDelivery extends AbstractAttachment {\n\n private final long purchaseId;\n private final EncryptedData goods;\n private final long discountNQT;\n private final boolean goodsIsText;\n\n DigitalGoodsDelivery(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n super(buffer, transactionVersion);\n this.purchaseId = buffer.getLong();\n int length = buffer.getInt();\n goodsIsText = length < 0;\n if (length < 0) {\n length &= Integer.MAX_VALUE;\n }\n this.goods = EncryptedData.readEncryptedData(buffer, length, Constants.MAX_DGS_GOODS_LENGTH);\n this.discountNQT = buffer.getLong();\n }\n\n DigitalGoodsDelivery(JSONObject attachmentData) {\n super(attachmentData);\n this.purchaseId = Convert.parseUnsignedLong((String)attachmentData.get(\"purchase\"));\n this.goods = new EncryptedData(Convert.parseHexString((String)attachmentData.get(\"goodsData\")),\n Convert.parseHexString((String)attachmentData.get(\"goodsNonce\")));\n this.discountNQT = Convert.parseLong(attachmentData.get(\"discountNQT\"));\n this.goodsIsText = Boolean.TRUE.equals(attachmentData.get(\"goodsIsText\"));\n }\n\n public DigitalGoodsDelivery(long purchaseId, EncryptedData goods, boolean goodsIsText, long discountNQT) {\n this.purchaseId = purchaseId;\n this.goods = goods;\n this.discountNQT = discountNQT;\n this.goodsIsText = goodsIsText;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsDelivery\";\n }\n\n @Override\n int getMySize() {\n return 8 + 4 + goods.getSize() + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(purchaseId);\n buffer.putInt(goodsIsText ? goods.getData().length | Integer.MIN_VALUE : goods.getData().length);\n buffer.put(goods.getData());\n buffer.put(goods.getNonce());\n buffer.putLong(discountNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"purchase\", Convert.toUnsignedLong(purchaseId));\n attachment.put(\"goodsData\", Convert.toHexString(goods.getData()));\n attachment.put(\"goodsNonce\", Convert.toHexString(goods.getNonce()));\n attachment.put(\"discountNQT\", discountNQT);\n attachment.put(\"goodsIsText\", goodsIsText);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.DELIVERY;\n }\n\n public long getPurchaseId() { return purchaseId; }\n\n public EncryptedData getGoods() { return goods; }\n\n public long getDiscountNQT() { return discountNQT; }\n\n public boolean goodsIsText() {\n return goodsIsText;\n }\n\n }\n\n public final static class DigitalGoodsFeedback extends AbstractAttachment {\n\n private final long purchaseId;\n\n DigitalGoodsFeedback(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.purchaseId = buffer.getLong();\n }\n\n DigitalGoodsFeedback(JSONObject attachmentData) {\n super(attachmentData);\n this.purchaseId = Convert.parseUnsignedLong((String)attachmentData.get(\"purchase\"));\n }\n\n public DigitalGoodsFeedback(long purchaseId) {\n this.purchaseId = purchaseId;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsFeedback\";\n }\n\n @Override\n int getMySize() {\n return 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(purchaseId);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"purchase\", Convert.toUnsignedLong(purchaseId));\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.FEEDBACK;\n }\n\n public long getPurchaseId() { return purchaseId; }\n\n }\n\n public final static class DigitalGoodsRefund extends AbstractAttachment {\n\n private final long purchaseId;\n private final long refundNQT;\n\n DigitalGoodsRefund(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.purchaseId = buffer.getLong();\n this.refundNQT = buffer.getLong();\n }\n\n DigitalGoodsRefund(JSONObject attachmentData) {\n super(attachmentData);\n this.purchaseId = Convert.parseUnsignedLong((String)attachmentData.get(\"purchase\"));\n this.refundNQT = Convert.parseLong(attachmentData.get(\"refundNQT\"));\n }\n\n public DigitalGoodsRefund(long purchaseId, long refundNQT) {\n this.purchaseId = purchaseId;\n this.refundNQT = refundNQT;\n }\n\n @Override\n String getAppendixName() {\n return \"DigitalGoodsRefund\";\n }\n\n @Override\n int getMySize() {\n return 8 + 8;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putLong(purchaseId);\n buffer.putLong(refundNQT);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"purchase\", Convert.toUnsignedLong(purchaseId));\n attachment.put(\"refundNQT\", refundNQT);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.DigitalGoods.REFUND;\n }\n\n public long getPurchaseId() { return purchaseId; }\n\n public long getRefundNQT() { return refundNQT; }\n\n }\n\n public final static class AccountControlEffectiveBalanceLeasing extends AbstractAttachment {\n\n private final short period;\n\n AccountControlEffectiveBalanceLeasing(ByteBuffer buffer, byte transactionVersion) {\n super(buffer, transactionVersion);\n this.period = buffer.getShort();\n }\n\n AccountControlEffectiveBalanceLeasing(JSONObject attachmentData) {\n super(attachmentData);\n this.period = ((Long) attachmentData.get(\"period\")).shortValue();\n }\n\n public AccountControlEffectiveBalanceLeasing(short period) {\n this.period = period;\n }\n\n @Override\n String getAppendixName() {\n return \"EffectiveBalanceLeasing\";\n }\n\n @Override\n int getMySize() {\n return 2;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n buffer.putShort(period);\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n attachment.put(\"period\", period);\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.AccountControl.EFFECTIVE_BALANCE_LEASING;\n }\n\n public short getPeriod() {\n return period;\n }\n }\n \n public final static class BurstMiningRewardRecipientAssignment extends AbstractAttachment {\n \t\n \tBurstMiningRewardRecipientAssignment(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t}\n \t\n \tBurstMiningRewardRecipientAssignment(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t}\n \t\n \tpublic BurstMiningRewardRecipientAssignment() {\n \t}\n \t\n \t@Override\n String getAppendixName() {\n return \"RewardRecipientAssignment\";\n }\n\n @Override\n int getMySize() {\n return 0;\n }\n\n @Override\n void putMyBytes(ByteBuffer buffer) {\n }\n\n @Override\n void putMyJSON(JSONObject attachment) {\n }\n\n @Override\n public TransactionType getTransactionType() {\n return TransactionType.BurstMining.REWARD_RECIPIENT_ASSIGNMENT;\n }\n }\n \n public final static class AdvancedPaymentEscrowCreation extends AbstractAttachment {\n \t\n \tprivate final Long amountNQT;\n \tprivate final byte requiredSigners;\n \tprivate final SortedSet<Long> signers = new TreeSet<>();\n \tprivate final int deadline;\n \tprivate final Escrow.DecisionType deadlineAction;\n \t\n \tAdvancedPaymentEscrowCreation(ByteBuffer buffer, byte transactionVersion) throws NxtException.NotValidException {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.amountNQT = buffer.getLong();\n \t\tthis.deadline = buffer.getInt();\n \t\tthis.deadlineAction = Escrow.byteToDecision(buffer.get());\n \t\tthis.requiredSigners = buffer.get();\n \t\tbyte totalSigners = buffer.get();\n \t\tif(totalSigners > 10 || totalSigners <= 0) {\n \t\t\tthrow new NxtException.NotValidException(\"Invalid number of signers listed on create escrow transaction\");\n \t\t}\n \t\tfor(int i = 0; i < totalSigners; i++) {\n \t\t\tif(!this.signers.add(buffer.getLong())) {\n \t\t\t\tthrow new NxtException.NotValidException(\"Duplicate signer on escrow creation\");\n \t\t\t}\n \t\t}\n \t}\n \t\n \tAdvancedPaymentEscrowCreation(JSONObject attachmentData) throws NxtException.NotValidException {\n \t\tsuper(attachmentData);\n \t\tthis.amountNQT = Convert.parseUnsignedLong((String)attachmentData.get(\"amountNQT\"));\n \t\tthis.deadline = ((Long)attachmentData.get(\"deadline\")).intValue();\n \t\tthis.deadlineAction = Escrow.stringToDecision((String)attachmentData.get(\"deadlineAction\"));\n \t\tthis.requiredSigners = ((Long)attachmentData.get(\"requiredSigners\")).byteValue();\n \t\tint totalSigners = ((JSONArray)attachmentData.get(\"signers\")).size();\n \t\tif(totalSigners > 10 || totalSigners <= 0) {\n \t\t\tthrow new NxtException.NotValidException(\"Invalid number of signers listed on create escrow transaction\");\n \t\t}\n \t\t//this.signers.addAll((JSONArray)attachmentData.get(\"signers\"));\n \t\tJSONArray signersJson = (JSONArray)attachmentData.get(\"signers\");\n \t\tfor(int i = 0; i < signersJson.size(); i++) {\n \t\t\tthis.signers.add(Convert.parseUnsignedLong((String)signersJson.get(i)));\n \t\t}\n \t\tif(this.signers.size() != ((JSONArray)attachmentData.get(\"signers\")).size()) {\n \t\t\tthrow new NxtException.NotValidException(\"Duplicate signer on escrow creation\");\n \t\t}\n \t}\n \t\n \tpublic AdvancedPaymentEscrowCreation(Long amountNQT, int deadline, Escrow.DecisionType deadlineAction,\n \t\t\t\t\t\t\t\t\t\t\t int requiredSigners, Collection<Long> signers) throws NxtException.NotValidException {\n \t\tthis.amountNQT = amountNQT;\n \t\tthis.deadline = deadline;\n \t\tthis.deadlineAction = deadlineAction;\n \t\tthis.requiredSigners = (byte)requiredSigners;\n \t\tif(signers.size() > 10 || signers.size() == 0) {\n \t\t\tthrow new NxtException.NotValidException(\"Invalid number of signers listed on create escrow transaction\");\n \t\t}\n \t\tthis.signers.addAll(signers);\n \t\tif(this.signers.size() != signers.size()) {\n \t\t\tthrow new NxtException.NotValidException(\"Duplicate signer on escrow creation\");\n \t\t}\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"EscrowCreation\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\tint size = 8 + 4 + 1 + 1 + 1;\n \t\tsize += (signers.size() * 8);\n \t\treturn size;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putLong(this.amountNQT);\n \t\tbuffer.putInt(this.deadline);\n \t\tbuffer.put(Escrow.decisionToByte(this.deadlineAction));\n \t\tbuffer.put(this.requiredSigners);\n \t\tbyte totalSigners = (byte) this.signers.size();\n \t\tbuffer.put(totalSigners);\n \t\tfor(Long id : this.signers) {\n \t\t\tbuffer.putLong(id);\n \t\t}\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"amountNQT\", Convert.toUnsignedLong(this.amountNQT));\n \t\tattachment.put(\"deadline\", this.deadline);\n \t\tattachment.put(\"deadlineAction\", Escrow.decisionToString(this.deadlineAction));\n \t\tattachment.put(\"requiredSigners\", (int)this.requiredSigners);\n \t\tJSONArray ids = new JSONArray();\n \t\t//ids.addAll(this.signers);\n \t\tfor(Long signer : this.signers) {\n \t\t\tids.add(Convert.toUnsignedLong(signer));\n \t\t}\n \t\tattachment.put(\"signers\", ids);\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.ESCROW_CREATION;\n \t}\n \t\n \tpublic Long getAmountNQT() { return amountNQT; }\n \t\n \tpublic int getDeadline() { return deadline; }\n \t\n \tpublic Escrow.DecisionType getDeadlineAction() { return deadlineAction; }\n \t\n \tpublic int getRequiredSigners() { return (int)requiredSigners; }\n \t\n \tpublic Collection<Long> getSigners() { return Collections.unmodifiableCollection(signers); }\n \t\n \tpublic int getTotalSigners() { return signers.size(); }\n }\n \n public final static class AdvancedPaymentEscrowSign extends AbstractAttachment {\n \t\n \tprivate final Long escrowId;\n \tprivate final Escrow.DecisionType decision;\n \t\n \tAdvancedPaymentEscrowSign(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.escrowId = buffer.getLong();\n \t\tthis.decision = Escrow.byteToDecision(buffer.get());\n \t}\n \t\n \tAdvancedPaymentEscrowSign(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t\tthis.escrowId = Convert.parseUnsignedLong((String)attachmentData.get(\"escrowId\"));\n \t\tthis.decision = Escrow.stringToDecision((String)attachmentData.get(\"decision\"));\n \t}\n \t\n \tpublic AdvancedPaymentEscrowSign(Long escrowId, Escrow.DecisionType decision) {\n \t\tthis.escrowId = escrowId;\n \t\tthis.decision = decision;\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"EscrowSign\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\treturn 8 + 1;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putLong(this.escrowId);\n \t\tbuffer.put(Escrow.decisionToByte(this.decision));\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"escrowId\", Convert.toUnsignedLong(this.escrowId));\n \t\tattachment.put(\"decision\", Escrow.decisionToString(this.decision));\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.ESCROW_SIGN;\n \t}\n \t\n \tpublic Long getEscrowId() { return this.escrowId; }\n \t\n \tpublic Escrow.DecisionType getDecision() { return this.decision; }\n }\n \n public final static class AdvancedPaymentEscrowResult extends AbstractAttachment {\n \t\n \tprivate final Long escrowId;\n \tprivate final Escrow.DecisionType decision;\n \t\n \tAdvancedPaymentEscrowResult(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.escrowId = buffer.getLong();\n \t\tthis.decision = Escrow.byteToDecision(buffer.get());\n \t}\n \t\n \tAdvancedPaymentEscrowResult(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t\tthis.escrowId = Convert.parseUnsignedLong((String) attachmentData.get(\"escrowId\"));\n \t\tthis.decision = Escrow.stringToDecision((String)attachmentData.get(\"decision\"));\n \t}\n \t\n \tpublic AdvancedPaymentEscrowResult(Long escrowId, Escrow.DecisionType decision) {\n \t\tthis.escrowId = escrowId;\n \t\tthis.decision = decision;\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"EscrowResult\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\treturn 8 + 1;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putLong(this.escrowId);\n \t\tbuffer.put(Escrow.decisionToByte(this.decision));\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"escrowId\", Convert.toUnsignedLong(this.escrowId));\n \t\tattachment.put(\"decision\", Escrow.decisionToString(this.decision));\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.ESCROW_RESULT;\n \t}\n }\n \n public final static class AdvancedPaymentSubscriptionSubscribe extends AbstractAttachment {\n \t\n \tprivate final Integer frequency;\n \t\n \tAdvancedPaymentSubscriptionSubscribe(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.frequency = buffer.getInt();\n \t}\n \t\n \tAdvancedPaymentSubscriptionSubscribe(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t\tthis.frequency = ((Long)attachmentData.get(\"frequency\")).intValue();\n \t}\n \t\n \tpublic AdvancedPaymentSubscriptionSubscribe(int frequency) {\n \t\tthis.frequency = frequency;\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"SubscriptionSubscribe\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\treturn 4;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putInt(this.frequency);\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"frequency\", this.frequency);\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.SUBSCRIPTION_SUBSCRIBE;\n \t}\n \t\n \tpublic Integer getFrequency() { return this.frequency; }\n }\n \n public final static class AdvancedPaymentSubscriptionCancel extends AbstractAttachment {\n \t\n \tprivate final Long subscriptionId;\n \t\n \tAdvancedPaymentSubscriptionCancel(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.subscriptionId = buffer.getLong();\n \t}\n \t\n \tAdvancedPaymentSubscriptionCancel(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t\tthis.subscriptionId = Convert.parseUnsignedLong((String)attachmentData.get(\"subscriptionId\"));\n \t}\n \t\n \tpublic AdvancedPaymentSubscriptionCancel(Long subscriptionId) {\n \t\tthis.subscriptionId = subscriptionId;\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"SubscriptionCancel\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\treturn 8;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putLong(subscriptionId);\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"subscriptionId\", Convert.toUnsignedLong(this.subscriptionId));\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.SUBSCRIPTION_CANCEL;\n \t}\n \t\n \tpublic Long getSubscriptionId() { return this.subscriptionId; }\n }\n \n public final static class AdvancedPaymentSubscriptionPayment extends AbstractAttachment {\n \t\n \tprivate final Long subscriptionId;\n \t\n \tAdvancedPaymentSubscriptionPayment(ByteBuffer buffer, byte transactionVersion) {\n \t\tsuper(buffer, transactionVersion);\n \t\tthis.subscriptionId = buffer.getLong();\n \t}\n \t\n \tAdvancedPaymentSubscriptionPayment(JSONObject attachmentData) {\n \t\tsuper(attachmentData);\n \t\tthis.subscriptionId = Convert.parseUnsignedLong((String) attachmentData.get(\"subscriptionId\"));\n \t}\n \t\n \tpublic AdvancedPaymentSubscriptionPayment(Long subscriptionId) {\n \t\tthis.subscriptionId = subscriptionId;\n \t}\n \t\n \t@Override\n \tString getAppendixName() {\n \t\treturn \"SubscriptionPayment\";\n \t}\n \t\n \t@Override\n \tint getMySize() {\n \t\treturn 8;\n \t}\n \t\n \t@Override\n \tvoid putMyBytes(ByteBuffer buffer) {\n \t\tbuffer.putLong(this.subscriptionId);\n \t}\n \t\n \t@Override\n \tvoid putMyJSON(JSONObject attachment) {\n \t\tattachment.put(\"subscriptionId\", Convert.toUnsignedLong(this.subscriptionId));\n \t}\n \t\n \t@Override\n \tpublic TransactionType getTransactionType() {\n \t\treturn TransactionType.AdvancedPayment.SUBSCRIPTION_PAYMENT;\n \t}\n }\n\n public final static class AutomatedTransactionsCreation extends AbstractAttachment{\n \t\n private final String name; \n private final String description;\n private final byte[] creationBytes;\n \t\n \t\n\t\tAutomatedTransactionsCreation(ByteBuffer buffer,\n\t\t\t\tbyte transactionVersion) throws NxtException.NotValidException {\n\t\t\tsuper(buffer, transactionVersion);\n\t\t\t\n\t\t\tthis.name = Convert.readString( buffer , buffer.get() , Constants.MAX_AUTOMATED_TRANSACTION_NAME_LENGTH );\n\t\t\tthis.description = Convert.readString( buffer , buffer.getShort() , Constants.MAX_AUTOMATED_TRANSACTION_DESCRIPTION_LENGTH );\n\t\t\t\n\t\t\tbyte[] dst = new byte[ buffer.capacity() - buffer.position() ];\n\t\t\tbuffer.get( dst , 0 , buffer.capacity() - buffer.position() );\n\t\t\tthis.creationBytes = dst;\n\t\t\t\n\t\t}\n\n\t\tAutomatedTransactionsCreation(JSONObject attachmentData) throws NxtException.NotValidException {\n\t\t\tsuper(attachmentData);\n\t\t\t\n\t\t\tthis.name = ( String ) attachmentData.get( \"name\" );\n\t\t\tthis.description = ( String ) attachmentData.get( \"description\" );\n\t\t\t\n\t\t\tthis.creationBytes = Convert.parseHexString( (String) attachmentData.get( \"creationBytes\" ) );\n\t\t\t\n\t\t}\n\t\t\t\n\t\tpublic AutomatedTransactionsCreation( String name, String description , byte[] creationBytes ) throws NotValidException\n\t\t{\n\t\t\tthis.name = name;\n\t\t\tthis.description = description;\n\t\t\tthis.creationBytes = creationBytes;\n\t\t\t\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic TransactionType getTransactionType() {\n\t\t\treturn TransactionType.AutomatedTransactions.AUTOMATED_TRANSACTION_CREATION;\n\t\t}\n\n\t\t@Override\n\t\tString getAppendixName() {\n return \"AutomatedTransactionsCreation\";\n }\n\t\t@Override\n\t\tint getMySize() {\n return 1 + Convert.toBytes( name ).length + 2 + Convert.toBytes( description ).length + creationBytes.length;\n\t\t}\n\n\t\t@Override\n\t\tvoid putMyBytes(ByteBuffer buffer) { \n byte[] nameBytes = Convert.toBytes( name ); \n buffer.put( ( byte ) nameBytes.length );\n buffer.put( nameBytes );\n byte[] descriptionBytes = Convert.toBytes( description );\n buffer.putShort( ( short ) descriptionBytes.length );\n buffer.put( descriptionBytes );\n \n buffer.put( creationBytes ); \n\t\t}\n\n\t\t@Override\n\t\tvoid putMyJSON(JSONObject attachment) { \n\t\t\tattachment.put(\"name\", name);\n attachment.put(\"description\", description);\n attachment.put(\"creationBytes\", Convert.toHexString( creationBytes ) ); \n\t\t}\n\n public String getName() { return name; }\n\n public String getDescription() { return description; }\n\n\t\tpublic byte[] getCreationBytes() {\n\t\t\treturn creationBytes;\n\t\t}\n \n \t\n }\n \n /*public final static class AutomatedTransactionsPayment extends AbstractAttachment{\n\n \tAutomatedTransactionsPayment(ByteBuffer buffer,\n\t\t\t\tbyte transactionVersion) throws NxtException.NotValidException {\n\t\t\tsuper(buffer, transactionVersion);\n\t\t}\n\n\t\tAutomatedTransactionsPayment(JSONObject attachmentData) throws NxtException.NotValidException {\n\t\t\tsuper(attachmentData);\n\t\t}\n\t\t\n\t\tpublic AutomatedTransactionsPayment() {\n\t\t}\n \t\n \t@Override\n\t\tpublic TransactionType getTransactionType() {\n\t\t\treturn TransactionType.AutomatedTransactions.AT_PAYMENT;\n\t\t}\n\n\t\t@Override\n\t\tString getAppendixName() {\n\t\t\treturn \"AutomatedTransactionsPayment\";\n\t\t}\n\n\t\t@Override\n\t\tint getMySize() {\n\t\t\treturn 0;\n\t\t}\n\n\t\t@Override\n\t\tvoid putMyBytes(ByteBuffer buffer) {\n\t\t}\n\n\t\t@Override\n\t\tvoid putMyJSON(JSONObject json) {\n\t\t}\n \t\n }*/\n \n\n}", "public final class Constants {\n\n\tpublic static int BURST_DIFF_ADJUST_CHANGE_BLOCK = 2700;\n\t\n\tpublic static long BURST_REWARD_RECIPIENT_ASSIGNMENT_START_BLOCK = 6500;\n public static long BURST_REWARD_RECIPIENT_ASSIGNMENT_WAIT_TIME = 4;\n \n public static long BURST_ESCROW_START_BLOCK = Integer.MAX_VALUE;\n public static long BURST_SUBSCRIPTION_START_BLOCK = Integer.MAX_VALUE;\n public static int BURST_SUBSCRIPTION_MIN_FREQ = 3600;\n public static int BURST_SUBSCRIPTION_MAX_FREQ = 31536000;\n \n\tpublic static final int BLOCK_HEADER_LENGTH = 232;\n public static final int MAX_NUMBER_OF_TRANSACTIONS = 255;\n public static final int MAX_PAYLOAD_LENGTH = MAX_NUMBER_OF_TRANSACTIONS * 176;\n public static final long MAX_BALANCE_NXT = 2158812800L;\n public static final long ONE_NXT = 100000000;\n public static final long MAX_BALANCE_NQT = MAX_BALANCE_NXT * ONE_NXT;\n public static final long INITIAL_BASE_TARGET = 18325193796L;\n public static final long MAX_BASE_TARGET = 18325193796L;\n public static final int MAX_ROLLBACK = Nxt.getIntProperty(\"nxt.maxRollback\");\n static {\n if (MAX_ROLLBACK < 1440) {\n throw new RuntimeException(\"nxt.maxRollback must be at least 1440\");\n }\n }\n\n public static final int MAX_ALIAS_URI_LENGTH = 1000;\n public static final int MAX_ALIAS_LENGTH = 100;\n\n public static final int MAX_ARBITRARY_MESSAGE_LENGTH = 1000;\n public static final int MAX_ENCRYPTED_MESSAGE_LENGTH = 1000;\n\n public static final int MAX_ACCOUNT_NAME_LENGTH = 100;\n public static final int MAX_ACCOUNT_DESCRIPTION_LENGTH = 1000;\n\n public static final long MAX_ASSET_QUANTITY_QNT = 1000000000L * 100000000L;\n public static final long ASSET_ISSUANCE_FEE_NQT = 1000 * ONE_NXT;\n public static final int MIN_ASSET_NAME_LENGTH = 3;\n public static final int MAX_ASSET_NAME_LENGTH = 10;\n public static final int MAX_ASSET_DESCRIPTION_LENGTH = 1000;\n public static final int MAX_ASSET_TRANSFER_COMMENT_LENGTH = 1000;\n\n public static final int MAX_POLL_NAME_LENGTH = 100;\n public static final int MAX_POLL_DESCRIPTION_LENGTH = 1000;\n public static final int MAX_POLL_OPTION_LENGTH = 100;\n public static final int MAX_POLL_OPTION_COUNT = 100;\n\n public static final int MAX_DGS_LISTING_QUANTITY = 1000000000;\n public static final int MAX_DGS_LISTING_NAME_LENGTH = 100;\n public static final int MAX_DGS_LISTING_DESCRIPTION_LENGTH = 1000;\n public static final int MAX_DGS_LISTING_TAGS_LENGTH = 100;\n public static final int MAX_DGS_GOODS_LENGTH = 10240;\n\n public static final int MAX_HUB_ANNOUNCEMENT_URIS = 100;\n public static final int MAX_HUB_ANNOUNCEMENT_URI_LENGTH = 1000;\n public static final long MIN_HUB_EFFECTIVE_BALANCE = 100000;\n\n public static final boolean isTestnet = Nxt.getBooleanProperty(\"nxt.isTestnet\");\n public static final boolean isOffline = Nxt.getBooleanProperty(\"nxt.isOffline\");\n\n public static final int ALIAS_SYSTEM_BLOCK = 0;\n public static final int TRANSPARENT_FORGING_BLOCK = 0;\n public static final int ARBITRARY_MESSAGES_BLOCK = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_2 = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_3 = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_4 = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_5 = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_6 = 0;\n public static final int TRANSPARENT_FORGING_BLOCK_7 = Integer.MAX_VALUE;\n public static final int TRANSPARENT_FORGING_BLOCK_8 = 0;\n public static final int NQT_BLOCK = 0;\n public static final int FRACTIONAL_BLOCK = 0;\n public static final int ASSET_EXCHANGE_BLOCK = 0;\n public static final int REFERENCED_TRANSACTION_FULL_HASH_BLOCK = 0;\n public static final int REFERENCED_TRANSACTION_FULL_HASH_BLOCK_TIMESTAMP = 0;\n public static final int VOTING_SYSTEM_BLOCK = isTestnet ? 0 : Integer.MAX_VALUE;\n public static final int DIGITAL_GOODS_STORE_BLOCK = 11800;\n public static final int PUBLIC_KEY_ANNOUNCEMENT_BLOCK = Integer.MAX_VALUE;\n\n public static final int MAX_AUTOMATED_TRANSACTION_NAME_LENGTH = 30;\n\tpublic static final int MAX_AUTOMATED_TRANSACTION_DESCRIPTION_LENGTH = 1000 ;\n\tprotected static final int AUTOMATED_TRANSACTION_BLOCK = 49200;\n\tpublic static final int AT_BLOCK_PAYLOAD = MAX_PAYLOAD_LENGTH/2;\n\tpublic static final int AT_FIX_BLOCK_2 = 67000;\n\tpublic static final int AT_FIX_BLOCK_3 = 92000;\n \n static final long UNCONFIRMED_POOL_DEPOSIT_NQT = (isTestnet ? 50 : 100) * ONE_NXT;\n\n public static final long EPOCH_BEGINNING;\n static {\n Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n calendar.set(Calendar.YEAR, 2014);\n calendar.set(Calendar.MONTH, Calendar.AUGUST);\n calendar.set(Calendar.DAY_OF_MONTH, 11);\n calendar.set(Calendar.HOUR_OF_DAY, 2);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.SECOND, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n EPOCH_BEGINNING = calendar.getTimeInMillis();\n }\n\n public static final String ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\n public static final int EC_RULE_TERMINATOR = 2400; /* cfb: This constant defines a straight edge when \"longest chain\"\n rule is outweighed by \"economic majority\" rule; the terminator\n is set as number of seconds before the current time. */\n\n public static final int EC_BLOCK_DISTANCE_LIMIT = 60;\n public static final int EC_CHANGE_BLOCK_1 = 67000;\n\t\n\n private Constants() {} // never\n\n}", "public class Escrow {\n\t\n\tpublic static enum DecisionType {\n\t\tUNDECIDED,\n\t\tRELEASE,\n\t\tREFUND,\n\t\tSPLIT;\n\t}\n\t\n\tpublic static String decisionToString(DecisionType decision) {\n\t\tswitch(decision) {\n\t\tcase UNDECIDED:\n\t\t\treturn \"undecided\";\n\t\tcase RELEASE:\n\t\t\treturn \"release\";\n\t\tcase REFUND:\n\t\t\treturn \"refund\";\n\t\tcase SPLIT:\n\t\t\treturn \"split\";\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static DecisionType stringToDecision(String decision) {\n\t\tswitch(decision) {\n\t\tcase \"undecided\":\n\t\t\treturn DecisionType.UNDECIDED;\n\t\tcase \"release\":\n\t\t\treturn DecisionType.RELEASE;\n\t\tcase \"refund\":\n\t\t\treturn DecisionType.REFUND;\n\t\tcase \"split\":\n\t\t\treturn DecisionType.SPLIT;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static Byte decisionToByte(DecisionType decision) {\n\t\tswitch(decision) {\n\t\tcase UNDECIDED:\n\t\t\treturn 0;\n\t\tcase RELEASE:\n\t\t\treturn 1;\n\t\tcase REFUND:\n\t\t\treturn 2;\n\t\tcase SPLIT:\n\t\t\treturn 3;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static DecisionType byteToDecision(Byte decision) {\n\t\tswitch(decision) {\n\t\tcase 0:\n\t\t\treturn DecisionType.UNDECIDED;\n\t\tcase 1:\n\t\t\treturn DecisionType.RELEASE;\n\t\tcase 2:\n\t\t\treturn DecisionType.REFUND;\n\t\tcase 3:\n\t\t\treturn DecisionType.SPLIT;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static boolean isEnabled() {\n\t\tif(Nxt.getBlockchain().getLastBlock().getHeight() >= Constants.BURST_ESCROW_START_BLOCK) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tAlias escrowEnabled = Alias.getAlias(\"featureescrow\");\n\t\tif(escrowEnabled != null && escrowEnabled.getAliasURI().equals(\"enabled\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static class Decision {\n\t\t\n\t\tprivate final Long escrowId;\n\t\tprivate final Long accountId;\n\t\tprivate final DbKey dbKey;\n\t\tprivate DecisionType decision;\n\t\t\n\t\tprivate Decision(Long escrowId, Long accountId, DecisionType decision) {\n\t\t\tthis.escrowId = escrowId;\n\t\t\tthis.accountId = accountId;\n\t\t\tthis.dbKey = decisionDbKeyFactory.newKey(this.escrowId, this.accountId);\n\t\t\tthis.decision = decision;\n\t\t}\n\t\t\n\t\tprivate Decision(ResultSet rs) throws SQLException {\n\t\t\tthis.escrowId = rs.getLong(\"escrow_id\");\n\t\t\tthis.accountId = rs.getLong(\"account_id\");\n\t\t\tthis.dbKey = decisionDbKeyFactory.newKey(this.escrowId, this.accountId);\n\t\t\tthis.decision = byteToDecision((byte)rs.getInt(\"decision\"));\n\t\t}\n\t\t\n\t\tprivate void save(Connection con) throws SQLException {\n\t\t\ttry (PreparedStatement pstmt = con.prepareStatement(\"MERGE INTO escrow_decision (escrow_id, \"\n\t\t\t\t\t+ \"account_id, decision, height, latest) KEY (escrow_id, account_id, height) VALUES (?, ?, ?, ?, TRUE)\")) {\n\t\t\t\tint i = 0;\n\t\t\t\tpstmt.setLong(++i, this.escrowId);\n\t\t\t\tpstmt.setLong(++i, this.accountId);\n\t\t\t\tpstmt.setInt(++i, decisionToByte(this.decision));\n\t\t\t\tpstmt.setInt(++i, Nxt.getBlockchain().getHeight());\n\t\t\t\tpstmt.executeUpdate();\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic Long getEscrowId() {\n\t\t\treturn this.escrowId;\n\t\t}\n\t\t\n\t\tpublic Long getAccountId() {\n\t\t\treturn this.accountId;\n\t\t}\n\t\t\n\t\tpublic DecisionType getDecision() {\n\t\t\treturn this.decision;\n\t\t}\n\t\t\n\t\tpublic void setDecision(DecisionType decision) {\n\t\t\tthis.decision = decision;\n\t\t}\n\t}\n\t\n\tprivate static final DbKey.LongKeyFactory<Escrow> escrowDbKeyFactory = new DbKey.LongKeyFactory<Escrow>(\"id\") {\n\t\t@Override\n\t\tpublic DbKey newKey(Escrow escrow) {\n\t\t\treturn escrow.dbKey;\n\t\t}\n\t};\n\t\n\tprivate static final VersionedEntityDbTable<Escrow> escrowTable = new VersionedEntityDbTable<Escrow>(\"escrow\", escrowDbKeyFactory) {\n\t\t@Override\n\t\tprotected Escrow load(Connection con, ResultSet rs) throws SQLException {\n\t\t\treturn new Escrow(rs);\n\t\t}\n\t\t@Override\n\t\tprotected void save(Connection con, Escrow escrow) throws SQLException {\n\t\t\tescrow.save(con);\n\t\t}\n\t};\n\t\n\tprivate static final DbKey.LinkKeyFactory<Decision> decisionDbKeyFactory = new DbKey.LinkKeyFactory<Decision>(\"escrow_id\", \"account_id\") {\n\t\t@Override\n\t\tpublic DbKey newKey(Decision decision) {\n\t\t\treturn decision.dbKey;\n\t\t}\n\t};\n\t\n\tprivate static final VersionedEntityDbTable<Decision> decisionTable = new VersionedEntityDbTable<Decision>(\"escrow_decision\", decisionDbKeyFactory) {\n\t\t@Override\n\t\tprotected Decision load(Connection con, ResultSet rs) throws SQLException {\n\t\t\treturn new Decision(rs);\n\t\t}\n\t\t@Override\n\t\tprotected void save(Connection con, Decision decision) throws SQLException {\n\t\t\tdecision.save(con);\n\t\t}\n\t};\n\t\n\tprivate static final ConcurrentSkipListSet<Long> updatedEscrowIds = new ConcurrentSkipListSet<>();\n\tprivate static final List<TransactionImpl> resultTransactions = new ArrayList<>();\n\t\n\tpublic static DbIterator<Escrow> getAllEscrowTransactions() {\n\t\treturn escrowTable.getAll(0, -1);\n\t}\n\t\n\tprivate static DbClause getEscrowParticipentClause(final long accountId) {\n\t\treturn new DbClause(\" (sender_id = ? OR recipient_id = ?) \") {\n\t\t\t@Override\n\t public int set(PreparedStatement pstmt, int index) throws SQLException {\n\t pstmt.setLong(index++, accountId);\n\t pstmt.setLong(index++, accountId);\n\t return index;\n\t }\n\t\t};\n\t}\n\t\n\tpublic static Collection<Escrow> getEscrowTransactionsByParticipent(Long accountId) {\n\t\tList<Escrow> filtered = new ArrayList<>();\n\t\tDbIterator<Decision> it = decisionTable.getManyBy(new DbClause.LongClause(\"account_id\", accountId), 0, -1);\n\t\twhile(it.hasNext()) {\n\t\t\tDecision decision = it.next();\n\t\t\tEscrow escrow = escrowTable.get(escrowDbKeyFactory.newKey(decision.escrowId));\n\t\t\tif(escrow != null) {\n\t\t\t\tfiltered.add(escrow);\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\t\n\tpublic static Escrow getEscrowTransaction(Long id) {\n\t\treturn escrowTable.get(escrowDbKeyFactory.newKey(id));\n\t}\n\t\n\tpublic static void addEscrowTransaction(Account sender,\n\t\t\t\t\t\t\t\t\t\t\tAccount recipient,\n\t\t\t\t\t\t\t\t\t\t\tLong id,\n\t\t\t\t\t\t\t\t\t\t\tLong amountNQT,\n\t\t\t\t\t\t\t\t\t\t\tint requiredSigners,\n\t\t\t\t\t\t\t\t\t\t\tCollection<Long> signers,\n\t\t\t\t\t\t\t\t\t\t\tint deadline,\n\t\t\t\t\t\t\t\t\t\t\tDecisionType deadlineAction) {\n\t\tEscrow newEscrowTransaction = new Escrow(sender,\n\t\t\t\t\t\t\t\t\t\t\t\t recipient,\n\t\t\t\t\t\t\t\t\t\t\t\t id,\n\t\t\t\t\t\t\t\t\t\t\t\t amountNQT,\n\t\t\t\t\t\t\t\t\t\t\t\t requiredSigners,\n\t\t\t\t\t\t\t\t\t\t\t\t deadline,\n\t\t\t\t\t\t\t\t\t\t\t\t deadlineAction);\n\t\tescrowTable.insert(newEscrowTransaction);\n\t\t\n\t\tDecision senderDecision = new Decision(id, sender.getId(), DecisionType.UNDECIDED);\n\t\tdecisionTable.insert(senderDecision);\n\t\tDecision recipientDecision = new Decision(id, recipient.getId(), DecisionType.UNDECIDED);\n\t\tdecisionTable.insert(recipientDecision);\n\t\tfor(Long signer : signers) {\n\t\t\tDecision decision = new Decision(id, signer, DecisionType.UNDECIDED);\n\t\t\tdecisionTable.insert(decision);\n\t\t}\n\t}\n\t\n\tpublic static void removeEscrowTransaction(Long id) {\n\t\tEscrow escrow = escrowTable.get(escrowDbKeyFactory.newKey(id));\n\t\tif(escrow == null) {\n\t\t\treturn;\n\t\t}\n\t\tDbIterator<Decision> decisionIt = escrow.getDecisions();\n\t\t\n\t\tList<Decision> decisions = new ArrayList<>();\n\t\twhile(decisionIt.hasNext()) {\n\t\t\tDecision decision = decisionIt.next();\n\t\t\tdecisions.add(decision);\n\t\t}\n\t\t\n\t\tfor(Decision decision : decisions) {\n\t\t\tdecisionTable.delete(decision);\n\t\t}\n\t\tescrowTable.delete(escrow);\n\t}\n\t\n\tprivate static DbClause getUpdateOnBlockClause(final int timestamp) {\n\t\treturn new DbClause(\" deadline < ? \") {\n\t\t\t@Override\n\t\t\tpublic int set(PreparedStatement pstmt, int index) throws SQLException {\n\t\t\t\tpstmt.setInt(index++, timestamp);\n\t\t\t\treturn index;\n\t\t\t}\n\t\t};\n\t}\n\t\n\tpublic static void updateOnBlock(Block block) {\n\t\tresultTransactions.clear();\n\t\t\n\t\tDbIterator<Escrow> deadlineEscrows = escrowTable.getManyBy(getUpdateOnBlockClause(block.getTimestamp()), 0, -1);\n\t\tfor(Escrow escrow : deadlineEscrows) {\n\t\t\tupdatedEscrowIds.add(escrow.getId());\n\t\t}\n\t\t\n\t\tif(updatedEscrowIds.size() > 0) {\n\t\t\tfor(Long escrowId : updatedEscrowIds) {\n\t\t\t\tEscrow escrow = escrowTable.get(escrowDbKeyFactory.newKey(escrowId));\n\t\t\t\tDecisionType result = escrow.checkComplete();\n\t\t\t\tif(result != DecisionType.UNDECIDED || escrow.getDeadline() < block.getTimestamp()) {\n\t\t\t\t\tif(result == DecisionType.UNDECIDED) {\n\t\t\t\t\t\tresult = escrow.getDeadlineAction();\n\t\t\t\t\t}\n\t\t\t\t\tescrow.doPayout(result, block);\n\t\t\t\t\t\n\t\t\t\t\tremoveEscrowTransaction(escrowId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(resultTransactions.size() > 0) {\n\t\t\t\ttry (Connection con = Db.getConnection()) {\n\t\t\t\t\tTransactionDb.saveTransactions(con, resultTransactions);\n\t\t\t\t}\n\t\t\t\tcatch(SQLException e) {\n\t\t\t\t\tthrow new RuntimeException(e.toString(), e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tupdatedEscrowIds.clear();\n\t\t}\n\t}\n\t\n\tprivate final Long senderId;\n\tprivate final Long recipientId;\n\tprivate final Long id;\n\tprivate final DbKey dbKey;\n\tprivate final Long amountNQT;\n\tprivate final int requiredSigners;\n\tprivate final int deadline;\n\tprivate final DecisionType deadlineAction;\n\t\n\tprivate Escrow(Account sender,\n\t\t\t\t Account recipient,\n\t\t\t\t Long id,\n\t\t\t\t Long amountNQT,\n\t\t\t\t int requiredSigners,\n\t\t\t\t int deadline,\n\t\t\t\t DecisionType deadlineAction) {\n\t\tthis.senderId = sender.getId();\n\t\tthis.recipientId = recipient.getId();\n\t\tthis.id = id;\n\t\tthis.dbKey = escrowDbKeyFactory.newKey(this.id);\n\t\tthis.amountNQT = amountNQT;\n\t\tthis.requiredSigners = requiredSigners;\n\t\tthis.deadline = deadline;\n\t\tthis.deadlineAction = deadlineAction;\n\t}\n\t\n\tprivate Escrow(ResultSet rs) throws SQLException {\n\t\tthis.id = rs.getLong(\"id\");\n\t\tthis.dbKey = escrowDbKeyFactory.newKey(this.id);\n\t\tthis.senderId = rs.getLong(\"sender_id\");\n\t\tthis.recipientId = rs.getLong(\"recipient_id\");\n\t\tthis.amountNQT = rs.getLong(\"amount\");\n\t\tthis.requiredSigners = rs.getInt(\"required_signers\");\n\t\tthis.deadline = rs.getInt(\"deadline\");\n\t\tthis.deadlineAction = byteToDecision((byte)rs.getInt(\"deadline_action\"));\n\t}\n\t\n\tprivate void save(Connection con) throws SQLException {\n\t\ttry (PreparedStatement pstmt = con.prepareStatement(\"MERGE INTO escrow (id, sender_id, \"\n\t\t\t\t+ \"recipient_id, amount, required_signers, deadline, deadline_action, height, latest) \"\n\t\t\t\t+ \"KEY (id, height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE)\")) {\n\t\t\tint i = 0;\n\t\t\tpstmt.setLong(++i, this.id);\n\t\t\tpstmt.setLong(++i, this.senderId);\n\t\t\tpstmt.setLong(++i, this.recipientId);\n\t\t\tpstmt.setLong(++i, this.amountNQT);\n\t\t\tpstmt.setInt(++i, this.requiredSigners);\n\t\t\tpstmt.setInt(++i, this.deadline);\n\t\t\tpstmt.setInt(++i, decisionToByte(this.deadlineAction));\n\t\t\tpstmt.setInt(++i, Nxt.getBlockchain().getHeight());\n\t\t\tpstmt.executeUpdate();\n\t\t}\n\t}\n\t\n\tpublic Long getSenderId() {\n\t\treturn senderId;\n\t}\n\t\n\tpublic Long getAmountNQT() {\n\t\treturn amountNQT;\n\t}\n\t\n\tpublic Long getRecipientId() {\n\t\treturn recipientId;\n\t}\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\t\n\tpublic int getRequiredSigners() {\n\t\treturn requiredSigners;\n\t}\n\t\n\tpublic DbIterator<Decision> getDecisions() {\n\t\treturn decisionTable.getManyBy(new DbClause.LongClause(\"escrow_id\", id), 0, -1);\n\t}\n\t\n\tpublic int getDeadline() {\n\t\treturn deadline;\n\t}\n\t\n\tpublic DecisionType getDeadlineAction() {\n\t\treturn deadlineAction;\n\t}\n\t\n\tpublic boolean isIdSigner(Long id) {\n\t\treturn decisionTable.get(decisionDbKeyFactory.newKey(this.id, id)) != null;\n\t}\n\t\n\tpublic Decision getIdDecision(Long id) {\n\t\treturn decisionTable.get(decisionDbKeyFactory.newKey(this.id, id));\n\t}\n\t\n\tpublic synchronized void sign(Long id, DecisionType decision) {\n\t\tif(id.equals(senderId) && decision != DecisionType.RELEASE) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(id.equals(recipientId) && decision != DecisionType.REFUND) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tDecision decisionChange = decisionTable.get(decisionDbKeyFactory.newKey(this.id, id));\n\t\tif(decisionChange == null) {\n\t\t\treturn;\n\t\t}\n\t\tdecisionChange.setDecision(decision);\n\t\t\n\t\tdecisionTable.insert(decisionChange);\n\t\t\n\t\tif(!updatedEscrowIds.contains(this.id)) {\n\t\t\tupdatedEscrowIds.add(this.id);\n\t\t}\n\t}\n\t\n\tprivate DecisionType checkComplete() {\n\t\tDecision senderDecision = decisionTable.get(decisionDbKeyFactory.newKey(id, senderId));\n\t\tif(senderDecision.getDecision() == DecisionType.RELEASE) {\n\t\t\treturn DecisionType.RELEASE;\n\t\t}\n\t\tDecision recipientDecision = decisionTable.get(decisionDbKeyFactory.newKey(id, recipientId));\n\t\tif(recipientDecision.getDecision() == DecisionType.REFUND) {\n\t\t\treturn DecisionType.REFUND;\n\t\t}\n\t\t\n\t\tint countRelease = 0;\n\t\tint countRefund = 0;\n\t\tint countSplit = 0;\n\t\t\n\t\tDbIterator<Decision> decisions = decisionTable.getManyBy(new DbClause.LongClause(\"escrow_id\", id), 0, -1);\n\t\twhile(decisions.hasNext()) {\n\t\t\tDecision decision = decisions.next();\n\t\t\tif(decision.getAccountId().equals(senderId) ||\n\t\t\t decision.getAccountId().equals(recipientId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswitch(decision.getDecision()) {\n\t\t\tcase RELEASE:\n\t\t\t\tcountRelease++;\n\t\t\t\tbreak;\n\t\t\tcase REFUND:\n\t\t\t\tcountRefund++;\n\t\t\t\tbreak;\n\t\t\tcase SPLIT:\n\t\t\t\tcountSplit++;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(countRelease >= requiredSigners) {\n\t\t\treturn DecisionType.RELEASE;\n\t\t}\n\t\tif(countRefund >= requiredSigners) {\n\t\t\treturn DecisionType.REFUND;\n\t\t}\n\t\tif(countSplit >= requiredSigners) {\n\t\t\treturn DecisionType.SPLIT;\n\t\t}\n\t\t\n\t\treturn DecisionType.UNDECIDED;\n\t}\n\t\n\tprivate synchronized void doPayout(DecisionType result, Block block) {\n\t\tswitch(result) {\n\t\tcase RELEASE:\n\t\t\tAccount.getAccount(recipientId).addToBalanceAndUnconfirmedBalanceNQT(amountNQT);\n\t\t\tsaveResultTransaction(block, id, recipientId, amountNQT, DecisionType.RELEASE);\n\t\t\tbreak;\n\t\tcase REFUND:\n\t\t\tAccount.getAccount(senderId).addToBalanceAndUnconfirmedBalanceNQT(amountNQT);\n\t\t\tsaveResultTransaction(block, id, senderId, amountNQT, DecisionType.REFUND);\n\t\t\tbreak;\n\t\tcase SPLIT:\n\t\t\tLong halfAmountNQT = amountNQT / 2;\n\t\t\tAccount.getAccount(recipientId).addToBalanceAndUnconfirmedBalanceNQT(halfAmountNQT);\n\t\t\tAccount.getAccount(senderId).addToBalanceAndUnconfirmedBalanceNQT(amountNQT - halfAmountNQT);\n\t\t\tsaveResultTransaction(block, id, recipientId, halfAmountNQT, DecisionType.SPLIT);\n\t\t\tsaveResultTransaction(block, id, senderId, amountNQT - halfAmountNQT, DecisionType.SPLIT);\n\t\t\tbreak;\n\t\tdefault: // should never get here\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tprivate static void saveResultTransaction(Block block, Long escrowId, Long recipientId, Long amountNQT, DecisionType decision) {\n\t\tAttachment.AbstractAttachment attachment = new Attachment.AdvancedPaymentEscrowResult(escrowId, decision);\n\t\tTransactionImpl.BuilderImpl builder = new TransactionImpl.BuilderImpl((byte)1, Genesis.CREATOR_PUBLIC_KEY,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t amountNQT, 0L, block.getTimestamp(), (short)1440, attachment);\n\t\tbuilder.senderId(0L)\n\t\t .recipientId(recipientId)\n\t\t .blockId(block.getId())\n\t\t .height(block.getHeight())\n\t\t .blockTimestamp(block.getTimestamp())\n\t\t .ecBlockHeight(0)\n\t\t .ecBlockId(0L);\n\t\t\n\t\tTransactionImpl transaction = null;\n\t\ttry {\n\t\t\ttransaction = builder.build();\n\t\t}\n\t\tcatch(NxtException.NotValidException e) {\n\t\t\tthrow new RuntimeException(e.toString(), e);\n\t\t}\n\t\t\n\t\tif(!TransactionDb.hasTransaction(transaction.getId())) {\n\t\t\tresultTransactions.add(transaction);\n\t\t}\n\t}\n}", "public final class Convert {\n\n private static final char[] hexChars = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };\n private static final long[] multipliers = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};\n\n public static final BigInteger two64 = new BigInteger(\"18446744073709551616\");\n\n private Convert() {} //never\n\n public static byte[] parseHexString(String hex) {\n if (hex == null) {\n return null;\n }\n byte[] bytes = new byte[hex.length() / 2];\n for (int i = 0; i < bytes.length; i++) {\n int char1 = hex.charAt(i * 2);\n char1 = char1 > 0x60 ? char1 - 0x57 : char1 - 0x30;\n int char2 = hex.charAt(i * 2 + 1);\n char2 = char2 > 0x60 ? char2 - 0x57 : char2 - 0x30;\n if (char1 < 0 || char2 < 0 || char1 > 15 || char2 > 15) {\n throw new NumberFormatException(\"Invalid hex number: \" + hex);\n }\n bytes[i] = (byte)((char1 << 4) + char2);\n }\n return bytes;\n }\n\n public static String toHexString(byte[] bytes) {\n if (bytes == null) {\n return null;\n }\n char[] chars = new char[bytes.length * 2];\n for (int i = 0; i < bytes.length; i++) {\n chars[i * 2] = hexChars[((bytes[i] >> 4) & 0xF)];\n chars[i * 2 + 1] = hexChars[(bytes[i] & 0xF)];\n }\n return String.valueOf(chars);\n }\n\n public static String toUnsignedLong(long objectId) {\n if (objectId >= 0) {\n return String.valueOf(objectId);\n }\n BigInteger id = BigInteger.valueOf(objectId).add(two64);\n return id.toString();\n }\n\n public static long parseUnsignedLong(String number) {\n if (number == null) {\n return 0;\n }\n BigInteger bigInt = new BigInteger(number.trim());\n if (bigInt.signum() < 0 || bigInt.compareTo(two64) != -1) {\n throw new IllegalArgumentException(\"overflow: \" + number);\n }\n return bigInt.longValue();\n }\n\n public static long parseLong(Object o) {\n if (o == null) {\n return 0;\n } else if (o instanceof Long) {\n return ((Long)o);\n } else if (o instanceof String) {\n return Long.parseLong((String)o);\n } else {\n throw new IllegalArgumentException(\"Not a long: \" + o);\n }\n }\n\n public static long parseAccountId(String account) {\n if (account == null) {\n return 0;\n }\n account = account.toUpperCase();\n if (account.startsWith(\"BURST-\")) {\n return Crypto.rsDecode(account.substring(6));\n } else {\n return parseUnsignedLong(account);\n }\n }\n\n public static String rsAccount(long accountId) {\n return \"BURST-\" + Crypto.rsEncode(accountId);\n }\n\n public static long fullHashToId(byte[] hash) {\n if (hash == null || hash.length < 8) {\n throw new IllegalArgumentException(\"Invalid hash: \" + Arrays.toString(hash));\n }\n BigInteger bigInteger = new BigInteger(1, new byte[] {hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0]});\n return bigInteger.longValue();\n }\n\n public static long fullHashToId(String hash) {\n if (hash == null) {\n return 0;\n }\n return fullHashToId(Convert.parseHexString(hash));\n }\n\n public static Date fromEpochTime(int epochTime) {\n return new Date(epochTime * 1000L + Constants.EPOCH_BEGINNING - 500L);\n }\n\n public static String emptyToNull(String s) {\n return s == null || s.length() == 0 ? null : s;\n }\n\n public static String nullToEmpty(String s) {\n return s == null ? \"\" : s;\n }\n\n public static byte[] emptyToNull(byte[] bytes) {\n if (bytes == null) {\n return null;\n }\n for (byte b : bytes) {\n if (b != 0) {\n return bytes;\n }\n }\n return null;\n }\n\n public static byte[] toBytes(String s) {\n try {\n return s.getBytes(\"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n public static String toString(byte[] bytes) {\n try {\n return new String(bytes, \"UTF-8\").trim();\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e.toString(), e);\n }\n }\n\n public static String readString(ByteBuffer buffer, int numBytes, int maxLength) throws NxtException.NotValidException {\n if (numBytes > 3 * maxLength) {\n throw new NxtException.NotValidException(\"Max parameter length exceeded\");\n }\n byte[] bytes = new byte[numBytes];\n buffer.get(bytes);\n return Convert.toString(bytes);\n }\n\n public static String truncate(String s, String replaceNull, int limit, boolean dots) {\n return s == null ? replaceNull : s.length() > limit ? (s.substring(0, dots ? limit - 3 : limit) + (dots ? \"...\" : \"\")) : s;\n }\n\n public static long parseNXT(String nxt) {\n return parseStringFraction(nxt, 8, Constants.MAX_BALANCE_NXT);\n }\n\n private static long parseStringFraction(String value, int decimals, long maxValue) {\n String[] s = value.trim().split(\"\\\\.\");\n if (s.length == 0 || s.length > 2) {\n throw new NumberFormatException(\"Invalid number: \" + value);\n }\n long wholePart = Long.parseLong(s[0]);\n if (wholePart > maxValue) {\n throw new IllegalArgumentException(\"Whole part of value exceeds maximum possible\");\n }\n if (s.length == 1) {\n return wholePart * multipliers[decimals];\n }\n long fractionalPart = Long.parseLong(s[1]);\n if (fractionalPart >= multipliers[decimals] || s[1].length() > decimals) {\n throw new IllegalArgumentException(\"Fractional part exceeds maximum allowed divisibility\");\n }\n for (int i = s[1].length(); i < decimals; i++) {\n fractionalPart *= 10;\n }\n return wholePart * multipliers[decimals] + fractionalPart;\n }\n\n // overflow checking based on https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow\n public static long safeAdd(long left, long right)\n throws ArithmeticException {\n if (right > 0 ? left > Long.MAX_VALUE - right\n : left < Long.MIN_VALUE - right) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return left + right;\n }\n\n public static long safeSubtract(long left, long right)\n throws ArithmeticException {\n if (right > 0 ? left < Long.MIN_VALUE + right\n : left > Long.MAX_VALUE + right) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return left - right;\n }\n\n public static long safeMultiply(long left, long right)\n throws ArithmeticException {\n if (right > 0 ? left > Long.MAX_VALUE/right\n || left < Long.MIN_VALUE/right\n : (right < -1 ? left > Long.MIN_VALUE/right\n || left < Long.MAX_VALUE/right\n : right == -1\n && left == Long.MIN_VALUE) ) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return left * right;\n }\n\n public static long safeDivide(long left, long right)\n throws ArithmeticException {\n if ((left == Long.MIN_VALUE) && (right == -1)) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return left / right;\n }\n\n public static long safeNegate(long a) throws ArithmeticException {\n if (a == Long.MIN_VALUE) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return -a;\n }\n\n public static long safeAbs(long a) throws ArithmeticException {\n if (a == Long.MIN_VALUE) {\n throw new ArithmeticException(\"Integer overflow\");\n }\n return Math.abs(a);\n }\n\n}" ]
import javax.servlet.http.HttpServletRequest; import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.Escrow; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware;
package nxt.http; public final class EscrowSign extends CreateTransaction { static final EscrowSign instance = new EscrowSign(); private EscrowSign() { super(new APITag[] {APITag.TRANSACTIONS, APITag.CREATE_TRANSACTION}, "escrow", "decision"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { Long escrowId; try { escrowId = Convert.parseUnsignedLong(Convert.emptyToNull(req.getParameter("escrow"))); } catch(Exception e) { JSONObject response = new JSONObject(); response.put("errorCode", 3); response.put("errorDescription", "Invalid or not specified escrow"); return response; }
Escrow escrow = Escrow.getEscrowTransaction(escrowId);
3
opencb/bionetdb
bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/CsvInfo.java
[ "public class Node {\n\n private long uid;\n\n private String id;\n private String name;\n\n private List<Label> labels;\n\n private ObjectMap attributes;\n\n private static long counter = 0;\n\n public enum Label {\n INTERNAL_CONNFIG,\n\n UNDEFINED,\n\n PHYSICAL_ENTITY,\n TRANSCRIPT,\n ENSEMBL_TRANSCRIPT,\n REFSEQ_TRANSCRIPT,\n EXON,\n ENSEMBL_EXON,\n REFSEQ_EXON,\n PROTEIN,\n PHYSICAL_ENTITY_COMPLEX,\n RNA,\n SMALL_MOLECULE,\n\n MIRNA,\n MIRNA_MATURE,\n MIRNA_TARGET,\n\n DNA,\n GENE,\n ENSEMBL_GENE,\n REFSEQ_GENE,\n VARIANT,\n REGULATION_REGION,\n TFBS,\n\n HGV,\n\n PANEL_GENE,\n PANEL_VARIANT,\n PANEL_STR,\n PANEL_REGION,\n\n PROTEIN_ANNOTATION,\n PROTEIN_FEATURE,\n\n STRUCTURAL_VARIATION,\n BREAKEND,\n BREAKEND_MATE,\n VARIANT_ANNOTATION,\n EVIDENCE_SUBMISSION,\n HERITABLE_TRAIT,\n PROPERTY,\n REPEAT,\n CYTOBAND,\n VARIANT_CONSEQUENCE_TYPE,\n SO_TERM,\n VARIANT_DRUG_INTERACTION,\n VARIANT_POPULATION_FREQUENCY,\n VARIANT_CONSERVATION_SCORE,\n VARIANT_FUNCTIONAL_SCORE,\n PROTEIN_VARIANT_ANNOTATION,\n PROTEIN_SUBSTITUTION_SCORE,\n VARIANT_CLASSIFICATION,\n\n GENE_ANNOTATION,\n CLINICAL_EVIDENCE,\n GENE_TRAIT_ASSOCIATION,\n GENE_DRUG_INTERACTION,\n DRUG,\n GENE_EXPRESSION,\n ONTOLOGY,\n FEATURE_ONTOLOGY_TERM_ANNOTATION,\n TRANSCRIPT_ANNOTATION_EVIDENCE,\n\n TRANSCRIPT_CONSTRAINT_SCORE,\n\n PATHWAY,\n\n CELLULAR_LOCATION,\n REGULATION,\n CATALYSIS,\n REACTION,\n COMPLEX_ASSEMBLY,\n TRANSPORT,\n INTERACTION,\n\n VARIANT_FILE,\n VARIANT_FILE_DATA,\n SAMPLE,\n VARIANT_SAMPLE_DATA,\n INDIVIDUAL,\n FAMILY,\n\n TRANSCRIPT_ANNOTATION_FLAG,\n EXON_OVERLAP,\n PROTEIN_KEYWORD,\n\n DISEASE_PANEL,\n GENOMIC_FEATURE,\n\n DISORDER,\n PHENOTYPE,\n ONTOLOGY_TERM,\n\n ASSEMBLY,\n\n CUSTOM,\n\n XREF\n }\n\n public Node() {\n this(-1, null, null, Collections.emptyList());\n }\n\n public Node(long uid) {\n this(uid, null, null, Collections.emptyList());\n }\n\n public Node(long uid, String id, String name, Label label) {\n this.labels = new ArrayList<>();\n this.labels.add(label);\n\n attributes = new ObjectMap();\n\n setUid(uid);\n setId(id);\n setName(name);\n\n counter++;\n }\n\n public Node(long uid, String id, String name, List<Label> labels) {\n this.labels = labels;\n\n attributes = new ObjectMap();\n\n setUid(uid);\n setId(id);\n setName(name);\n\n counter++;\n }\n\n public String toStringEx() {\n final StringBuilder sb = new StringBuilder(\"Node{\");\n sb.append(\"uid='\").append(uid).append('\\'');\n sb.append(\", id='\").append(id).append('\\'');\n sb.append(\", name='\").append(name).append('\\'');\n sb.append(\", labels=\").append(labels);\n sb.append(\", attributes={\");\n if (MapUtils.isNotEmpty(attributes)) {\n for (String key: attributes.keySet()) {\n sb.append(key).append(\"=\").append(attributes.get(key)).append(',');\n }\n }\n sb.append(\"}}\");\n return sb.toString();\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Node{\");\n sb.append(\"uid='\").append(uid).append('\\'');\n sb.append(\"id='\").append(id).append('\\'');\n sb.append(\", name='\").append(name).append('\\'');\n sb.append(\", labels=\").append(labels);\n sb.append(\", attributes=\").append(attributes);\n sb.append('}');\n return sb.toString();\n }\n\n public long getUid() {\n return uid;\n }\n\n public Node setUid(long uid) {\n this.uid = uid;\n return this;\n }\n\n public String getId() {\n return id;\n }\n\n public Node setId(String id) {\n this.id = id;\n return this;\n }\n\n public String getName() {\n return name;\n }\n\n public Node setName(String name) {\n this.name = name;\n return this;\n }\n\n public List<Label> getLabels() {\n return labels;\n }\n\n public Node setLabels(List<Label> labels) {\n this.labels = labels;\n return this;\n }\n\n public ObjectMap getAttributes() {\n return attributes;\n }\n\n public void setAttributes(ObjectMap attributes) {\n this.attributes = attributes;\n }\n\n public void addAttribute(String key, Object value) {\n if (key != null && value != null) {\n attributes.put(key, value);\n }\n }\n\n public static long getCounter() {\n return counter;\n }\n}", "public class Relation {\n\n private long uid;\n\n private String name;\n\n private long origUid;\n private Node.Label origLabel;\n\n private long destUid;\n private Node.Label destLabel;\n\n private Label label;\n\n private ObjectMap attributes;\n\n private static long counter = 0;\n\n public Relation(long uid, String name, long origUid, Node.Label origLabel, long destUid, Node.Label destLabel, Label label) {\n this.uid = uid;\n\n this.name = name;\n\n this.origUid = origUid;\n this.origLabel = origLabel;\n\n this.destUid = destUid;\n this.destLabel = destLabel;\n\n this.label = label;\n\n this.attributes = new ObjectMap();\n\n counter++;\n }\n\n public enum Label {\n\n // REACTOME\n\n COMPONENT_OF_PHYSICAL_ENTITY_COMPLEX,\n COMPONENT_OF_PATHWAY,\n PATHWAY_NEXT_STEP,\n INTERACTION,\n REACTION,\n CATALYSIS,\n REGULATION,\n COLOCALIZATION,\n CELLULAR_LOCATION,\n CONTROLLED,\n CONTROLLER,\n COFACTOR,\n PRODUCT,\n REACTANT,\n\n // GENERAL\n\n HAS,\n MOTHER_OF,\n FATHER_OF,\n TARGET,\n IS,\n ANNOTATION,\n DATA,\n MATURE\n }\n\n public Relation() {\n attributes = new ObjectMap();\n }\n\n public Relation(long uid) {\n this.uid = uid;\n\n attributes = new ObjectMap();\n }\n\n public void addAttribute(String key, Object value) {\n if (key != null && value != null) {\n attributes.put(key, value);\n }\n }\n\n public long getUid() {\n return uid;\n }\n\n public Relation setUid(long uid) {\n this.uid = uid;\n return this;\n }\n\n public String getName() {\n return name;\n }\n\n public Relation setName(String name) {\n this.name = name;\n return this;\n }\n\n public long getOrigUid() {\n return origUid;\n }\n\n public Relation setOrigUid(long origUid) {\n this.origUid = origUid;\n return this;\n }\n\n public Node.Label getOrigLabel() {\n return origLabel;\n }\n\n public long getDestUid() {\n return destUid;\n }\n\n public Node.Label getDestLabel() {\n return destLabel;\n }\n\n public Relation setDestUid(long destUid) {\n this.destUid = destUid;\n return this;\n }\n\n public Label getLabel() {\n return label;\n }\n\n public Relation setLabel(Label label) {\n this.label = label;\n return this;\n }\n\n public ObjectMap getAttributes() {\n return attributes;\n }\n\n public Relation setAttributes(ObjectMap attributes) {\n this.attributes = attributes;\n return this;\n }\n\n public static long getCounter() {\n return counter;\n }\n}", "public class GeneCache extends Cache<Gene> {\n private static Logger logger;\n\n public GeneCache(Path indexPath) {\n super(indexPath + \"/genes.rocksdb\", indexPath + \"/xref.genes.rocksdb\");\n\n objReader = objMapper.reader(Gene.class);\n logger = LoggerFactory.getLogger(this.getClass());\n }\n}", "public class ProteinCache extends Cache<Entry> {\n\n protected static Logger logger;\n\n public ProteinCache(Path indexPath) {\n super(indexPath + \"/proteins.rocksdb\", indexPath + \"/xref.proteins.rocksdb\");\n\n objReader = objMapper.reader(Entry.class);\n logger = LoggerFactory.getLogger(this.getClass());\n }\n}", "public static final String PREFIX_ATTRIBUTES = \"attr_\";" ]
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.formats.protein.uniprot.v202003jaxb.Entry; import org.opencb.biodata.models.core.Gene; import org.opencb.biodata.models.metadata.Individual; import org.opencb.biodata.models.metadata.Sample; import org.opencb.biodata.models.variant.metadata.VariantFileHeaderComplexLine; import org.opencb.biodata.models.variant.metadata.VariantFileMetadata; import org.opencb.biodata.models.variant.metadata.VariantMetadata; import org.opencb.biodata.models.variant.metadata.VariantStudyMetadata; import org.opencb.bionetdb.core.models.network.Node; import org.opencb.bionetdb.core.models.network.Relation; import org.opencb.bionetdb.lib.utils.cache.GeneCache; import org.opencb.bionetdb.lib.utils.cache.ProteinCache; import org.opencb.commons.utils.FileUtils; import org.rocksdb.RocksDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.Path; import java.util.*; import static org.opencb.bionetdb.lib.utils.Utils.PREFIX_ATTRIBUTES;
REACTANT___REACTION___PHYSICAL_ENTITY_COMPLEX("REACTANT___REACTION___PHYSICAL_ENTITY_COMPLEX"), REACTANT___REACTION___UNDEFINED("REACTANT___REACTION___UNDEFINED"), REACTANT___REACTION___DNA("REACTANT___REACTION___DNA"), REACTANT___REACTION___RNA("REACTANT___REACTION___RNA"), PRODUCT___REACTION___PROTEIN("PRODUCT___REACTION___PROTEIN"), PRODUCT___REACTION___SMALL_MOLECULE("PRODUCT___REACTION___SMALL_MOLECULE"), PRODUCT___REACTION___PHYSICAL_ENTITY_COMPLEX("PRODUCT___REACTION___PHYSICAL_ENTITY_COMPLEX"), PRODUCT___REACTION___UNDEFINED("PRODUCT___REACTION___UNDEFINED"), PRODUCT___REACTION___RNA("PRODUCT___REACTION___RNA"), CONTROLLER___CATALYSIS___PROTEIN("CONTROLLER___CATALYSIS___PROTEIN"), CONTROLLER___CATALYSIS___PHYSICAL_ENTITY_COMPLEX("CONTROLLER___CATALYSIS___PHYSICAL_ENTITY_COMPLEX"), CONTROLLER___CATALYSIS___UNDEFINED("CONTROLLER___CATALYSIS___UNDEFINED"), CONTROLLER___REGULATION___PHYSICAL_ENTITY_COMPLEX("CONTROLLER___REGULATION___PHYSICAL_ENTITY_COMPLEX"), CONTROLLER___REGULATION___PROTEIN("CONTROLLER___REGULATION___PROTEIN"), CONTROLLER___REGULATION___UNDEFINED("CONTROLLER___REGULATION___UNDEFINED"), CONTROLLER___REGULATION___SMALL_MOLECULE("CONTROLLER___REGULATION___SMALL_MOLECULE"), CONTROLLER___REGULATION___RNA("CONTROLLER___REGULATION___RNA"), CONTROLLED___REGULATION___CATALYSIS("CONTROLLED___REGULATION___CATALYSIS"), CONTROLLED___CATALYSIS___REACTION("CONTROLLED___CATALYSIS___REACTION"), CONTROLLED___REGULATION___REACTION("CONTROLLED___REGULATION___REACTION"), CONTROLLED___REGULATION___PATHWAY("CONTROLLED___REGULATION___PATHWAY"), COMPONENT_OF_PATHWAY___PATHWAY___PATHWAY("COMPONENT_OF_PATHWAY___PATHWAY___PATHWAY"), COMPONENT_OF_PATHWAY___REACTION___PATHWAY("COMPONENT_OF_PATHWAY___REACTION___PATHWAY"), PATHWAY_NEXT_STEP___PATHWAY___PATHWAY("PATHWAY_NEXT_STEP___PATHWAY___PATHWAY"), PATHWAY_NEXT_STEP___CATALYSIS___REACTION("PATHWAY_NEXT_STEP___CATALYSIS___REACTION"), PATHWAY_NEXT_STEP___REACTION___REACTION("PATHWAY_NEXT_STEP___REACTION___REACTION"), PATHWAY_NEXT_STEP___REACTION___CATALYSIS("PATHWAY_NEXT_STEP___REACTION___CATALYSIS"), PATHWAY_NEXT_STEP___CATALYSIS___CATALYSIS("PATHWAY_NEXT_STEP___CATALYSIS___CATALYSIS"), PATHWAY_NEXT_STEP___REACTION___REGULATION("PATHWAY_NEXT_STEP___REACTION___REGULATION"), PATHWAY_NEXT_STEP___REACTION___PATHWAY("PATHWAY_NEXT_STEP___REACTION___PATHWAY"), PATHWAY_NEXT_STEP___REGULATION___REACTION("PATHWAY_NEXT_STEP___REGULATION___REACTION"), PATHWAY_NEXT_STEP___REGULATION___PATHWAY("PATHWAY_NEXT_STEP___REGULATION___PATHWAY"), PATHWAY_NEXT_STEP___REGULATION___CATALYSIS("PATHWAY_NEXT_STEP___REGULATION___CATALYSIS"), PATHWAY_NEXT_STEP___REGULATION___REGULATION("PATHWAY_NEXT_STEP___REGULATION___REGULATION"), PATHWAY_NEXT_STEP___CATALYSIS___REGULATION("PATHWAY_NEXT_STEP___CATALYSIS___REGULATION"), PATHWAY_NEXT_STEP___CATALYSIS___PATHWAY("PATHWAY_NEXT_STEP___CATALYSIS___PATHWAY"), PATHWAY_NEXT_STEP___PATHWAY___CATALYSIS("PATHWAY_NEXT_STEP___PATHWAY___CATALYSIS"), PATHWAY_NEXT_STEP___PATHWAY___REACTION("PATHWAY_NEXT_STEP___PATHWAY___REACTION"), PATHWAY_NEXT_STEP___PATHWAY___REGULATION("PATHWAY_NEXT_STEP___PATHWAY___REGULATION"); private final String relation; RelationFilename(String relation) { this.relation = relation; } public List<RelationFilename> getAll() { List<RelationFilename> list = new ArrayList<>(); return list; } } public CsvInfo(Path inputPath, Path outputPath) { uid = 1; this.inputPath = inputPath; this.outputPath = outputPath; csvWriters = new HashMap<>(); rocksDbManager = new RocksDbManager(); uidRocksDb = this.rocksDbManager.getDBConnection(outputPath.toString() + "/uidRocksDB", true); geneCache = new GeneCache(outputPath); proteinCache = new ProteinCache(outputPath); mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); geneReader = mapper.reader(Gene.class); proteinReader = mapper.reader(Entry.class); objWriter = mapper.writer(); logger = LoggerFactory.getLogger(this.getClass()); } public long getAndIncUid() { long ret = uid; uid++; return ret; } public void openCSVFiles(List<File> variantFiles) throws IOException { BufferedWriter bw; String filename; noAttributes = createNoAttributes(); nodeAttributes = createNodeAttributes(variantFiles); // CSV files for nodes for (Node.Label label : Node.Label.values()) { filename = label.toString() + ".csv.gz"; bw = FileUtils.newBufferedWriter(outputPath.resolve(filename)); csvWriters.put(label.toString(), bw); if (CollectionUtils.isNotEmpty(nodeAttributes.get(label.toString()))) { bw.write(getNodeHeaderLine(nodeAttributes.get(label.toString()))); bw.newLine(); } } // CSV files for relationships for (RelationFilename name : RelationFilename.values()) { filename = name.name() + ".csv.gz"; bw = FileUtils.newBufferedWriter(outputPath.resolve(filename)); // Write header bw.write(getRelationHeaderLine(name.name())); bw.newLine(); // Add writer to the map csvWriters.put(name.name(), bw); }
for (Relation.Label label : Relation.Label.values()) {
1
cwan/im-log-stats
im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/ant/ReportParameterDataType.java
[ "public enum ReportType {\n\n\tHTML,\n\tCSV,\n\tTSV,\n\tVISUALIZE,\n\tTEMPLATE;\n\n\tpublic static ReportType toEnum(String s) {\n\n\t\tif (s == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\ts = s.toLowerCase();\n\n\t\tif (\"html\".equals(s)) {\n\t\t\treturn HTML;\n\t\t} else if (\"csv\".equals(s)) {\n\t\t\treturn CSV;\n\t\t} else if (\"tsv\".equals(s)) {\n\t\t\treturn TSV;\n\t\t} else if (\"visualize\".equals(s)) {\n\t\t\treturn VISUALIZE;\n\t\t} else if (\"template\".equals(s)) {\n\t\t\treturn TEMPLATE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public interface ReportFormatter {\n\n\t/**\n\t * レポートを生成する。\n\t * @param report\n\t * @throws IOException\n\t */\n\tpublic abstract void format(Report report) throws IOException;\n}", "public class TemplateFileReportFormatter extends AbstractFileReportFormatter {\n\n\tprivate static final Log logger = LogFactory.getLog(TemplateFileReportFormatter.class);\n\n\tprivate static final Pattern JSSPS_URL_PATTERN = Pattern.compile(\".*/(.+?)\\\\.jssp[s|(rpc)]?.*\");\n\n\t/** テンプレートファイル */\n\tprivate File templateFile = null;\n\n\t/** テンプレートファイルパス */\n\tprivate String templeteResourceFilePath = null;\n\n\t/** カスタムテンプレートファイルの文字コード */\n\tprivate String templateFileCharset = Charset.defaultCharset().toString();\n\n\t/** 項目の区切り文字 */\n\tprivate String separator = null;\n\n\t/**\n\t * コンストラクタ\n\t * @param output レポートの出力先\n\t * @param charset レポートの文字コード\n\t * @param parserParameter パーサパラメータ\n\t * @param reportParameter レポートパラメータ\n\t */\n\tpublic TemplateFileReportFormatter(\n\t\t\tFile output,\n\t\t\tString charset,\n\t\t\tParserParameter parserParameter,\n\t\t\tReportParameter reportParameter) {\n\n\t\tsuper(output, charset, parserParameter, reportParameter);\n\t}\n\n\t/**\n\t * レポートの文字コードはシステムデフォルトを使用するコンストラクタ。\n\t * @param output レポートの出力先\n\t * @param parserParameter パーサパラメータ\n\t * @param reportParameter レポートパラメータ\n\t */\n\tpublic TemplateFileReportFormatter(\n\t\t\t\tFile output,\n\t\t\t\tParserParameter parserParameter,\n\t\t\t\tReportParameter reportParameter) {\n\n\t\tsuper(output, parserParameter, reportParameter);\n\t}\n\n\t/**\n\t * テンプレートファイルを設定する。\n\t * @param templateFile\n\t * @throws FileNotFoundException\n\t */\n\tpublic void setTemplateFile(File templateFile) throws FileNotFoundException {\n\n\t\tif (!templateFile.exists() || !templateFile.isFile()) {\n\t\t\tthrow new FileNotFoundException(templateFile.getPath());\n\t\t}\n\n\t\tthis.templateFile = templateFile;\n\t}\n\n\t/**\n\t * テンプレートファイルパス(リソース)を設定する。\n\t * @param templeteResourceFilePath\n\t * @since 1.0.8\n\t */\n\tpublic void setTempleteResourceFilePath(String templeteResourceFilePath) {\n\t\tthis.templeteResourceFilePath = templeteResourceFilePath;\n\t}\n\n\t/**\n\t * カスタムテンプレートファイルの文字コードを設定する。\n\t * @param templateFileCharset\n\t */\n\tpublic void setTemplateFileCharset(String templateFileCharset) {\n\t\tthis.templateFileCharset = templateFileCharset;\n\t}\n\n\t/**\n\t * 項目の区切り文字を設定する。\n\t * @param separator\n\t * @since 1.0.8\n\t */\n\tpublic void setSeparator(String separator) {\n\t\tthis.separator = separator;\n\t}\n\n\n\t@Override\n\tpublic void doFormat(Report report) throws IOException {\n\n\t\tConfiguration fmConfig = new Configuration();\n\n\t\tInputStream in = null;\n\t\tReader reader = null;\n\n\t\ttry {\n\n\t\t\tif (this.templateFile != null) {\n\n\t\t\t\tin = new BufferedInputStream(new FileInputStream(this.templateFile));\n\t\t\t\treader = new InputStreamReader(in, this.templateFileCharset);\n\n\t\t\t} else if (this.templeteResourceFilePath != null) {\n\n\t\t\t\tin = new BufferedInputStream(getClass().getResourceAsStream(this.templeteResourceFilePath));\n\t\t\t\treader = new InputStreamReader(in, this.templateFileCharset);\n\n\t\t\t} else {\n\t\t\t\tthrow new IOException(\"Neither 'templateFile' nor 'templeteResourceFilePath' is set.\");\n\t\t\t}\n\n\n\t\t\tTemplate template = new Template(\"im-memory\", reader, fmConfig);\n\n\t\t\tMap<String, Object> rootMap = new HashMap<String, Object>();\n\n\t\t\trootMap.put(\"charset\", this.charset);\n\t\t\trootMap.put(\"reportName\", report.getParameter().getName());\n\t\t\trootMap.put(\"signature\", report.getParameter().getSignature());\n\t\t\trootMap.put(\"generatedTime\", new Date());\n\t\t\trootMap.put(\"separator\", this.separator);\n\t\t\trootMap.put(\"totalPageTime\", report.getTotalPageTime());\n\t\t\trootMap.put(\"totalRequestCount\", report.getRequestCount());\n\t\t\trootMap.put(\"projectVersion\", Application.getInstance().getProjectVersion());\n\t\t\trootMap.put(\"projectUrl\", Application.getInstance().getProjectUrl());\n\t\t\trootMap.put(\"timeZone\", TimeZone.getDefault());\n\n\t\t\tsetParameters(rootMap);\n\t\t\tsetTimeSpanStatistics(report, rootMap);\n\t\t\tsetRequestPageTimeRank(report, rootMap);\n\t\t\tsetRequestUrlRank(report, rootMap);\n\t\t\tsetSessionRank(report, rootMap);\n\t\t\tsetTenantStatistics(report, rootMap);\n\t\t\tsetExceptionRank(report, rootMap);\n\t\t\tsetLogFiles(report, rootMap);\n\n\t\t\ttemplate.process(rootMap, this.writer);\n\n\t\t} catch (TemplateException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t\tthrow new IOException(e.getMessage());\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(reader);\n\t\t\tIOUtils.closeQuietly(in);\n\t\t}\n\t}\n\n\t/**\n\t * パラメータを設定する。\n\t * @param rootMap\n\t */\n\tprivate void setParameters(Map<String, Object> rootMap) {\n\n\t\trootMap.put(\"parserParameter\", this.parserParameter);\n\t\trootMap.put(\"reportParameter\", this.reportParameter);\n\t}\n\n\t/**\n\t * 期間別統計を設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setTimeSpanStatistics(Report report, Map<String, Object> rootMap) {\n\n\t\treport.countActiveSessions();\n\n\t\tMap<String, Object> timeSpanStat = new HashMap<String, Object>();\n\t\trootMap.put(\"timeSpanStat\", timeSpanStat);\n\n\t\ttimeSpanStat.put(\"span\", report.getParameter().getSpan());\n\n\t\tList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();\n\t\ttimeSpanStat.put(\"list\", list);\n\n\t\tfor (TimeSpanStatistics stat : report.getTimeSpanStatisticsList()) {\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\tlist.add(row);\n\n\t\t\tList<Long> pageTimes = stat.getRequestPageTimes();\n\n\t\t\tPageTimeStat pageTimeStat = new PageTimeStat();\n\t\t\tReport.setPageTimeStat(pageTimeStat, pageTimes);\n\n\t\t\trow.put(\"startDate\", stat.getStartDate());\n\t\t\trow.put(\"endDate\", stat.getEndDate());\n\t\t\trow.put(\"requestCount\", stat.getRequestCount());\n\t\t\trow.put(\"pageTimeSum\", pageTimeStat.pageTimeSum);\n\t\t\trow.put(\"pageTimeAverage\", pageTimeStat.pageTimeAverage);\n\t\t\trow.put(\"pageTimeMin\", pageTimeStat.pageTimeMin);\n\t\t\trow.put(\"pageTimeMedian\", pageTimeStat.pageTimeMedian);\n\t\t\trow.put(\"pageTimeP90\", pageTimeStat.pageTimeP90);\n\t\t\trow.put(\"pageTimeMax\", pageTimeStat.pageTimeMax);\n\t\t\trow.put(\"pageTimeStandardDeviation\", pageTimeStat.pageTimeStandardDeviation);\n\t\t\trow.put(\"uniqueUserCount\", stat.getUniqueUserCount());\n\t\t\trow.put(\"uniqueSessionCount\", stat.getUniqueSessionCount());\n\t\t\trow.put(\"activeSessionCount\", stat.getActiveSessionCount());\n\t\t\trow.put(\"exceptionCount\", stat.getExceptionCount());\n\t\t\trow.put(\"transitionCount\", stat.getTransitionCount());\n\t\t\trow.put(\"transitionExceptionCount\", stat.getTransitionExceptionCount());\n\t\t\trow.put(\"maxConcurrentRequestCount\", stat.getMaxConcurrentRequest());\n\t\t}\n\t}\n\n\t/**\n\t * リクエスト処理時間のランキング(総合トップN)を設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setRequestPageTimeRank(Report report, Map<String, Object> rootMap) {\n\n\t\tMap<String, Object> requestPageTimeRank = new HashMap<String, Object>();\n\t\trootMap.put(\"requestPageTimeRank\", requestPageTimeRank);\n\n\t\tList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();\n\t\trequestPageTimeRank.put(\"list\", list);\n\n\t\trequestPageTimeRank.put(\"size\", report.getParameter().getRequestPageTimeRankSize());\n\t\trequestPageTimeRank.put(\"requestCount\", report.getRequestCount());\n\n\t\tfor (RequestEntry req : report.getRequestPageTimeRank()) {\n\n\t\t\tif (req == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\tlist.add(row);\n\n\t\t\trow.put(\"requestUrl\", req.url);\n\t\t\trow.put(\"requestPageTime\", req.time);\n\t\t\trow.put(\"date\", req.date);\n\t\t\trow.put(\"sessionId\", req.sessionId);\n\t\t\trow.put(\"userId\", report.getUserIdFromSessionId(req.sessionId, \"\"));\n\n\t\t\tif (reportParameter.isJsspPath()) {\n\t\t\t\trow.put(\"jsspPath\", getJsspPath(req.url));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * リクエスト処理時間のランキング(URL別・処理時間合計トップN)を設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setRequestUrlRank(Report report, Map<String, Object> rootMap) {\n\n\t\tMap<String, Object> requestUrlRank = new HashMap<String, Object>();\n\t\trootMap.put(\"requestUrlRank\", requestUrlRank);\n\n\t\tList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();\n\t\trequestUrlRank.put(\"list\", list);\n\n\t\tList<RequestUrlReportEntry> reportList = report.getRequestUrlReportList();\n\n\t\trequestUrlRank.put(\"size\", report.getParameter().getRequestUrlRankSize());\n\t\trequestUrlRank.put(\"total\", reportList.size());\n\n\t\tMathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP);\n\n\t\tint i = 0;\n\n\t\tfor (RequestUrlReportEntry entry : reportList) {\n\n\t\t\tif (++i > report.getParameter().getRequestUrlRankSize()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\tlist.add(row);\n\n\t\t\trow.put(\"url\", entry.url);\n\t\t\trow.put(\"count\", entry.count);\n\t\t\trow.put(\"pageTimeSum\", entry.pageTimeSum);\n\t\t\trow.put(\"pageTimeAverage\", entry.pageTimeAverage);\n\t\t\trow.put(\"pageTimeMin\", entry.pageTimeMin);\n\t\t\trow.put(\"pageTimeMedian\", entry.pageTimeMedian);\n\t\t\trow.put(\"pageTimeP90\", entry.pageTimeP90);\n\t\t\trow.put(\"pageTimeMax\", entry.pageTimeMax);\n\t\t\trow.put(\"pageTimeStandardDeviation\", entry.pageTimeStandardDeviation);\n\t\t\trow.put(\"countRate\", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue());\n\t\t\trow.put(\"pageTimeRate\", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue());\n\n\t\t\tif (reportParameter.isJsspPath()) {\n\t\t\t\trow.put(\"jsspPath\", getJsspPath(entry.url));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * リクエスト処理時間のランキング(セッション別・処理時間合計トップN)を設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setSessionRank(Report report, Map<String, Object> rootMap) {\n\n\t\tMap<String, Object> sessionRank = new HashMap<String, Object>();\n\t\trootMap.put(\"sessionRank\", sessionRank);\n\n\t\tList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();\n\t\tsessionRank.put(\"list\", list);\n\n\t\tList<SessionReportEntry> reportList = report.getSessionReportList();\n\n\t\tsessionRank.put(\"size\", report.getParameter().getSessionRankSize());\n\t\tsessionRank.put(\"total\", reportList.size());\n\n\t\tMathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP);\n\n\t\tint i = 0;\n\n\t\tfor (SessionReportEntry entry : reportList) {\n\n\t\t\tif (++i > report.getParameter().getSessionRankSize()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\tlist.add(row);\n\n\t\t\trow.put(\"sessionId\", entry.sessionId);\n\t\t\trow.put(\"userId\", report.getUserIdFromSessionId(entry.sessionId, \"\"));\n\t\t\trow.put(\"count\", entry.count);\n\t\t\trow.put(\"pageTimeSum\", entry.pageTimeSum);\n\t\t\trow.put(\"pageTimeAverage\", entry.pageTimeAverage);\n\t\t\trow.put(\"pageTimeMin\", entry.pageTimeMin);\n\t\t\trow.put(\"pageTimeMedian\", entry.pageTimeMedian);\n\t\t\trow.put(\"pageTimeP90\", entry.pageTimeP90);\n\t\t\trow.put(\"pageTimeMax\", entry.pageTimeMax);\n\t\t\trow.put(\"pageTimeStandardDeviation\", entry.pageTimeStandardDeviation);\n\t\t\trow.put(\"countRate\", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue());\n\t\t\trow.put(\"pageTimeRate\", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue());\n\t\t\trow.put(\"firstAccessTime\", entry.firstAccessTime);\n\t\t\trow.put(\"lastAccessTime\", entry.lastAccessTime);\n\t\t}\n\t}\n\n\t/**\n\t * テナント別統計を設定する。\n\t * @since 1.0.16\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setTenantStatistics(Report report, Map<String, Object> rootMap) {\n\n\t\tMap<String, Object> tenantStat = new HashMap<String, Object>();\n\t\trootMap.put(\"tenantStat\", tenantStat);\n\n\t\tList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();\n\t\ttenantStat.put(\"list\", list);\n\n\t\tfor (TenantStatistics stat : report.getTenantStatisticsList()) {\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\tlist.add(row);\n\n\t\t\tList<Long> pageTimes = stat.getRequestPageTimes();\n\n\t\t\tPageTimeStat pageTimeStat = new PageTimeStat();\n\t\t\tReport.setPageTimeStat(pageTimeStat, pageTimes);\n\n\t\t\trow.put(\"tenantId\", stat.getTenantId());\n\t\t\trow.put(\"requestCount\", stat.getRequestCount());\n\t\t\trow.put(\"pageTimeSum\", pageTimeStat.pageTimeSum);\n\t\t\trow.put(\"pageTimeAverage\", pageTimeStat.pageTimeAverage);\n\t\t\trow.put(\"pageTimeMin\", pageTimeStat.pageTimeMin);\n\t\t\trow.put(\"pageTimeMedian\", pageTimeStat.pageTimeMedian);\n\t\t\trow.put(\"pageTimeP90\", pageTimeStat.pageTimeP90);\n\t\t\trow.put(\"pageTimeMax\", pageTimeStat.pageTimeMax);\n\t\t\trow.put(\"pageTimeStandardDeviation\", pageTimeStat.pageTimeStandardDeviation);\n\t\t\trow.put(\"uniqueUserCount\", stat.getUniqueUserCount());\n\t\t\trow.put(\"uniqueSessionCount\", stat.getUniqueSessionCount());\n\t\t\trow.put(\"exceptionCount\", stat.getExceptionCount());\n\t\t\trow.put(\"transitionCount\", stat.getTransitionCount());\n\t\t\trow.put(\"transitionExceptionCount\", stat.getTransitionExceptionCount());\n\t\t\trow.put(\"maxConcurrentRequestCount\", stat.getMaxConcurrentRequest());\n\t\t}\n\t}\n\n\t/**\n\t * 例外回数を設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setExceptionRank(Report report, Map<String, Object> rootMap) {\n\n\t\tList<Map<String, Object>> exceptionList = new ArrayList<Map<String, Object>>();\n\t\trootMap.put(\"exceptionList\", exceptionList);\n\n\t\tfor (ExceptionReportEntry e : report.getExceptionReport()) {\n\n\t\t\tMap<String, Object> row = new HashMap<String, Object>();\n\t\t\texceptionList.add(row);\n\n\t\t\trow.put(\"level\", e.level);\n\t\t\trow.put(\"message\", e.message);\n\t\t\trow.put(\"groupingLineOfStackTrace\", e.groupingLineOfStackTrace);\n\t\t\trow.put(\"count\", e.count);\n\t\t}\n\t}\n\n\t/**\n\t * 解析対象ログファイルを設定する。\n\t * @param report\n\t * @param rootMap\n\t */\n\tprivate void setLogFiles(Report report, Map<String, Object> rootMap) {\n\n\t\tMap<String, Object> logFiles = new HashMap<String, Object>();\n\t\trootMap.put(\"logFiles\", logFiles);\n\n\t\tlogFiles.put(\"requestLogFiles\",\n\t\t\t\treport.getRequestLogFiles() != null ?\n\t\t\t\treport.getRequestLogFiles() :\n\t\t\t\tListUtils.EMPTY_LIST);\n\n\t\tlogFiles.put(\"transitionLogFiles\",\n\t\t\t\treport.getTransitionLogFiles() != null ?\n\t\t\t\treport.getTransitionLogFiles() :\n\t\t\t\tListUtils.EMPTY_LIST);\n\n\t\tlogFiles.put(\"exceptionLogFiles\",\n\t\t\t\treport.getExceptionLogFiles() != null ?\n\t\t\t\treport.getExceptionLogFiles() :\n\t\t\t\tListUtils.EMPTY_LIST);\n\n\t\tlogFiles.put(\"transitionLogOnly\",\n\t\t\t\tCollectionUtils.isEmpty(report.getRequestLogFiles()));\n\t}\n\n\t/**\n\t * JSSPページパスを取得する。\n\t * @param url\n\t * @return\n\t * @since 1.0.11\n\t */\n\tprivate String getJsspPath(String url) {\n\n\t\tif (url == null) {\n\t\t\treturn StringUtils.EMPTY;\n\t\t}\n\n\t\tMatcher matcher = JSSPS_URL_PATTERN.matcher(url);\n\n\t\tif (!matcher.matches()) {\n\t\t\treturn StringUtils.EMPTY;\n\t\t}\n\n\t\tString path = matcher.group(1);\n\n\t\tpath = StringUtils.replace(path, \"(2f)\", \"/\");\n\t\tpath = StringUtils.replace(path, \"(5f)\", \"_\");\n\n\t\treturn path;\n\t}\n}", "public class ParserParameter {\n\n\t/** ログファイルの文字コード */\n\tprivate String charset = Charset.defaultCharset().toString();\n\n\t/** リクエストログのレイアウト */\n\tprivate String requestLogLayout = null;\n\n\t/** 画面遷移ログのレイアウト */\n\tprivate String transitionLogLayout = null;\n\n\t/** 開始日時(これ以前のログは切り捨てる) */\n\tprivate Date begin = null;\n\n\t/** 終了日時(これ以降のログは切り捨てる) */\n\tprivate Date end = null;\n\n\t/**\n\t * テナントIDフィルタ(これが指定されている場合は、他のテナントのログは集計しない)\n\t * @since 1.0.16\n\t */\n\tprivate String tenantId = null;\n\n\t/** ログのバージョン */\n\tprivate Version version = Version.V80;\n\n\t/** 例外のグルーピング方法 */\n\tprivate ExceptionLog.GroupingType exceptionGroupingType = ExceptionLog.GroupingType.CAUSE;\n\n\t/** パーサエラーカンター */\n\tprivate ParserErrorCounter errorCounter = new ParserErrorCounter(1000);\n\n\t/**\n\t * リクエストURLのスキーム、ネットロケーション部を削除するかどうか\n\t * @since 1.0.11\n\t */\n\tprivate boolean truncateRequestUrl = false;\n\n\t/**\n\t * 集約URLパターン\n\t * @since 1.0.20\n\t */\n\tprivate List<String> aggregatedUrlPatterns = new ArrayList<String>();\n\n\t/**\n\t * @return charset\n\t */\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n\t/**\n\t * @param charset セットする charset\n\t */\n\tpublic void setCharset(String charset) {\n\t\tthis.charset = charset;\n\t}\n\n\t/**\n\t * リクエストログレイアウトを取得する。\n\t * 未設定の場合は、バージョン標準のレイアウトを取得する。\n\t * @return requestLogLayout\n\t */\n\tpublic String getRequestLogLayout() {\n\n\t\tif (this.requestLogLayout == null) {\n\t\t\treturn LogLayoutDefinitions.getStandardRequestLogLayout(getVersion());\n\t\t} else {\n\t\t\treturn requestLogLayout;\n\t\t}\n\t}\n\n\t/**\n\t * @param requestLogLayout セットする requestLogLayout\n\t */\n\tpublic void setRequestLogLayout(String requestLogLayout) {\n\t\tthis.requestLogLayout = requestLogLayout;\n\t}\n\n\t/**\n\t * 画面遷移ログレイアウトを取得する。\n\t * 未設定の場合は、バージョン標準のレイアウトを取得する。\n\t * @return transitionLogLayout\n\t */\n\tpublic String getTransitionLogLayout() {\n\n\t\tif (this.transitionLogLayout == null) {\n\t\t\treturn LogLayoutDefinitions.getStandardTransitionLogLayout(getVersion());\n\t\t} else {\n\t\t\treturn transitionLogLayout;\n\t\t}\n\t}\n\n\t/**\n\t * @param transitionLogLayout セットする transitionLogLayout\n\t */\n\tpublic void setTransitionLogLayout(String transitionLogLayout) {\n\t\tthis.transitionLogLayout = transitionLogLayout;\n\t}\n\n\t/**\n\t * @return begin\n\t */\n\tpublic Date getBegin() {\n\t\treturn begin;\n\t}\n\n\t/**\n\t *\n\t * @return\n\t * @since 1.0.8\n\t */\n\tpublic ExceptionLog.GroupingType getExceptionGroupingType() {\n\t\treturn exceptionGroupingType;\n\t}\n\n\t/**\n\t *\n\t * @return\n\t * @since 1.0.8\n\t */\n\tpublic boolean isExceptionGroupingByCause() {\n\t\treturn this.exceptionGroupingType == ExceptionLog.GroupingType.CAUSE;\n\t}\n\n\t/**\n\t * @param begin セットする begin\n\t */\n\tpublic void setBegin(Date begin) {\n\t\tthis.begin = begin;\n\t}\n\n\t/**\n\t * @return end\n\t */\n\tpublic Date getEnd() {\n\t\treturn end;\n\t}\n\n\t/**\n\t * @param end セットする end\n\t */\n\tpublic void setEnd(Date end) {\n\t\tthis.end = end;\n\t}\n\n\t/**\n\t * テナントIDフィルタを取得する。\n\t * @since 1.0.16\n\t * @return\n\t */\n\tpublic String getTenantId() {\n\t\treturn tenantId;\n\t}\n\n\t/**\n\t * テナントIDフィルタを設定する。\n\t * @since 1.0.16\n\t * @param tenantId\n\t */\n\tpublic void setTenantId(String tenantId) {\n\t\tthis.tenantId = tenantId;\n\t}\n\n\t/**\n\t * @return version\n\t */\n\tpublic Version getVersion() {\n\t\treturn version;\n\t}\n\n\t/**\n\t * @param version セットする version\n\t */\n\tpublic void setVersion(Version version) {\n\t\tthis.version = version;\n\t}\n\n\t/**\n\t *\n\t * @param exceptionGroupingType\n\t * @since 1.0.8\n\t */\n\tpublic void setExceptionGroupingType(\n\t\t\tExceptionLog.GroupingType exceptionGroupingType) {\n\t\tthis.exceptionGroupingType = exceptionGroupingType;\n\t}\n\n\t/**\n\t *\n\t * @param errorCounter\n\t * @since 1.0.10\n\t */\n\tpublic void setErrorCounter(ParserErrorCounter errorCounter) {\n\t\tthis.errorCounter = errorCounter;\n\t}\n\n\t/**\n\t *\n\t * @return\n\t * @since 1.0.10\n\t */\n\tpublic ParserErrorCounter getErrorCounter() {\n\t\treturn errorCounter;\n\t}\n\n\t/**\n\t * リクエストURLのスキーム、ネットロケーション部を削除するかどうかを取得する。\n\t * @return\n\t * @since 1.0.11\n\t */\n\tpublic boolean isTruncateRequestUrl() {\n\t\treturn truncateRequestUrl;\n\t}\n\n\t/**\n\t * リクエストURLのスキーム、ネットロケーション部を削除するかどうかを設定する。\n\t * @param truncateRequestUrl\n\t * @since 1.0.11\n\t */\n\tpublic void setTruncateRequestUrl(boolean truncateRequestUrl) {\n\t\tthis.truncateRequestUrl = truncateRequestUrl;\n\t}\n\n\t/**\n\t * 集約URLパターンを取得する。\n\t * @since 1.0.20\n\t * @return\n\t */\n\tpublic List<String> getAggregatedUrlPatterns() {\n\t\treturn aggregatedUrlPatterns;\n\t}\n\n\t/**\n\t * 集約URLパターンを設定する。\n\t * @param aggregatedUrlPatterns\n\t * @since 1.0.20\n\t */\n\tpublic void setAggregatedUrlPatterns(List<String> aggregatedUrlPatterns) {\n\t\tthis.aggregatedUrlPatterns = aggregatedUrlPatterns;\n\t}\n\n}", "public enum Version {\r\n\r\n\tV60(\"6.0\"),\r\n\r\n\tV61(\"6.1\"),\r\n\r\n\tV70(\"7.0\"),\r\n\r\n\tV71(\"7.1\"),\r\n\r\n\tV72(\"7.2\"),\r\n\r\n\tV80(\"8.0\"),\r\n\r\n\tV800(\"8.0.0\"),\r\n\r\n\tV801(\"8.0.1\"),\r\n\r\n\tV802(\"8.0.2\"),\r\n\r\n\tV803(\"8.0.3\"),\r\n\r\n\tV804(\"8.0.4\"),\r\n\r\n\tV805(\"8.0.5\"),\r\n\r\n\tV806(\"8.0.6\"),\r\n\r\n\tV807(\"8.0.7\"),\t// 2014 Spring\r\n\r\n\tV808(\"8.0.8\"),\t// 2014 Summer\r\n\r\n\tV809(\"8.0.9\"),\t// 2014 Winter\r\n\r\n\tV8010(\"8.0.10\"),\t// 2015 Spring\r\n\r\n\tV8011(\"8.0.11\"),\t// 2015 Summer\r\n\r\n\tV8012(\"8.0.12\"),\t// 2015 Winter\r\n\r\n\tV8013(\"8.0.13\"),\t// 2016 Spring\r\n\r\n\tV8014(\"8.0.14\"),\t// 2016 Summer\r\n\r\n\tV8015(\"8.0.15\"),\t// 2016 Winter\r\n\r\n\tV8016(\"8.0.16\");\t// 2017 Spring\r\n\r\n\r\n\tprivate final String name;\r\n\r\n\tprivate Version(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic static Version toEnum(String name) {\r\n\r\n\t\tfor (Version version : Version.values()) {\r\n\t\t\tif (version.name.equals(name)) {\r\n\t\t\t\treturn version;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\tpublic boolean isVersion6() {\r\n\t\treturn this == V60 || this == V61;\r\n\t}\r\n\r\n\tpublic boolean isVersion7() {\r\n\t\treturn !isVersion6();\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n}\r", "public class ReportParameter {\n\n\t/**\n\t * 解析間隔(分)\n\t */\n\tprivate long span = 5L;\n\n\t/**\n\t * セッションタイムアウト時間(分)\n\t */\n\tprivate int sessionTimeout = 10;\n\n\t/**\n\t * リクエスト処理時間ランクの出力件数\n\t */\n\tprivate int requestPageTimeRankSize = 20;\n\n\t/**\n\t * リクエスト処理時間ランクの閾値(ミリ秒)\n\t * @since 1.0.11\n\t */\n\tprivate long requestPageTimeRankThresholdMillis = -1L;\n\n\t/**\n\t * リクエストURLランクの出力件数\n\t */\n\tprivate int requestUrlRankSize = 20;\n\n\t/**\n\t * セッションランクの出力件数\n\t */\n\tprivate int sessionRankSize = 20;\n\n\t/**\n\t * JSSPページパスを表示するかどうか\n\t * @since 1.0.11\n\t */\n\tprivate boolean jsspPath = false;\n\n\t/**\n\t * 最大同時リクエスト数を表示するかどうか\n\t * @since 1.0.13\n\t */\n\tprivate boolean maxConcurrentRequest = true;\n\n\t/**\n\t * レポート名\n\t */\n\tprivate String name = \"intra-mart ログ統計レポート\";\n\n\t/**\n\t * 署名\n\t */\n\tprivate String signature = \"\";\n\n\t/** バージョン */\n\tprivate Version version = Version.V72;\n\n\t/**\n\t * visualizeのベースURL\n\t * @since 1.0.15\n\t */\n\tprivate String visualizeBaseUrl = \"visualize\";\n\n\t/**\n\t * 解析間隔(分)を取得する。\n\t * @return\n\t */\n\tpublic long getSpan() {\n\t\treturn span;\n\t}\n\n\t/**\n\t * 解析間隔(分)を設定する。\n\t * @param span\n\t */\n\tpublic void setSpan(long span) {\n\t\tthis.span = span;\n\t}\n\n\t/**\n\t * セッションタイムアウト時間(分)を取得する。\n\t * @return\n\t */\n\tpublic int getSessionTimeout() {\n\t\treturn sessionTimeout;\n\t}\n\n\t/**\n\t * セッションタイムアウト時間(分)を設定する。\n\t * @param sessionTimeout\n\t */\n\tpublic void setSessionTimeout(int sessionTimeout) {\n\t\tthis.sessionTimeout = sessionTimeout;\n\t}\n\n\t/**\n\t * リクエスト処理時間ランクの出力件数を取得する。\n\t * @return\n\t */\n\tpublic int getRequestPageTimeRankSize() {\n\t\treturn requestPageTimeRankSize;\n\t}\n\n\t/**\n\t * リクエスト処理時間ランクの出力件数を設定する。\n\t * @param requestPageTimeRankSize\n\t */\n\tpublic void setRequestPageTimeRankSize(int requestPageTimeRankSize) {\n\t\tthis.requestPageTimeRankSize = requestPageTimeRankSize;\n\t}\n\n\t/**\n\t * リクエストURLランクの出力件数を取得する。\n\t * @return\n\t */\n\tpublic int getRequestUrlRankSize() {\n\t\treturn requestUrlRankSize;\n\t}\n\n\t/**\n\t * リクエスト処理時間ランクの閾値(ミリ秒)を設定する。\n\t * @param requestPageTimeRankThresholdMillis\n\t * @since 1.0.11\n\t */\n\tpublic void setRequestPageTimeRankThresholdMillis(long requestPageTimeRankThresholdMillis) {\n\t\tthis.requestPageTimeRankThresholdMillis = requestPageTimeRankThresholdMillis;\n\t}\n\n\t/**\n\t * リクエスト処理時間ランクの閾値(ミリ秒)を取得する。\n\t * @return\n\t * @since 1.0.11\n\t */\n\tpublic long getRequestPageTimeRankThresholdMillis() {\n\t\treturn requestPageTimeRankThresholdMillis;\n\t}\n\n\t/**\n\t * リクエストURLランクの出力件数を設定する。\n\t * @param requestUrlRankSize\n\t */\n\tpublic void setRequestUrlRankSize(int requestUrlRankSize) {\n\t\tthis.requestUrlRankSize = requestUrlRankSize;\n\t}\n\n\t/**\n\t * セッションランクの出力件数を設定する。\n\t * @return\n\t */\n\tpublic int getSessionRankSize() {\n\t\treturn sessionRankSize;\n\t}\n\n\t/**\n\t * セッションランクの出力件数を設定する。\n\t * @param sessionRankSize\n\t */\n\tpublic void setSessionRankSize(int sessionRankSize) {\n\t\tthis.sessionRankSize = sessionRankSize;\n\t}\n\n\t/**\n\t * JSSPページパスを表示するかどうかを取得する。\n\t * @return\n\t * @since 1.0.11\n\t */\n\tpublic boolean isJsspPath() {\n\t\treturn jsspPath;\n\t}\n\n\t/**\n\t * JSSPページパスを表示するかどうかを設定する。\n\t * @param jsspPath\n\t * @since 1.0.11\n\t */\n\tpublic void setJsspPath(boolean jsspPath) {\n\t\tthis.jsspPath = jsspPath;\n\t}\n\n\t/**\n\t * 最大同時リクエスト数を表示するかどうかを取得する。\n\t * @return\n\t * @since 1.0.13\n\t */\n\tpublic boolean isMaxConcurrentRequest() {\n\t\treturn maxConcurrentRequest;\n\t}\n\n\t/**\n\t * 最大同時リクエスト数を表示するかどうかを設定する。\n\t * @param maxConcurrentRequest\n\t * @since 1.0.13\n\t */\n\tpublic void setMaxConcurrentRequest(boolean maxConcurrentRequest) {\n\t\tthis.maxConcurrentRequest = maxConcurrentRequest;\n\t}\n\n\t/**\n\t * レポート名を取得する\n\t * @return\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * レポート名を設定する\n\t * @param name\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * 署名を取得する。\n\t * @return\n\t */\n\tpublic String getSignature() {\n\t\treturn signature;\n\t}\n\n\t/**\n\t * 署名を設定する。\n\t * @param signature\n\t */\n\tpublic void setSignature(String signature) {\n\t\tthis.signature = signature;\n\t}\n\n\tpublic Version getVersion() {\n\t\treturn version;\n\t}\n\n\tpublic void setVersion(Version version) {\n\t\tthis.version = version;\n\t}\n\n\tpublic String getVisualizeBaseUrl() {\n\t\treturn visualizeBaseUrl;\n\t}\n\n\tpublic void setVisualizeBaseUrl(String visualizeBaseUrl) {\n\t\tthis.visualizeBaseUrl = visualizeBaseUrl;\n\t}\n}" ]
import java.io.File; import java.io.FileNotFoundException; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import net.mikaboshi.intra_mart.tools.log_stats.entity.ReportType; import net.mikaboshi.intra_mart.tools.log_stats.formatter.ReportFormatter; import net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter; import net.mikaboshi.intra_mart.tools.log_stats.parser.ParserParameter; import net.mikaboshi.intra_mart.tools.log_stats.parser.Version; import net.mikaboshi.intra_mart.tools.log_stats.report.ReportParameter; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.DataType;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package net.mikaboshi.intra_mart.tools.log_stats.ant; /** * ログ統計レポート設定のネスト要素 * * @version 1.0.16 * @author <a href="https://github.com/cwan">cwan</a> */ public class ReportParameterDataType extends DataType { /** レポートタイプ */ private ReportType type = ReportType.HTML; /** 期間別統計の単位(分) */ private long span = 0L; /** セッションタイムアウト時間(分) */ private int sessionTimeout = 0; /** リクエスト処理時間ランクの出力件数 */ private int requestPageTimeRankSize = 0; /** * リクエスト処理時間ランクの閾値(ミリ秒) * @since 1.0.11 */ private long requestPageTimeRankThresholdMillis = -1L; /** リクエストURLランクの出力件数 */ private int requestUrlRankSize = 0; /** セッションランクの出力件数 */ private int sessionRankSize = 0; /** * JSSPページパスを表示するかどうか * @since 1.0.11 */ private Boolean jsspPath = null; /** * 最大同時リクエスト数を表示するかどうか * @since 1.0.13 */ private Boolean maxConcurrentRequest = null; /** レポート名 */ private String name = null; /** 署名 */ private String signature = null; /** * カスタムテンプレートファイルパス */ private String templateFile = null; /** * カスタムテンプレートファイルの文字コード */ private String templateCharset = Charset.defaultCharset().toString(); /** レポート出力先パス */ private String output = "report_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()); /** レポートの文字コード */ private String charset = Charset.defaultCharset().toString(); /** * visualizeのベースURL * @since 1.0.15 */ private String visualizeBaseUrl = null; public void setType(String s) { this.type = ReportType.toEnum(s); if (this.type == null) { throw new BuildException("Unsupported report type : " + s); } } /** * @param span セットする span */ public void setSpan(long span) { this.span = span; } /** * @param sessionTimeout セットする sessionTimeout */ public void setSessionTimeout(int sessionTimeout) { this.sessionTimeout = sessionTimeout; } /** * @param requestPageTimeRankSize セットする requestPageTimeRankSize */ public void setRequestPageTimeRankSize(int requestPageTimeRankSize) { this.requestPageTimeRankSize = requestPageTimeRankSize; } /** * * @param requestPageTimeRankThresholdMillis * @since 1.0.11 */ public void setRequestPageTimeRankThresholdMillis(long requestPageTimeRankThresholdMillis) { this.requestPageTimeRankThresholdMillis = requestPageTimeRankThresholdMillis; } /** * @param requestUrlRankSize セットする requestUrlRankSize */ public void setRequestUrlRankSize(int requestUrlRankSize) { this.requestUrlRankSize = requestUrlRankSize; } /** * @param sessionRankSize セットする sessionRankSize */ public void setSessionRankSize(int sessionRankSize) { this.sessionRankSize = sessionRankSize; } /** * * @param jsspPath * @since 1.0.11 */ public void setJsspPath(Boolean jsspPath) { this.jsspPath = jsspPath; } /** * * @param maxConcurrentRequest * @since 1.0.13 */ public void setMaxConcurrentRequest(Boolean maxConcurrentRequest) { this.maxConcurrentRequest = maxConcurrentRequest; } /** * @param name セットする name */ public void setName(String name) { this.name = name; } /** * @param signature セットする signature */ public void setSignature(String signature) { this.signature = signature; } public void setTemplateFile(String templateFile) { this.templateFile = templateFile; } public void setTemplateCharset(String templateCharset) { this.templateCharset = templateCharset; } public void setOutput(String output) { try { this.output = AntParameterUtil.getReportOutput(output); } catch (IllegalArgumentException e) { throw new BuildException("Parameter 'output' is invalid : " + output); } } public void setCharset(String charset) { this.charset = charset; } public void setVisualizeBaseUrl(String visualizeBaseUrl) { this.visualizeBaseUrl = visualizeBaseUrl; } /** * 設定内容を元に、ReportFormatterのインスタンスを取得する。 * @return * @throws BuildException */
public ReportFormatter getReportFormatter(
1
inouire/baggle
baggle-client/src/inouire/baggle/client/gui/modules/ServerListPanel.java
[ "public class Language {\n\n static String[] tooltip_fr = new String[]{\n \"Lister les serveurs sur le réseau officiel\",//0\n \"Lister les serveurs en réseau local\",//1\n };\n static String[] tooltip_en = new String[]{\n \"List servers of the official network\",//0\n \"List servers on the local network\",//1\n };\n \n static String[] fr = new String[] {\n \"Protégé par un mot de passe\",//0\n \"Serveur:\",\"Port:\",\"Connecter\",//1\n \"Vous devez choisir un pseudo:\",//4\n \"Le port doit être un entier.\",//5\n \"Erreur\",//6\n \"Connexion au serveur...\",//7\n \"B@ggle, connecté sur \",//8\n \"J'ai lancé un serveur\",//9\n \"Avatar:\",\"Pseudo:\",\"Scan du réseau local...\",//10\n \"Récupération de la liste des salons...\",//13\n \"Tous les mots trouvés comptent\",//14\n \"Rejoindre une partie\",\"Connexion manuelle\",//15\n \"Mode barre intelligente\",\"Mode jeu uniquement\",\"Mode discussion uniquement\",//17\n \"Temps restant à jouer pour cette partie\",//20\n \"Joueurs\",\"Chat\",//21\n \"Saisir un mot\",//23\n \"(click ou Shift-Enter pour changer de mode)\",//24\n \"Mots trouvés\",//25\n \"Rechercher une définition\",//26\n \"Impossible de lancer un navigateur internet.\",//27\n \"À propos de b@ggle\",//28\n \"Se déconnecter de ce salon\",//29\n \"Impossible d'envoyer un mot, pas de partie en cours.\",//30\n \"Je suis prêt\",\"Signaler au serveur que vous êtes prêt à jouer (SHIFT-Enter)\",//31\n \"Faire une petite pause.\",\"Revenir dans le jeu.\",\"Changer de grille\",//33\n \"Signaler au serveur que vous voulez changer de grille (SHIFT-Backspace)\",//36\n \"Nombre de mots que \",\" a trouvé par rapport au nombre total de mots trouvés\",//37\n \" joueurs\",\"Entrez le mot de passe pour ce salon:\",//39\n \"Résultats\",//41\n \"Impossible de se connecter à internet.\",\"Connexion bloquée par un proxy ou un firewall\",//42\n \"Choisir un salon depuis la liste\",//44\n \"Nom d'hôte inconnu.\",//45\n \"Serveur injoignable sur ce port.\\n\\nÊtes vous bien connectés au reseau ?\\nLe serveur est il bien lancé sur le port \",//46\n \" ?\\nLe port est il ouvert sur le firewall de la machine serveur ?\",//47\n \"Numéro de port invalide.\",//48\n \"La partie va commencer...\",\"Nouvelle grille !\",//49\n \"Impossible de se connecter à ce salon.\",//51\n \"La connexion avec le serveur a été perdue\",//52\n \"Password incorrect !\",//53\n \"Mot à chercher:\",//54\n \"Aller voir le tableau des scores\",\"Impossible de lancer un navigateur internet, rendez-vous manuellement sur \"+Main.OFFICIAL_WEBSITE+\"/scores.php\",//55\n \"Tourner la grille dans le sens horaire (SHIFT-DROITE)\",\"Tourner la grille dans le sens anti-horaire (SHIFT-GAUCHE)\",//57\n \"Modifier la taille de la grille\",//59\n \"Pas de réponse de la part du server principal\",//60\n \"inconnue\",//61\n \"Ajouter un robot\",\"Deconnecter le robot\",//62\n \"Finalement, non !\",\"Annuler la demande de changement de grille (SHIFT-Backspace)\",//64\n \"Mot valide\",\"Le mot est trop court\",\"Le mot n'est pas dans la grille\",\"Le mot n'est pas dans le dictionnaire\",\"Le mot a été filtré par le controle parental\",//66\n \"Me voilà !\",\"à bientôt\",//71\n \"Signaler au serveur que vous n'êtes pas prêt à jouer\",//73\n \"Seuls les mots que je suis seul à trouver comptent\",//74\n \"est disponible\",\"Aller à la page de téléchargement\",//75\n \"La nouvelle version peut être téléchargée sur\",//77\n \"Pas de partie en cours\",\"Cliquer sur 'Je suis prêt' pour jouer\",//78\n \"Obtenir plus d'informations sur les règles dans ce salon\",\"Règles\",//80\n \"Réseau officiel\",\"Réseau local\",//82\n \"Il n'y a plus de place dans ce salon.\",//84\n \"Palmarès\"//85,\n \n };\n\n static String[] en = new String[] {\n \"Protected by a password\",\n \"Server:\",\n \"Port:\",\n \"Connect\",\n \"You must choose a nick:\",\n \"The port number must be an integer\",\n \"Error\",\n \"Connecting to server...\",\n \"B@ggle, connected on \",\n \"I started a server\",\n \"Avatar:\",\n \"Nick:\",\n \"Local network auto scan...\",\n \"Collecting rooms list...\",\n \"Each word found earn points\",\n \"Join a game\",\n \"Manual connection\",\n \"Smart field mode\",\n \"Game Only Mode \",\n \"Chat Only Mode\",\n \"Time left for this game\",\n \"Players\",\n \"Chat\",\n \"Enter a word\",\n \"(click or shift-enter to change mode)\",\n \"Found words\",\n \"Look for a definition\",\n \"Error while starting an internet browser\",\n \"About b@ggle...\",\n \"Disconnect from this room\",\n \"Unable to send word, no game running now\",\n \"I'm ready\",\n \"Notify server you're ready to play (SHIFT-Enter)\",\n \"Have a break\",\n \"Resume game\",\n \"Change grid\",\n \"Tell the server that you want to play with a new grid (SHIFT-Backspace)\",\n \"Number of words \",\n \"has found compared to the total number of words found by all the players.\",\n \"players\",\n \"Enter a password for this room: \",\n \"Results\",\n \"Impossible to connect to the internet\",\n \"Connection may be locked by a proxy or a firewall\",\n \"Pick a room from the list\",//44\n \"Unknown host name\",\n \"Server unreachable on this port.\\n\\nAre you connected to the network ?\\nIs the server listenning on port \",\n \"?\\nIs the port opened on the firewall of the server machine ?\",\n \"Invalid port number\",\n \"The game is about to start...\",\n \"New grid !\",\n \"Impossible to connect to this room\",\n \"Lost server connection\",\n \"Wrong password !\",\n \"Word to find:\",//54,\n \"Go to the hall of fame\",\"Error while starting an internet browser, go to \"+Main.OFFICIAL_WEBSITE+\"/scores.php\",//55\n \"Turn the grid clockwise (SHIFT-RIGHT)\",\"Turn the grid counter-clockwise (SHIFT-LEFT)\",//57\n \"Modify grid size\",//59\n \"No response from master server\",//60\n \"unknown\",//61\n \"Connect a robot\",\"Disconnect bot\",//62\n \"Well... finally, no !\",\"Cancel grid change request (SHIFT-Backspace)\",//63\n \"Word accepted\",\"This word is too short\",\"This word is not in the grid\",\"This word is not in the dictionnary\",\"This word has been filtered\",//66\n \"Here I am !\",\"Good bye\",//71\n \"Tell the server that you're not so ready to play\",//73\n \"Words that I'm the only one to find earn points\",//74\n \"is out\",\"Go to download page\",//75\n \"The new version can be downloaded at\",//77\n \"No game in progress\",\"Click on 'I'm ready' to play\",//78\n \"Know more about the rules in this room\",\"Rules\",//80\n \"Official network\",\"Local network\",//82\n \"Maximum number of players has been reached, try another room\",//84\n \"Ranking\"//85\n \n };\n\n public static String getString(int id){\n String a=\"###\";\n try{\n if(Main.LOCALE.equals(\"fr\")){\n a=fr[id];\n }else if(Main.LOCALE.equals(\"en\")){\n a=en[id];\n }\n }catch(Exception ex){\n ex.printStackTrace();\n }finally{\n return a;\n }\n }\n\n public static String getToolTip(int id){\n String a=\"###\";\n try{\n if(Main.LOCALE.equals(\"fr\")){\n a=tooltip_fr[id];\n }else if(Main.LOCALE.equals(\"en\")){\n a=tooltip_en[id];\n }\n }catch(Exception ex){\n ex.printStackTrace();\n }finally{\n return a;\n }\n }\n \n public static String getAboutMessage(){\n String s;\n if(Main.LOCALE.equals(\"fr\")){\n s=\"B@ggle version \"+ Main.VERSION + \"\\n\\n\"+\n \"B@ggle est un logiciel libre (license GPLv3) principalement écrit par Edouard de Labareyre.\\n\"+\n \"- Le dictionnaire français est régulièrement mis à jour par Bernard Javerliat\\n\"+ \n \"- La liste des mots du filtre parental a été constituée par Ersatz.\\n\"+\n \"- L'excellente structure de stockage du dictionnaire (DAWG) est de JohnPaul Adamovsky.\\n\"+\n \" http://pathcom.com/~vadco/dawg.html\\n\\n\"+\n \"Si vous ne connaissez pas les règles du jeu de boggle, il est possible de les afficher\\n\"+\n \"une fois que vous êtes connectés à un salon de jeu.\\n\\n\"+\n \"Pour plus d'informations, visitez le site \"+Main.OFFICIAL_WEBSITE;\n }else{\n s=\"B@ggle version \"+ Main.VERSION + \"\\n\\n\"+\n \"B@ggle is a free software (GPLv3 license) mainly developed by Edouard de Labareyre.\\n\"+\n \"- The french dictionnary is continuously updated by Bernard Javerliat\\n\"+ \n \"- The list of french words for parental filter has been made by Ersatz.\\n\"+ \n \"- The awesome storage structure for dictionnary (DAWG) is from JohnPaul Adamovsky.\\n\"+\n \" http://pathcom.com/~vadco/dawg.html\\n\\n\"+\n \"If you don't know boggle rules, you can display them when you are connected to a room.\\n\\n\"+\n \"For more information you can visit the website at \"+Main.OFFICIAL_WEBSITE;\n }\n return s;\n }\n \n public static String[] getRules(){\n \n String[] rules = new String[11];\n \n if(Main.LOCALE.equals(\"fr\")){\n rules[0]= \"Règles génériques\";\n rules[1]=\"Le but du boggle est de former des mots à partir des lettres \"+\n \"de la grille, sachant que les lettres doivent se toucher (sur le coté ou en diagonale).\\n\"+\n \"Les mots doivent être dans le dictionnaire, mais peuvent être mis au pluriel, \"+\n \"conjugués, accordés en genre et en nombre...\";\n rules[2]=\"Exemple: on peut trouver le mot TRIA dans cette grille (du verbe trier).\";\n rules[3]=\"Attention, un même dé ne peut pas être utilisé pour un mot donné.\";\n rules[4]=\"Exemple: on peut former le mot SERRA (du verbe serrer), mais pas PAVA !\";\n rules[5]=\"Règles spécifiques à ce salon\";\n rules[6]=\"Dans ce salon c'est la règle officielle qui s'applique. Ainsi ne rapportent \"+\n \"des points que les mots qu'un joueur est le seul à trouver. \";\n rules[7]=\"Dans ce salon, la règle qui s'applique est un dérivé de la règle officielle. Tous \"+\n \"les mots comptent, sachant que plus ils sont longs plus ils rapportent de points. \";\n rules[8]=\"Les mots doivent comporter au minimum \";\n rules[9]=\" lettres pour être acceptés. \";\n rules[10]=\"En cas de problème n'hésitez pas à demander de l'aide via le chat !\";\n }else{\n rules[0]= \"Generic rules\";\n rules[1]=\"The purpose of boggle is to form words from the letters of the grid,\\n\"+\n \"knowing that the letters must touch (on the side or diagonally).\"+\n \"Words must be in the dictionary, but may be plural, conjugated\\n\"+\n \"granted in gender and number...\";\n rules[2]=\"Example: you can find the word CORE in this grid.\";\n rules[3]=\"Note that a dice cannot be used twice in the same word.\";\n rules[4]=\"Example: you cannot find the word CANCEL in this grid because C cannot be used twice !\";\n rules[5]=\"Specific rules for this room\";\n rules[6]=\"In this room the official boggle rule is used. It means that you have to be the only\"+\n \"player who finds a word in order to earn points with this word.\";\n rules[7]=\"In this room, the rule is a derivate from the official rule. All the words \"+\n \"count, and the longer they are, the more points you win. \";\n rules[8]=\"Words shall contain at least \";\n rules[9]=\" letters to be valid. \";\n rules[10]=\"If you have troubles to play, feel free to ask fro help in the chat !\";\n }\n \n return rules;\n }\n \n}", "public class Main {\n\n //global variables\n public static String LOCALE=System.getProperty(\"user.language\");\n \n public final static String VERSION = \"3.7\";\n public final static int BUILD=3700;\n \n public static final String OFFICIAL_WEBSITE=\"http://baggle.org\";\n public static String MASTER_SERVER_HOST=\"masterserver.baggle.org\";\n public static int MASTER_SERVER_PORT=80;\n \n public static String STATIC_SERVER_IP=\"localhost\";\n public static int STATIC_SERVER_PORT=42705;\n\n public static boolean STORE_CONFIG_LOCALLY=false;\n public static String CONNECT_ONLY_TO=null;\n public static File CONFIG_FOLDER;\n\n public static MainFrame mainFrame;\n\n public static ServerConnection connection;\n public static BotServerConnection bot;\n \n public static CachedServersList cachedServers;\n public static CachedServersList cachedLANServers;\n \n public static AvatarFactory avatarFactory;\n public static UserConfiguration configuration;\n \n public static void printUsage(){\n System.out.println(\"B@ggle client version \"+Main.VERSION);\n System.out.println(\"Usage: \\n\\t-M [master server host]\"+\n \"\\n\\t-P [master server port]\"+\n \"\\n\\t-l (store config file in current directory)\");\n System.out.println(\"All parameters are optionnal.\");\n }\n \n /**\n * Main function for baggle-client.\n * Schedules all the others\n * @param Args the command line Arguments\n */\n public static void main(String[] args) throws InterruptedException {\n\n Utils.setBestLookAndFeelAvailable();\n\n printUsage();\n \n SimpleLog.initConsoleConfig();\n SimpleLog.logger.setLevel(Level.INFO);\n \n MASTER_SERVER_HOST = Args.getStringOption(\"-M\",args,MASTER_SERVER_HOST);\n MASTER_SERVER_PORT = Args.getIntegerOption(\"-P\", args, MASTER_SERVER_PORT);\n STORE_CONFIG_LOCALLY = Args.getOption(\"-l\",args);\n CONNECT_ONLY_TO = Args.getStringOption(\"--only\",args,CONNECT_ONLY_TO);\n \n //set path of config folder\n if(Main.STORE_CONFIG_LOCALLY){\n CONFIG_FOLDER=new File(\".baggle\"+File.separator);\n }else{\n CONFIG_FOLDER=new File(System.getProperty(\"user.home\")+File.separator+\".baggle\"+File.separator);\n }\n \n //init graphical elements\n avatarFactory=new AvatarFactory();\n \n //init main frame with connect panel only (for faster startup)\n mainFrame = new MainFrame();\n mainFrame.initConnectionPanel();\n mainFrame.setVisible(true);\n \n //load configuration\n configuration = new UserConfiguration();\n configuration.loadFromFile();\n \n //load cached servers list\n cachedServers = new CachedServersList(Main.MASTER_SERVER_HOST);\n cachedServers.loadList(7);\n \n //set auto refresh for server detection\n Timer T = new Timer();\n T.schedule(new AutoRefresh(), 0, 120000);//every 2 minutes\n \n //now init the game part of the main frame\n mainFrame.initGamePanel();\n \n //check for new version in the background\n mainFrame.connectionPane.sideConnectionPane.newVersionPane.checkForNewVersion();\n }\n}", "public class ColorFactory {\n final static public Color BROWN_BOARD= new Color(74,50,19);\n final static public Color BLUE_BOARD = new Color(28,47,85);\n final static public Color GREEN_BOARD = new Color(23,77,19);\n final static public Color RED_BOARD = new Color(113,38,35);\n final static public Color PURPLE_BOARD = new Color(58,42,69);\n \n final static public Color LIGHT_BLUE = new Color(164,178,207);\n final static public Color LIGHT_RED = new Color(255,113,113);\n final static public Color LIGHT_GREEN = new Color(157,195,104);\n \n final static public Color VERY_LIGHT_GRAY = new Color(220,220,220);\n final static public Color LIGHT_GRAY = new Color(190,190,190);\n \n final static public Color YELLOW_NOTIF = new Color(255,250,151);\n\n final static public Color SERVER_BG=Color.LIGHT_GRAY;\n final static public Color MOBILE_BG=Color.LIGHT_GRAY;\n final static public Color UNKNOWN_BG=Color.LIGHT_GRAY;\n final static public Color ROBOT_BG=new Color(255,250,151);\n \n final static public Color DONKEY_BG=new Color(159,196,123);\n final static public Color LADYBUG_BG=new Color(255,215,247);\n final static public Color HAT_BG=new Color(127,141,157);\n final static public Color TIGER_BG=new Color(211,214,255);\n final static public Color TUX_BG=new Color(255,219,151);\n final static public Color WINE_BG=new Color(255,155,155);\n final static public Color COFFEE_BG =new Color(199,192,175);\n final static public Color COLORS_BG=new Color(210,214,234);\n \n final static public Color GOOD_WORD = new Color(70,122,15);\n final static public Color BAD_WORD = new Color(187,41,41);\n \n// new Color(246,205,147),\n// new Color(191,191,191),\n// new Color(219,180,121),\n// new Color(175,180,132),\n// new Color(220,220,220),\n\n \n public static Color getAvatarColor(String name){\n Color c=Color.LIGHT_GRAY;\n if(name.equals(\"robot\")){\n c=ROBOT_BG;\n }else if(name.equals(\"donkey\")){\n c=DONKEY_BG;\n }else if(name.equals(\"ladybug\")){\n c=LADYBUG_BG;\n }else if(name.equals(\"hat\")){\n c=HAT_BG;\n }else if(name.equals(\"tiger\")){\n c=TIGER_BG;\n }else if(name.equals(\"tux\")){\n c=TUX_BG;\n }else if(name.equals(\"wine\")){\n c=WINE_BG;\n }else if(name.equals(\"coffee\")){\n c=COFFEE_BG;\n }else if(name.equals(\"colors\")){\n c=COLORS_BG;\n }\n return c;\n }\n \n public static Color getBoardColor(boolean big_board,String game_mode){\n Color c;\n if(big_board){\n if(game_mode.equalsIgnoreCase(\"trad\")){\n c=ColorFactory.PURPLE_BOARD;\n }else{\n c=ColorFactory.BROWN_BOARD;\n }\n }else{\n if(game_mode.equalsIgnoreCase(\"all\")){\n c=ColorFactory.BLUE_BOARD;\n }else{\n c=ColorFactory.GREEN_BOARD;\n }\n }\n return c;\n }\n\n}", "public class ServerConnection extends Thread{\n\n public String SERVER;\n public int PORT;\n\n //player properties\n public String my_nick;\n public String my_logo;\n public String my_auth_token;\n public int my_id;\n\n //server properties\n public String LANG;\n public boolean CHAT;\n public int MIN_LENGTH;\n public boolean PARENTAL_FILTER;\n public String GAME_MODE;\n public boolean BIG_BOARD;\n public boolean REWARD_BIG_WORDS;\n \n //communication channels\n public PrintWriter out = null;\n public BufferedReader in = null;\n public Socket socket = null;\n \n //game properties\n public String grid=\"????????????????\";\n\n public HashMap<Integer,String> players_id_name = new HashMap<Integer,String>();\n public HashMap<Integer,String> players_id_avatar = new HashMap<Integer,String>();\n \n public boolean in_game = false;\n public boolean is_connected=false; \n \n public ServerConnection(String server, int port){\n this.SERVER = server;\n this.PORT = port;\n }\n\n /**\n * Send a message to the server through the opened socket\n * @param message\n */\n public void send(String message){\n if(out != null){\n out.println(message);\n SimpleLog.logger.trace(\"[SND>>] \"+message);\n }\n }\n \n public void disconnect(){\n send(new DISCONNECTDatagram().toString());\n \n is_connected=false;\n try{\n out.close();\n in.close();\n socket.close();\n }catch(Exception e){\n \n }\n }\n \n /**\n * Connect to the server and performs the negociation phase\n * @param nick the nickname of the player in the room\n * @param logo the id of the logo in the room (between 1 and 10)\n * @return 0 if the connection is successful\n * other codes:\n * 1: misc problem\n * 2: unkown host\n * 3: too many players\n * 4: give password\n * 5: bad password\n */\n public int connect(String nick,String logo){\n this.my_nick=nick;\n this.my_logo=logo;\n\n \n this.socket=null;\n try {\n socket = new Socket(SERVER, PORT);\n out = new PrintWriter(socket.getOutputStream(), true);\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n } catch (UnknownHostException e) {\n SimpleLog.logger.warn(Language.getString(45)+\" - \"+Language.getString(6));\n return 2;\n } catch (IOException e) {\n SimpleLog.logger.warn(Language.getString(46)+PORT+Language.getString(47)+\" - \"+Language.getString(6));\n return 1;\n } catch (IllegalArgumentException e) {\n SimpleLog.logger.warn(Language.getString(48)+\" - \"+Language.getString(6));\n return 1;\n }\n\n //negociation phase\n send(new CONNECTDatagram(Datagram.replaceAccents(nick),logo).toString());\n\n String packet;\n String[] datagram;\n Key key=null;\n\n try{\n while ((packet = in.readLine()) != null){\n\n datagram = packet.split(\"\\\\|\");\n SimpleLog.logger.debug(\"[<<RECV] \"+packet);\n try{\n key=Key.valueOf(datagram[0]);\n switch (key){\n case ACCEPT:\n ACCEPTDatagram acceptD = new ACCEPTDatagram(datagram);\n acceptAction(acceptD);\n return 0;\n case DENY:\n DENYDatagram statusD = new DENYDatagram(datagram);\n denyAction(statusD);\n if(statusD.reason.contains(\"server_full\")){\n return 3;\n }else{\n return 1;\n }\n case PASSWORD:\n passwordAction();\n break;\n default:\n SimpleLog.logger.warn(\"Unexpected message: \"+packet);\n break;\n }\n }catch(Exception e){\n SimpleLog.logger.warn(\"Illegal datagram received from server: \"+packet);\n }\n }\n }catch(IOException e){\n SimpleLog.logger.warn(\"IOException during negociation phase\");\n }\n return 1;\n }\n\n /**\n * Hook when receiving an ACCEPT datagram during negociation phase\n * @param acceptD the parsed datagram\n */\n public void acceptAction(ACCEPTDatagram acceptD){\n //get useful server info\n my_auth_token = acceptD.auth;\n LANG=acceptD.lang;\n CHAT=acceptD.chat;\n MIN_LENGTH=acceptD.min;\n PARENTAL_FILTER=acceptD.pf;\n GAME_MODE=acceptD.mode;\n BIG_BOARD=acceptD.big;\n REWARD_BIG_WORDS=acceptD.rewardbigwords;\n my_id=acceptD.id;\n\n //update UI\n Main.mainFrame.roomPane.setGameMode(GAME_MODE,BIG_BOARD);\n Main.mainFrame.roomPane.wordsFoundPane.setLanguage(LANG);\n Main.mainFrame.roomPane.wordsFoundPane.setMinWordLength(MIN_LENGTH);\n Main.mainFrame.roomPane.wordsFoundPane.setGameMode(GAME_MODE);\n Main.mainFrame.roomPane.rulesPane.updateRules(acceptD);\n \n //by default, show nothing\n Main.mainFrame.roomPane.showNothing();\n\n //launch the game thread\n this.start();\n }\n\n /**\n * Hook when receiving a DENY datagram during negociation phase\n * @param statusD the parsed datagram\n */\n private void denyAction(DENYDatagram statusD){\n SimpleLog.logger.info(\"Access to server denied: \"+statusD.reason);\n }\n\n /**\n * Hook when receiving a PASSWORD datagram during negociation phase\n */\n private void passwordAction(){\n// send(new PASSWORDDatagram(password));\n SimpleLog.logger.info(\"Sending password\");\n }\n\n /**\n * Game thread\n */\n @Override\n public void run(){\n\n is_connected=true;\n \n String packet;\n String[] datagram;\n Key key;\n \n try{\n while ((packet = in.readLine()) != null){\n datagram = packet.split(\"\\\\|\");\n SimpleLog.logger.trace(\"[<<RCV] \"+packet);\n try{\n key=Key.valueOf(datagram[0]);\n switch (key){\n //related to game\n case START:\n STARTDatagram startD = new STARTDatagram(datagram);\n STARTAction(startD);\n break;\n case TIME:\n TIMEDatagram timeD = new TIMEDatagram(datagram);\n TIMEAction(timeD);\n break;\n case WORD:\n WORDDatagram wordD = new WORDDatagram(datagram);\n WORDAction(wordD);\n break;\n case STOP:\n STOPDatagram stopD = new STOPDatagram(datagram);\n STOPAction(stopD);\n break;\n case RESULT:\n RESULTDatagram resultD = new RESULTDatagram(datagram);\n RESULTAction(resultD);\n break;\n\n //related to players\n case JOIN:\n JOINDatagram joinD = new JOINDatagram(datagram);\n JOINAction(joinD);\n break;\n case LEAVE:\n LEAVEDatagram leaveD = new LEAVEDatagram(datagram);\n LEAVEAction(leaveD);\n break;\n case PROGRESS:\n PROGRESSDatagram progressD = new PROGRESSDatagram(datagram);\n PROGRESSAction(progressD);\n break;\n case SCORE:\n SCOREDatagram scoreD = new SCOREDatagram(datagram);\n SCOREAction(scoreD);\n break;\n case CLIENT:\n CLIENTDatagram clientD = new CLIENTDatagram(datagram);\n CLIENTAction(clientD);\n break;\n\n //generic\n case CHAT:\n CHATDatagram chatD = new CHATDatagram(datagram);\n CHATAction(chatD);\n break;\n case STATUS:\n STATUSDatagram statusD = new STATUSDatagram(datagram);\n STATUSAction(statusD);\n break;\n default:\n SimpleLog.logger.warn(\"Unexpected message: \"+packet);\n break;\n }\n }catch(Exception e){\n SimpleLog.logger.warn(\"Illegal datagram received from server: \"+packet);\n }\n }\n }catch(IOException e){\n SimpleLog.logger.debug(\"IOException during game phase\");\n }\n SimpleLog.logger.info(\"Connection lost unexpectly\");\n if(is_connected){//ie on a perdu la connexion sans passer par la case \"disconnect volontaire\"\n JOptionPane.showMessageDialog(Main.mainFrame,\n Language.getString(52),\n Language.getString(6),\n JOptionPane.ERROR_MESSAGE);\n Main.mainFrame.leaveRoom();\n }\n \n }\n\n /**\n * Action when receiving a JOIN datagram\n * @param st\n */\n private void JOINAction(JOINDatagram joinD){\n String nick=Datagram.addAccents(joinD.nick);\n players_id_name.put(joinD.id,nick);\n players_id_avatar.put(joinD.id,joinD.logo);\n Main.mainFrame.roomPane.playersPane.addPlayer(joinD.id,nick, joinD.logo);\n }\n\n /**\n * Action when receiving a LEAVE datagram\n * @param st\n */\n private void LEAVEAction(LEAVEDatagram leaveD){\n players_id_name.remove(leaveD.id);\n players_id_avatar.remove(leaveD.id);\n Main.mainFrame.roomPane.playersPane.removePlayer(leaveD.id);\n }\n\n /**\n * Action when receiving a STATUS datagram\n * @param st\n */\n private void STATUSAction(STATUSDatagram statusD){\n Main.mainFrame.roomPane.playersPane.updateStatus(statusD.id, statusD.state);\n }\n\n /**\n * Action when receiving a CHAT datagram\n * @param st\n */\n private void CHATAction(CHATDatagram chatD){\n if(chatD.id==0){\n Main.mainFrame.roomPane.chatPane.addServerInfo(chatD.msg);\n }else{\n Main.mainFrame.roomPane.chatPane.addMessage(chatD.id,chatD.msg);\n }\n }\n\n /**\n * Action when receiving a TIME datagram\n * @param st\n */\n private void TIMEAction(TIMEDatagram timeD){\n Main.mainFrame.roomPane.timePane.setServerTime(timeD.rem,timeD.tot);\n }\n\n /**\n * Action when receiving a PROGRESS datagram\n * @param st\n */\n private void PROGRESSAction(PROGRESSDatagram progressD){\n Main.mainFrame.roomPane.playersPane.setGauge(progressD.id,progressD.prog);\n }\n\n /**\n * Action when receiving a SCORE datagram\n * @param st\n */\n private void SCOREAction(SCOREDatagram scoreD){\n Main.mainFrame.roomPane.playersPane.setTotalScore(scoreD.id,scoreD.score);\n }\n\n /**\n * Action when receiving a START datagram\n * @param st\n */\n private void STARTAction(STARTDatagram startD) {\n in_game=true;\n grid=startD.grid;\n \n Main.mainFrame.roomPane.boardPane.setBigBoard(BIG_BOARD);\n Main.mainFrame.roomPane.boardPane.enableAll();\n Main.mainFrame.roomPane.boardPane.enableAll();\n Main.mainFrame.roomPane.resetActionPane.setToMode(true);\n Main.mainFrame.roomPane.readyActionPane.setToMode(true);\n Main.mainFrame.roomPane.wordsFoundPane.setMaxPoints(startD.max);\n Main.mainFrame.roomPane.wordsFoundPane.resetWordsFound();\n \n Main.mainFrame.roomPane.showGame();\n\n Main.mainFrame.roomPane.wordEntryPane.giveFocus();\n Main.mainFrame.roomPane.refreshCenter();\n \n Main.mainFrame.roomPane.boardPane.animateShuffle();\n }\n\n /**\n * Action when receiving a WORD datagram\n * @param st\n */\n private void WORDAction(WORDDatagram wordD) {\n if(wordD.status==Words.GOOD){\n Main.mainFrame.roomPane.wordsFoundPane.addWord(wordD.word.toUpperCase());\n }\n Main.mainFrame.roomPane.wordStatusPane.setWord(wordD.word.toUpperCase(), wordD.status);\n }\n\n /**\n * Action when receiving a STOP datagram\n * @param st\n */\n private void STOPAction(STOPDatagram stopD) {\n \n //update 'in game' variable\n in_game=false;\n \n RoomPanel gamePane=Main.mainFrame.roomPane;\n \n gamePane.resetActionPane.setToMode(true);\n gamePane.readyActionPane.setToMode(true);\n gamePane.playersPane.resetAllGauges();\n gamePane.boardPane.disableAll();\n gamePane.wordStatusPane.reset();\n gamePane.timePane.resetTimer();\n gamePane.resultsPane.clearResults();\n gamePane.resultsPane.setGrid(grid);\n \n if(stopD.reason.equals(\"eot\")){\n //display results\n Main.mainFrame.roomPane.showResults();\n }else if(stopD.reason.equals(\"nogame\")){\n //display the 'nogame' screen\n Main.mainFrame.roomPane.showNoGame();\n }\n \n \n }\n\n /**\n * Action when receiving a RESULT datagram\n * @param st\n */\n private void RESULTAction(RESULTDatagram resultD) {\n //add result to result pane\n Main.mainFrame.roomPane.resultsPane.addResult(resultD);\n }\n\n /**\n * Action when receiving a CLIENT datagram\n * @param st\n */\n private void CLIENTAction(CLIENTDatagram clientD) {\n //TODO\n SimpleLog.logger.info(\"FYI, \"+ players_id_name.get(clientD.id)+\" runs version \"+clientD.version+\" for \"+clientD.os);\n }\n \n public static PINGDatagram pingLocalServer(String host,int port){\n return pingServer(host,port,200);\n }\n \n public static PINGDatagram pingWebServer(String host,int port){\n return pingServer(host,port,4000);\n }\n \n private static PINGDatagram pingServer(String host,int port,int timeout){\n \n PINGDatagram pingD=null;\n\n //connection avec le serveur\n Socket socket = null;\n PrintWriter out=null;\n BufferedReader in = null;\n SocketAddress sockaddr = new InetSocketAddress(host, port);\n try {\n socket = new Socket();\n socket.connect(sockaddr,timeout);\n out = new PrintWriter(socket.getOutputStream(), true);\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n }catch (Exception e) {\n SimpleLog.logger.info(\"Connection with \"+host+\":\"+port+\" failed\");\n return null;\n }\n \n //récupération des données\n String packet=null;\n String[] datagram;\n Key key=null;\n\n out.println(\"PING|\");\n \n try{\n if ((packet = in.readLine()) != null){\n\n datagram = packet.split(\"\\\\|\");\n\n try{\n key=Key.valueOf(datagram[0]);\n if(key==Key.PING){\n pingD = new PINGDatagram(datagram);\n }\n }catch(Exception e){\n SimpleLog.logger.warn(\"Illegal datagram received from server: \"+packet);\n }\n }\n }catch(IOException e){\n SimpleLog.logger.warn(\"Error while sending data to server \"+host+\":\"+port);\n }finally{\n try{\n out.close();\n socket.close();\n in.close();\n }catch(Exception ex){}\n }\n return pingD;\n }\n}", "public class PINGDatagram {\n\n public String lang=null;\n public Boolean chat=null;\n public Integer min=null;\n public Boolean pf=null;\n public String mode=null;\n public Integer nb=null;\n public Integer max=null;\n public String name=null;\n public Boolean priv=null;\n public String grid=null;\n public Integer time=null;\n public Integer port=null;\n public String players=null;\n public Boolean big=false;\n public Boolean rewardbigwords=false;\n \n public Integer returnPort=null;\n \n public PINGDatagram(int returnPort){\n this.returnPort=returnPort;\n }\n \n //PING|lang=fr|chat=yes|min=3|pf=no|mode=trad|nb=3|max=5|name=salut a toi|priv=no|grid=BAGRIURGUIGIUEG|time=120|players=bibi,beber,mika|big=no|rewardbigwords=no\n public PINGDatagram(int port,String name,String lang,boolean chat,int min,boolean pf, String mode,int nb,int max,boolean priv,String grid,int time,String players, boolean big, boolean rewardbigwords){\n this.port=port;\n this.lang=lang;\n this.chat=chat;\n this.min=min;\n this.pf=pf;\n this.mode=mode;\n this.nb=nb;\n this.max=max;\n this.name=name;\n this.priv=priv;\n this.grid=grid;\n this.time=time;\n this.players=players;\n this.big=big;\n this.rewardbigwords=rewardbigwords;\n }\n\n public PINGDatagram(String[] args) throws IllegalDatagramException{\n try{\n for(int k=1;k<args.length;k++){\n parseArg(args[k]);\n }\n }catch(Exception e){\n throw new IllegalDatagramException();\n }\n checkDatagram();\n }\n\n private void checkDatagram() throws IllegalDatagramException {\n if(returnPort==null){\n if(name==null || nb==null || lang==null || max==null || min==null || pf==null || chat==null || priv==null || grid==null || time==null){\n throw new IllegalDatagramException();\n }\n }\n }\n\n private void parseArg(String arg){\n String [] keyValue = Datagram.decompArg(arg);\n if(keyValue!=null){\n\n String key=keyValue[0];\n String value=keyValue[1];\n\n if(key.equals(\"lang\")){\n lang=value.toLowerCase();\n }else if(key.equals(\"mode\")){\n mode=value.toLowerCase();\n }else if(key.equals(\"nb\")){\n nb=Integer.parseInt(value);\n }else if(key.equals(\"max\")){\n max=Integer.parseInt(value);\n }else if(key.equals(\"min\")){\n min=Integer.parseInt(value);\n }else if(key.equals(\"chat\")){\n if(value.equals(\"yes\")){\n chat=true;\n }else if(value.equals(\"no\")){\n chat=false;\n }\n }else if(key.equals(\"pf\")){\n if(value.equals(\"yes\")){\n pf=true;\n }else if(value.equals(\"no\")){\n pf=false;\n }\n }else if(key.equals(\"name\")){\n name=Datagram.addAccents(value);\n }else if(key.equals(\"priv\")){\n if(value.equals(\"yes\")){\n priv=true;\n }else if(value.equals(\"no\")){\n priv=false;\n }\n }else if(key.equals(\"grid\")){\n grid=value.toUpperCase();\n }else if(key.equals(\"time\")){\n time=Integer.parseInt(value);\n }else if(key.equals(\"returnport\")){\n returnPort=Integer.parseInt(value);\n }else if(key.equals(\"port\")){\n port=Integer.parseInt(value);\n }else if(key.equals(\"players\")){\n players=value;\n }else if(key.equals(\"big\")){\n if(value.equals(\"yes\")){\n this.big=true;\n }else if(value.equals(\"no\")){\n this.big=false;\n }\n }else if(key.equals(\"rewardbigwords\")){\n if(value.equals(\"yes\")){\n this.rewardbigwords=true;\n }else if(value.equals(\"no\")){\n this.rewardbigwords=false;\n }\n }\n }\n }\n\n @Override\n public String toString(){\n if(returnPort!=null){\n return \"PING|returnPort=\"+returnPort;\n }else{\n String p,c,pr,pl,b,rbw;\n if(pf){\n p=\"yes\";\n }else{\n p=\"no\";\n }\n if(chat){\n c=\"yes\";\n }else{\n c=\"no\";\n }\n if(priv){\n pr=\"yes\";\n }else{\n pr=\"no\";\n }\n if(players!=null && players.length()>0){\n pl = \"|players=\"+players;\n }else{\n pl=\"\";\n }\n if(big){\n b=\"yes\";\n }else{\n b=\"no\";\n }\n if(rewardbigwords){\n rbw=\"yes\";\n }else{\n rbw=\"no\";\n }\n return \"PING|port=\"+port+\"|lang=\"+lang+\"|chat=\"+c+\"|min=\"+min+\"|pf=\"+p+\"|mode=\"+mode+\"|nb=\"+nb+\n \"|max=\"+max+\"|name=\"+Datagram.replaceAccents(name)+\"|priv=\"+pr+\"|grid=\"+grid+\"|time=\"+time+pl+\n \"|big=\"+\"|rewardbigwords=\"+rbw;\n }\n }\n\n}" ]
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import inouire.baggle.client.Language; import inouire.baggle.client.Main; import inouire.baggle.client.gui.ColorFactory; import inouire.baggle.client.threads.ServerConnection; import inouire.baggle.datagrams.PINGDatagram; import inouire.basics.SimpleLog;
package inouire.baggle.client.gui.modules; /** * * @author edouard */ public class ServerListPanel extends JPanel{ ImageIcon[] language_icons = { new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/fr.png")), new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/en.png")), }; private JList serverList; private DefaultListModel serverListModel; private final static int REF_WIDTH=400; private final static int REF_HEIGHT=140; private int heightMax=0; private int cellWidth=REF_WIDTH; private boolean deadAngle=false; public ServerListPanel() { super(); serverListModel = new DefaultListModel(); serverList = new JList(serverListModel); serverList.setCellRenderer(new OneServerListCellRenderer()); serverList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); serverList.setLayoutOrientation(JList.HORIZONTAL_WRAP); serverList.setVisibleRowCount(-1); serverList.setFixedCellHeight(REF_HEIGHT); serverList.setFixedCellWidth(REF_WIDTH); // put the JList in a JScrollPane JScrollPane resultsListScrollPane = new JScrollPane(serverList); resultsListScrollPane.setMinimumSize(new Dimension(150, 50)); resultsListScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); this.setLayout(new BorderLayout()); this.add(resultsListScrollPane,BorderLayout.CENTER); addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { notifyResize(); } @Override public void componentMoved(ComponentEvent e) {} @Override public void componentShown(ComponentEvent e) {} @Override public void componentHidden(ComponentEvent e) {} }); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { int index = getSelectedIndex(me); if(index>=0){ OneServerPanel one = (OneServerPanel) serverListModel.get(index); SimpleLog.logger.debug(one.host+":"+one.port+" - "+one.server_name +"has been clicked"); one.connectToThisServer(); } } @Override public void mouseExited(MouseEvent arg0) { clearHighlight(); repaint(); } }; serverList.addMouseListener(mouseListener); MouseMotionListener mouseMotionListener = new MouseMotionListener(){ @Override public void mouseDragged(MouseEvent me) { } @Override public void mouseMoved(MouseEvent me) { clearHighlight(); int index = getSelectedIndex(me); if(index>=0){ OneServerPanel selectedServer = (OneServerPanel)serverListModel.get(index); selectedServer.highlighted=true; serverList.setToolTipText(selectedServer.players); }else{ serverList.setToolTipText(null); } repaint(); } }; serverList.addMouseMotionListener(mouseMotionListener); } private int getSelectedIndex(MouseEvent me){ if(me.getY()>heightMax){ return -1; } if(me.getX()<cellWidth){ return serverList.locationToIndex(me.getPoint()); } if(me.getY()<heightMax-REF_HEIGHT){ return serverList.locationToIndex(me.getPoint()); } if(deadAngle){ return -1; }else{ return serverList.locationToIndex(me.getPoint()); } } private void clearHighlight(){ for(int k=0;k<serverListModel.getSize();k++){ ((OneServerPanel)serverListModel.get(k)).highlighted=false; } } public void notifyResize() { int width=serverList.getSize().width; if(width < REF_WIDTH){ cellWidth=width; heightMax = serverListModel.size() * REF_HEIGHT; }else{ cellWidth=width/2; if(serverListModel.size()%2==1){ deadAngle=true; heightMax = ((serverListModel.size()/2)+1) * REF_HEIGHT; }else{ deadAngle=false; heightMax = serverListModel.size() * REF_HEIGHT / 2; } } serverList.setFixedCellWidth(cellWidth); } public void resetList(){ serverListModel.removeAllElements(); repaint(); }
public synchronized void addServer(String ip, int port,PINGDatagram pingD){
4
ArthurHub/Android-Fast-Image-Loader
fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/DiskCacheImpl.java
[ "public interface Decoder {\n\n /**\n * Load image from disk file on the current thread and set it in the image request object.\n */\n void decode(MemoryPool memoryPool, ImageRequest imageRequest, File file, ImageLoadSpec spec);\n}", "public final class ImageLoadSpec {\n\n //region: Fields and Consts\n\n /**\n * the unique key of the spec used for identification and debug\n */\n private final String mKey;\n\n /**\n * the width of the image in pixels\n */\n private final int mWidth;\n\n /**\n * the height of the image in pixels\n */\n private final int mHeight;\n\n /**\n * The format of the image.\n */\n private final Format mFormat;\n\n /**\n * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)\n */\n private final Bitmap.Config mPixelConfig;\n\n /**\n * The URI enhancer to use for this spec image loading\n */\n private final ImageServiceAdapter mImageServiceAdapter;\n //endregion\n\n /**\n * Init image loading spec.\n *\n * @param key the unique key of the spec used for identification and debug\n * @param width the width of the image in pixels\n * @param height the height of the image in pixels\n * @param format The format of the image.\n * @param pixelConfig the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)\n * @param imageServiceAdapter The URI enhancer to use for this spec image loading\n */\n ImageLoadSpec(String key, int width, int height, Format format, Bitmap.Config pixelConfig, ImageServiceAdapter imageServiceAdapter) {\n mKey = key;\n mWidth = width;\n mHeight = height;\n mFormat = format;\n mPixelConfig = pixelConfig;\n mImageServiceAdapter = imageServiceAdapter;\n }\n\n /**\n * the unique key of the spec used for identification and debug\n */\n public String getKey() {\n return mKey;\n }\n\n /**\n * the width of the image in pixels\n */\n public int getWidth() {\n return mWidth;\n }\n\n /**\n * the height of the image in pixels\n */\n public int getHeight() {\n return mHeight;\n }\n\n /**\n * The format of the image.\n */\n public Format getFormat() {\n return mFormat;\n }\n\n /**\n * the pixel configuration to load the image in (4 bytes per image pixel, 2 bytes, etc.)\n */\n public Bitmap.Config getPixelConfig() {\n return mPixelConfig;\n }\n\n /**\n * The URI enhancer to use for this spec image loading\n */\n public ImageServiceAdapter getImageServiceAdapter() {\n return mImageServiceAdapter;\n }\n\n /**\n * Is the spec define specific width and height for the image.\n */\n public boolean isSizeBounded() {\n return mWidth > 0 && mHeight > 0;\n }\n\n @Override\n public String toString() {\n return \"ImageLoadSpec{\" +\n \"mKey='\" + mKey + '\\'' +\n \", mWidth=\" + mWidth +\n \", mHeight=\" + mHeight +\n \", mFormat=\" + mFormat +\n \", mPixelConfig=\" + mPixelConfig +\n \", mImageServiceAdapter=\" + mImageServiceAdapter +\n '}';\n }\n\n //region: Inner class: Format\n\n /**\n * The format of the image.\n */\n public static enum Format {\n UNCHANGE,\n JPEG,\n PNG,\n WEBP,\n }\n //endregion\n}", "public interface MemoryPool {\n\n /**\n * Retrieve an image for the specified {@code url} and {@code spec}.<br>\n * If not found for primary spec, use the alternative.\n */\n ReusableBitmap get(String url, ImageLoadSpec spec, ImageLoadSpec altSpec);\n\n /**\n * Store an image in the cache for the specified {@code key}.\n */\n void set(ReusableBitmap bitmap);\n\n /**\n * TODO:a. doc\n */\n ReusableBitmap getUnused(ImageLoadSpec spec);\n\n /**\n * TODO:a. doc\n */\n void returnUnused(ReusableBitmap bitmap);\n\n /**\n * Clears the cache/pool.\n */\n void clear();\n\n /**\n * Handle trim memory event to release image caches on memory pressure.\n */\n void onTrimMemory(int level);\n}", "public final class FILLogger {\n\n /**\n * The tag to use for all logs\n */\n private static final String TAG = \"FastImageLoader\";\n\n /**\n * If to write logs to logcat.\n */\n public static boolean mLogcatEnabled = false;\n\n /**\n * Extensibility appender to write the logs to.\n */\n public static LogAppender mAppender;\n\n /**\n * The min log level to write logs at, logs below this level are ignored.\n */\n public static int mLogLevel = Log.INFO;\n\n /**\n * Image load operation complete.\n *\n * @param url the url of the image\n * @param specKey the spec of the image load request\n * @param from from where the image was loaded (MEMORY/DISK/NETWORK)\n * @param successful was the image load successful\n * @param time the time in milliseconds it took from request to finish\n */\n public static void operation(String url, String specKey, LoadedFrom from, boolean successful, long time) {\n if (mLogcatEnabled) {\n String msg = FILUtils.format(\"Operation: LoadImage [{}] [{}] [{}] [{}]\", from, specKey, successful, time);\n Log.println(from == LoadedFrom.MEMORY ? Log.DEBUG : Log.INFO, TAG, msg);\n }\n if (mAppender != null)\n mAppender.imageLoadOperation(url, specKey, from, successful, time);\n }\n\n /**\n * Image download operation complete.\n *\n * @param url the url of the image\n * @param specKey the spec of the image load request\n * @param responseCode the response code of the download web request\n * @param time the time in milliseconds it took to download the image\n * @param bytes the number of bytes received if download was successful\n * @param error optional: if download failed will contain the error\n */\n public static void operation(String url, String specKey, int responseCode, long time, long bytes, Throwable error) {\n if (mLogcatEnabled) {\n String msg = FILUtils.format(\"Operation: DownloadImage [{}] [{}] [{}] [{}] [{}]\", url, specKey, responseCode, bytes, time);\n if (error == null) {\n Log.i(TAG, msg);\n } else {\n Log.e(TAG, msg, error);\n }\n }\n if (mAppender != null)\n mAppender.imageDownloadOperation(url, specKey, responseCode, time, bytes, error);\n }\n\n public static void debug(String msg) {\n if (mLogLevel <= Log.DEBUG) {\n if (mLogcatEnabled)\n Log.d(TAG, msg);\n if (mAppender != null)\n mAppender.log(Log.DEBUG, TAG, msg, null);\n }\n }\n\n public static void debug(String msg, Object arg1) {\n if (mLogLevel <= Log.DEBUG) {\n if (mLogcatEnabled)\n Log.d(TAG, FILUtils.format(msg, arg1));\n if (mAppender != null)\n mAppender.log(Log.DEBUG, TAG, FILUtils.format(msg, arg1), null);\n }\n }\n\n public static void debug(String msg, Object arg1, Object arg2) {\n if (mLogLevel <= Log.DEBUG) {\n if (mLogcatEnabled)\n Log.d(TAG, FILUtils.format(msg, arg1, arg2));\n if (mAppender != null)\n mAppender.log(Log.DEBUG, TAG, FILUtils.format(msg, arg1, arg2), null);\n }\n }\n\n public static void debug(String msg, Object arg1, Object arg2, Object arg3) {\n if (mLogLevel <= Log.DEBUG) {\n if (mLogcatEnabled)\n Log.d(TAG, FILUtils.format(msg, arg1, arg2, arg3));\n if (mAppender != null)\n mAppender.log(Log.DEBUG, TAG, FILUtils.format(msg, arg1, arg2, arg3), null);\n }\n }\n\n public static void debug(String msg, Object arg1, Object arg2, Object arg3, Object arg4) {\n if (mLogLevel <= Log.DEBUG) {\n if (mLogcatEnabled)\n Log.d(TAG, FILUtils.format(msg, arg1, arg2, arg3, arg4));\n if (mAppender != null)\n mAppender.log(Log.DEBUG, TAG, FILUtils.format(msg, arg1, arg2, arg3, arg4), null);\n }\n }\n\n public static void info(String msg) {\n if (mLogLevel <= Log.INFO) {\n if (mLogcatEnabled)\n Log.i(TAG, msg);\n if (mAppender != null)\n mAppender.log(Log.INFO, TAG, msg, null);\n }\n }\n\n public static void info(String msg, Object arg1) {\n if (mLogLevel <= Log.INFO) {\n if (mLogcatEnabled)\n Log.i(TAG, FILUtils.format(msg, arg1));\n if (mAppender != null)\n mAppender.log(Log.INFO, TAG, FILUtils.format(msg, arg1), null);\n }\n }\n\n public static void info(String msg, Object arg1, Object arg2) {\n if (mLogLevel <= Log.INFO) {\n if (mLogcatEnabled)\n Log.i(TAG, FILUtils.format(msg, arg1, arg2));\n if (mAppender != null)\n mAppender.log(Log.INFO, TAG, FILUtils.format(msg, arg1, arg2), null);\n }\n }\n\n public static void info(String msg, Object arg1, Object arg2, Object arg3) {\n if (mLogLevel <= Log.INFO) {\n if (mLogcatEnabled)\n Log.i(TAG, FILUtils.format(msg, arg1, arg2, arg3));\n if (mAppender != null)\n mAppender.log(Log.INFO, TAG, FILUtils.format(msg, arg1, arg2, arg3), null);\n }\n }\n\n public static void info(String msg, Object... args) {\n if (mLogLevel <= Log.INFO) {\n if (mLogcatEnabled)\n Log.i(TAG, FILUtils.format(msg, args));\n if (mAppender != null)\n mAppender.log(Log.INFO, TAG, FILUtils.format(msg, args), null);\n }\n }\n\n public static void warn(String msg, Object... args) {\n if (mLogLevel <= Log.WARN) {\n if (mLogcatEnabled)\n Log.w(TAG, FILUtils.format(msg, args));\n if (mAppender != null)\n mAppender.log(Log.WARN, TAG, FILUtils.format(msg, args), null);\n }\n }\n\n public static void warn(String msg, Throwable e, Object... args) {\n if (mLogLevel <= Log.WARN) {\n if (mLogcatEnabled)\n Log.w(TAG, FILUtils.format(msg, args), e);\n if (mAppender != null)\n mAppender.log(Log.WARN, TAG, FILUtils.format(msg, args), e);\n }\n }\n\n public static void error(String msg) {\n if (mLogLevel <= Log.ERROR) {\n if (mLogcatEnabled)\n Log.e(TAG, msg);\n if (mAppender != null)\n mAppender.log(Log.ERROR, TAG, msg, null);\n }\n }\n\n public static void error(String msg, Object... args) {\n if (mLogLevel <= Log.ERROR) {\n msg = FILUtils.format(msg, args);\n if (mLogcatEnabled)\n Log.e(TAG, msg);\n if (mAppender != null)\n mAppender.log(Log.ERROR, TAG, msg, null);\n }\n }\n\n public static void error(String msg, Throwable e, Object... args) {\n if (mLogLevel <= Log.ERROR) {\n msg = FILUtils.format(msg, args);\n if (mLogcatEnabled)\n Log.e(TAG, msg, e);\n if (mAppender != null)\n mAppender.log(Log.ERROR, TAG, msg, e);\n }\n }\n\n public static void critical(String msg, Object... args) {\n if (mLogLevel <= Log.ASSERT) {\n msg = FILUtils.format(msg, args);\n Exception e = new Exception(msg);\n if (mLogcatEnabled)\n Log.e(TAG, msg, e);\n if (mAppender != null)\n mAppender.log(Log.ASSERT, TAG, msg, e);\n }\n }\n\n public static void critical(String msg, Throwable e, Object... args) {\n if (mLogLevel <= Log.ASSERT) {\n msg = FILUtils.format(msg, args);\n if (mLogcatEnabled)\n Log.e(TAG, msg, e);\n if (mAppender != null)\n mAppender.log(Log.ASSERT, TAG, msg, e);\n }\n }\n}", "public final class FILUtils {\n\n /**\n * Reuse Rect object\n */\n public static final Rect rect = new Rect();\n\n /**\n * Reuse RectF object\n */\n public static final RectF rectF = new RectF();\n\n /**\n * The ID of the main thread of the application, used to know if currently execution on main thread.\n */\n public static long MainThreadId;\n\n /**\n * Validate that the current executing thread is the main Android thread for the app.\n *\n * @throws RuntimeException current thread is not main thread.\n */\n public static void verifyOnMainThread() {\n if (!isOnMainThread())\n throw new RuntimeException(\"Access to this method must be on main thread only\");\n }\n\n /**\n * Returns true if the current executing thread is the main Android app thread, false otherwise.\n */\n public static boolean isOnMainThread() {\n return Thread.currentThread().getId() == MainThreadId;\n }\n\n /**\n * Validate given argument isn't null.\n *\n * @param arg argument to validate\n * @param argName name of the argument to show in error message\n * @throws IllegalArgumentException\n */\n public static void notNull(Object arg, String argName) {\n if (arg == null) {\n throw new IllegalArgumentException(\"argument is null: \" + argName);\n }\n }\n\n /**\n * Validate given string argument isn't null or empty string.\n *\n * @param arg argument to validate\n * @param argName name of the argument to show in error message\n * @throws IllegalArgumentException\n */\n public static void notNullOrEmpty(String arg, String argName) {\n if (arg == null || arg.length() < 1) {\n throw new IllegalArgumentException(\"argument is null: \" + argName);\n }\n }\n\n /**\n * Validate given array argument isn't null or empty string.\n *\n * @param arg argument to validate\n * @param argName name of the argument to show in error message\n * @throws IllegalArgumentException\n */\n public static <T> void notNullOrEmpty(T[] arg, String argName) {\n if (arg == null || arg.length < 1) {\n throw new IllegalArgumentException(\"argument is null: \" + argName);\n }\n }\n\n /**\n * Validate given collection argument isn't null or empty string.\n *\n * @param arg argument to validate\n * @param argName name of the argument to show in error message\n * @throws IllegalArgumentException\n */\n public static <T> void notNullOrEmpty(Collection<T> arg, String argName) {\n if (arg == null || arg.size() < 1) {\n throw new IllegalArgumentException(\"argument is null: \" + argName);\n }\n }\n\n /**\n * Safe parse the given string to long value.\n */\n public static long parseLong(String value, long defaultValue) {\n if (!TextUtils.isEmpty(value)) {\n try {\n return Integer.parseInt(value);\n } catch (Exception ignored) {\n }\n }\n return defaultValue;\n }\n\n /**\n * combine two path into a single path with File.separator.\n * Handle all cases where the separator already exists.\n */\n public static String pathCombine(String path1, String path2) {\n if (path2 == null)\n return path1;\n else if (path1 == null)\n return path2;\n\n path1 = path1.trim();\n path2 = path2.trim();\n if (path1.endsWith(File.separator)) {\n if (path2.startsWith(File.separator))\n return path1 + path2.substring(1);\n else\n return path1 + path2;\n } else {\n if (path2.startsWith(File.separator))\n return path1 + path2;\n else\n return path1 + File.separator + path2;\n }\n }\n\n /**\n * Close the given closeable object (Stream) in a safe way: check if it is null and catch-log\n * exception thrown.\n *\n * @param closeable the closable object to close\n */\n public static void closeSafe(Closeable closeable) {\n if (closeable != null) {\n try {\n closeable.close();\n } catch (IOException e) {\n FILLogger.warn(\"Failed to close closable object [{}]\", e, closeable);\n }\n }\n }\n\n /**\n * Delete the given file in a safe way: check if it is null and catch-log exception thrown.\n *\n * @param file the file to delete\n */\n public static void deleteSafe(File file) {\n if (file != null) {\n try {\n //noinspection ResultOfMethodCallIgnored\n file.delete();\n } catch (Throwable e) {\n FILLogger.warn(\"Failed to delete file [{}]\", e, file);\n }\n }\n }\n\n /**\n * Format the given <i>format</i> string by replacing {} placeholders with given arguments.\n */\n public static String format(String format, Object arg1) {\n return replacePlaceHolder(format, arg1);\n }\n\n /**\n * Format the given <i>format</i> string by replacing {} placeholders with given arguments.\n */\n public static String format(String format, Object arg1, Object arg2) {\n format = replacePlaceHolder(format, arg1);\n return replacePlaceHolder(format, arg2);\n }\n\n /**\n * Format the given <i>format</i> string by replacing {} placeholders with given arguments.\n */\n public static String format(String format, Object arg1, Object arg2, Object arg3) {\n format = replacePlaceHolder(format, arg1);\n format = replacePlaceHolder(format, arg2);\n return replacePlaceHolder(format, arg3);\n }\n\n /**\n * Format the given <i>format</i> string by replacing {} placeholders with given arguments.\n */\n public static String format(String format, Object arg1, Object arg2, Object arg3, Object arg4) {\n format = replacePlaceHolder(format, arg1);\n format = replacePlaceHolder(format, arg2);\n format = replacePlaceHolder(format, arg3);\n return replacePlaceHolder(format, arg4);\n }\n\n /**\n * Format the given <i>format</i> string by replacing {} placeholders with given arguments.\n */\n public static String format(String format, Object... args) {\n for (Object arg : args) {\n format = replacePlaceHolder(format, arg);\n }\n return format;\n }\n\n /**\n * Replace the first occurrence of {} placeholder in <i>format</i> string by <i>arg1</i> toString() value.\n */\n private static String replacePlaceHolder(String format, Object arg1) {\n int idx = format.indexOf(\"{}\");\n if (idx > -1) {\n format = format.substring(0, idx) + arg1 + format.substring(idx + 2);\n }\n return format;\n }\n\n public static ThreadFactory threadFactory(final String name, final boolean daemon) {\n return new ThreadFactory() {\n @Override\n public Thread newThread(Runnable runnable) {\n Thread result = new Thread(runnable, name);\n result.setDaemon(daemon);\n return result;\n }\n };\n }\n\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.format.DateUtils; import com.theartofdev.fastimageloader.Decoder; import com.theartofdev.fastimageloader.ImageLoadSpec; import com.theartofdev.fastimageloader.MemoryPool; import com.theartofdev.fastimageloader.impl.util.FILLogger; import com.theartofdev.fastimageloader.impl.util.FILUtils; import java.io.File; import java.text.NumberFormat; import java.util.Arrays; import java.util.Comparator; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" package com.theartofdev.fastimageloader.impl; /** * Disk cache for image handler.<br> */ public class DiskCacheImpl implements com.theartofdev.fastimageloader.DiskCache { //region: Fields and Consts /** * The key to persist stats last scan data */ protected static final String STATS_LAST_SCAN = "DiskImageCache_lastCheck"; /** * The key to persist stats cache size data */ protected static final String STATS_CACHE_SIZE = "DiskImageCache_size"; /** * The max size of the cache (50MB) */ protected final long mMaxSize; /** * The bound to delete cached data to this size */ protected final long mMaxSizeLowerBound; /** * The max time image is cached without use before delete */ protected final long mCacheTtl; /** * The interval to execute cache scan even when max size has not reached */ protected final long SCAN_INTERVAL = 2 * DateUtils.DAY_IN_MILLIS; /** * the folder that the image cached on disk are located */ protected final File mCacheFolder; /** * Application context */ protected final Context mContext; /** * Threads service for all read operations. */ protected final ThreadPoolExecutor mReadExecutorService; /** * Threads service for scan of cached folder operation. */ protected final ThreadPoolExecutor mScanExecutorService; /** * The time of the last cache check */ private long mLastCacheScanTime = -1; /** * the current size of the cache */ private long mCurrentCacheSize; //endregion /** * @param context the application object to read config stuff * @param cacheFolder the folder to keep the cached image data * @param maxSize the max size of the disk cache in bytes * @param cacheTtl the max time a cached image remains in cache without use before deletion */ public DiskCacheImpl(Context context, File cacheFolder, long maxSize, long cacheTtl) {
FILUtils.notNull(context, "context");
4
Kaysoro/KaellyBot
src/main/java/commands/model/AbstractCommand.java
[ "public class Constants {\n\n /**\n * Application name\n */\n public final static String name = \"Kaelly\";\n\n /**\n * Application version\n */\n public final static String version = \"1.6.4\";\n\n /**\n * Changelog\n */\n public final static String changelog = \"https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png\";\n\n /**\n * Author id\n */\n public final static long authorId = 162842827183751169L;\n\n /**\n * Author name\n */\n public final static String authorName = \"Kaysoro#8327\";\n\n /**\n * Author avatar\n */\n public final static String authorAvatar = \"https://avatars0.githubusercontent.com/u/5544670?s=460&v=4\";\n\n /**\n * URL for Kaelly twitter account\n */\n public final static String twitterAccount = \"https://twitter.com/KaellyBot\";\n\n /**\n * URL for github KaellyBot repository\n */\n public final static String git = \"https://github.com/Kaysoro/KaellyBot\";\n\n /**\n * Official link invite\n */\n public final static String invite = \"https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot\";\n\n /**\n * Official paypal link\n */\n public final static String paypal = \"https://paypal.me/kaysoro\";\n\n /**\n * Database name\n */\n public final static String database = \"bdd.sqlite\";\n\n /**\n * Path to the database (can be left empty)\n */\n public final static String database_path = \"\";\n\n /**\n * Path to the folder containing sounds (can be left empty)\n */\n public final static String sound_path = \"\";\n\n /**\n * prefix used for command call.\n * WARN : it is injected into regex expression.\n * If you use special characters as '$', don't forget to prefix it with '\\\\' like this : \"\\\\$\"\n */\n public final static String prefixCommand = \"!\";\n\n public final static Language defaultLanguage = Language.FR;\n\n /**\n * Game desserved\n */\n public final static Game game = Game.DOFUS;\n\n /**\n * Official Ankama Game Logo\n */\n public final static String officialLogo = \"https://s.ankama.com/www/static.ankama.com/g/modules/masterpage/block/header/navbar/dofus/logo.png\";\n\n /**\n * Tutorial URL\n */\n public final static String dofusPourLesNoobURL = \"http://www.dofuspourlesnoobs.com\";\n\n /**\n * Tutorial Search URL\n */\n public final static String dofusPourLesNoobSearch = \"/apps/search\";\n\n /**\n * DofusRoom build URL\n */\n public final static String dofusRoomBuildUrl = \"https://www.dofusroom.com/buildroom/build/show/\";\n\n public final static String turnamentMapImg = \"https://dofus-tournaments.fr/_default/src/img/maps/A{number}.jpg\";\n\n /**\n * Twitter Icon from Wikipedia\n */\n public final static String twitterIcon = \"https://upload.wikimedia.org/wikipedia/fr/thumb/c/c8/Twitter_Bird.svg/langfr-20px-Twitter_Bird.svg.png\";\n\n /**\n * RSS Icon from Wikipedia\n */\n public final static String rssIcon = \"https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Feed-icon.svg/20px-Feed-icon.svg.png\";\n\n /**\n * Character limit for nickname discord\n */\n public final static int nicknameLimit = 32;\n\n /**\n * Character limit for prefixe discord\n */\n public final static int prefixeLimit = 3;\n\n /**\n * User or channel dedicated to receive info logs.\n */\n public final static long chanReportID = 321197720629149698L;\n\n /**\n * User or channel dedicated to receive error logs.\n */\n public final static long chanErrorID = 358201712600678400L;\n\n /**\n * Official changelog\n */\n public final static long newsChan = 330475075381886976L;\n\n /**\n * Almanax API URL\n */\n public final static String almanaxURL = \"https://alm.dofusdu.de/{game}/v1/{language}/{date}\";\n\n /**\n * Almanax Redis cache time to live for each cached day\n */\n public final static int almanaxCacheHoursTTL = 3;\n\n /**\n * Discord invite link\n */\n public final static String discordInvite = \"https://discord.gg/VsrbrYC\";\n}", "public class Guild {\n\n private final static Logger LOG = LoggerFactory.getLogger(Guild.class);\n private static Map<String, Guild> guilds;\n private String id;\n private String name;\n private Map<String, CommandForbidden> commands;\n private String prefix;\n private ServerDofus server;\n private Language language;\n\n public Guild(String id, String name, Language lang){\n this(id, name, Constants.prefixCommand, lang, null);\n }\n\n private Guild(String id, String name, String prefix, Language lang, String serverDofus){\n this.id = id;\n this.name = name;\n this.prefix = prefix;\n commands = CommandForbidden.getForbiddenCommands(this);\n this.language = lang;\n this.server = ServerDofus.getServersMap().get(serverDofus);\n }\n\n public synchronized void addToDatabase(){\n if (! getGuilds().containsKey(id)){\n getGuilds().put(id, this);\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement request = connection.prepareStatement(\"INSERT INTO\"\n + \" Guild(id, name, prefixe, lang) VALUES (?, ?, ?, ?);\");\n request.setString(1, id);\n request.setString(2, name);\n request.setString(3, prefix);\n request.setString(4, language.getAbrev());\n request.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n }\n\n public synchronized void removeToDatabase() {\n if (getGuilds().containsKey(id)) {\n getGuilds().remove(id);\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement request = connection.prepareStatement(\"DELETE FROM Guild WHERE ID = ?;\");\n request.setString(1, id);\n request.executeUpdate();\n\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n }\n\n public synchronized void setName(String name){\n this.name = name;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET name = ? WHERE id = ?;\");\n preparedStatement.setString(1, name);\n preparedStatement.setString(2, id);\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setPrefix(String prefix){\n this.prefix = prefix;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET prefixe = ? WHERE id = ?;\");\n preparedStatement.setString(1, prefix);\n preparedStatement.setString(2, id);\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setServer(ServerDofus server){\n this.server = server;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET server_dofus = ? WHERE id = ?;\");\n if (server != null) preparedStatement.setString(1, server.getName());\n else preparedStatement.setNull(1, Types.VARCHAR);\n preparedStatement.setString(2, id);\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setLanguage(Language lang){\n this.language = lang;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET lang = ? WHERE id = ?;\");\n preparedStatement.setString(1, lang.getAbrev());\n preparedStatement.setString(2, id);\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized static Map<String, Guild> getGuilds(){\n if (guilds == null){\n guilds = new ConcurrentHashMap<>();\n String id;\n String name;\n String prefix;\n String server;\n String lang;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement query = connection.prepareStatement(\"SELECT id, name, prefixe, server_dofus, lang FROM Guild\");\n ResultSet resultSet = query.executeQuery();\n\n while (resultSet.next()) {\n id = resultSet.getString(\"id\");\n name = resultSet.getString(\"name\");\n prefix = resultSet.getString(\"prefixe\");\n server = resultSet.getString(\"server_dofus\");\n lang = resultSet.getString(\"lang\");\n\n guilds.put(id, new Guild(id, name, prefix, Language.valueOf(lang), server));\n }\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n return guilds;\n }\n\n public static Guild getGuild(discord4j.core.object.entity.Guild guild){\n return getGuild(guild, true);\n }\n\n public synchronized static Guild getGuild(discord4j.core.object.entity.Guild discordGuild, boolean forceCache){\n Guild guild = getGuilds().get(discordGuild.getId().asString());\n\n if (guild == null && forceCache){\n guild = new Guild(discordGuild.getId().asString(), discordGuild.getName(), Constants.defaultLanguage);\n guild.addToDatabase();\n }\n\n return guild;\n }\n\n public String getId(){\n return id;\n }\n\n public String getName(){\n return name;\n }\n\n public String getPrefix(){ return prefix; }\n\n public Language getLanguage() {\n return language;\n }\n\n public Map<String, CommandForbidden> getForbiddenCommands(){\n return commands;\n }\n\n public ServerDofus getServerDofus() {\n return server;\n }\n}", "public enum Language {\n\n FR(\"Français\", \"FR\"), EN(\"English\", \"EN\"), ES(\"Español\", \"ES\");\n\n private String name;\n private String abrev;\n\n Language(String name, String abrev){\n this.name = name;\n this.abrev = abrev;\n }\n\n public String getName() {\n return name;\n }\n\n public String getAbrev() {\n return abrev;\n }\n\n @Override\n public String toString(){\n return name;\n }\n}", "public class BadUseCommandDiscordException implements DiscordException {\n\n @Override\n public void throwException(Message message, Command command, Language lg, Object... arguments) {\n message.getAuthor().ifPresent(author -> message.getChannel().flatMap(chan -> chan\n .createMessage(Translator.getLabel(lg, \"exception.bad_use_command\")\n .replace(\"{author}\", Matcher.quoteReplacement(author.getMention()))\n .replaceAll(\"\\\\{prefix}\", Matcher.quoteReplacement(AbstractCommand.getPrefix(message)))\n .replaceAll(\"\\\\{cmd.name}\", command.getName())\n .replace(\"{HelpCmd.name}\", HelpCommand.NAME)))\n .subscribe());\n }\n}", "public class BasicDiscordException implements DiscordException {\n\n private final static Logger LOG = LoggerFactory.getLogger(BasicDiscordException.class);\n public final static BasicDiscordException ALMANAX = new BasicDiscordException(\"exception.basic.almanax\");\n public final static BasicDiscordException ALLIANCEPAGE_INACCESSIBLE = new BasicDiscordException(\"exception.basic.alliancepage_inaccessible\");\n public final static BasicDiscordException GUILDPAGE_INACCESSIBLE = new BasicDiscordException(\"exception.basic.guildpage_inaccessible\");\n public final static BasicDiscordException CHARACTERPAGE_INACCESSIBLE = new BasicDiscordException(\"exception.basic.characterpage_inaccessible\");\n public final static BasicDiscordException CHARACTER_TOO_OLD = new BasicDiscordException(\"exception.basic.character_too_old\");\n public final static BasicDiscordException COMMAND_FORBIDDEN = new BasicDiscordException(\"exception.basic.command_forbidden\");\n public final static BasicDiscordException FORBIDDEN_COMMAND_FOUND = new BasicDiscordException(\"exception.basic.forbidden_command_found\");\n public final static BasicDiscordException FORBIDDEN_COMMAND_NOTFOUND = new BasicDiscordException(\"exception.basic.forbidden_command_notfound\");\n public final static BasicDiscordException INCORRECT_DATE_FORMAT = new BasicDiscordException(\"exception.basic.incorrect_date_format\");\n public final static BasicDiscordException IN_DEVELOPPMENT = new BasicDiscordException(\"exception.basic.in_developpment\");\n public final static BasicDiscordException NO_EXTERNAL_EMOJI_PERMISSION = new BasicDiscordException(\"exception.basic.no_external_emoji_permission\");\n public final static BasicDiscordException NO_SEND_TEXT_PERMISSION = new BasicDiscordException(\"exception.basic.no_send_text_permission\");\n public final static BasicDiscordException NO_NSFW_CHANNEL = new BasicDiscordException(\"exception.basic.no_nsfw_channel\");\n public final static BasicDiscordException NO_ENOUGH_RIGHTS = new BasicDiscordException(\"exception.basic.no_enough_rights\");\n public final static BasicDiscordException NO_VOICE_PERMISSION = new BasicDiscordException(\"exception.basic.no_voice_permission\");\n public final static BasicDiscordException NOT_IN_VOCAL_CHANNEL = new BasicDiscordException(\"exception.basic.not_in_vocal_channel\");\n public final static BasicDiscordException NOT_USABLE_IN_MP = new BasicDiscordException(\"exception.basic.not_usable_in_mp\");\n public final static BasicDiscordException UNKNOWN_ERROR = new BasicDiscordException(\"exception.basic.unknown_error\");\n public final static BasicDiscordException USER_NEEDED = new BasicDiscordException(\"exception.basic.user_needed\");\n public final static BasicDiscordException VOICE_CHANNEL_LIMIT = new BasicDiscordException(\"exception.basic.voice_channel_limit\");\n private String messageKey;\n\n private BasicDiscordException(String message){\n this.messageKey = message;\n }\n @Override\n public void throwException(Message message, Command command, Language lg, Object... arguments) {\n message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, messageKey))).subscribe();\n }\n}", "public interface DiscordException {\n\n void throwException(Message message, Command command, Language lg, Object... arguments);\n}", "public class Reporter {\n\n private static Logger LOG = LoggerFactory.getLogger(Reporter.class);\n private static Reporter instance = null;\n\n private final static String GUILD = \"Guild\";\n private final static String CHANNEL = \"Channel\";\n private final static String USER = \"User\";\n private final static String MESSAGE = \"Message\";\n\n\n private Reporter(){\n // Charge Sentry.dsn au cas où\n ClientConfig.getInstance();\n }\n\n private static Reporter getInstance(){\n if (instance == null)\n instance = new Reporter();\n return instance;\n }\n\n /**\n * Rejette une exception dans un salon discord via Sentry. Politique du \"posté uniquement une fois\"\n * @param e Exception à rejeter\n */\n public static void report(Exception e){\n Reporter.getInstance().send(e, null, null, null, null);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param e Exception à rejeter\n * @param guild Guilde d'origine de l'erreur\n */\n public static void report(Exception e, Guild guild){\n Reporter.getInstance().send(e, guild, null, null, null);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param e Exception à rejeter\n * @param channel Salon d'origine de l'erreur\n */\n public static void report(Exception e, Channel channel){\n Reporter.getInstance().send(e, null, channel, null, null);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param exception Exception à rejeter\n * @param user Auteur du message d'origine de l'erreur\n */\n public static synchronized void report(Exception exception, User user){\n Reporter.getInstance().send(exception, null, null, user, null);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param exception Exception à rejeter\n * @param guild Guilde d'origine de l'erreur\n * @param channel Salon d'origine de l'erreur\n */\n public static synchronized void report(Exception exception, Guild guild, Channel channel){\n Reporter.getInstance().send(exception, guild, channel, null, null);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param exception Exception à rejeter\n * @param guild Guilde d'origine de l'erreur\n * @param channel Salon d'origine de l'erreur\n * @param user Auteur du message d'origine de l'erreur\n * @param message Contenu du message à l'origine de l'erreur\n */\n public static synchronized void report(Exception exception, Guild guild, Channel channel, User user, discord4j.core.object.entity.Message message){\n Reporter.getInstance().send(exception, guild, channel, user, message);\n }\n\n /**\n * Rejette une exception dans un salon discord. Politique du \"posté uniquement une fois\"\n * @param exception Exception à rejeter\n * @param guild Guilde d'origine de l'erreur\n * @param channel Salon d'origine de l'erreur\n * @param user Auteur du message d'origine de l'erreur\n * @param message Contenu du message à l'origine de l'erreur\n */\n public void send(Exception exception, Guild guild, Channel channel, User user, discord4j.core.object.entity.Message message){\n try {\n Sentry.getContext().clearTags();\n if (guild != null)\n Sentry.getContext().addTag(GUILD, guild.getId().asString() + \" - \" + guild.getName());\n if (channel != null)\n Sentry.getContext().addTag(CHANNEL, channel.getId().asString() + \" - \" + channel.getId());\n if (user != null)\n Sentry.getContext().addTag(USER, user.getId().asString() + \" - \" + user.getUsername());\n if (message != null)\n Sentry.getContext().addTag(MESSAGE, message.getContent());\n\n Sentry.capture(exception);\n\n } catch(Exception e){\n Sentry.capture(exception);\n LOG.error(\"report\", exception);\n Sentry.capture(e);\n LOG.error(\"report\", e);\n }\n }\n}", "public class Translator {\n\n private final static Logger LOG = LoggerFactory.getLogger(Translator.class);\n private static final int MAX_MESSAGES_READ = 100;\n private static final int MAX_CHARACTER_ACCEPTANCE = 20;\n private static Map<Language, Properties> labels;\n private static LanguageDetector languageDetector;\n\n private static LanguageDetector getLanguageDetector(){\n if (languageDetector == null){\n try {\n List<String> languages = new ArrayList<>();\n for(Language lg : Language.values())\n languages.add(lg.getAbrev().toLowerCase());\n\n List<LanguageProfile> languageProfiles = new LanguageProfileReader().read(languages);\n languageDetector = LanguageDetectorBuilder.create(NgramExtractors.standard())\n .withProfiles(languageProfiles).build();\n }\n catch (IOException e) {\n LOG.error(\"Translator.getLanguageDetector\", e);\n }\n }\n return languageDetector;\n }\n\n /**\n * Fournit la langue utilisée dans un salon textuel\n * @param channel Salon textuel\n * @return Langue de la guilde ou du salon si précisé\n */\n public static Language getLanguageFrom(MessageChannel channel){\n Language result = Constants.defaultLanguage;\n if (channel instanceof GuildMessageChannel) {\n\n Guild guild = Guild.getGuild(((GuildMessageChannel) channel).getGuild().block());\n result = guild.getLanguage();\n ChannelLanguage channelLanguage = ChannelLanguage.getChannelLanguages().get(channel.getId().asLong());\n if (channelLanguage != null)\n result = channelLanguage.getLang();\n }\n return result;\n }\n public static Language getLanguageFrom(RestChannel channel) {\n Guild guild = Guild.getGuilds().get(channel.getData().block().guildId().get().asString());\n Language result = guild.getLanguage();\n\n ChannelLanguage channelLanguage = ChannelLanguage.getChannelLanguages().get(channel.getData().block().id().asLong());\n if (channelLanguage != null)\n result = channelLanguage.getLang();\n\n return result;\n }\n\n /**\n * Génère une liste de source formatée à partir d'un salon textuel\n * @param channel Salon d'origine\n * @return Liste de message éligibles à une reconnaissance de langue\n */\n private static List<String> getReformatedMessages(MessageChannel channel){\n List<String> result = new ArrayList<>();\n\n if (channel != null) {\n try {\n List<Message> messages = channel.getMessagesBefore(Snowflake.of(Instant.now()))\n .take(MAX_MESSAGES_READ).collectList().blockOptional().orElse(Collections.emptyList());\n for (Message message : messages) {\n String content = message.getContent().replaceAll(\":\\\\w+:\", \"\").trim();\n if (content.length() > MAX_CHARACTER_ACCEPTANCE)\n result.add(content);\n }\n } catch (Exception e){\n LOG.warn(\"Impossible to gather data from \" + channel.getId().asString());\n }\n }\n return result;\n }\n\n private static List<String> getReformatedMessages(RestChannel channel){\n List<String> result = new ArrayList<>();\n\n if (channel != null) {\n try {\n List<MessageData> messages = channel.getMessagesBefore(Snowflake.of(Instant.now()))\n .take(MAX_MESSAGES_READ).collectList().blockOptional().orElse(Collections.emptyList());\n for (MessageData message : messages) {\n String content = message.content().replaceAll(\":\\\\w+:\", \"\").trim();\n if (content.length() > MAX_CHARACTER_ACCEPTANCE)\n result.add(content);\n }\n } catch (Exception e){\n LOG.warn(\"Impossible to gather data from rest channel\");\n }\n }\n return result;\n }\n\n /**\n * Détermine une langue à partir d'une source textuelle\n * @param source Source textuelle\n * @return Langue majoritaire détectée au sein de la source\n */\n private static Language getLanguageFrom(String source){\n TextObject textObject = CommonTextObjectFactories.forDetectingOnLargeText().forText(source);\n LdLocale lang = getLanguageDetector().detect(textObject)\n .or(LdLocale.fromString(Constants.defaultLanguage.getAbrev().toLowerCase()));\n\n for(Language lg : Language.values())\n if(lang.getLanguage().equals(lg.getAbrev().toLowerCase()))\n return lg;\n return Constants.defaultLanguage;\n }\n\n /**\n * Détecte la langue majoritaire utilisée dans un salon textuel\n * @param channel Salon textuel à étudier\n * @return Langue majoritaire (ou Constants.defaultLanguage si non trouvée)\n */\n public static Language detectLanguage(GuildMessageChannel channel){\n Language result = Constants.defaultLanguage;\n Map<Language, LanguageOccurrence> languages = new HashMap<>();\n for(Language lang : Language.values())\n languages.put(lang, LanguageOccurrence.of(lang));\n\n List<String> sources = getReformatedMessages(channel);\n for (String source : sources)\n languages.get(getLanguageFrom(source)).increment();\n\n int longest = languages.values().stream()\n .mapToInt(LanguageOccurrence::getOccurrence)\n .max()\n .orElse(-1);\n\n if (longest > 0){\n List<Language> languagesSelected = languages.values().stream()\n .filter(lo -> lo.getOccurrence() == longest)\n .map(LanguageOccurrence::getLanguage)\n .collect(Collectors.toList());\n if (! languagesSelected.contains(result))\n return languagesSelected.get(0);\n }\n\n return result;\n }\n\n /**\n * Fournit un libellé dans la langue choisi, pour un code donné\n * @param lang Language du libellé\n * @param property code du libellé\n * @return Libellé correspondant au code, dans la langue choisie\n */\n public synchronized static String getLabel(Language lang, String property){\n if (labels == null){\n labels = new ConcurrentHashMap<>();\n\n for(Language language : Language.values())\n try(InputStream file = Translator.class.getResourceAsStream(\"/label_\" + language.getAbrev())) {\n Properties prop = new Properties();\n prop.load(new BufferedReader(new InputStreamReader(file, StandardCharsets.UTF_8)));\n labels.put(language, prop);\n } catch (IOException e) {\n LOG.error(\"Translator.getLabel\", e);\n }\n }\n\n String value = labels.get(lang).getProperty(property);\n if (value == null || value.trim().isEmpty())\n if (Constants.defaultLanguage != lang) {\n LOG.warn(\"Missing label in \" + lang.getAbrev() + \" : \" + property);\n return getLabel(Constants.defaultLanguage, property);\n }\n else\n return property;\n return value;\n }\n\n /**\n * Classe dédiée à la détection de la langue la plus utilisée au sein d'un salon textuel\n */\n private static class LanguageOccurrence {\n private final static LanguageOccurrence DEFAULT_LANGUAGE = of(Constants.defaultLanguage);\n private final static int DEFAULT_VALUE = 0;\n private Language language;\n private int occurrence;\n\n private LanguageOccurrence(Language language, int occurrence){\n this.language = language;\n this.occurrence = occurrence;\n }\n\n private static LanguageOccurrence of(Language language){\n return new LanguageOccurrence(language, DEFAULT_VALUE);\n }\n\n public Language getLanguage(){\n return language;\n }\n\n private int getOccurrence(){\n return occurrence;\n }\n\n private void increment(){\n occurrence++;\n }\n\n public boolean equals(LanguageOccurrence lgo){\n return language.equals(lgo.language);\n }\n }\n}" ]
import data.Constants; import data.Guild; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.*; import discord4j.core.object.entity.channel.GuildMessageChannel; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.core.object.entity.channel.PrivateChannel; import discord4j.core.object.entity.channel.TextChannel; import discord4j.rest.util.Permission; import discord4j.rest.util.PermissionSet; import enums.Language; import exceptions.BadUseCommandDiscordException; import exceptions.BasicDiscordException; import exceptions.DiscordException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.Reporter; import util.Translator; import java.util.regex.Matcher; import java.util.regex.Pattern;
package commands.model; /** * Created by steve on 14/07/2016. */ public abstract class AbstractCommand implements Command { private final static Logger LOG = LoggerFactory.getLogger(AbstractCommand.class); protected String name; protected String pattern; protected DiscordException badUse; private boolean isPublic; private boolean isUsableInMP; private boolean isAdmin; private boolean isHidden; protected AbstractCommand(String name, String pattern){ super(); this.name = name; this.pattern = pattern; this.isPublic = true; this.isUsableInMP = true; this.isAdmin = false; this.isHidden = false; badUse = new BadUseCommandDiscordException(); } @Override public final void request(MessageCreateEvent event, Message message) { Language lg = Translator.getLanguageFrom(message.getChannel().block()); try { Matcher m = getMatcher(message); boolean isFound = m.find(); // Caché si la fonction est désactivée/réservée aux admin et que l'auteur n'est pas super-admin if ((!isPublic() || isAdmin()) && message.getAuthor()
.map(user -> user.getId().asLong() != Constants.authorId).orElse(false))
0
ScreamingHawk/fate-sheets
app/src/main/java/link/standen/michael/fatesheets/adapter/CoreCharacterEditSectionAdapter.java
[ "public class CharacterEditAspectsFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\treturn inflater.inflate(R.layout.character_edit_aspects, container, false);\n\t}\n\n\t@Override\n\tpublic void onViewCreated(View rootView, Bundle savedInstanceState) {\n\n\t\tCharacter character = getCharacter();\n\n\t\t// High Concept\n\t\tTextView view = (TextView) rootView.findViewById(R.id.high_concept);\n\t\tview.addTextChangedListener(new TextWatcher() {\n\t\t\t@Override\n\t\t\tpublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}\n\n\t\t\t@Override\n\t\t\tpublic void onTextChanged(CharSequence s, int start, int before, int count) {}\n\n\t\t\t@Override\n\t\t\tpublic void afterTextChanged(Editable s) {\n\t\t\t\tgetCharacter().setHighConcept(s.toString());\n\t\t\t}\n\t\t});\n\t\tview.setText(character.getHighConcept());\n\t\t// Trouble\n\t\tview = (TextView) rootView.findViewById(R.id.trouble);\n\t\tview.addTextChangedListener(new TextWatcher() {\n\t\t\t@Override\n\t\t\tpublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}\n\n\t\t\t@Override\n\t\t\tpublic void onTextChanged(CharSequence s, int start, int before, int count) {}\n\n\t\t\t@Override\n\t\t\tpublic void afterTextChanged(Editable s) {\n\t\t\t\tgetCharacter().setTrouble(s.toString());\n\t\t\t}\n\t\t});\n\t\tview.setText(character.getTrouble());\n\n\t\t// Aspects\n\t\tFragment childFragment = new AspectFragment();\n\t\tFragmentTransaction transaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.aspect_container, childFragment).commit();\n\t}\n\n\t/**\n\t * Class for managing aspects.\n\t */\n\tpublic static class AspectFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tView rootView = inflater.inflate(R.layout.character_edit_aspects_aspect, container, false);\n\n\t\t\t// Aspects\n\t\t\tfinal DeletableStringArrayAdapter aspectListAdapter = new DeletableStringArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.character_edit_aspects_list_item, getCharacter().getAspects());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.aspect_list)).setAdapter(aspectListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_aspect).setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tgetCharacter().getAspects().add(\"\");\n\t\t\t\t\taspectListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n}", "public class CharacterEditDescriptionFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\tView rootView = inflater.inflate(R.layout.character_edit_description, container, false);\n\n\t\tCharacter character = getCharacter();\n\n\t\t// Name\n\t\tTextView view = (TextView) rootView.findViewById(R.id.name);\n\t\tview.addTextChangedListener(new TextWatcher() {\n\t\t\t@Override\n\t\t\tpublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}\n\n\t\t\t@Override\n\t\t\tpublic void onTextChanged(CharSequence s, int start, int before, int count) {}\n\n\t\t\t@Override\n\t\t\tpublic void afterTextChanged(Editable s) {\n\t\t\t\tgetCharacter().setName(s.toString());\n\t\t\t}\n\t\t});\n\t\tview.setText(character.getName());\n\t\t// Description\n\t\tview = (TextView) rootView.findViewById(R.id.description);\n\t\tview.addTextChangedListener(new TextWatcher() {\n\t\t\t@Override\n\t\t\tpublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}\n\n\t\t\t@Override\n\t\t\tpublic void onTextChanged(CharSequence s, int start, int before, int count) {}\n\n\t\t\t@Override\n\t\t\tpublic void afterTextChanged(Editable s) {\n\t\t\t\tgetCharacter().setDescription(s.toString());\n\t\t\t}\n\t\t});\n\t\tview.setText(character.getDescription());\n\t\t// Fate Points\n\t\tfinal TextView fatePoints = (TextView) rootView.findViewById(R.id.fate_points);\n\t\tfatePoints.setText(character.getFatePoints().toString());\n\t\trootView.findViewById(R.id.fate_points_up).setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tgetCharacter().incrementFatePoints();\n\t\t\t\tfatePoints.setText(getCharacter().getFatePoints().toString());\n\t\t\t}\n\t\t});\n\t\trootView.findViewById(R.id.fate_points_down).setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tgetCharacter().decrementFatePoints();\n\t\t\t\tfatePoints.setText(getCharacter().getFatePoints().toString());\n\t\t\t}\n\t\t});\n\n\t\treturn rootView;\n\t}\n}", "public class CoreCharacterEditSkillsFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\treturn inflater.inflate(R.layout.core_character_edit_skills, container, false);\n\t}\n\n\t@Override\n\tpublic void onViewCreated(View view, Bundle savedInstanceState) {\n\t\t// Skill\n\t\tFragment childFragment = new SkillFragment();\n\t\tFragmentTransaction transaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.skill_container, childFragment).commit();\n\t}\n\n\t/**\n\t * Class for managing skills.\n\t */\n\tpublic static class SkillFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tCoreCharacter character = getCoreCharacter();\n\n\t\t\tView rootView = inflater.inflate(R.layout.core_character_edit_skills_skill, container, false);\n\n\t\t\t// Skills\n\t\t\tfinal SkillArrayAdapter skillListAdapter = new SkillArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.core_character_edit_skills_list_item, character.getSkills());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.skills_list)).setAdapter(skillListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_skill).setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tgetCoreCharacter().getSkills().add(new Skill(null, \"\"));\n\t\t\t\t\tskillListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Sort\n\t\t\trootView.findViewById(R.id.sort_skills).setOnClickListener(new View.OnClickListener() {\n\n\t\t\t\tboolean sortAlpha = false;\n\n\t\t\t\tComparator<Skill> alphaComparator = new Comparator<Skill>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Skill o1, Skill o2) {\n\t\t\t\t\t\tif (o1 == null || o1.getDescription() == null || o1.getDescription().trim().isEmpty()){\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t} else if (o2 == null || o2.getDescription() == null || o2.getDescription().trim().isEmpty()){\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn o1.getDescription().compareTo(o2.getDescription());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tComparator<Skill> numberComparator = new Comparator<Skill>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int compare(Skill o1, Skill o2) {\n\t\t\t\t\t\tif (o1 == null || o1.getValue() == null){\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t} else if (o2 == null || o2.getValue() == null){\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn o2.getValue().compareTo(o1.getValue());\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tsortAlpha = !sortAlpha;\n\t\t\t\t\tif (sortAlpha){\n\t\t\t\t\t\tCollections.sort(getCoreCharacter().getSkills(), alphaComparator);\n\t\t\t\t\t\tif (v instanceof ImageButton){\n\t\t\t\t\t\t\t((ImageButton) v).setImageResource(R.mipmap.ic_sort_1_black_24dp);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tCollections.sort(getCoreCharacter().getSkills(), numberComparator);\n\t\t\t\t\t\tif (v instanceof ImageButton){\n\t\t\t\t\t\t\t((ImageButton) v).setImageResource(R.mipmap.ic_sort_a_black_24dp);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tskillListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n}", "public class CoreCharacterEditStressFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\treturn inflater.inflate(R.layout.core_character_edit_stress, container, false);\n\t}\n\n\t@Override\n\tpublic void onViewCreated(View view, Bundle savedInstanceState) {\n\t\t// Physical\n\t\tFragment childFragment = new PhysicalStressFragment();\n\t\tFragmentTransaction transaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.physical_stress_container, childFragment).commit();\n\t\t// Mental\n\t\tchildFragment = new MentalStressFragment();\n\t\ttransaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.mental_stress_container, childFragment).commit();\n\t\t// Consequence\n\t\tchildFragment = new ConsequenceFragment();\n\t\ttransaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.consequence_container, childFragment).commit();\n\t}\n\n\t/**\n\t * Class for managing physical stress.\n\t */\n\tpublic static class PhysicalStressFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tCoreCharacter character = getCoreCharacter();\n\n\t\t\tView rootView = inflater.inflate(R.layout.core_character_edit_stress_physical, container, false);\n\n\t\t\t// Physical Stress\n\t\t\tfinal StressArrayAdapter physicalStressListAdapter = new StressArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.character_edit_stress_list_item, character.getPhysicalStress());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.physical_stress_list)).setAdapter(physicalStressListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_physical_stress).setOnClickListener(new View.OnClickListener(){\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tint nextValue = getCoreCharacter().getPhysicalStress().size() + 1;\n\t\t\t\t\tgetCoreCharacter().getPhysicalStress().add(new Stress(nextValue));\n\t\t\t\t\tphysicalStressListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n\n\t/**\n\t * Class for managing mental stress.\n\t */\n\tpublic static class MentalStressFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tCoreCharacter character = getCoreCharacter();\n\n\t\t\tView rootView = inflater.inflate(R.layout.core_character_edit_stress_mental, container, false);\n\n\t\t\tfinal StressArrayAdapter mentalStressListAdapter = new StressArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.character_edit_stress_list_item, character.getMentalStress());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.mental_stress_list)).setAdapter(mentalStressListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_mental_stress).setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tint nextValue = getCoreCharacter().getMentalStress().size() + 1;\n\t\t\t\t\tgetCoreCharacter().getMentalStress().add(new Stress(nextValue));\n\t\t\t\t\tmentalStressListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n\n\t/**\n\t * Class for managing consequences.\n\t */\n\tpublic static class ConsequenceFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tView rootView = inflater.inflate(R.layout.character_edit_stress_consequence, container, false);\n\n\t\t\t// Consequences\n\t\t\tfinal ConsequenceArrayAdapter consequenceListAdapter = new ConsequenceArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.character_edit_consequence_list_item, getCharacter().getConsequences());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.consequence_list)).setAdapter(consequenceListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_consequence).setOnClickListener(new View.OnClickListener(){\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tint nextValue = getCoreCharacter().getConsequences().size() * 2 + 2;\n\t\t\t\t\tgetCoreCharacter().getConsequences().add(new Consequence(nextValue));\n\t\t\t\t\tconsequenceListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n}", "public class CoreCharacterEditStuntsFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\treturn inflater.inflate(R.layout.core_character_edit_stunts, container, false);\n\t}\n\n\t@Override\n\tpublic void onViewCreated(View view, Bundle savedInstanceState) {\n\t\t// Stunt\n\t\tFragment childFragment = new StuntFragment();\n\t\tFragmentTransaction transaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.stunt_container, childFragment).commit();\n\t\t// Extra\n\t\tchildFragment = new ExtraFragment();\n\t\ttransaction = getChildFragmentManager().beginTransaction();\n\t\ttransaction.replace(R.id.extra_container, childFragment).commit();\n\t}\n\n\t/**\n\t * Class for managing stunts.\n\t */\n\tpublic static class StuntFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tView rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);\n\n\t\t\t// Stunts\n\t\t\tfinal DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.character_edit_stunts_list_item, getCharacter().getStunts());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.stunts_list)).setAdapter(stuntListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_stunt).setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tgetCoreCharacter().getStunts().add(\"\");\n\t\t\t\t\tstuntListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n\n\t/**\n\t * Class for managing extras.\n\t */\n\tpublic static class ExtraFragment extends CharacterEditAbstractFragment {\n\n\t\t@Override\n\t\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\n\t\t\tView rootView = inflater.inflate(R.layout.core_character_edit_stunts_extra, container, false);\n\n\t\t\t// Extras\n\t\t\tfinal DeletableStringArrayAdapter extraListAdapter = new DeletableStringArrayAdapter(getContext(),\n\t\t\t\t\tR.layout.core_character_edit_extras_list_item, getCoreCharacter().getExtras());\n\t\t\t((AdapterLinearLayout) rootView.findViewById(R.id.extras_list)).setAdapter(extraListAdapter);\n\n\t\t\trootView.findViewById(R.id.add_extra).setOnClickListener(new View.OnClickListener(){\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tgetCoreCharacter().getExtras().add(\"\");\n\t\t\t\t\textraListAdapter.notifyDataSetChanged();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn rootView;\n\t\t}\n\t}\n}" ]
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import link.standen.michael.fatesheets.R; import link.standen.michael.fatesheets.fragment.CharacterEditAspectsFragment; import link.standen.michael.fatesheets.fragment.CharacterEditDescriptionFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditSkillsFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditStressFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditStuntsFragment;
package link.standen.michael.fatesheets.adapter; /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections. */ public class CoreCharacterEditSectionAdapter extends FragmentPagerAdapter { private final Context context; public CoreCharacterEditSectionAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position) { case 0:
return new CharacterEditDescriptionFragment();
1
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/processors/impl/MetricsAggregationsProccessor.java
[ "public class ElasticEdmEntitySet extends EdmEntitySetImpl {\n\n private ElasticCsdlEntitySet csdlEntitySet;\n private ElasticEdmProvider provider;\n\n /**\n * Initialize fields.\n * \n * @param provider\n * the EDM provider\n * @param container\n * the EDM entity container\n * @param entitySet\n * the EDM entity set\n */\n public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container,\n ElasticCsdlEntitySet entitySet) {\n super(provider, container, entitySet);\n this.provider = provider;\n this.csdlEntitySet = entitySet;\n }\n\n /**\n * Get's index name in Elasticsearch.\n * \n * @return index name\n */\n public String getESIndex() {\n return csdlEntitySet.getESIndex();\n }\n\n /**\n * Get's type name in Elasticsearch.\n * \n * @return type name\n */\n public String getESType() {\n return csdlEntitySet.getESType();\n }\n\n @Override\n public ElasticEdmEntityType getEntityType() {\n EdmEntityType entityType = provider.getEntityType(new FullQualifiedName(\n csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType()));\n return entityType != null ? (ElasticEdmEntityType) entityType\n : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN());\n }\n\n /**\n * Sets index to entity set.\n * \n * @param esIntex\n * ES index\n */\n public void setESIndex(String esIntex) {\n csdlEntitySet.setESIndex(esIntex);\n }\n\n /**\n * Sets type to entity set.\n * \n * @param esType\n * ES type\n */\n public void setESType(String esType) {\n csdlEntitySet.setESType(esType);\n }\n\n /**\n * Override because of if child entity type has name which starts with as\n * parent entity type name, then wrong entity set is returning.\n */\n @Override\n public EdmBindingTarget getRelatedBindingTarget(final String path) {\n if (path == null) {\n return null;\n }\n EdmBindingTarget bindingTarget = null;\n boolean found = false;\n for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings()\n .iterator(); itor.hasNext() && !found;) {\n EdmNavigationPropertyBinding binding = itor.next();\n checkBinding(binding);\n // Replace 'startsWith' to 'equals'\n if (path.equals(binding.getPath())) {\n Target target = new Target(binding.getTarget(), getEntityContainer());\n EdmEntityContainer entityContainer = getEntityContainer(\n target.getEntityContainer());\n try {\n bindingTarget = entityContainer.getEntitySet(target.getTargetName());\n if (bindingTarget == null) {\n throw new EdmException(\"Cannot find EntitySet \" + target.getTargetName());\n }\n } catch (EdmException e) {\n bindingTarget = entityContainer.getSingleton(target.getTargetName());\n if (bindingTarget == null) {\n throw new EdmException(\"Cannot find Singleton \" + target.getTargetName(),\n e);\n }\n } finally {\n found = bindingTarget != null;\n }\n }\n }\n return bindingTarget;\n }\n\n private void checkBinding(EdmNavigationPropertyBinding binding) {\n if (binding.getPath() == null || binding.getTarget() == null) {\n throw new EdmException(\n \"Path or Target in navigation property binding must not be null!\");\n }\n }\n\n private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) {\n EdmEntityContainer entityContainer = edm.getEntityContainer(containerName);\n if (entityContainer == null) {\n throw new EdmException(\"Cannot find entity container with name: \" + containerName);\n }\n return entityContainer;\n }\n\n}", "public class MetricsAggregationsParser\n extends SingleResponseParser<EdmEntityType, AbstractEntityCollection> {\n\n private String countAlias;\n\n /**\n * Constructor.\n * \n * @param countAlias\n * name of count alias, or null if no count option applied\n */\n public MetricsAggregationsParser(String countAlias) {\n this.countAlias = countAlias;\n }\n\n @Override\n public InstanceData<EdmEntityType, AbstractEntityCollection> parse(SearchResponse response,\n ElasticEdmEntitySet entitySet) {\n ElasticEdmEntityType entityType = entitySet.getEntityType();\n Entity entity = new Entity();\n Aggregations aggs = response.getAggregations();\n if (aggs != null) {\n aggs.asList().stream().filter(SingleValue.class::isInstance)\n .map(SingleValue.class::cast)\n .map(aggr -> createProperty(aggr.getName(), aggr.value(), entityType))\n .forEach(entity::addProperty);\n }\n addCountIfNeeded(entity, response.getHits().getTotalHits());\n EntityCollection entities = new EntityCollection();\n entities.getEntities().add(entity);\n return new InstanceData<>(entityType, entities);\n }\n\n /**\n * Creates {@link Property} with {@link #countAlias} name if $count was in\n * URL.\n *\n * @param entity\n * parent entity\n * @param count\n * count value\n */\n protected void addCountIfNeeded(Entity entity, long count) {\n if (countAlias != null) {\n entity.addProperty(new Property(null, countAlias, ValueType.PRIMITIVE, count));\n }\n }\n\n}", "@Getter\npublic class AggregateRequest extends BaseRequest {\n private final String countAlias;\n\n /**\n * Constructor to initialize query and entity.\n *\n * @param query\n * aggregate query\n * @param entitySet\n * the edm entity set\n */\n public AggregateRequest(AggregateQuery query, ElasticEdmEntitySet entitySet) {\n this(query, entitySet, null, null);\n }\n\n /**\n * Constructor to initialize query and entity.\n *\n * @param query\n * aggregate query\n * @param entitySet\n * the edm entity set\n * @param countAlias\n * name of count alias, or null if no count option applied\n */\n public AggregateRequest(AggregateQuery query, ElasticEdmEntitySet entitySet,\n String countAlias) {\n this(query, entitySet, null, countAlias);\n }\n\n /**\n * Constructor to initialize query and entity.\n *\n * @param query\n * aggregate query\n * @param entitySet\n * the edm entity set\n * @param pagination\n * pagination information\n */\n public AggregateRequest(AggregateQuery query, ElasticEdmEntitySet entitySet,\n Pagination pagination) {\n this(query, entitySet, pagination, null);\n }\n\n /**\n * Constructor to initialize query and entity.\n * \n * @param query\n * aggregate query\n * @param entitySet\n * the edm entity set\n * @param pagination\n * pagination information\n * @param countAlias\n * name of count alias, or null if no count option applied\n */\n public AggregateRequest(AggregateQuery query, ElasticEdmEntitySet entitySet,\n Pagination pagination, String countAlias) {\n super(query, entitySet, pagination);\n this.countAlias = countAlias;\n }\n\n @Override\n public SearchResponse execute() throws ODataApplicationException {\n return ESClient.getInstance().executeRequest(getQuery());\n }\n\n @Override\n public AggregateQuery getQuery() {\n return (AggregateQuery) super.getQuery();\n }\n\n}", "public interface ESRequest {\n\n /**\n * Gets query.\n * \n * @return query\n */\n Query getQuery();\n\n /**\n * Gets pagination.\n *\n * @return pagination\n */\n Pagination getPagination();\n\n /**\n * Gets entity set.\n * \n * @return the edm entity set\n */\n ElasticEdmEntitySet getEntitySet();\n\n /**\n * Executes request and returns search response.\n * \n * @return found data\n * @throws ODataApplicationException\n * if any error appeared during executing request\n */\n SearchResponse execute() throws ODataApplicationException;\n\n}", "public class MetricsAggregationsRequestCreator extends AbstractAggregationsRequestCreator {\n\n /**\n * Default constructor.\n */\n public MetricsAggregationsRequestCreator() {\n super();\n }\n\n /**\n * Constructor to initialize ES query builder.\n * \n * @param queryBuilder\n * ES query builder\n */\n public MetricsAggregationsRequestCreator(ESQueryBuilder<?> queryBuilder) {\n super(queryBuilder);\n }\n\n @Override\n public AggregateRequest create(UriInfo uriInfo) throws ODataApplicationException {\n ESRequest baseRequestInfo = getBaseRequestInfo(uriInfo);\n Query baseQuery = baseRequestInfo.getQuery();\n ElasticEdmEntitySet entitySet = baseRequestInfo.getEntitySet();\n\n List<Aggregate> aggregations = getAggregations(uriInfo.getApplyOption());\n List<AggregationBuilder> metricsQueries = getMetricsAggQueries(aggregations);\n\n AggregateQuery aggregateQuery = new AggregateQuery(baseQuery.getIndex(),\n baseQuery.getTypes(), baseQuery.getQueryBuilder(), metricsQueries,\n Collections.emptyList());\n return new AggregateRequest(aggregateQuery, entitySet, getCountAlias());\n }\n\n}", "public abstract class AbstractESCollectionProcessor\n extends AbstractESReadProcessor<EdmEntityType, AbstractEntityCollection> {\n\n @Override\n protected SerializerResult serialize(ODataSerializer serializer,\n InstanceData<EdmEntityType, AbstractEntityCollection> data,\n ElasticEdmEntitySet entitySet, UriInfo uriInfo) throws SerializerException {\n String id = request.getRawBaseUri() + \"/\" + entitySet.getEntityType();\n ExpandOption expand = uriInfo.getExpandOption();\n SelectOption select = uriInfo.getSelectOption();\n CountOption count = uriInfo.getCountOption();\n return serializer.entityCollection(serviceMetadata, data.getType(), data.getValue(),\n EntityCollectionSerializerOptions.with()\n .contextURL(createContextUrl(entitySet, false, expand, select, null)).id(id)\n .count(count).select(select).expand(expand).build());\n }\n\n}", "@AllArgsConstructor\n@Getter\npublic class InstanceData<T, V> {\n\n private final T type;\n private final V value;\n\n}" ]
import org.apache.olingo.commons.api.data.AbstractEntityCollection; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.api.uri.UriInfo; import org.elasticsearch.action.search.SearchResponse; import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.elastic.parsers.MetricsAggregationsParser; import com.hevelian.olastic.core.elastic.requests.AggregateRequest; import com.hevelian.olastic.core.elastic.requests.ESRequest; import com.hevelian.olastic.core.elastic.requests.creators.MetricsAggregationsRequestCreator; import com.hevelian.olastic.core.processors.AbstractESCollectionProcessor; import com.hevelian.olastic.core.processors.data.InstanceData;
package com.hevelian.olastic.core.processors.impl; /** * Custom Elastic processor for handling metrics aggregations. * * @author rdidyk */ public class MetricsAggregationsProccessor extends AbstractESCollectionProcessor { private String countAlias; @Override protected ESRequest createRequest(UriInfo uriInfo) throws ODataApplicationException { AggregateRequest request = new MetricsAggregationsRequestCreator().create(uriInfo); countAlias = request.getCountAlias(); return request; } @Override protected InstanceData<EdmEntityType, AbstractEntityCollection> parseResponse(
SearchResponse response, ElasticEdmEntitySet entitySet) {
0
hufeiya/CoolSignIn
AndroidClient/app/src/main/java/com/hufeiya/SignIn/net/AsyncHttpHelper.java
[ "public class CategorySelectionActivity extends AppCompatActivity {\n\n private static final String EXTRA_PLAYER = \"player\";\n private User user;\n\n public static void start(Activity activity, User user, ActivityOptionsCompat options) {\n Intent starter = getStartIntent(activity, user);\n ActivityCompat.startActivity(activity, starter, options.toBundle());\n }\n\n public static void start(Context context, User user) {\n Intent starter = getStartIntent(context, user);\n context.startActivity(starter);\n }\n\n @NonNull\n static Intent getStartIntent(Context context, User user) {\n Intent starter = new Intent(context, CategorySelectionActivity.class);\n starter.putExtra(EXTRA_PLAYER, user);\n return starter;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_category_selection);\n user = getIntent().getParcelableExtra(EXTRA_PLAYER);\n if (!PreferencesHelper.isSignedIn(this) && user != null) {\n PreferencesHelper.writeToPreferences(this, user);\n }\n setUpToolbar(user);\n if (savedInstanceState == null) {\n attachCategoryGridFragment();\n } else {\n setProgressBarVisibility(View.GONE);\n }\n supportPostponeEnterTransition();\n\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n }\n\n public void setUpToolbar(User user) {\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_player);\n setSupportActionBar(toolbar);\n //noinspection ConstantConditions\n getSupportActionBar().setDisplayShowTitleEnabled(false);\n final AvatarView avatarView = (AvatarView) toolbar.findViewById(R.id.avatar);\n avatarView.setAvatar(user.getAvatar().getDrawableId());\n //noinspection PrivateResource\n ((TextView) toolbar.findViewById(R.id.title)).setText(getDisplayName());\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_category, menu);\n return true;\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.category_container);\n if (fragment != null) {\n fragment.onActivityResult(requestCode, resultCode, data);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.sign_out: {\n signOut();\n return true;\n }\n }\n return super.onOptionsItemSelected(item);\n }\n\n @SuppressLint(\"NewApi\")\n private void signOut() {\n AsyncHttpHelper.clearAllCookies();\n\n PreferencesHelper.signOut(this);\n if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {\n getWindow().setExitTransition(TransitionInflater.from(this)\n .inflateTransition(R.transition.category_enter));\n }\n SignInActivity.start(this, false);\n ActivityCompat.finishAfterTransition(this);\n }\n\n private String getDisplayName() {\n JsonUser user = AsyncHttpHelper.user;\n if (user == null){\n return \"登录中...\";\n }\n String type;\n if (user.getUserType()){\n type = \"同学\";\n }else{\n type = \"老师\";\n }\n return user.getUsername() + \" \" + type;\n }\n\n private void attachCategoryGridFragment() {\n FragmentManager supportFragmentManager = getSupportFragmentManager();\n Fragment fragment = supportFragmentManager.findFragmentById(R.id.category_container);\n if (!(fragment instanceof CategorySelectionFragment)) {\n fragment = CategorySelectionFragment.newInstance();\n }\n supportFragmentManager.beginTransaction()\n .replace(R.id.category_container, fragment)\n .commit();\n setProgressBarVisibility(View.GONE);\n }\n\n private void setProgressBarVisibility(int visibility) {\n findViewById(R.id.progress).setVisibility(visibility);\n }\n\n public User getUser(){\n return user;\n }\n}", "public class QuizActivity extends AppCompatActivity implements LocationListener, CameraPreviewfFragment.OnRecognizedFaceListener {\n\n private static final String QI_NIU_DOMAIN = \"http://7xp62n.com1.z0.glb.clouddn.com/\";//the domain to save the photo on Qi Niu\n private static final String TAG = \"QuizActivity\";\n private static final String IMAGE_CATEGORY = \"image_category_\";\n private static final String STATE_IS_PLAYING = \"isPlaying\";\n private static final int REQUEST_CODE_FOR_POSITON = 88;\n private static final int REQUEST_CAMARA_PERMISSION = 89;\n private Location location;\n\n private Interpolator mInterpolator;\n private FloatingActionButton mQuizFab;\n private boolean mSavedStateIsPlaying;\n private View mToolbarBack;\n private static Category category;\n private CourseInfoFragment courseInfoFragment;\n private CameraPreviewfFragment cameraPreviewfFragment;\n private LocationManager locationManager;\n private ProgressBar progressBar;\n private Fragment mContent;\n private boolean isUploading = false;\n private boolean isShootingAccomplished = false;\n private int sid = 0;//signID for student user\n\n\n final View.OnClickListener mOnClickListener = new View.OnClickListener() {\n @Override\n public void onClick(final View v) {\n switch (v.getId()) {\n case R.id.back:\n onBackPressed();\n break;\n case R.id.fab_quiz:\n fabButtonPress();\n break;\n }\n }\n };\n\n public static Intent getStartIntent(Context context, Category category) {\n Intent starter = new Intent(context, QuizActivity.class);\n QuizActivity.category = category;\n return starter;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n mInterpolator = new FastOutSlowInInterpolator();\n if (null != savedInstanceState) {\n mSavedStateIsPlaying = savedInstanceState.getBoolean(STATE_IS_PLAYING);\n }\n super.onCreate(savedInstanceState);\n populate();\n setEnterSharedElementCallback();\n inflateFragment();\n getLocation();\n\n }\n\n private void setEnterSharedElementCallback() {\n int categoryNameTextSize = getResources()\n .getDimensionPixelSize(R.dimen.category_item_text_size);\n int paddingStart = getResources().getDimensionPixelSize(R.dimen.spacing_double);\n final int startDelay = getResources().getInteger(R.integer.toolbar_transition_duration);\n ActivityCompat.setEnterSharedElementCallback(this,\n new TextSharedElementCallback(categoryNameTextSize, paddingStart) {\n @Override\n public void onSharedElementStart(List<String> sharedElementNames,\n List<View> sharedElements,\n List<View> sharedElementSnapshots) {\n super.onSharedElementStart(sharedElementNames,\n sharedElements,\n sharedElementSnapshots);\n mToolbarBack.setScaleX(0f);\n mToolbarBack.setScaleY(0f);\n }\n\n @Override\n public void onSharedElementEnd(List<String> sharedElementNames,\n List<View> sharedElements,\n List<View> sharedElementSnapshots) {\n super.onSharedElementEnd(sharedElementNames,\n sharedElements,\n sharedElementSnapshots);\n // Make sure to perform this animation after the transition has ended.\n ViewCompat.animate(mToolbarBack)\n .setStartDelay(startDelay)\n .scaleX(1f)\n .scaleY(1f)\n .alpha(1f);\n }\n });\n }\n\n\n private void inflateFragment() {\n FragmentTransaction transaction = getFragmentManager().beginTransaction();\n if (AsyncHttpHelper.user.getUserType()) {//student\n if (category.getId().equals(\"addcourse\")) {\n\n } else {\n courseInfoFragment = CourseInfoFragment.newInstance(category.getName());\n transaction.replace(R.id.content, courseInfoFragment);\n }\n\n } else {//teacher\n\n }\n transaction.commit();\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n }\n\n @Override\n public void onSaveInstanceState(@NonNull Bundle outState) {\n outState.putBoolean(STATE_IS_PLAYING, mQuizFab.getVisibility() == View.GONE);\n super.onSaveInstanceState(outState);\n }\n\n @Override\n public void onBackPressed() {\n if (mQuizFab == null) {\n // Skip the animation if icon or fab are not initialized.\n super.onBackPressed();\n return;\n } else if (mContent != null && mContent == cameraPreviewfFragment) {\n switchContent(cameraPreviewfFragment, courseInfoFragment);\n mContent = courseInfoFragment;\n return;\n }\n\n ViewCompat.animate(mToolbarBack)\n .scaleX(0f)\n .scaleY(0f)\n .alpha(0f)\n .setDuration(100)\n .start();\n\n\n ViewCompat.animate(mQuizFab)\n .scaleX(0f)\n .scaleY(0f)\n .setInterpolator(mInterpolator)\n .setStartDelay(100)\n .setListener(new ViewPropertyAnimatorListenerAdapter() {\n @SuppressLint(\"NewApi\")\n @Override\n public void onAnimationEnd(View view) {\n if (isFinishing() ||\n (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.JELLY_BEAN_MR1)\n && isDestroyed())) {\n return;\n }\n QuizActivity.super.onBackPressed();\n }\n })\n .start();\n }\n\n\n @SuppressLint(\"NewApi\")\n public void setToolbarElevation(boolean shouldElevate) {\n if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {\n mToolbarBack.setElevation(shouldElevate ?\n getResources().getDimension(R.dimen.elevation_header) : 0);\n }\n }\n\n\n @SuppressLint(\"NewApi\")\n private void populate() {\n setTheme(category.getTheme().getStyleId());\n if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {\n Window window = getWindow();\n window.setStatusBarColor(ContextCompat.getColor(this,\n category.getTheme().getPrimaryDarkColor()));\n }\n initLayout(category.getId());\n initToolbar(category);\n }\n\n private void initLayout(String categoryId) {\n setContentView(R.layout.activity_quiz);\n progressBar = (ProgressBar) findViewById(R.id.progress);\n mQuizFab = (FloatingActionButton) findViewById(R.id.fab_quiz);\n mQuizFab.setImageResource(R.drawable.ic_play);\n if (mSavedStateIsPlaying) {\n mQuizFab.hide();\n } else {\n mQuizFab.show();\n }\n mQuizFab.setOnClickListener(mOnClickListener);\n }\n\n private void initToolbar(Category category) {\n mToolbarBack = findViewById(R.id.back);\n mToolbarBack.setOnClickListener(mOnClickListener);\n TextView titleView = (TextView) findViewById(R.id.category_title);\n if (category.getName().equals(\"添加课程\")) {\n titleView.setText(category.getName());\n } else {\n titleView.setText(AsyncHttpHelper.user.getJsonCoursesMap().get(Integer.parseInt(category.getName())).getCourseName());\n }\n\n titleView.setTextColor(ContextCompat.getColor(this,\n category.getTheme().getTextPrimaryColor()));\n if (mSavedStateIsPlaying) {\n // the toolbar should not have more elevation than the content while playing\n setToolbarElevation(false);\n }\n }\n\n private void fabButtonPress() {\n if (AsyncHttpHelper.user.getUserType()) {//student user\n if (!category.getId().equals(\"addcourse\")) {\n if (isShootingAccomplished) {\n isShootingAccomplished = false;\n progressBar.setVisibility(View.VISIBLE);\n cameraPreviewfFragment.shooting();\n Toast.makeText(this, \"正在上传哦\", Toast.LENGTH_LONG).show();\n } else if (isRightTimeToSign()) {\n if (this.location == null) {\n Toast.makeText(this, \"还没获取到位置,抱歉蛤\", Toast.LENGTH_SHORT).show();\n } else {\n Log.d(\"quiz\", \"start send location\");\n if (isUploading) {\n Toast.makeText(this, \"正在检查位置哦\", Toast.LENGTH_SHORT).show();\n } else {\n isUploading = true;\n progressBar.setVisibility(View.VISIBLE);\n AsyncHttpHelper.uploadLocation(this, category.getName(), location.getLatitude(), location.getLongitude());\n }\n\n }\n } else {\n Toast.makeText(QuizActivity.this, \"还没到签到时间哦\", Toast.LENGTH_SHORT).show();\n }\n } else {\n\n }\n } else {//teacher user\n if (category.getId().equals(\"addcourse\")) {\n\n } else {\n\n }\n }\n }\n\n private boolean isRightTimeToSign() {\n //TODO\n return true;\n }\n\n\n private void getLocation() {\n locationManager = (LocationManager) MyApplication.getContext().getSystemService(Context.LOCATION_SERVICE);\n if (ActivityCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)\n != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyApplication.getContext(),\n Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(QuizActivity.this, \"我没有位置权限 ( > c < ) \", Toast.LENGTH_SHORT).show();\n String locationPermissions[] = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};\n int currentapiVersion = android.os.Build.VERSION.SDK_INT;\n if (currentapiVersion >= 23) {\n requestPermissions(locationPermissions, REQUEST_CODE_FOR_POSITON);\n }\n return;\n }\n locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);\n locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);\n }\n\n private boolean getCameraPremission() {\n if (ActivityCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.CAMERA)\n != PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(QuizActivity.this, \"我没有拍照权限 ( > c < ) \", Toast.LENGTH_SHORT).show();\n String locationPermissions[] = {Manifest.permission.CAMERA};\n int currentapiVersion = android.os.Build.VERSION.SDK_INT;\n if (currentapiVersion >= 23) {\n requestPermissions(locationPermissions, REQUEST_CAMARA_PERMISSION);\n }\n return false;\n } else {\n return true;\n }\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case REQUEST_CODE_FOR_POSITON:\n if (grantResults.length > 0\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);\n locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);\n\n } else {\n // TODO permission denied, boo! Disable the\n // functionality that depends on this permission.\n }\n break;\n case REQUEST_CAMARA_PERMISSION:\n if (grantResults.length > 0\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n setStateBeforeCameraPreview();\n startCameraPreview();\n }\n }\n\n }\n\n @Override\n public void onLocationChanged(Location location) {\n this.location = location;\n }\n\n //When your location is in the right scale.Called by AsyncHttpHelper.\n public void startSign() {\n if (getCameraPremission()) {\n setStateBeforeCameraPreview();\n startCameraPreview();\n } else {\n //I have no idea.I WANT the CAMERA!\n }\n\n }\n\n private void setStateBeforeCameraPreview() {\n mQuizFab.hide();\n isUploading = false;\n progressBar.setVisibility(View.INVISIBLE);\n }\n\n public void toastNetUnavalible() {\n Toast.makeText(this, \"蛤(-__-),网络连接失败.\", Toast.LENGTH_SHORT).show();\n }\n\n public void startCameraPreview() {\n if (cameraPreviewfFragment == null) {\n cameraPreviewfFragment = CameraPreviewfFragment.newInstance();\n }\n switchContent(courseInfoFragment, cameraPreviewfFragment);\n }\n\n public void switchContent(Fragment from, Fragment to) {\n if (mContent != to) {\n mContent = to;\n FragmentTransaction transaction = getFragmentManager().beginTransaction();\n //.setCustomAnimations(android.R.anim.fade_in, android.R.anim.slide_out_right);\n if (!to.isAdded()) { // 先判断是否被add过\n transaction.hide(from).add(R.id.content, to).commit(); // 隐藏当前的fragment,add下一个到Activity中\n } else {\n transaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个\n }\n }\n }\n\n @Override\n public void onRecognizedFace() {\n isShootingAccomplished = true;\n mQuizFab.show();\n }\n\n @Override\n public void onNotRedcognizedFace() {\n isShootingAccomplished = false;\n mQuizFab.hide();\n }\n\n //When the Photo is taken by CameraPreviewFragment,this method called.\n @Override\n public void onPhotoTaken(byte[] data) {\n Map signInfos = AsyncHttpHelper.user.getJsonCoursesMap().get(Integer.parseInt(category.getName())).getSignInfos();\n Iterator iterator = signInfos.entrySet().iterator();\n while (iterator.hasNext()) {\n sid = (Integer) ((Map.Entry) iterator.next()).getKey();\n }\n AsyncHttpHelper.getUptokenAndUploadPhoto(this, data, Integer.toString(sid));\n }\n\n public void uploadPhotoSuccess() {\n //TODO\n progressBar.setVisibility(View.INVISIBLE);\n Toast.makeText(this, \"上传照片成功咯.开始上传签到信息\", Toast.LENGTH_LONG).show();\n generateSignInfoAndUpload();\n\n }\n\n public void generateSignInfoAndUpload(){\n int cid = Integer.parseInt(category.getName());\n JsonSignInfo jsonSignInfo = AsyncHttpHelper.user.getJsonCoursesMap().get(cid).getSignInfos().get(sid);\n String signDetail = jsonSignInfo.getSignDetail();\n if(signDetail == null || signDetail.equals(\"\")){\n jsonSignInfo.setSignDetail(Long.toString(System.currentTimeMillis()/1000));\n }else{\n jsonSignInfo.setSignDetail(signDetail+\",\"+System.currentTimeMillis()/1000);\n }\n jsonSignInfo.setLastSignPhoto(QI_NIU_DOMAIN + sid);\n jsonSignInfo.setSignTimes(jsonSignInfo.getSignId() + 1);\n AsyncHttpHelper.uploadSignInfo(this,jsonSignInfo);\n }\n\n /**when sign done,The @AsyncHttpHelper calls it.*/\n public void onSignSuccess(){\n Toast.makeText(this, \"签到成功咯!\", Toast.LENGTH_LONG).show();\n }\n\n public void uploadPhotoFail() {\n //TODO\n progressBar.setVisibility(View.INVISIBLE);\n Toast.makeText(this, \"上传照片失败啦抱歉,再试试吧\", Toast.LENGTH_LONG).show();\n }\n\n @Override\n protected void onStop() {\n super.onStop();\n\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n Log.d(\"quiz\", \"onDestory() executed!!\");\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n\n }\n\n\n}", "public class MyApplication extends Application {\n\n private static Context mContext;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mContext = getApplicationContext();\n }\n\n public static Context getContext() {\n return mContext;\n }\n}", "public class CategorySelectionFragment extends Fragment {\n\n private static final int REQUEST_CATEGORY = 0x2300;\n private CategoryAdapter mAdapter;\n public SwipeRefreshLayout swipeRefreshLayout;\n private Drawer drawer;\n\n public static CategorySelectionFragment newInstance() {\n return new CategorySelectionFragment();\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_categories, container, false);\n\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n final User user = ((CategorySelectionActivity)getActivity()).getUser();\n swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipe_refresh_layout);\n swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n\n AsyncHttpHelper.refrash(user.getPhone(), user.getPass(), CategorySelectionFragment.this);\n }\n });\n setUpQuizGrid((RecyclerView) view.findViewById(R.id.categories));\n swipeRefreshLayout.post(new Runnable() {\n @Override\n public void run() {\n swipeRefreshLayout.setRefreshing(true);\n }\n });\n AsyncHttpHelper.refrash(user.getPhone(), user.getPass(), CategorySelectionFragment.this);\n super.onViewCreated(view, savedInstanceState);\n }\n\n private void setUpQuizGrid(RecyclerView categoriesView) {\n final int spacing = getContext().getResources()\n .getDimensionPixelSize(R.dimen.spacing_nano);\n categoriesView.addItemDecoration(new OffsetDecoration(spacing));\n mAdapter = new CategoryAdapter(getActivity());\n mAdapter.setOnItemClickListener(\n new CategoryAdapter.OnItemClickListener() {\n @Override\n public void onClick(View v, int position) {\n Activity activity = getActivity();\n startQuizActivityWithTransition(activity,\n v.findViewById(R.id.category_title),\n mAdapter.getItem(position));\n }\n });\n categoriesView.setAdapter(mAdapter);\n }\n\n @Override\n public void onResume() {\n getActivity().supportStartPostponedEnterTransition();\n super.onResume();\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n if (requestCode == REQUEST_CATEGORY && resultCode == R.id.solved) {\n mAdapter.notifyItemChanged(data.getStringExtra(JsonAttributes.ID));\n }\n super.onActivityResult(requestCode, resultCode, data);\n }\n\n private void startQuizActivityWithTransition(Activity activity, View toolbar,\n Category category) {\n\n final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, false,\n new Pair<>(toolbar, activity.getString(R.string.transition_toolbar)));\n @SuppressWarnings(\"unchecked\")\n ActivityOptionsCompat sceneTransitionAnimation = ActivityOptionsCompat\n .makeSceneTransitionAnimation(activity, pairs);\n\n // Start the activity with the participants, animating from one to the other.\n final Bundle transitionBundle = sceneTransitionAnimation.toBundle();\n Intent startIntent = QuizActivity.getStartIntent(activity, category);\n ActivityCompat.startActivityForResult(activity,\n startIntent,\n REQUEST_CATEGORY,\n transitionBundle);\n }\n public void toastLoginFail(String failType){\n if (failType.equals(\"account\")){\n Toast.makeText(getActivity(), \"蛤 (@[]@!!),你需要重新登录\", Toast.LENGTH_SHORT).show();\n }else if(failType.equals(\"unknown\")){\n Toast.makeText(getActivity(),\"刷新失败, ( ° △ °|||)︴ ,主人请检查下网络\",Toast.LENGTH_SHORT).show();\n }else if (failType.equals(\"json\")){\n Toast.makeText(getActivity(),\"json解析错误,这是个bug额(⊙o⊙)…\",Toast.LENGTH_SHORT).show();\n }\n\n }\n public CategoryAdapter getmAdapter(){\n return mAdapter;\n }\n\n public void setDrawer(){\n if (drawer != null){\n return;\n }\n JsonUser user = AsyncHttpHelper.user;\n if (user.getUserType()){\n setStudentDrawer(user);\n }else{\n setTeacherDrawer(user);\n }\n\n }\n private void setStudentDrawer(JsonUser user){\n // Create the AccountHeader\n AccountHeader headerResult = new AccountHeaderBuilder()\n .withActivity(getActivity())\n .withHeaderBackground(new ColorDrawable(Color.BLUE))\n .addProfiles(\n new ProfileDrawerItem().withName(user.getUsername()).withEmail(user.getUserNo()).\n withIcon(getResources().getDrawable(R.drawable.avatar_10))\n )\n .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {\n @Override\n public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {\n return false;\n }\n })\n .build();\n PrimaryDrawerItem index = new PrimaryDrawerItem().withName(\"主页\");\n SecondaryDrawerItem mySignItem = new SecondaryDrawerItem().withName(\"我的签到\");\n\n\n//create the drawer and remember the `Drawer` result object\n drawer = new DrawerBuilder()\n .withAccountHeader(headerResult)\n .withActivity(getActivity())\n .addDrawerItems(\n index,\n new DividerDrawerItem(),\n mySignItem\n )\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n // do something with the clicked item :D\n return true;\n }\n })\n .build();\n }\n private void setTeacherDrawer(JsonUser user){\n // Create the AccountHeader\n AccountHeader headerResult = new AccountHeaderBuilder()\n .withActivity(getActivity())\n .withHeaderBackground(new ColorDrawable(Color.BLUE))\n .addProfiles(\n new ProfileDrawerItem().withName(user.getUsername()).withEmail(user.getUserNo()).\n withIcon(getResources().getDrawable(R.drawable.avatar_10))\n )\n .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {\n @Override\n public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {\n return false;\n }\n })\n .build();\n PrimaryDrawerItem index = new PrimaryDrawerItem().withName(\"主页\");\n SecondaryDrawerItem studentSheetItem = new SecondaryDrawerItem().withName(\"学生名单\");\n\n\n//create the drawer and remember the `Drawer` result object\n drawer = new DrawerBuilder()\n .withAccountHeader(headerResult)\n .withActivity(getActivity())\n .addDrawerItems(\n index,\n new DividerDrawerItem(),\n studentSheetItem\n )\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n // do something with the clicked item :D\n return true;\n }\n })\n .build();\n }\n}", "public class SignInFragment extends Fragment {\n\n private static final String ARG_EDIT = \"EDIT\";\n private static final String KEY_SELECTED_AVATAR_INDEX = \"selectedAvatarIndex\";\n private User mUser;\n private EditText phone;\n private EditText pass;\n private Avatar mSelectedAvatar = Avatar.ONE;\n private View mSelectedAvatarView;\n private GridView mAvatarGrid;\n private FloatingActionButton mDoneFab;\n private boolean edit;\n public ProgressBar progressBar;\n\n public static SignInFragment newInstance(boolean edit) {\n Bundle args = new Bundle();\n args.putBoolean(ARG_EDIT, edit);\n SignInFragment fragment = new SignInFragment();\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n if (savedInstanceState != null) {\n int savedAvatarIndex = savedInstanceState.getInt(KEY_SELECTED_AVATAR_INDEX);\n mSelectedAvatar = Avatar.values()[savedAvatarIndex];\n }\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,\n @Nullable Bundle savedInstanceState) {\n final View contentView = inflater.inflate(R.layout.fragment_sign_in, container, false);\n contentView.addOnLayoutChangeListener(new View.\n OnLayoutChangeListener() {\n @Override\n public void onLayoutChange(View v, int left, int top, int right, int bottom,\n int oldLeft, int oldTop, int oldRight, int oldBottom) {\n v.removeOnLayoutChangeListener(this);\n setUpGridView(getView());\n }\n });\n return contentView;\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n outState.putInt(KEY_SELECTED_AVATAR_INDEX, mSelectedAvatar.ordinal());\n super.onSaveInstanceState(outState);\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n assurePlayerInit();\n checkIsInEditMode();\n\n if (null == mUser || edit) {\n view.findViewById(R.id.empty).setVisibility(View.GONE);\n view.findViewById(R.id.content).setVisibility(View.VISIBLE);\n initContentViews(view);\n initContents();\n } else {\n final Activity activity = getActivity();\n CategorySelectionActivity.start(activity, mUser);\n activity.finish();\n }\n super.onViewCreated(view, savedInstanceState);\n }\n\n private void checkIsInEditMode() {\n final Bundle arguments = getArguments();\n //noinspection SimplifiableIfStatement\n if (null == arguments) {\n edit = false;\n } else {\n edit = arguments.getBoolean(ARG_EDIT, false);\n }\n }\n\n private void initContentViews(View view) {\n TextWatcher textWatcher = new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n /* no-op */\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n // showing the floating action button if text is entered\n if (s.length() == 0) {\n mDoneFab.hide();\n } else {\n mDoneFab.show();\n }\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n /* no-op */\n }\n };\n progressBar = (ProgressBar)view.findViewById(R.id.empty);\n phone = (EditText) view.findViewById(R.id.phone);\n phone.addTextChangedListener(textWatcher);\n pass = (EditText) view.findViewById(R.id.pass);\n pass.addTextChangedListener(textWatcher);\n mDoneFab = (FloatingActionButton) view.findViewById(R.id.done);\n mDoneFab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n switch (v.getId()) {\n case R.id.done:\n\n\n progressBar.setVisibility(View.VISIBLE);\n\n AsyncHttpHelper.login(phone.getText().toString(),pass.getText().toString(),SignInFragment.this);\n break;\n default:\n throw new UnsupportedOperationException(\n \"The onClick method has not been implemented for \" + getResources()\n .getResourceEntryName(v.getId()));\n }\n }\n });\n\n }\n\n private void removeDoneFab(@Nullable Runnable endAction) {\n ViewCompat.animate(mDoneFab)\n .scaleX(0)\n .scaleY(0)\n .setInterpolator(new FastOutSlowInInterpolator())\n .withEndAction(endAction)\n .start();\n }\n\n private void setUpGridView(View container) {\n mAvatarGrid = (GridView) container.findViewById(R.id.avatars);\n mAvatarGrid.setAdapter(new AvatarAdapter(getActivity()));\n mAvatarGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n mSelectedAvatarView = view;\n mSelectedAvatar = Avatar.values()[position];\n }\n });\n mAvatarGrid.setNumColumns(calculateSpanCount());\n mAvatarGrid.setItemChecked(mSelectedAvatar.ordinal(), true);\n }\n\n\n private void performSignInWithTransition(View v) {\n final Activity activity = getActivity();\n\n final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, true,\n new Pair<>(v, activity.getString(R.string.transition_avatar)));\n @SuppressWarnings(\"unchecked\")\n ActivityOptionsCompat activityOptions = ActivityOptionsCompat\n .makeSceneTransitionAnimation(activity, pairs);\n CategorySelectionActivity.start(activity, mUser, activityOptions);\n }\n\n private void initContents() {\n assurePlayerInit();\n if (null != mUser) {\n phone.setText(mUser.getPhone());\n pass.setText(mUser.getPass());\n mSelectedAvatar = mUser.getAvatar();\n }\n }\n\n private void assurePlayerInit() {\n if (null == mUser) {\n mUser = PreferencesHelper.getPlayer(getActivity());\n }\n }\n\n public void savePlayer(String md5pass) {\n mUser = new User(phone.getText().toString(), md5pass,\n mSelectedAvatar);\n PreferencesHelper.writeToPreferences(getActivity(), mUser);\n }\n\n /**\n * Calculates spans for avatars dynamically.\n *\n * @return The recommended amount of columns.\n */\n private int calculateSpanCount() {\n int avatarSize = getResources().getDimensionPixelSize(R.dimen.size_fab);\n int avatarPadding = getResources().getDimensionPixelSize(R.dimen.spacing_double);\n return mAvatarGrid.getWidth() / (avatarSize + avatarPadding);\n }\n\n public void toastLoginFail(String failType){\n if (failType.equals(\"account\")){\n Toast.makeText(getActivity(),\"蛤 (@[]@!!),账号或密码错误\",Toast.LENGTH_SHORT).show();\n }else if(failType.equals(\"unknown\")){\n Toast.makeText(getActivity(),\"登录失败, ( ° △ °|||)︴ ,主人请检查下网络\",Toast.LENGTH_SHORT).show();\n }else if (failType.equals(\"json\")){\n Toast.makeText(getActivity(),\"json解析错误,这是个bug额(⊙o⊙)…\",Toast.LENGTH_SHORT).show();\n }\n\n }\n public void enterTheCategorySelectionActivity(){\n removeDoneFab(new Runnable() {\n @Override\n public void run() {\n if (null == mSelectedAvatarView) {\n performSignInWithTransition(mAvatarGrid.getChildAt(\n mSelectedAvatar.ordinal()));\n } else {\n performSignInWithTransition(mSelectedAvatarView);\n }\n }\n });\n }\n\n}", "public class JsonSignInfo {\n\n\t// Fields\n\n\tprivate Integer signId;\n\tprivate String studentName;\n\tprivate String studengNo;\n\tprivate String signDetail;\n\tprivate Integer signTimes;\n\tprivate String lastSignPhoto;\n\n\t// Constructors\n\n\t/** default constructor */\n\tpublic JsonSignInfo() {\n\t}\n\n\n\t/** full constructor */\n\tpublic JsonSignInfo(String studentName,String studentNo, String signDetail,\n\t\t\tInteger signTimes, String lastSignPhoto) {\n\t\tthis.setStudentName(studentName);\n\t\tthis.setStudengNo(studentNo);\n\t\tthis.signDetail = signDetail;\n\t\tthis.signTimes = signTimes;\n\t\tthis.lastSignPhoto = lastSignPhoto;\n\t}\n\n\t// Property accessors\n\n\tpublic Integer getSignId() {\n\t\treturn this.signId;\n\t}\n\n\tpublic void setSignId(Integer signId) {\n\t\tthis.signId = signId;\n\t}\n\n\tpublic String getSignDetail() {\n\t\treturn this.signDetail;\n\t}\n\n\tpublic void setSignDetail(String signDetail) {\n\t\tthis.signDetail = signDetail;\n\t}\n\n\tpublic Integer getSignTimes() {\n\t\treturn this.signTimes;\n\t}\n\n\tpublic void setSignTimes(Integer signTimes) {\n\t\tthis.signTimes = signTimes;\n\t}\n\n\tpublic String getLastSignPhoto() {\n\t\treturn this.lastSignPhoto;\n\t}\n\n\tpublic void setLastSignPhoto(String lastSignPhoto) {\n\t\tthis.lastSignPhoto = lastSignPhoto;\n\t}\n\n\n\tpublic String getStudentName() {\n\t\treturn studentName;\n\t}\n\n\n\tpublic void setStudentName(String studentName) {\n\t\tthis.studentName = studentName;\n\t}\n\n\n\tpublic String getStudengNo() {\n\t\treturn studengNo;\n\t}\n\n\n\tpublic void setStudengNo(String studengNo) {\n\t\tthis.studengNo = studengNo;\n\t}\n\n}", "public class JsonUser {\n\n\t// Fields\n\n\tprivate Integer uid;\n\tprivate String username;\n\tprivate String pass;\n\tprivate String userNo;\n\tprivate String phone;\n\tprivate Boolean userType;\n\tprivate Map<Integer, JsonCourse> jsonCoursesMap = new HashMap<Integer, JsonCourse>();\n\t// Constructors\n\n\t/** default constructor */\n\tpublic JsonUser() {\n\t}\n\n\t/** full constructor */\n\tpublic JsonUser(String username, String pass, String userNo, String phone,\n\t\t\tBoolean userType) {\n\t\tthis.username = username;\n\t\tthis.pass = pass;\n\t\tthis.userNo = userNo;\n\t\tthis.phone = phone;\n\t\tthis.userType = userType;\n\t}\n\t\n\n\n\t// Property accessors\n\n\tpublic Integer getUid() {\n\t\treturn this.uid;\n\t}\n\n\tpublic void setUid(Integer uid) {\n\t\tthis.uid = uid;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn this.username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPass() {\n\t\treturn this.pass;\n\t}\n\n\tpublic void setPass(String pass) {\n\t\tthis.pass = pass;\n\t}\n\n\tpublic Map<Integer, JsonCourse> getJsonCoursesMap() {return jsonCoursesMap;}\n\n\tpublic void setJsonCoursesMap(Map<Integer, JsonCourse> jsonCoursesMap) {this.jsonCoursesMap = jsonCoursesMap;}\n\n\tpublic String getUserNo() {\n\t\treturn this.userNo;\n\t}\n\n\tpublic void setUserNo(String userNo) {\n\t\tthis.userNo = userNo;\n\t}\n\n\tpublic String getPhone() {\n\t\treturn this.phone;\n\t}\n\n\tpublic void setPhone(String phone) {\n\t\tthis.phone = phone;\n\t}\n\n\tpublic Boolean getUserType() {\n\t\treturn this.userType;\n\t}\n\n\tpublic void setUserType(Boolean userType) {\n\t\tthis.userType = userType;\n\t}\n\n}" ]
import android.content.Context; import android.util.Log; import android.view.View; import com.google.gson.Gson; import com.hufeiya.SignIn.activity.CategorySelectionActivity; import com.hufeiya.SignIn.activity.QuizActivity; import com.hufeiya.SignIn.application.MyApplication; import com.hufeiya.SignIn.fragment.CategorySelectionFragment; import com.hufeiya.SignIn.fragment.SignInFragment; import com.hufeiya.SignIn.jsonObject.JsonSignInfo; import com.hufeiya.SignIn.jsonObject.JsonUser; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.PersistentCookieStore; import com.loopj.android.http.RequestParams; import com.qiniu.android.http.ResponseInfo; import com.qiniu.android.storage.UpCompletionHandler; import com.qiniu.android.storage.UploadManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import cz.msebera.android.httpclient.Header;
package com.hufeiya.SignIn.net; /** * Created by hufeiya on 15-12-1. */ public class AsyncHttpHelper { private static AsyncHttpClient client = new AsyncHttpClient();
public static JsonUser user;
6
ChristinGorman/baxter
src/test/java/no/gorman/please/timeline/TimelineServletTest.java
[ "public class DB {\n\n private static final Logger log = LoggerFactory.getLogger(DB.class);\n\n\n private final Connection connection;\n final List<Runnable> onSuccessActions = new ArrayList<>(); //to be run when transaction completes successfully\n\n public DB(Connection connection) {\n this.connection = connection;\n }\n\n public <T> List<T> select(Class<T> clazz, Where... whereClause) {\n return select(clazz, new ArrayList<>(), whereClause);\n }\n\n public <T> List<T> select(Class<T> clazz, OrderBy orderBy, Where... whereClause) {\n return select(clazz, asList(orderBy), whereClause);\n }\n\n public <T> Optional<T> selectOnlyOne(Class<T> clazz, Where... where) {\n List<T> results = select(clazz, where);\n if (results.isEmpty()) return Optional.empty();\n if (results.size() > 1) throw new IllegalArgumentException(\"Expected only one value, but got \" + results.size() + \". \" + Arrays.toString(where));\n return Optional.of(results.get(0));\n }\n\n private <T> List<T> select(Class<T> clazz, List<OrderBy> orderBy, Where... whereClause) {\n String select = makeSelect(clazz, orderBy, whereClause);\n\n Set<Table> tables = getTables(clazz, whereClause);\n Collection<Join> joins = new ArrayList<>();\n if (tables.size() > 1) {\n joins.addAll(findJoins(tables));\n joins.forEach(join -> {\n tables.add(join.primary.getTable());\n tables.add(join.foreign.getTable());});\n }\n\n String from = \" FROM \" + join(tables, \", \");\n String where = makeWhere(joins, whereClause);\n String groupBy = makeGroupBy(clazz, orderBy);\n\n List<String> orderByStrings = orderBy.stream().map(by -> by.getColumn().name() + \" \" + by.getOrder()).collect(toList());\n String orderByStr = orderBy.isEmpty() ? \"\" : \"ORDER BY \" + join(orderByStrings, \",\");\n\n String sql = join(asList(select, from, where, groupBy, orderByStr), \" \");\n log.info(sql);\n return runSQL(clazz, sql, createParameterList(whereClause));\n }\n\n public <T> List<T> runSQL(Class<T> clazz, String sql, List<Object> parameters) {\n try (PreparedStatement stmt = connection.prepareStatement(sql)) {\n addParameters(stmt, parameters);\n try (ResultSet result = stmt.executeQuery()) {\n List<T> list = new ArrayList<>();\n while (result.next()) {\n T instance = clazz.newInstance();\n for (Field f : getMappedFields(clazz)) {\n set(f, instance, getValueFromRS(result, getColumn(f)));\n }\n list.add(instance);\n }\n return list;\n }\n } catch (RuntimeException e) {\n log.error(sql);\n throw e;\n } catch (Exception e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n\n public <T> List<T> select(DatabaseColumns column, Class<T> clazz, Where... whereClause) {\n\n if (!column.getFieldClass().isAssignableFrom(clazz)) throw new IllegalArgumentException(column + \" is not of type \" + clazz.getSimpleName());\n String select = \"SELECT DISTINCT \" + column.name();\n Set<Table> tables = getTables(column.getFieldClass(), whereClause);\n tables.add(column.getTable());\n Collection<Join> joins = new ArrayList<>();\n if (tables.size() > 1) {\n joins.addAll(findJoins(tables));\n joins.forEach(join -> {tables.add(join.primary.getTable());tables.add(join.foreign.getTable());});\n }\n\n String from = \" FROM \" + join(tables, \",\");\n String where = makeWhere(joins, whereClause);\n String sql = join(asList(trim(select), trim(from), trim(where)), \" \").replace(\" \", \" \");\n log.info(sql);\n try (PreparedStatement stmt = connection.prepareStatement(sql)) {\n addParameters(stmt, createParameterList(whereClause));\n try (ResultSet result = stmt.executeQuery()) {\n List<T> list = new ArrayList<>();\n while (result.next()) {\n list.add((T)getValueFromRS(result, column));\n }\n return list;\n }\n } catch (RuntimeException e) {\n log.error(sql);\n throw e;\n } catch (Exception e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n public <T> void update(T updated) {\n update(updated, getMainTable(updated));\n }\n\n public <T> void update(final T updated, Table table) {\n List<Field> all = DBFunctions.getMappedFields(updated.getClass());\n\n Optional<Field> versionField = all.stream().filter(f -> getColumn(f).getType() == Version).findFirst();\n versionField.ifPresent(field -> {if (get(field, updated) == null) set(field, updated, 0);});\n\n List<Field> inMainTable = all.stream()\n .filter(f -> getColumn(f).getTable() == table)\n .filter(f -> getColumn(f).getType() != PrimaryKey)\n .collect(toList());\n List<String> setExpressions = inMainTable.stream()\n .map(f -> getColumn(f).name() + \" = ?\")\n .collect(Collectors.toList());\n List<Object> params = inMainTable.stream()\n .map(f -> (getColumn(f).getType() == Version) ? (1 + (int) get(f, updated)) : get(f, updated))\n .collect(toList());\n\n Field pk = all.stream().filter(f -> getColumn(f).getType() == PrimaryKey).findFirst()\n .orElseThrow(() -> new IllegalStateException(\"Cannot update \" + updated.getClass().getName() + \" as it has no primary key field\"));\n\n String pkName = getColumn(pk).name();\n String sql = \"UPDATE \" + table.name() + \" SET \" + join(setExpressions, \", \") + \" WHERE \" + pkName + \" = \" + get(pk, updated);\n if (versionField.isPresent()) {\n String versionName = getColumn(versionField.get()).name();\n sql += \" AND \" + versionName + \" = \" + get(versionField.get(), updated);\n }\n log.info(sql);\n try (PreparedStatement stmt = connection.prepareStatement(sql)) {\n addParameters(stmt, params);\n if (stmt.executeUpdate() == 0) {\n String errorMsg = \"Could not find row in table \" + table + \" with \" + pkName + \" = \" + get(pk, updated);\n if (versionField.isPresent()) {\n errorMsg += \" and \" + getColumn(versionField.get()) + \" = \" + get(versionField.get(), updated);\n throw new ConcurrentModificationException(errorMsg);\n }\n throw new RuntimeException(errorMsg);\n }\n if (versionField.isPresent()) {\n set(versionField.get(), updated, (Integer) (get(versionField.get(), updated)) + 1);\n }\n onSuccessActions.add(() -> BigBrother.informAllAgents(updated));\n } catch (SQLException e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n public void insert(Object... newOnes) {\n asList(newOnes).forEach(obj -> insert(obj, getMainTable(obj)));\n }\n\n public <T> Long insert(final T newInstance, Table table) {\n List<Field> all = DBFunctions.getMappedFields(newInstance.getClass());\n List<Field> inMainTable = all.stream()\n .filter(f -> getColumn(f).getTable() == table)\n .filter(f -> getColumn(f).getType() != PrimaryKey)\n .collect(toList());\n List<String> fieldNames = inMainTable.stream().map(f -> getColumn(f).name()).collect(toList());\n List<String> valueMarkers = fieldNames.stream().map(name -> \"?\").collect(toList());\n List<Object> params = inMainTable.stream()\n .map(f -> get(f, newInstance))\n .collect(toList());\n\n String sql = \"INSERT INTO \" + table.name() + \"(\" + join(fieldNames, \", \") + \") VALUES(\" + join(valueMarkers, \", \") + \")\";\n log.info(sql);\n try (PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {\n addParameters(stmt, params);\n stmt.execute();\n ResultSet newIdRS = stmt.getGeneratedKeys();\n newIdRS.next();\n long newId = newIdRS.getLong(1);\n Optional<Field> pk = all.stream().filter(f -> getColumn(f).getType() == PrimaryKey).findFirst();\n if (pk.isPresent()) {\n set(pk.get(), newInstance, newId);\n }\n onSuccessActions.add(() -> BigBrother.informAllAgents(newInstance));\n return newId;\n } catch (Exception e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n public <T> void delete(Class<T> clazz, Where... where) {\n Table table = getMainTableForClass(clazz);\n Collection<T> deleted = select(clazz, where);\n Optional<DatabaseColumns> pk = DatabaseColumns.getPrimaryKey(table);\n String sql = \"DELETE FROM \" + table.name() + \" \" + makeWhere(new ArrayList<Join>(), where);\n log.info(sql);\n try (PreparedStatement stmt = connection.prepareStatement(sql)) {\n addParameters(stmt, createParameterList(where));\n stmt.execute();\n onSuccessActions.add(() -> BigBrother.informAllAgents(deleted.toArray()));\n } catch (Exception e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Joins a with b via a many-to-many-table-entry.\n * Saves you having to create separate java objects representing each simple many-to-many-join.\n * <p/>\n * example:\n * <p/>\n * Child c = new Child(1);\n * GrownUp g = new GrownUp(2);\n * DB.link(c,g);\n * will first find a many-to-many-relationship table that links the two tables Child and GrownUp : GrownUpChild.\n * it will then run the following SQL-statement:\n * INSERT INTO GrownUpChild(gcChildId, gcGrownUpId) VALUES(1,2);\n *\n */\n public void link(Object from, Object to) {\n manyToManyOperation(from, to, \"INSERT INTO %s (%s, %s) VALUES(?, ?)\");\n }\n\n public void unlink(Object from, Object to) {\n manyToManyOperation(from, to, \"DELETE FROM %s WHERE %s = ? AND %s = ?\");\n }\n\n private void manyToManyOperation(Object from, Object to, String sql) {\n Table manyToMany = findManyToManyTable(from, to).orElseThrow(()-> new IllegalArgumentException(\"No mapping table found between \" + from + \" and \" + to));\n DatabaseColumns fkFrom = DatabaseColumns.getForeignKey(getMainTable(from), manyToMany).orElseThrow(() -> new IllegalArgumentException(\"no foreign keys found for \" + from ));\n DatabaseColumns fkTo = DatabaseColumns.getForeignKey(getMainTable(to), manyToMany).orElseThrow(() -> new IllegalArgumentException(\"no foreign keys found for \" + to ));\n String filledOut = String.format(sql, manyToMany.name(),fkFrom.name(), fkTo.name());\n log.info(filledOut);\n\n try (PreparedStatement stmt = connection.prepareStatement(filledOut)) {\n Long fromId = (Long) getPrimaryKeyField(from).get(from);\n Long toId = (Long) getPrimaryKeyField(to).get(to);\n stmt.setLong(1, fromId);\n stmt.setLong(2, toId);\n stmt.executeUpdate();\n onSuccessActions.add(() -> BigBrother.inform(new BigBrother.RowIdentifier(fkFrom, fromId), to));\n onSuccessActions.add(() -> BigBrother.inform(new BigBrother.RowIdentifier(fkTo, toId), from));\n\n } catch (Exception e) {\n log.error(sql);\n throw new RuntimeException(e);\n }\n }\n\n public static void addParameters(PreparedStatement stmt, List<Object> params) {\n try {\n for (int i = 1; i <= params.size(); i++) {\n Object p = params.get(i-1);\n if (p == null) {\n stmt.setObject(i, null);\n } else if (p instanceof String) {\n stmt.setString(i, (String) p);\n } else if (p instanceof Integer) {\n stmt.setInt(i, (Integer) p);\n } else if (p instanceof Long) {\n stmt.setLong(i, (Long) p);\n } else if (p instanceof LocalDate) {\n stmt.setInt(i, Integer.parseInt(((LocalDate) p).format(YYYY_MM_DD)));\n } else if (p.getClass().isEnum()) {\n stmt.setString(i, ((Enum<?>) p).name());\n } else if (p.getClass() == byte[].class) {\n stmt.setBytes(i, (byte[])p);\n } else {\n throw new IllegalArgumentException(\"No mapping found for \" + p);\n }\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Object getValueFromRS(ResultSet rs, DatabaseColumns col) throws IllegalAccessException, SQLException {\n Class<?> clazz = col.getFieldClass();\n String colName = col.name();\n if (clazz == String.class) {\n return rs.getString(colName);\n } else if (INT_TYPES.contains(clazz)) {\n int intValue = rs.getInt(colName);\n return (rs.wasNull() ? null : intValue);\n } else if (LONG_TYPES.contains(clazz)) {\n long longValue = rs.getLong(colName);\n return (rs.wasNull() ? null : longValue);\n } else if (clazz == LocalDate.class) {\n String dateString = String.valueOf(rs.getInt(colName));\n return (rs.wasNull() ? null : LocalDate.parse(dateString, YYYY_MM_DD));\n } else if (clazz == LocalDateTime.class) {\n Timestamp timestamp = rs.getTimestamp(colName);\n return (rs.wasNull() ? null : timestamp.toLocalDateTime());\n }else if (clazz == byte[].class) {\n byte[] array = rs.getBytes(colName);\n return rs.wasNull() ? null : array;\n } else if (clazz.isEnum()) {\n String enumVal = trim(rs.getString(colName));\n if (!rs.wasNull()) {\n try {\n return Enum.valueOf((Class<? extends Enum>) clazz, enumVal);\n } catch (Exception e) {\n log.error(\"Failed to load \" + clazz + \": \" + e.getMessage());\n }\n }\n return null;\n } else {\n throw new IllegalArgumentException(\"Damn it, didn't find any type for \" + colName + \" with type \" + clazz);\n }\n }\n\n public void commitAndReleaseConnection() {\n try {\n if (connection == null) return;\n if (connection.isClosed()) return;\n connection.commit();\n onSuccessActions.forEach(runnable -> runnable.run());\n onSuccessActions.clear();\n connection.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void rollback() {\n try {\n if (connection == null) return;\n if (connection.isClosed()) return;\n connection.rollback();\n onSuccessActions.clear();\n connection.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n}", "public class DBTestRunner extends BlockJUnit4ClassRunner {\n\n static {\n try {\n Properties props = new Properties();\n props.load(DB.class.getResourceAsStream(\"/baxter.properties\"));\n DB.class.getResourceAsStream(\"/baxter.properties\").close();\n DBFunctions.setupConnectionPool(props.getProperty(\"testdb\"), props.getProperty(\"username\"), props.getProperty(\"password\"), 5);\n } catch (Exception e) {\n e.printStackTrace();\n throw new RuntimeException(\"Could not find properties file baxter.properties on classpath\");\n }\n }\n\n public DBTestRunner(Class<?> klass) throws InitializationError {\n super(klass);\n }\n\n @Override\n public void runChild(FrameworkMethod method, RunNotifier notifier) {\n Connection conn = DBFunctions.getConnection();\n DB db = new DB(conn);\n try {\n conn.setAutoCommit(false);\n setDBField(db);\n super.runChild(method, notifier);\n }catch (Exception e) {\n throw new RuntimeException(e);\n } finally {\n db.rollback();\n }\n }\n\n private void setDBField(DB db) throws IllegalAccessException {\n for (Field f : getTestClass().getJavaClass().getDeclaredFields()) {\n if (f.getType().equals(DB.class)) {\n f.setAccessible(true);\n f.set(null, db);\n return;\n }\n }\n }\n}", "public class Where {\n\n public final DatabaseColumns column;\n public final String operator;\n public final Object value;\n\n public Where(DatabaseColumns column, String operator) {\n this.column = column;\n this.operator = operator;\n this.value = null;\n }\n\n public Where(DatabaseColumns column, String operator, Object value) {\n this.column = column;\n this.operator = operator;\n this.value = value;\n }\n \n @Override\n public String toString() {\n return column.getTable() + \".\" + column.name() + \" \" + operator + \" \" + value;\n }\n}", "public class RegisteredUser implements BigBrother.Spy{\n private static final Logger log = LoggerFactory.getLogger(RegisteredUser.class);\n private GrownUp user;\n private final AtomicReference<Continuation> continuation;\n private final AtomicLong timestamp;\n private Collection<FileItem> uploadedFiles = synchronizedCollection(new ArrayList<>());\n\n public static RegisteredUser getCurrentUser(HttpSession session) {\n return (RegisteredUser) session.getAttribute(LOGGED_IN);\n }\n\n public static void login(HttpSession session, RegisteredUser user) {\n session.setAttribute(LOGGED_IN, user);\n }\n\n public RegisteredUser(GrownUp grownup) {\n this.user = grownup;\n this.timestamp = new AtomicLong(0);\n this.continuation = new AtomicReference<>();\n }\n\n public void resume(Object suspect) {\n log.debug(\"resuming continuation because of updates to \" + suspect);\n Continuation c = continuation.getAndSet(null);\n if (c == null || c.isExpired()) {\n return;\n }\n ServletResponse response = c.getServletResponse();\n response.setContentType(\"text/json;charset=utf-8\");\n print(response, new Gson().toJson(Arrays.asList(suspect)));\n c.complete();\n }\n\n private void print(ServletResponse response, String json) {\n try {\n log.debug(json);\n response.getWriter().print(json);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public GrownUp getGrownup() {\n return user;\n }\n\n public long getGrownUpId() {\n return user.getGrownUpId();\n }\n\n public void waitForChanges(Continuation c) {\n continuation.set(c);\n }\n\n @Override\n public void suspectAltered(Object suspect) {\n resume(suspect);\n }\n\n public void addFiles(Collection<FileItem> uploadedFiles) {\n this.uploadedFiles.addAll(uploadedFiles);\n }\n\n public Collection<FileItem> getAndRemoveUploadedFiles() {\n Collection<FileItem> tmp = new ArrayList<>(this.uploadedFiles);\n uploadedFiles.clear();\n return tmp;\n }\n}", "public class Child implements NameMethods {\n\n public Child() {\n \n }\n\n @Column(column=DatabaseColumns.child_id)\n private Long child_id;\n \n @Column(column=DatabaseColumns.dob)\n private LocalDate DOB;\n\n @Column(column=DatabaseColumns.child_first_name)\n private String child_first_name;\n\n @Column(column=DatabaseColumns.child_middle_name)\n private String child_middle_name;\n\n @Column(column=DatabaseColumns.child_last_name)\n private String child_last_name;\n\n @Column(column=DatabaseColumns.nickname)\n private String nickname;\n\n @Column(column=DatabaseColumns.child_version)\n private int child_version = 0;\n\n @Column(column=DatabaseColumns.color)\n private String color;\n\n @Column(column=DatabaseColumns.child_daycare_id)\n private Long child_daycare_id;\n\n public Long getChildId() {\n return child_id;\n }\n public void setChildId(Long childId) {\n this.child_id = childId;\n }\n public LocalDate getDOB() {\n return DOB;\n }\n public void setDOB(LocalDate dOB) {\n DOB = dOB;\n }\n\n @Override\n public String getFirstName() {\n return child_first_name;\n }\n public void setFirstName(String firstName) {\n this.child_first_name = firstName;\n }\n\n @Override\n public String getMiddleName() {\n return child_middle_name;\n }\n public void setMiddleName(String middleName) {\n this.child_middle_name = middleName;\n }\n\n @Override\n public String getLastName() {\n return child_last_name;\n }\n public void setLastName(String lastName) {\n this.child_last_name = lastName;\n }\n\n @Override\n public String getNickname() {\n return nickname;\n }\n public void setNickname(String nickname) {\n this.nickname = nickname;\n }\n public int getVersion() {\n return child_version;\n }\n public void setVersion(int version) {\n this.child_version = version;\n }\n public String getColor() {\n return color;\n }\n public void setColor(String color) {\n this.color = color;\n }\n\n public Long getDaycareId() {\n return child_daycare_id;\n }\n\n public void setDaycareId(Long daycare) {\n this.child_daycare_id = daycare;\n }\n\n @Override\n public String toString() {\n return nickname + \"(\" + child_version + \")\";\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(child_id, child_version);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Child other = (Child)obj;\n return Objects.equals(other.child_id, child_id) && (Objects.equals(other.child_version, child_version));\n }\n\n public static Child withNickname(String nick) {\n Child child = new Child();\n child.setNickname(nick);\n return child;\n }\n}", "public class DayCareCenter {\n\n @Column(column=DatabaseColumns.daycare_id)\n private Long daycare_id;\n\n @Column(column=DatabaseColumns.daycare_name)\n private String daycare_name;\n\n public DayCareCenter() {\n \n }\n \n public DayCareCenter(String name) {\n daycare_name = name;\n }\n\n public Long getDayCareCenterId() {\n return daycare_id;\n }\n\n public String getDayCareName() {\n return daycare_name;\n }\n\n public void setDayCareName(String dayCareName) {\n daycare_name = dayCareName;\n }\n\n public static DayCareCenter withName(String name) {\n DayCareCenter newOne = new DayCareCenter();\n newOne.setDayCareName(name);\n return newOne;\n }\n}", "public class GrownUp implements NameMethods {\n\n @Column(column=DatabaseColumns.grownup_id)\n private Long grownup_id;\n\n @Column(column=DatabaseColumns.grownup_first_name)\n private String grownup_first_name;\n\n @Column(column=DatabaseColumns.grownup_middle_name)\n private String grownup_middle_name;\n\n @Column(column=DatabaseColumns.grownup_last_name)\n private String grownup_last_name;\n\n @Column(column=DatabaseColumns.telephone)\n private String telephone;\n\n @Column(column=DatabaseColumns.email)\n private String email;\n\n @Column(column=DatabaseColumns.password)\n private String password;\n\n @Column(column=DatabaseColumns.grownup_daycare_id)\n private Long grownup_daycare_id;\n\n @Column(column=DatabaseColumns.daycare_name)\n private String daycare_name;\n\n @Column(column=DatabaseColumns.grownup_version)\n private int grownup_version = 0;\n\n private Set<String> club_id = new HashSet<>();\n\n public Long getGrownUpId() {\n return grownup_id;\n }\n\n public void setGrownUpId(Long grownUpId) {\n grownup_id = grownUpId;\n }\n\n @Override\n public String getFirstName() {\n return grownup_first_name;\n }\n\n public void setFirstName(String grownUpFirstName) {\n grownup_first_name = grownUpFirstName;\n }\n\n @Override\n public String getMiddleName() {\n return grownup_middle_name;\n }\n\n public void setMiddleName(String grownUpMiddleName) {\n grownup_middle_name = grownUpMiddleName;\n }\n\n @Override\n public String getLastName() {\n return grownup_last_name;\n }\n\n public void setLastName(String grownUpLastName) {\n grownup_last_name = grownUpLastName;\n }\n\n public String getTelephone() {\n return telephone;\n }\n\n public void setTelephone(String telephone) {\n this.telephone = telephone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Long getDayCareId() {\n return grownup_daycare_id;\n }\n\n public void setDayCareId(Long dayCareCenterId) {\n this.grownup_daycare_id = dayCareCenterId;\n }\n\n public String getDayCareName() {\n return daycare_name;\n }\n\n public void setVersion(int version){\n this.grownup_version = version;\n }\n\n public int getVersion() {\n return grownup_version;\n }\n\n @Override\n public String getNickname() {\n return getFirstName();\n }\n\n public void addClubs(Collection<String> clubNames) {\n this.club_id.addAll(clubNames);\n }\n}", "public enum DatabaseColumns {\n\n UNDEFINED(null, null),\n\n daycare_id(Long.TYPE, Table.daycare, PrimaryKey),\n daycare_name(String.class, Table.daycare),\n \n child_id(Long.TYPE, Table.child, PrimaryKey),\n\tdob(LocalDate.class, Table.child),\n\tchild_first_name(String.class, Table.child),\n\tchild_middle_name(String.class, Table.child),\n\tchild_last_name(String.class, Table.child),\n\tnickname(String.class, Table.child),\n\tcolor(String.class, Table.child),\n\tchild_daycare_id(Long.TYPE, Table.child, ForeignKey, Table.daycare),\n\tchild_version(Integer.TYPE, Table.child, Version),\n\n\tgc_grownup_id(Long.TYPE, grownup_child, ForeignKey, Table.grownup),\n\tgc_child_id(Long.TYPE, grownup_child, ForeignKey, Table.child),\n\n\tgrownup_id(Long.TYPE, grownup, PrimaryKey),\n\tgrownup_first_name(String.class, Table.grownup),\n grownup_middle_name(String.class, Table.grownup),\n grownup_last_name(String.class, Table.grownup),\n\ttelephone(String.class, Table.grownup),\n\temail(String.class, Table.grownup, 255),\n\tpassword(String.class, Table.grownup),\n grownup_version(Integer.TYPE, Table.grownup, Version),\n grownup_daycare_id(Long.TYPE, Table.grownup, ForeignKey, Table.daycare),\n\n event_id(Long.TYPE, Table.event, PrimaryKey),\n event_name(String.class, Table.event, 500),\n event_time(Long.TYPE, Table.event),\n event_creator(Long.TYPE, Table.event, ForeignKey, Table.grownup),\n\n ec_child_id(Long.TYPE, Table.event_child, ForeignKey, child),\n ec_event_id(Long.TYPE, Table.event_child, ForeignKey, Table.event),\n\n attachment_id(Long.TYPE, Table.attachment, PrimaryKey),\n attachment(byte[].class, Table.attachment),\n thumbnail(byte[].class, Table.attachment),\n attachment_event_id(Long.TYPE, Table.attachment, ForeignKey, Table.event),\n content_type(String.class, Table.attachment, 50),\n\n schedule_id(Long.TYPE, Table.schedule, PrimaryKey),\n schedule_child_id(Long.TYPE, Table.schedule, ForeignKey, Table.child),\n last_event(Long.TYPE, Table.schedule),\n interval(Integer.TYPE, Table.schedule),\n schedule_name(String.class, Table.schedule),\n\n club_id(Long.TYPE, Table.club, PrimaryKey),\n club_name(String.class, Table.club),\n club_color(String.class, Table.club),\n club_daycare_id(Long.TYPE, Table.club, ForeignKey, daycare),\n\n grc_child_id(Long.TYPE, Table.club_child, ForeignKey, child),\n grc_club_id(Long.TYPE, Table.club_child, ForeignKey, club),\n\n grg_grownup_id(Long.TYPE, Table.club_grownup, ForeignKey, grownup),\n grg_club_id(Long.TYPE, Table.club_grownup, ForeignKey, club),\n\n ecl_club_id(Long.TYPE, Table.event_club, ForeignKey, club),\n ecl_event_id(Long.TYPE, Table.event_club, ForeignKey, Table.event);\n\t\n private final Table table;\n private final Table joinedTo;\n private final ColumnType type;\n private final Class<?> clazz;\n private final int length;\n\n private DatabaseColumns(Class<?> clazz, Table table) {\n this(clazz, table, 50);\n }\n\n private DatabaseColumns(Class<?> clazz, Table table, int length) {\n this.clazz = clazz;\n this.table = table;\n type = ColumnType.Field;\n this.joinedTo = null;\n this.length = length;\n }\n\n private DatabaseColumns(Class<?> clazz, Table table, ColumnType type) {\n this.clazz = clazz;\n this.table = table;\n this.type = type;\n this.joinedTo = null;\n this.length = 50;\n }\n \n private DatabaseColumns(Class<?> clazz, Table table, ColumnType type, Table joinedTo) {\n this.clazz = clazz;\n this.table = table;\n this.type = type;\n this.joinedTo = joinedTo;\n this.length = 50;\n }\n\n public Table getTable() {\n return this.table;\n }\n\n public Class<?> getFieldClass() {\n return clazz;\n }\n\n public int getDataLength() {\n return length;\n }\n\n public Table getJoinedTo() {\n return joinedTo;\n }\n\n public ColumnType getType() {\n return type;\n }\n\n public static Optional<DatabaseColumns> getForeignKey(Table primaryKeyTable, Table foreignKeyTable) {\n return asList(values())\n .stream()\n .filter(col -> col.getJoinedTo() == primaryKeyTable && col.getTable() == foreignKeyTable)\n .findFirst();\n }\n\n public static Optional<DatabaseColumns> getPrimaryKey(Table table) {\n return asList(values())\n .stream()\n .filter(c -> (c.getType() == PrimaryKey && c.getTable() == table))\n .findFirst();\n }\n\n public static Collection<DatabaseColumns> incomingReferenceColumns(Table t) {\n Stream<DatabaseColumns> colStream = asList(DatabaseColumns.values()).stream()\n .filter(col -> col.getType() == ForeignKey && col.getJoinedTo() == t);\n return (Collection<DatabaseColumns>)colStream.collect(toList());\n }\n\n public static Collection<DatabaseColumns> getColumnsFor(Table t) {\n Stream<DatabaseColumns> dbStream = asList(DatabaseColumns.values()).stream().filter(c -> c.getTable() == t);\n return (Collection<DatabaseColumns>)dbStream.collect(toList());\n }\n}", "public static final String LOGGED_IN = \"logged_in\";" ]
import com.google.gson.Gson; import no.gorman.database.DB; import no.gorman.database.DBTestRunner; import no.gorman.database.Where; import no.gorman.please.RegisteredUser; import no.gorman.please.common.Child; import no.gorman.please.common.DayCareCenter; import no.gorman.please.common.GrownUp; import org.fest.assertions.Assertions; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.atomic.AtomicReference; import static java.util.Arrays.asList; import static no.gorman.database.DatabaseColumns.*; import static no.gorman.please.LoginServlet.LOGGED_IN; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package no.gorman.please.timeline; @RunWith(DBTestRunner.class) public class TimelineServletTest { Child one = new Child(); Child two = new Child(); Child three = new Child(); Child four = new Child(); GrownUp grownup = new GrownUp();
DayCareCenter daycare = DayCareCenter.withName("test");
5
baishui2004/common_gui_tools
src/main/java/bs/tool/commongui/plugins/more/EscapeCharacterTool.java
[ "public abstract class AbstractGuiJPanel extends JPanel {\n\n private static final long serialVersionUID = 1L;\n\n public AbstractGuiJPanel() {\n }\n\n /**\n * 获取当前面板.\n */\n public JPanel getContextPanel() {\n return this;\n }\n\n /**\n * 给面板增加指定标题及字体的Label.\n */\n public void addJLabel(JPanel panel, String name, Font font) {\n JLabel label = new JLabel(name);\n label.setFont(font);\n panel.add(label);\n }\n\n /**\n * 给面板增加指定标题及字体的Label,并指定布局位置.\n */\n public void addJLabel(JPanel panel, String name, Font font, String layout) {\n JLabel label = new JLabel(name);\n label.setFont(font);\n panel.add(label, layout);\n }\n\n /**\n * 给面板增加指定字体的JTextField.\n */\n public void addJTextField(JPanel panel, JTextField textField, Font font) {\n textField.setFont(font);\n panel.add(textField);\n }\n\n /**\n * 给面板增加指定字体的JTextField,并指定布局位置.\n */\n public void addJTextField(JPanel panel, JTextField textField, Font font, String layout) {\n textField.setFont(font);\n panel.add(textField, layout);\n }\n\n /**\n * 创建指定字体、自动换行的JTextArea.\n */\n public JTextArea createJTextArea(Font font) {\n return createJTextArea(font, \"\");\n }\n\n /**\n * 创建指定字体、自动换行的JTextArea.\n */\n public JTextArea createJTextArea(Font font, String defaultText) {\n JTextArea textArea = new JTextArea(defaultText);\n textArea.setFont(font);\n textArea.setLineWrap(true);\n return textArea;\n }\n\n /**\n * 浏览按钮对于JFileChooser表单选择文件/文件夹的事件.\n */\n public ActionListener buttonBrowseListener(final JFileChooser fileChooser, final JTextField pathTextField) {\n return new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent event) {\n fileChooserBrowse(fileChooser, pathTextField);\n }\n };\n }\n\n /**\n * JFileChooser表单选择文件/文件夹.\n */\n public void fileChooserBrowse(final JFileChooser fileChooser, final JTextField pathTextField) {\n if (fileChooser.showDialog(getContextPanel(), \"确定\") != JFileChooser.CANCEL_OPTION) {\n File selectFile = fileChooser.getSelectedFile();\n if (selectFile != null) {\n pathTextField.setText(selectFile.getAbsolutePath());\n }\n }\n }\n\n /**\n * 图片选择.\n */\n public JFileChooser createImageChooser() {\n return createFileChooser(\"png, jpg, jpeg, gif, bmp\", \"png\", \"jpg\", \"jpeg\", \"gif\", \"bmp\");\n }\n\n /**\n * 文件选择.\n *\n * @param description 描述\n * @param extensions 文件后缀\n * @return\n */\n public JFileChooser createFileChooser(String description, String... extensions) {\n JFileChooser fileChooser = new JFileChooser();\n fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);\n // 不显示所有文件\n fileChooser.setAcceptAllFileFilterUsed(false);\n fileChooser.addChoosableFileFilter(new FileNameExtensionFilter(description, extensions));\n return fileChooser;\n }\n\n /**\n * 给面板增加指定标题、名称、字体及ActionListener的JButton.\n */\n public void addJButton(JPanel panel, String title, String name, Font font, ActionListener listener) {\n JButton button = createJButton(title, name, font);\n button.addActionListener(listener);\n panel.add(button);\n }\n\n /**\n * 给面板增加指定标题、名称、字体及MouseListener的JButton.\n */\n public void addJButton(JPanel panel, String title, String name, Font font, MouseListener listener) {\n JButton button = createJButton(title, name, font);\n button.addMouseListener(listener);\n panel.add(button);\n }\n\n /**\n * 创建指定标题、名称、字体的JButton.\n */\n public JButton createJButton(String title, String name, Font font) {\n JButton button = new JButton(title);\n button.setFont(font);\n button.setName(name);\n return button;\n }\n\n /**\n * 给面板增加指定标题、是否selected、字体及ActionListener的JCheckbox.\n */\n public void addJCheckBox(JPanel panel, String title, boolean isSelected, Font font, ActionListener listener) {\n panel.add(createJCheckBox(title, isSelected, font, listener));\n }\n\n /**\n * 给面板增加指定标题、是否selected、字体及ActionListener的JCheckbox,并指定布局位置.\n */\n public void addJCheckBox(JPanel panel, String title, boolean isSelected, Font font, ActionListener listener,\n String layout) {\n panel.add(createJCheckBox(title, isSelected, font, listener), layout);\n }\n\n /**\n * 获取指定标题、是否selected、字体及ActionListener的JCheckbox.\n */\n public JCheckBox createJCheckBox(String title, boolean isSelected, Font font, ActionListener listener) {\n JCheckBox checkBox = new JCheckBox(title);\n checkBox.setFont(font);\n checkBox.setSelected(isSelected);\n checkBox.addActionListener(listener);\n return checkBox;\n }\n\n /**\n * 给面板增加指定下拉Items、字体及ActionListener的JComboBox.\n */\n public void addJComboBox(JPanel panel, String[] items, Font font, ActionListener listener) {\n panel.add(createJComboBox(items, font, listener));\n }\n\n /**\n * 给面板增加指定下拉Items、字体及ActionListener的JComboBox,并选择特定位置的Item.\n */\n public void addJComboBox(JPanel panel, String[] items, Integer selectIndex, Font font, ActionListener listener) {\n panel.add(createJComboBox(items, selectIndex, font, listener));\n }\n\n /**\n * 给面板增加指定下拉Items、字体及ActionListener的JComboBox,并指定布局位置.\n */\n public void addJComboBox(JPanel panel, String[] items, Font font, ActionListener listener, String layout) {\n panel.add(createJComboBox(items, font, listener), layout);\n }\n\n /**\n * 给面板增加指定下拉Items、字体及ActionListener的JComboBox,并指定布局位置,并选择特定位置的Item.\n */\n public void addJComboBox(JPanel panel, String[] items, Integer selectIndex, Font font, ActionListener listener,\n String layout) {\n panel.add(createJComboBox(items, selectIndex, font, listener), layout);\n }\n\n /**\n * 创建指定下拉Items、字体及ActionListener的JComboBox.\n */\n public JComboBox createJComboBox(String[] items, Font font, ActionListener listener) {\n return createJComboBox(items, 0, font, listener);\n }\n\n /**\n * 创建指定下拉Items、字体及ActionListener的JComboBox,并选择特定位置的Item.\n */\n public JComboBox createJComboBox(String[] items, Integer selectIndex, Font font, ActionListener listener) {\n JComboBox comboBox = new JComboBox();\n comboBox.setFont(font);\n for (int i = 0; i < items.length; i++) {\n comboBox.addItem(items[i]);\n }\n comboBox.setSelectedIndex(selectIndex);\n comboBox.addActionListener(listener);\n return comboBox;\n }\n\n /**\n * 消息提示.\n */\n public void showMessage(String message, String title, int type) {\n JOptionPane.showMessageDialog(this, message, title, type);\n }\n\n /**\n * 消息提示.\n */\n public void showTextAreaMessage(String message, String title, int type, Font font, Color background) {\n JTextArea textArea = new JTextArea(message);\n if (font == null) {\n textArea.setFont(GuiUtils.font14_un);\n } else {\n textArea.setFont(font);\n }\n textArea.setEditable(false);\n if (background == null) {\n textArea.setBackground(new Color(214, 217, 223));\n } else {\n textArea.setBackground(background);\n }\n JOptionPane.showMessageDialog(this, textArea, title, type);\n }\n\n /**\n * 确认提示.\n */\n public int showConfirmMessage(String message, String title, int type) {\n return JOptionPane.showConfirmDialog(this, message, title, type);\n }\n\n /**\n * 格式化数字-三位有效数字.\n */\n public DecimalFormat formatDouble3 = new DecimalFormat(\"0.000\");\n /**\n * 格式化数字-六位有效数字.\n */\n public DecimalFormat formatDouble6 = new DecimalFormat(\"0.000000\");\n\n /**\n * 日期格式化Formatter yyyyMMdd.\n */\n public final static String FORMATTER_YYYYMMDD = \"yyyyMMdd\";\n /**\n * 日期格式化Formatter yyyy-MM-dd HH:mm:ss.\n */\n public final static String FORMATTER_YYYYMMDDHHMMSS = \"yyyy-MM-dd HH:mm:ss\";\n\n /**\n * 时间输入表单,默认格式yyyy-MM-dd HH:mm:ss.\n */\n public JFormattedTextField createDateTextField() {\n return createDateTextField(new SimpleDateFormat(FORMATTER_YYYYMMDDHHMMSS), (GuiUtils.IS_MAC ? 11 : 19), GuiUtils.font14_cn, \"\");\n }\n\n /**\n * 获取格式化时间字符串的Long型表示.\n */\n public Long getLongFormatTime(String fomartStr, SimpleDateFormat dateFormat) {\n Long time = null;\n try {\n if (fomartStr != null && fomartStr.length() != 0) {\n time = dateFormat.parse(fomartStr).getTime();\n }\n } catch (ParseException e) {\n GuiUtils.log(e);\n }\n return time;\n }\n\n /**\n * 时间输入表单. 时间格式为\"yyyyMMdd\"或\"yyyy-MM-dd\"或\"yyyy.MM.dd\"或\"yyyy,MM,dd\"或\"yyyy-MM-dd HH:mm:ss\".\n */\n public JFormattedTextField createDateTextField(Format format, int columns, Font font, String defaultValue) {\n JFormattedTextField field = new JFormattedTextField(format);\n field.setColumns(columns);\n field.setFont(font);\n field.setText(defaultValue);\n /**\n * <pre>\n * JFormattedTextField.REVERT 恢复显示以匹配 getValue,这可能丢失当前的编辑内容。\n * JFormattedTextField.COMMIT 提交当前值。如果 AbstractFormatter 不认为所编辑的值是合法值,则抛出 ParseException,然后不更改该值并保留已编辑的值。\n * JFormattedTextField.COMMIT_OR_REVERT 与COMMIT 类似,但是如果该值不是合法的,则其行为类似于 REVERT。\n * JFormattedTextField.PERSIST 不执行任何操作,不获取新的 AbstractFormatter 也不更新该值。\n * 默认值为 JFormattedTextField.COMMIT_OR_REVERT。\n * </pre>\n */\n field.setFocusLostBehavior(JFormattedTextField.COMMIT);\n field.addFocusListener(new FocusListener() {\n @Override\n public void focusLost(FocusEvent event) {\n JFormattedTextField field = (JFormattedTextField) event.getSource();\n String value = field.getText().trim();\n if (value.length() == 8 || value.length() == 10) {\n String mayDate = value.replace(\"-\", \"\").replace(\".\", \"\").replace(\",\", \"\");\n if (mayDate.length() == 8) {\n try {\n new SimpleDateFormat(FORMATTER_YYYYMMDD).parse(mayDate);\n field.setText(mayDate.substring(0, 4) + \"-\" + mayDate.substring(4, 6) + \"-\"\n + mayDate.substring(6, 8) + \" 00:00:00\");\n } catch (ParseException e) {\n GuiUtils.log(e);\n }\n }\n }\n if (value.length() != 0 && !field.isEditValid()) {\n SimpleDateFormat dateFormat = (SimpleDateFormat) (((DateFormatter) field.getFormatter())\n .getFormat());\n showMessage(\n \"时间格式必须为\\\"yyyyMMdd\\\"或\\\"yyyy-MM-dd\\\"或\\\"yyyy.MM.dd\\\"或\\\"yyyy,MM,dd\\\"或\\\"\"\n + dateFormat.toPattern() + \"\\\"!\", \"警告\", JOptionPane.WARNING_MESSAGE);\n field.setText(\"\");\n }\n }\n\n @Override\n public void focusGained(FocusEvent event) {\n }\n });\n return field;\n }\n\n /**\n * 数字输入表单.\n */\n public JFormattedTextField createNumberTextField() {\n return createNumberTextField(new NumberFormatter(), (GuiUtils.IS_MAC ? 7 : 13), GuiUtils.font14_cn, \"\");\n }\n\n /**\n * 数字输入表单.\n */\n public JFormattedTextField createNumberTextField(NumberFormatter format, int columns, Font font, String defaultValue) {\n JFormattedTextField field = new JFormattedTextField(format);\n field.setColumns(columns);\n field.setFont(font);\n field.setText(defaultValue);\n /**\n * <pre>\n * JFormattedTextField.REVERT 恢复显示以匹配 getValue,这可能丢失当前的编辑内容。\n * JFormattedTextField.COMMIT 提交当前值。如果 AbstractFormatter 不认为所编辑的值是合法值,则抛出 ParseException,然后不更改该值并保留已编辑的值。\n * JFormattedTextField.COMMIT_OR_REVERT 与COMMIT 类似,但是如果该值不是合法的,则其行为类似于 REVERT。\n * JFormattedTextField.PERSIST 不执行任何操作,不获取新的 AbstractFormatter 也不更新该值。\n * 默认值为 JFormattedTextField.COMMIT_OR_REVERT。\n * </pre>\n */\n field.setFocusLostBehavior(JFormattedTextField.COMMIT);\n field.addFocusListener(new FocusListener() {\n @Override\n public void focusLost(FocusEvent event) {\n JFormattedTextField field = (JFormattedTextField) event.getSource();\n String value = field.getText().trim();\n if (value.length() != 0 && !field.isEditValid()) {\n /*\n * NumberFormat numberFormat = (NumberFormat) (((NumberFormatter)\n * field.getFormatter()).getFormat());\n */\n showMessage(\"必须填写数字!\", \"警告\", JOptionPane.WARNING_MESSAGE);\n field.setText(\"\");\n }\n }\n\n @Override\n public void focusGained(FocusEvent event) {\n }\n });\n return field;\n }\n\n /**\n * 文件大小单位.\n */\n public String[] fileSizeUnit = new String[]{GuiUtils.FileSize_G, GuiUtils.FileSize_M, GuiUtils.FileSize_KB,\n GuiUtils.FileSize_Byte};\n\n /**\n * 文件大小单位下拉框.\n */\n public JComboBox createFileSizeUnitBox(Font font) {\n JComboBox fileSizeUnitBox = new JComboBox();\n fileSizeUnitBox.setFont(font);\n for (int i = 0; i < fileSizeUnit.length; i++) {\n fileSizeUnitBox.addItem(fileSizeUnit[i]);\n }\n fileSizeUnitBox.setSelectedIndex(1);\n return fileSizeUnitBox;\n }\n\n /**\n * 异常输出.\n *\n * @param e 异常\n */\n public void showExceptionMessage(Exception e) {\n showExceptionMessage(e, e.getClass().getName() + \": \" + e.getMessage());\n }\n\n /**\n * 异常输出.\n *\n * @param e 异常\n * @param message 提示信息\n */\n public void showExceptionMessage(Exception e, String message) {\n GuiUtils.log(e);\n showMessage(message, \"异常\", JOptionPane.ERROR_MESSAGE);\n }\n\n /**\n * 加载配置异常输出.\n *\n * @param filePath 配置文件路径\n * @param e 异常\n */\n public void logLoadPropertiesException(String filePath, Exception e) {\n GuiUtils.log(\"加载配置\\\"\" + filePath + \"\\\"出错!\", e);\n }\n\n}", "public class GuiUtils {\n\n private static Logger logger = LoggerFactory.getLogger(GuiUtils.class);\n\n\n /**************************** 编码 ****************************/\n\n // 下面两个转码结果一样\n public static String CHARSET_ISO_8859_1 = \"ISO-8859-1\";\n public static String CHARSET_US_ASCII = \"US-ASCII\";\n\n // java转义\\ u后面跟的编码, 即Java Unicode转义字符\n public static String CHARSET_UTF_16BE = \"UTF-16BE\";\n public static String CHARSET_UTF_16LE = \"UTF-16LE\";\n\n public static String CHARSET_UTF_8 = \"UTF-8\";\n\n // 下面两个转码结果一样\n public static String CHARSET_UTF_16 = \"UTF-16\";\n public static String CHARSET_Unicode = \"Unicode\";\n\n // GB2312 < GBK < GB18030\n public static String CHARSET_GB2312 = \"GB2312\";\n public static String CHARSET_GBK = \"GBK\";\n public static String CHARSET_GB18030 = \"GB18030\";\n\n public static String CHARSET_Big5 = \"Big5\";\n\n /**************************** 算法 ****************************/\n // 可解密/解码算法\n public static String CRYPTO_ASCII = \"Ascii\";\n public static String CRYPTO_HEX = \"Hex\";\n public static String CRYPTO_BASE32 = \"Base32\";\n public static String CRYPTO_BASE64 = \"Base64\";\n public static String CRYPTO_URL = \"URL\";\n // 不可解密算法\n public static String CRYPTO_MD5 = \"MD5\";\n public static String CRYPTO_SHA = \"SHA\";\n public static String CRYPTO_SHA256 = \"SHA256\";\n public static String CRYPTO_SHA384 = \"SHA384\";\n public static String CRYPTO_SHA512 = \"SHA512\";\n\n /**************************** 字体 ****************************/\n\n /**************************** Code类型 ****************************/\n public static String CODE_TYPE_JSON = \"JSON\";\n public static String CODE_TYPE_PROPERTIES = \"Properties\";\n public static String CODE_TYPE_YML = \"YML\";\n public static String CODE_TYPE_XML = \"XML\";\n public static String CODE_TYPE_JAVA = \"Java\";\n public static String CODE_TYPE_JS = \"JS\";\n public static String CODE_TYPE_PYTHON = \"Python\";\n public static String CODE_TYPE_SQL = \"SQL\";\n\n /**************************** Code类型 ****************************/\n\n /**************************** Split类型 ****************************/\n public static String SPLIT_TYPE_SIZE = \"Size(MB)\";\n public static String SPLIT_TYPE_LINE = \"Line\";\n\n /**************************** Split类型 ****************************/\n\n /**************************** 密码组合类型 ****************************/\n public static String PASSWORD_COMBINATION_8_CHAR_NUM_SIMPLE = \"8位字母数字[简单]\";\n public static String PASSWORD_COMBINATION_8_CHAR_NUM_POPULAR = \"8位字母数字[复杂]\";\n\n /**************************** 密码组合类型 ****************************/\n\n /**\n * 所有字体.\n */\n public static Map<String, Font> availableFontsMap = availableFontsMap();\n\n /**\n * 中文字体集.\n */\n public static String[] fontStyles_cn;\n /**\n * 中文字体.\n */\n public static String fontStyle_cn;\n /**\n * 英文字体集.\n */\n public static String[] fontStyles;\n /**\n * 英文字体.\n */\n public static String fontStyle;\n /**\n * 支持Unicode的字体集.\n */\n public static String[] fontStyles_un;\n /**\n * 支持Unicode的字体.\n */\n public static String fontStyle_un;\n\n public static Font font12_cn;\n\n public static Font font13;\n public static Font font13_cn;\n\n public static Font font14_cn;\n public static Font font14_un;\n public static Font font14b;\n public static Font font14b_cn;\n\n public static Font font16;\n\n /**************************** 文件大小单位 ****************************/\n public static String FileSize_PB = \"PB\";\n public static String FileSize_TB = \"TB\";\n public static String FileSize_G = \"G\";\n public static String FileSize_M = \"M\";\n public static String FileSize_KB = \"KB\";\n public static String FileSize_Byte = \"Byte\";\n\n /**\n * 初始化字体.\n */\n public static void initFont() {\n font12_cn = new Font(fontStyle_cn, Font.PLAIN, 12);\n\n font13 = new Font(fontStyle, Font.PLAIN, 13);\n font13_cn = new Font(fontStyle_cn, Font.PLAIN, 13);\n\n font14_cn = new Font(fontStyle_cn, Font.PLAIN, 14);\n font14_un = new Font(fontStyle_un, Font.PLAIN, 14);\n font14b = new Font(fontStyle, Font.BOLD, 14);\n font14b_cn = new Font(fontStyle_cn, Font.BOLD, 14);\n\n font16 = new Font(fontStyle, Font.PLAIN, 16);\n }\n\n /**\n * 当前Java虚拟机支持的charset.\n */\n public static SortedMap<String, Charset> availableCharsets() {\n return Charset.availableCharsets();\n }\n\n /**\n * 支持的字体.\n */\n public static Font[] availableFonts() {\n GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();\n return environment.getAllFonts();\n }\n\n /**\n * 支持的字体.\n */\n public static Map<String, Font> availableFontsMap() {\n Font[] fonts = availableFonts();\n Map<String, Font> fontsMap = new HashMap<String, Font>();\n for (Font font : fonts) {\n fontsMap.put(font.getFontName(), font);\n }\n return fontsMap;\n }\n\n /**\n * 按字符集解码.\n */\n public static String encode(String string, String encode, String decode) throws UnsupportedEncodingException {\n return new String(string.getBytes(encode), decode);\n }\n\n /**\n * 字符串前缀字符填充.\n */\n public static String addFillString(String string, String fill, int interval) {\n StringBuilder sb = new StringBuilder();\n int len = string.length();\n int loop = len / interval;\n for (int i = 0; i < loop; i++) {\n sb.append(fill).append(string.substring(interval * i, interval * (i + 1)));\n }\n if (loop * interval != len) {\n sb.append(fill).append(string.substring(loop * interval, len));\n }\n return sb.toString();\n }\n\n /**\n * 字符串前填充以满足固定长度.\n */\n public static String fillStringBefore(String string, String fill, int size) {\n StringBuilder sb = new StringBuilder();\n int len = string.length();\n for (int i = 0; i < size - len; i++) {\n sb.append(fill);\n }\n return sb.append(string).toString();\n }\n\n /**\n * 优先使用前面的字体,如果不存在,则一个一个向后查找..\n */\n public static String getAvailableFont(String[] fontStyles) {\n String fontName = \"\";\n for (String fontStyle : fontStyles) {\n if (availableFontsMap.containsKey(fontStyle)) {\n fontName = fontStyle;\n break;\n }\n }\n return fontName;\n }\n\n /**\n * 右填充字符串.\n * <p>\n * <pre>\n * 依据UTF-8编码中文占三个字节, 英文占一个字节, 且宋体下中文占两个半角空格位, 英文占一个半角空格位的特点;\n * 变通填充为字符中有一个中文字符即当两个半角空格位, 一个英文字符即当一个半角空格位.\n * </pre>\n */\n public static String getFillUpString(String string, int size) {\n StringBuilder sb = new StringBuilder(string);\n int len = 0;\n try {\n len = string.length();\n len = len + (string.getBytes(\"UTF-8\").length - len) / 2;\n } catch (UnsupportedEncodingException e) {\n GuiUtils.log(e);\n }\n for (int i = 0; i < size - len; i++) {\n sb.append(\" \");\n }\n return sb.toString();\n }\n\n /**\n * 计算时间, 形式1Days 2Hours 3Minutes 4Seconds.\n */\n public static String getCountTime(long time) {\n time = time / 1000L;\n long minute = 60L;\n long hour = minute * 60L;\n long day = hour * 24L;\n long seconds = time % minute;\n long minutes = (time - seconds) % hour / minute;\n long hours = (time - minutes - seconds) % day / hour;\n long days = (time - hour - minutes - seconds) / day;\n return days + \" Days \" + hours + \" Hours \" + minutes + \" Minutes \" + seconds + \" Seconds\";\n }\n\n /**\n * 计算文件(单位)大小,单位为字节Byte.\n */\n public static Double getCountFileSizeUnit(String size, String unit) {\n return getCountFileSizeUnit(size.length() == 0 ? null : Double.parseDouble(size), unit);\n }\n\n /**\n * 计算文件(单位)大小,单位为字节Byte.\n */\n public static Double getCountFileSizeUnit(Double size, String unit) {\n if (size == null) {\n return null;\n }\n Double bSize = null;\n int cas = 1024;\n if (unit.equals(FileSize_Byte)) {\n bSize = size;\n } else if (unit.equals(FileSize_KB)) {\n bSize = size * cas;\n } else if (unit.equals(FileSize_M)) {\n bSize = size * cas * cas;\n } else if (unit.equals(FileSize_G)) {\n bSize = size * cas * cas * cas;\n } else if (unit.equals(FileSize_TB)) {\n bSize = size * cas * cas * cas * cas;\n } else if (unit.equals(FileSize_PB)) {\n bSize = size * cas * cas * cas * cas * cas;\n }\n return bSize;\n }\n\n /**\n * 获取目录img/icon目录下的图标.\n */\n public static Icon getIcon(String path, Toolkit kit) {\n return new ImageIcon(getImage(path, kit));\n }\n\n /**\n * 获取目录img/icon目录下的图片.\n */\n public static Image getImage(String path, Toolkit kit) {\n URL imgURL = null;\n try {\n imgURL = new File(getActualPath(path)).toURI().toURL();\n } catch (MalformedURLException e) {\n GuiUtils.log(\"Load Image Error.\", e);\n }\n return kit.getImage(imgURL);\n }\n\n /**\n * 获取类加载路径下的图标.\n */\n public static Icon getIconFromClassloader(String classLoaderImagePath, Toolkit kit) {\n return new ImageIcon(getImageFromClassloader(classLoaderImagePath, kit));\n }\n\n /**\n * 获取类加载路径下的图片.\n */\n public static Image getImageFromClassloader(String classLoaderImagePath, Toolkit kit) {\n // 这种方式可以从jar包中获取资源路径\n URL imgURL = ClassLoader.getSystemResource(classLoaderImagePath);\n return kit.getImage(imgURL);\n }\n\n /**\n * 获取与Jar lib或classes目录(前提是GuiUtils类被编译在其下)同级的文件(夹)或同级文件夹的子文件(夹)的绝对路径.\n */\n public static String getActualPath(String path) {\n return LIB_PARENT_PATH + path;\n }\n\n /**\n * Jar lib或classes目录(前提是GuiUtils类被编译在其下)的父路径.\n */\n private static String LIB_PARENT_PATH = getLibParentPath();\n\n /**\n * 获取Jar lib或classes目录(前提是GuiUtils类被编译在其下)的父路径.\n */\n private static String getLibParentPath() {\n String classResource = GuiUtils.class.getName().replace(\".\", \"/\") + \".class\";\n String path = \"\";\n try {\n path = GuiUtils.class.getClassLoader().getResource(classResource).getPath();\n // \"+\"号decode后为空格\" \",\"%2b\"号decode后为\"+\"号\n path = path.replace(\"+\", \"%2b\");\n path = URLDecoder.decode(path, \"UTF-8\");\n path = path.substring(0, path.length() - classResource.length());\n if (path.contains(\".jar!\")) {\n path = path.substring(5, path.indexOf(\".jar!\") + 4);\n path = path.substring(0, path.lastIndexOf(\"/\"));\n path = path.substring(0, path.length() - \"lib\".length());\n } else {\n path = path.substring(0, path.length() - \"classes\".length() - 1);\n }\n } catch (UnsupportedEncodingException e) {\n GuiUtils.log(e);\n }\n return path;\n }\n\n /**\n * 消息输出到控制台.\n *\n * @param msg 消息\n */\n public static void log(String msg) {\n logger.info(msg);\n GuiMain.msgTextArea.append(msg + \"\\n\");\n }\n\n /**\n * 异常输出到控制台.\n *\n * @param e 异常\n */\n public static void log(Exception e) {\n e.printStackTrace();\n logger.error(\"\", e);\n StackTraceElement[] ste = e.getStackTrace();\n StringBuilder esb = new StringBuilder();\n esb.append(\"Exception: \").append(e.getClass().getName()).append(\": \").append(e.getMessage()).append(\"\\n\");\n for (int i = 0; i < 5 && i < ste.length; i++) {\n esb.append(\" \").append(ste[i].toString()).append(\"\\n\");\n }\n GuiMain.msgTextArea.append(esb.toString());\n }\n\n /**\n * 消息、异常输出到控制台.\n *\n * @param msg 消息\n * @param e 异常\n */\n public static void log(String msg, Throwable e) {\n e.printStackTrace();\n logger.error(msg, e);\n log(msg);\n log(e.getMessage());\n }\n\n /**\n * parseFalse, 有且仅当对象toString值equalsIgnoreCase(\"false\")时返回false, 其他时候返回true.\n */\n public static boolean parseFalse(Object obj) {\n return \"false\".equalsIgnoreCase(toString(obj)) ? false : true;\n }\n\n /**\n * trim.\n */\n public static String trim(Object obj) {\n return toString(obj).trim();\n }\n\n /**\n * toString.\n */\n public static String toString(Object obj) {\n return obj == null ? \"\" : obj.toString();\n }\n\n /**\n * is mac.\n */\n public static boolean IS_MAC = System.getProperty(\"os.name\").contains(\"Mac\");\n\n public static void showAboutMessage(Toolkit kit, JPanel contextPanel, Map<String, String> propsMap) {\n JOptionPane.showMessageDialog(contextPanel, \"Version: \" + propsMap.get(\"Version\")\n + \"\\nAuthor: [email protected]\\nDevelop Date: \" + propsMap.get(\"Develop_Date\"), \"About\",\n JOptionPane.INFORMATION_MESSAGE, GuiUtils.getIcon(\"img/icon/cgt_About.png\", kit));\n }\n\n}", "public class EscapeUtils {\n\n /**\n * 转义字符.\n *\n * @param string 字符\n * @param type 字符类型\n */\n public static String escape(String string, String type) {\n String unescape = \"不支持对\" + type + \"字符的转义\";\n if (type.equals(LanguageUtils.CONST_HTML)) {\n unescape = StringEscapeUtils.escapeHtml(string);\n } else if (type.equals(LanguageUtils.CONST_XML)) {\n unescape = StringEscapeUtils.escapeXml(string);\n } else if (type.equals(LanguageUtils.CONST_SQL)) {\n unescape = StringEscapeUtils.escapeSql(string);\n } else if (type.equals(LanguageUtils.CONST_JAVA)) {\n unescape = StringEscapeUtils.escapeJava(string);\n } else if (type.equals(LanguageUtils.CONST_JAVASCRIPT)) {\n unescape = StringEscapeUtils.escapeJavaScript(string);\n } else if (type.equals(LanguageUtils.CONST_CSV)) {\n unescape = StringEscapeUtils.escapeCsv(string);\n }\n return unescape;\n }\n\n /**\n * 还原转义字符.\n *\n * @param string 转义字符\n * @param type 字符类型\n */\n public static String unescape(String string, String type) {\n String escape = \"转义字符还原遇到错误\";\n if (type.equals(LanguageUtils.CONST_HTML)) {\n escape = StringEscapeUtils.unescapeHtml(string);\n } else if (type.equals(LanguageUtils.CONST_XML)) {\n escape = StringEscapeUtils.unescapeXml(string);\n } else if (type.equals(LanguageUtils.CONST_SQL)) {\n escape = type + \"转义字符不能进行还原\";\n } else if (type.equals(LanguageUtils.CONST_JAVA)) {\n escape = StringEscapeUtils.unescapeJava(string);\n } else if (type.equals(LanguageUtils.CONST_JAVASCRIPT)) {\n escape = StringEscapeUtils.unescapeJavaScript(string);\n } else if (type.equals(LanguageUtils.CONST_CSV)) {\n escape = StringEscapeUtils.unescapeCsv(string);\n }\n return escape;\n }\n\n}", "public class LanguageUtils {\n\n /**\n * JAVA.\n */\n public static final String CONST_JAVA = \"JAVA\";\n\n /**\n * SQL.\n */\n public static final String CONST_SQL = \"SQL\";\n\n /**\n * HTML.\n */\n public static final String CONST_HTML = \"HTML\";\n\n /**\n * XML.\n */\n public static final String CONST_XML = \"XML\";\n\n /**\n * JavaScript.\n */\n public static final String CONST_JAVASCRIPT = \"JavaScript\";\n\n /**\n * URI.\n */\n public static final String CONST_URI = \"URI\";\n\n /**\n * JSON.\n */\n public static final String CONST_JSON = \"JSON\";\n\n /**\n * CSS.\n */\n public static final String CONST_CSS = \"CSS\";\n\n /**\n * CSV.\n */\n public static final String CONST_CSV = \"CSV\";\n\n}", "public class SimpleMouseListener implements MouseListener {\n\n @Override\n public void mouseClicked(MouseEvent e) {\n\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n\n }\n\n}" ]
import bs.tool.commongui.AbstractGuiJPanel; import bs.tool.commongui.GuiUtils; import bs.tool.commongui.utils.EscapeUtils; import bs.tool.commongui.utils.LanguageUtils; import bs.tool.commongui.utils.SimpleMouseListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent;
package bs.tool.commongui.plugins.more; /** * 字符转义工具. */ public class EscapeCharacterTool extends AbstractGuiJPanel { private static final long serialVersionUID = 1L; /** * 字符文本域. */ private JTextArea unescapeTextArea = createJTextArea(GuiUtils.font14_un); /** * 转义文本域. */ private JTextArea escapeTextArea = createJTextArea(GuiUtils.font14_un); /** * 帮助文本域. */ private JTextArea helpTextArea = createJTextArea(GuiUtils.font14_un); /** * 字符类型. */
private String[] characterTypes = new String[]{LanguageUtils.CONST_HTML, LanguageUtils.CONST_XML,
3
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/rest/SelfossRestWrapper.java
[ "@DatabaseTable(daoClass = ArticleDao.class)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Article implements Parcelable {\n\n\tprivate static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\tstatic {\n\t\tDATETIME_FORMAT.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\t}\n\n\t@DatabaseField(id = true, columnName = ArticleDao.COLUMN_ID)\n private int id;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_DATETIME)\n private long dateTime;\n\t@DatabaseField\n private String title;\n\t@DatabaseField\n private String content;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_UNREAD)\n private boolean unread;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_STARRED)\n private boolean starred;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_SOURCE_ID)\n private int sourceId;\n\t@DatabaseField\n private String thumbnail;\n\t@DatabaseField\n private String icon;\n\t@DatabaseField\n private String uid;\n\t@DatabaseField\n private String link;\n\t@DatabaseField\n\t@JsonProperty(\"sourcetitle\")\n\tprivate String sourceTitle;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_TAGS)\n private String tags;\n @DatabaseField\n private String imageUrl;\n\t@DatabaseField(columnName = ArticleDao.COLUMN_UPDATE_TIME)\n\t@JsonProperty(\"updatetime\")\n\tprivate String updateTime;\n\n\tpublic Article() {\n\n\t}\n\n\t@JsonProperty(\"id\")\n public void setId(Object id) {\n\t\tif (id instanceof Number) {\n\t\t\tthis.id = (Integer) id;\n\t\t} else if (id instanceof String) {\n\t\t\tthis.id = Integer.valueOf((String) id);\n\t\t}\n }\n\n\t@JsonProperty(\"datetime\")\n public void setDateTime(String dateTimeStr) throws ParseException {\n\t\tdateTime = DATETIME_FORMAT.parse(dateTimeStr).getTime();\n\t}\n\n\t@JsonProperty(\"unread\")\n\tpublic void setUnread(Object unread) {\n\t\tif (unread instanceof Boolean) {\n\t\t\tthis.unread = (Boolean) unread;\n\t\t} else if (unread instanceof String) {\n\t\t\tthis.unread = \"1\".equals(unread);\n\t\t}\n\t}\n\n\t@JsonProperty(\"starred\")\n\tpublic void setStarred(Object starred) {\n\t\tif (starred instanceof Boolean) {\n\t\t\tthis.starred = (Boolean) starred;\n\t\t} else if (starred instanceof String) {\n\t\t\tthis.starred = \"1\".equals(starred);\n\t\t}\n\t}\n\n\t@JsonProperty(\"source\")\n\tpublic void setSourceId(Object sourceId) {\n\t\tif (sourceId instanceof Number) {\n\t\t\tthis.sourceId = (Integer) sourceId;\n\t\t} else if (sourceId instanceof String) {\n\t\t\tthis.sourceId = Integer.valueOf((String) sourceId);\n\t\t}\n\t}\n\n\tpublic int getId() {\n\t\treturn Math.abs(id);\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic long getDateTime() {\n\t\treturn dateTime;\n\t}\n\n\tpublic void setDateTime(long dateTime) {\n\t\tthis.dateTime = dateTime;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\t@JsonProperty(\"title\")\n\tpublic void setTitle(String title) {\n\t\tthis.title = StringEscapeUtils.unescapeHtml4(title);\n\t}\n\n\tpublic String getContent() {\n\t\treturn content;\n\t}\n\n\tpublic void setContent(String content) {\n\t\tthis.content = content;\n\t}\n\n\tpublic boolean isUnread() {\n\t\treturn unread;\n\t}\n\n\tpublic void setUnread(boolean unread) {\n\t\tthis.unread = unread;\n\t}\n\n\tpublic boolean isStarred() {\n\t\treturn starred;\n\t}\n\n\tpublic void setStarred(boolean starred) {\n\t\tthis.starred = starred;\n\t}\n\n\tpublic int getSourceId() {\n\t\treturn sourceId;\n\t}\n\n\tpublic void setSourceId(int sourceId) {\n\t\tthis.sourceId = sourceId;\n\t}\n\n\tpublic String getThumbnail() {\n\t\treturn thumbnail;\n\t}\n\n\tpublic void setThumbnail(String thumbnail) {\n\t\tthis.thumbnail = thumbnail;\n\t}\n\n\tpublic boolean hasIcon() {\n\t\treturn icon != null && !icon.isEmpty();\n\t}\n\n\tpublic String getIcon() {\n\t\treturn icon;\n\t}\n\n\tpublic void setIcon(String icon) {\n\t\tthis.icon = icon;\n\t}\n\n\tpublic String getUid() {\n\t\treturn uid;\n\t}\n\n\tpublic void setUid(String uid) {\n\t\tthis.uid = uid;\n\t}\n\n\tpublic String getLink() {\n\t\treturn link;\n\t}\n\n\tpublic void setLink(String link) {\n\t\tthis.link = link;\n\t}\n\n\tpublic String getSourceTitle() {\n\t\treturn sourceTitle;\n\t}\n\n\tpublic void setSourceTitle(String sourceTitle) {\n\t\tthis.sourceTitle = sourceTitle;\n\t}\n\n\tpublic String getTags() {\n\t\treturn tags;\n\t}\n\n\tpublic void setTags(String tags) {\n\t\tthis.tags = tags;\n\t}\n\n public String getImageUrl() {\n return imageUrl;\n }\n\n public void setImageUrl(String imageUrl) {\n this.imageUrl = imageUrl;\n }\n\n\tpublic String getUpdateTime() {\n\t\treturn updateTime;\n\t}\n\n\tpublic void setUpdateTime(String updateTime) {\n\t\tthis.updateTime = updateTime;\n\t}\n\n\tpublic boolean hasImage() {\n return imageUrl != null;\n }\n\n public boolean isCached() {\n\t\treturn id < 0;\n\t}\n\n\tpublic void setCached(boolean cached) {\n\t\tif (cached) {\n\t\t\tthis.id = - getId();\n\t\t} else {\n\t\t\tthis.id = getId();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Article))\n\t\t\treturn false;\n\t\treturn getId() == ((Article) o).getId();\n\t}\n\n\t@Override\n\tpublic int describeContents() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void writeToParcel(Parcel dest, int flags) {\n\t\tdest.writeInt(this.id);\n\t\tdest.writeLong(this.dateTime);\n\t\tdest.writeString(this.title);\n\t\tdest.writeString(this.content);\n\t\tdest.writeByte(unread ? (byte) 1 : (byte) 0);\n\t\tdest.writeByte(starred ? (byte) 1 : (byte) 0);\n\t\tdest.writeInt(this.sourceId);\n\t\tdest.writeString(this.thumbnail);\n\t\tdest.writeString(this.icon);\n\t\tdest.writeString(this.uid);\n\t\tdest.writeString(this.link);\n\t\tdest.writeString(this.sourceTitle);\n\t\tdest.writeString(this.tags);\n dest.writeString(this.imageUrl);\n\t\tdest.writeString(this.updateTime);\n\t}\n\n\tprivate Article(Parcel in) {\n\t\tthis.id = in.readInt();\n\t\tthis.dateTime = in.readLong();\n\t\tthis.title = in.readString();\n\t\tthis.content = in.readString();\n\t\tthis.unread = in.readByte() != 0;\n\t\tthis.starred = in.readByte() != 0;\n\t\tthis.sourceId = in.readInt();\n\t\tthis.thumbnail = in.readString();\n\t\tthis.icon = in.readString();\n\t\tthis.uid = in.readString();\n\t\tthis.link = in.readString();\n\t\tthis.sourceTitle = in.readString();\n\t\tthis.tags = in.readString();\n this.imageUrl = in.readString();\n\t\tthis.updateTime = in.readString();\n\t}\n\n\tpublic static Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() {\n\t\tpublic Article createFromParcel(Parcel source) {\n\t\t\treturn new Article(source);\n\t\t}\n\n\t\tpublic Article[] newArray(int size) {\n\t\t\treturn new Article[size];\n\t\t}\n\t};\n}", "public enum ArticleType {\n\n\tNewest(R.id.newest, R.string.newest, \"\"),\n\tUnread(R.id.unread, R.string.unread, \"unread\"),\n\tStarred(R.id.starred, R.string.starred, \"starred\");\n\n\tprivate int id;\n\tprivate int nameResId;\n\tprivate String apiName;\n\n\tprivate ArticleType(int id, int nameResId, String apiName) {\n\t\tthis.id = id;\n\t\tthis.nameResId = nameResId;\n\t\tthis.apiName = apiName;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName(Context context) {\n\t\treturn context.getString(nameResId);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn apiName;\n\t}\n\n\tpublic static ArticleType fromId(int id) {\n\t\tfor (ArticleType type : ArticleType.values()) {\n\t\t\tif (type.getId() == id) {\n\t\t\t\treturn type;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"There is no ArticleType for this id : \" + id);\n\t}\n}", "@DatabaseTable(daoClass = TagDao.class)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Tag implements Parcelable {\n\n\tpublic static final Tag ALL = new Tag(R.string.allTags);\n\n\tpublic static final Comparator<Tag> COMPARATOR_UNREAD_INVERSE = new Comparator<Tag>() {\n\t\t@Override\n\t\tpublic int compare(Tag lhs, Tag rhs) {\n\t\t\treturn - Integer.valueOf(lhs.getUnread()).compareTo(rhs.getUnread());\n\t\t}\n\t};\n\n public static List<Integer> colorsOfTags(List<Tag> tags) {\n List<Integer> colors = new ArrayList<Integer>();\n for (Tag tag : tags) {\n colors.add(tag.getColor());\n }\n return colors;\n }\n\n\t@DatabaseField(id = true, columnName = TagDao.COLUMN_NAME)\n\t@JsonProperty(\"tag\")\n\tprivate String name;\n\tprivate int nameId;\n\t@DatabaseField\n\tprivate int color;\n\t@DatabaseField\n\tprivate int unread;\n\n\tpublic Tag() {\n\n\t}\n\n\tprivate Tag(int nameId) {\n\t\tthis.nameId = nameId;\n\t}\n\n\tpublic String getName(Context context) {\n\t\tif (nameId != 0)\n\t\t\treturn context.getString(nameId);\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic int getColor() {\n\t\treturn color;\n\t}\n\n\t@JsonProperty(\"color\")\n\tpublic void setColor(String color) {\n\t\tthis.color = ColorUtil.parseColor(color);\n\t}\n\n\tpublic int getUnread() {\n\t\treturn unread;\n\t}\n\n\tpublic void setUnread(int unread) {\n\t\tthis.unread = unread;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Tag))\n\t\t\treturn false;\n\t\tTag oTag = (Tag) o;\n\t\tif (name == null)\n\t\t\treturn nameId == oTag.nameId;\n\t\treturn name.equals(oTag.name);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif (name == null)\n\t\t\treturn \"All\";\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic int describeContents() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void writeToParcel(Parcel dest, int flags) {\n\t\tdest.writeString(this.name);\n\t\tdest.writeInt(this.nameId);\n\t\tdest.writeInt(this.color);\n\t\tdest.writeInt(this.unread);\n\t}\n\n\tprivate Tag(Parcel in) {\n\t\tthis.name = in.readString();\n\t\tthis.nameId = in.readInt();\n\t\tthis.color = in.readInt();\n\t\tthis.unread = in.readInt();\n\t}\n\n\tpublic static Parcelable.Creator<Tag> CREATOR = new Parcelable.Creator<Tag>() {\n\t\tpublic Tag createFromParcel(Parcel source) {\n\t\t\treturn new Tag(source);\n\t\t}\n\n\t\tpublic Tag[] newArray(int size) {\n\t\t\treturn new Tag[size];\n\t\t}\n\t};\n}", "public class ArticleSyncActionDao extends BaseDaoImpl<ArticleSyncAction, Integer> {\n\n\tpublic static final String COLUMN_ARTICLEID = \"articleId\";\n\tpublic static final String COLUMN_ACTION = \"action\";\n\n\tpublic ArticleSyncActionDao(ConnectionSource connectionSource) throws SQLException {\n\t\tsuper(connectionSource, ArticleSyncAction.class);\n\t}\n\n\t@Override\n\tpublic List<ArticleSyncAction> queryForAll() {\n\t\ttry {\n\t\t\treturn super.queryForAll();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic List<ArticleSyncAction> queryForMarkRead() {\n\t\ttry {\n\t\t\treturn queryBuilder().where().eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkRead).query();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic ArticleSyncAction queryForArticle(Article article) {\n\t\ttry {\n\t\t\treturn queryBuilder().where().eq(COLUMN_ARTICLEID, article.getId()).queryForFirst();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void markRead(Article article) {\n\t\ttry {\n\t\t\tdeleteMarkReadAndUnread(article);\n\t\t\tcreate(new ArticleSyncAction(article, ArticleSyncAction.Action.MarkRead));\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void markUnread(Article article) {\n\t\ttry {\n\t\t\tdeleteMarkReadAndUnread(article);\n\t\t\tcreate(new ArticleSyncAction(article, ArticleSyncAction.Action.MarkUnread));\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void markStarred(Article article) {\n\t\ttry {\n\t\t\tdeleteMarkStarredAndUnStarred(article);\n\t\t\tcreate(new ArticleSyncAction(article, ArticleSyncAction.Action.MarkStarred));\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void markUnstarred(Article article) {\n\t\ttry {\n\t\t\tdeleteMarkStarredAndUnStarred(article);\n\t\t\tcreate(new ArticleSyncAction(article, ArticleSyncAction.Action.MarkUnstarred));\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int delete(ArticleSyncAction data) {\n\t\ttry {\n\t\t\treturn super.delete(data);\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic int deleteMarkRead() {\n\t\ttry {\n\t\t\tDeleteBuilder<ArticleSyncAction, Integer> deleteBuilder = deleteBuilder();\n\t\t\tdeleteBuilder.where().eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkRead);\n\t\t\treturn deleteBuilder.delete();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic int deleteMarkReadAndUnread(Article article) {\n\t\ttry {\n\t\t\tDeleteBuilder<ArticleSyncAction, Integer> deleteBuilder = deleteBuilder();\n\t\t\tWhere<ArticleSyncAction, Integer> where = deleteBuilder.where();\n\t\t\twhere.and(where.eq(COLUMN_ARTICLEID, article.getId()),\n\t\t\t\t\twhere.eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkRead)\n\t\t\t\t\t\t.or().eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkUnread));\n\t\t\treturn deleteBuilder.delete();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic int deleteMarkStarredAndUnStarred(Article article) {\n\t\ttry {\n\t\t\tDeleteBuilder<ArticleSyncAction, Integer> deleteBuilder = deleteBuilder();\n\t\t\tWhere<ArticleSyncAction, Integer> where = deleteBuilder.where();\n\t\t\twhere.and(where.eq(COLUMN_ARTICLEID, article.getId()),\n\t\t\t\t\twhere.eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkStarred)\n\t\t\t\t\t\t\t.or().eq(COLUMN_ACTION, ArticleSyncAction.Action.MarkUnstarred));\n\t\t\treturn deleteBuilder.delete();\n\t\t} catch (SQLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n}", "public class DatabaseHelper extends OrmLiteSqliteOpenHelper {\n\n\tpublic static final String ACTION_TABLES_CLEARED = \"fr.ydelouis.selfoss.ACTION_TABLES_CLEARED\";\n\n\tprivate static final String DATABASE_NAME = \"selfoss.db\";\n\tprivate static final int DATABASE_VERSION = 5;\n\n\tprivate Context context;\n\n\tpublic DatabaseHelper(Context context) {\n\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n\t\tthis.context = context;\n\t}\n\n\t@Override\n\tpublic void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {\n\t\ttry {\n\t\t\tTableUtils.createTable(connectionSource, Tag.class);\n\t\t\tTableUtils.createTable(connectionSource, Source.class);\n\t\t\tTableUtils.createTable(connectionSource, Article.class);\n\t\t\tTableUtils.createTable(connectionSource, ArticleSyncAction.class);\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {\n\t\ttry {\n\t\t\tif (oldVersion < 2) {\n\t\t\t\tTableUtils.dropTable(connectionSource, Article.class, true);\n\t\t\t\tTableUtils.createTable(connectionSource, Article.class);\n\t\t\t}\n\t\t\tif (oldVersion < 3) {\n\t\t\t\tTableUtils.createTable(connectionSource, Source.class);\n\t\t\t}\n if (oldVersion < 4) {\n TableUtils.dropTable(connectionSource, Article.class, true);\n TableUtils.createTable(connectionSource, Article.class);\n }\n\t\t\tif (oldVersion < 5) {\n\t\t\t\tTableUtils.dropTable(connectionSource, Article.class, true);\n\t\t\t\tTableUtils.createTable(connectionSource, Article.class);\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void clearTables() {\n\t\ttry {\n\t\t\tTableUtils.clearTable(getConnectionSource(), Tag.class);\n\t\t\tTableUtils.clearTable(getConnectionSource(), Source.class);\n\t\t\tTableUtils.clearTable(getConnectionSource(), Article.class);\n\t\t\tTableUtils.clearTable(getConnectionSource(), ArticleSyncAction.class);\n\t\t\tcontext.sendBroadcast(new Intent(ACTION_TABLES_CLEARED));\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}", "@DatabaseTable(daoClass = ArticleSyncActionDao.class)\npublic class ArticleSyncAction {\n\n\tpublic enum Action {\n\t\tMarkRead {\n\t\t\t@Override\n\t\t\tpublic Success execute(SelfossRest rest, int articleId) {\n\t\t\t\treturn rest.markRead(articleId);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void execute(Article article) {\n\t\t\t\tarticle.setUnread(false);\n\t\t\t}\n\t\t},\n\t\tMarkUnread {\n\t\t\t@Override\n\t\t\tpublic Success execute(SelfossRest rest, int articleId) {\n\t\t\t\treturn rest.markUnread(articleId);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void execute(Article article) {\n\t\t\t\tarticle.setUnread(true);\n\t\t\t}\n\t\t},\n\t\tMarkStarred {\n\t\t\t@Override\n\t\t\tpublic Success execute(SelfossRest rest, int articleId) {\n\t\t\t\treturn rest.markStarred(articleId);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void execute(Article article) {\n\t\t\t\tarticle.setStarred(true);\n\t\t\t}\n\t\t},\n\t\tMarkUnstarred {\n\t\t\t@Override\n\t\t\tpublic Success execute(SelfossRest rest, int articleId) {\n\t\t\t\treturn rest.markUnstarred(articleId);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void execute(Article article) {\n\t\t\t\tarticle.setStarred(false);\n\t\t\t}\n\t\t};\n\n\t\tpublic abstract Success execute(SelfossRest rest, int articleId);\n\n\t\tpublic abstract void execute(Article article);\n\t}\n\n\t@DatabaseField(generatedId = true)\n\tprivate int id;\n\t@DatabaseField(columnName = ArticleSyncActionDao.COLUMN_ARTICLEID)\n\tprivate int articleId;\n\t@DatabaseField(columnName = ArticleSyncActionDao.COLUMN_ACTION)\n\tprivate Action action;\n\n\tpublic ArticleSyncAction() {\n\n\t}\n\n\tpublic ArticleSyncAction(Article article, Action action) {\n\t\tthis.articleId = article.getId();\n\t\tthis.action = action;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic int getArticleId() {\n\t\treturn articleId;\n\t}\n\n\tpublic void setArticleId(int articleId) {\n\t\tthis.articleId = articleId;\n\t}\n\n\tpublic Action getAction() {\n\t\treturn action;\n\t}\n\n\tpublic void setAction(Action action) {\n\t\tthis.action = action;\n\t}\n\n\tpublic void execute(SelfossRest rest) {\n\t\taction.execute(rest, articleId);\n\t}\n}", "public class ArticleContentParser {\n\n private Article article;\n\n public ArticleContentParser(Article article) {\n this.article = article;\n }\n\n public List<String> getImagesUrls() {\n List<String> imageUrls = new ArrayList<String>();\n Document document = Jsoup.parse(article.getContent());\n for (Element element : document.getElementsByTag(\"img\")) {\n String src = element.attr(\"src\");\n if (src != null && !src.isEmpty()) {\n imageUrls.add(src);\n }\n }\n return imageUrls;\n }\n\n public String getTitleOfImage(String imageSrc) {\n Document document = Jsoup.parse(article.getContent());\n for (Element element : document.getElementsByTag(\"img\")) {\n if (imageSrc.equals(element.attr(\"src\"))) {\n return element.attr(\"title\");\n }\n }\n return null;\n }\n\n\tpublic String getContentWithoutImage() {\n\t\tString content = article.getContent();\n\t\tif (article.hasImage()) {\n\t\t\tDocument document = Jsoup.parse(content);\n\t\t\tfor (Element element : document.getElementsByTag(\"img\")) {\n\t\t\t\tString src = element.attr(\"src\");\n\t\t\t\tif (article.getImageUrl().equals(src)) {\n\t\t\t\t\telement.remove();\n\t\t\t\t\tdocument.outputSettings().charset(\"ISO-8859-1\");\n\t\t\t\t\tcontent = document.html();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn content;\n\t}\n}", "@EBean\npublic class SelfossImageLoader implements ImageDownloader {\n\n\t@Bean protected ConfigManager configManager;\n\t@RootContext protected Context context;\n\t@Bean protected SelfossApiRequestFactory requestFactory;\n\tprivate ImageLoader loader;\n\n\t@AfterInject\n\tprotected void init() {\n\t\tDisplayImageOptions options = new DisplayImageOptions.Builder()\n\t\t\t\t.cacheInMemory(true)\n\t\t\t\t.cacheOnDisk(true)\n\t\t\t\t.displayer(new FadeInBitmapDisplayer(500, true, false, false))\n\t\t\t\t.build();\n\t\tImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)\n\t\t\t\t.defaultDisplayImageOptions(options)\n\t\t\t\t.imageDownloader(this)\n\t\t\t\t.build();\n\t\tloader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();\n\t\tif (!loader.isInited()) {\n\t\t\tloader.init(config);\n\t\t}\n\t}\n\n\tpublic String faviconUrl(String favicon) {\n\t\tConfig config = configManager.get();\n\t\tString url = config != null ? config.getUrl() : \"\";\n\t\treturn getScheme() + url + \"/favicons/\" + favicon;\n\t}\n\n\tprivate String getScheme() {\n\t\tConfig config = configManager.get();\n\t\tboolean useHttps = config != null && config.useHttps();\n\t\treturn useHttps ? \"https://\" : \"http://\";\n\t}\n\n\tpublic String faviconUrl(Article article) {\n\t\treturn faviconUrl(article.getIcon());\n\t}\n\n\tpublic String faviconUrl(Source source) {\n\t\treturn faviconUrl(source.getIcon());\n\t}\n\n\tpublic void displayFavicon(Article article, ImageLoadingListener listener) {\n\t\tloader.loadImage(faviconUrl(article), listener);\n\t}\n\n\tpublic void displayFavicon(Article article, ImageView imageView) {\n\t\tloader.displayImage(faviconUrl(article), imageView);\n\t}\n\n\tpublic void displayFavicon(Source source, ImageView imageView) {\n\t\tloader.displayImage(faviconUrl(source), imageView);\n\t}\n\n\tpublic void displayImage(Article article, ImageView image) {\n\t\tloader.displayImage(article.getImageUrl(), image);\n\t}\n\n\tpublic Bitmap loadImageSync(String imageUrl) {\n\t\treturn loader.loadImageSync(imageUrl);\n\t}\n\n\t@Override\n\tpublic InputStream getStream(String imageUrl, Object extra) throws IOException {\n\t\tConfig config = configManager.get();\n\t\tLog.d(\"Plop\", imageUrl);\n\t\tURL url = new URL(imageUrl);\n\t\tURLConnection http = url.openConnection();\n\t\tif (config != null && config.requireAuth()) {\n\t\t\tString auth = config.getUsername() + \":\" + config.getPassword();\n\t\t\tString authHeader = \"Basic \" + Base64.encodeToString(auth.getBytes(Charset.forName(\"US-ASCII\")), Base64.DEFAULT);\n\t\t\thttp.setRequestProperty(\"Authorization\", authHeader);\n\t\t}\n\t\treturn http.getInputStream();\n\t}\n}" ]
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.OrmLiteDao; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.rest.RestService; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import fr.ydelouis.selfoss.entity.Article; import fr.ydelouis.selfoss.entity.ArticleType; import fr.ydelouis.selfoss.entity.Tag; import fr.ydelouis.selfoss.model.ArticleSyncActionDao; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.ArticleSyncAction; import fr.ydelouis.selfoss.util.ArticleContentParser; import fr.ydelouis.selfoss.util.SelfossImageLoader;
package fr.ydelouis.selfoss.rest; @EBean public class SelfossRestWrapper { @RestService protected SelfossRest rest; @OrmLiteDao(helper = DatabaseHelper.class)
protected ArticleSyncActionDao articleSyncActionDao;
3
wrey75/WaveCleaner
src/main/java/com/oxande/xmlswing/components/FrameUI.java
[ "public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> LIST_SEL_MODE = new HashMap<String, String>();\r\n\t\r\n\tstatic {\r\n\t\t\r\n\t\tCURSORS.put( \"crosshair\", \"CROSSHAIR_CURSOR\" );\r\n\t\tCURSORS.put( \"default\", \"DEFAULT_CURSOR\" );\r\n\t\tCURSORS.put( \"hand\", \"HAND_CURSOR\" );\r\n\t\tCURSORS.put( \"move\", \"MOVE_CURSOR\" );\r\n\t\t\r\n//\t\tpublic static final int \tCUSTOM_CURSOR \t-1\r\n//\t\tpublic static final int \tN_RESIZE_CURSOR \t8\r\n//\t\tpublic static final int \tNE_RESIZE_CURSOR \t7\r\n//\t\tpublic static final int \tNW_RESIZE_CURSOR \t6\r\n//\t\tpublic static final int \tS_RESIZE_CURSOR \t9\r\n//\t\tpublic static final int \tSE_RESIZE_CURSOR \t5\r\n//\t\tpublic static final int \tSW_RESIZE_CURSOR \t4\r\n//\t\tCURSORS.put( \"\", \"W_RESIZE_CURSOR\" );\r\n\t\t\r\n\t\tCURSORS.put( \"text\", \"TEXT_CURSOR\" );\r\n\t\tCURSORS.put( \"wait\", \"WAIT_CURSOR\" );\r\n\t\t\r\n\t\tCLOSE_OPERATIONS.put( \"nothing\", \"DO_NOTHING_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"hide\", \"HIDE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"dispose\", \"DISPOSE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"exit\", \"EXIT_ON_CLOSE\" );\r\n\r\n\t\tString scName = SwingConstants.class.getName();\r\n\t\tALIGNS.put( \"bottom\", scName + \".BOTTOM\" );\r\n\t\tALIGNS.put( \"center\", scName + \".CENTER\" );\r\n\t\tALIGNS.put( \"east\", scName + \".EAST\" );\r\n\t\tALIGNS.put( \"leading\", scName + \".LEADING\" );\r\n\t\tALIGNS.put( \"left\", scName + \".LEFT\" );\r\n\t\tALIGNS.put( \"next\", scName + \".NEXT\" );\r\n\t\tALIGNS.put( \"north\", scName + \".NORTH\" );\r\n\t\tALIGNS.put( \"right\", scName + \".RIGHT\" );\r\n\t\tALIGNS.put( \"top\", scName + \".TOP\" );\r\n\t\tALIGNS.put( \"trailing\", scName + \".TRAILING\" );\r\n\t\tALIGNS.put( \"west\", scName + \".WEST\" );\r\n\t\t\r\n\t\t\r\n\t\tLIST_SEL_MODE.put(\"single\", \"javax.swing.ListSelectionModel.SINGLE_SELECTION\" ); \r\n\t\tLIST_SEL_MODE.put(\"interval\", \"javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION\" );\r\n\t\tLIST_SEL_MODE.put(\"any\", \"javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION\" );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Values for automatic affectation of the correct\r\n\t * parameters for the methods. \r\n\t *\r\n\t */\r\n\tpublic enum ClassType {\r\n\t\tTEXT,\r\n\t\tSTRING,\r\n\t\tCHAR,\r\n\t\tINTEGER,\r\n\t\tBOOLEAN,\r\n\t\tPERCENT,\r\n\t\tCOLOR,\r\n\t\tALIGNMENT,\r\n\t\tDIMENSION,\r\n\t\tINSETS,\r\n\t\tKEYSTROKE,\r\n\t\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\t\tJSPLITPANE_ORIENTATION,\r\n\t\tJLIST_ORIENTATION,\r\n\t\tICON,\r\n\t\tCURSOR,\r\n\t\tCOMPONENT,\r\n\t\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\t\tJLIST_SELECT_MODE,\r\n\t};\r\n\t\r\n\tprivate String attrName;\r\n\tprivate String methodName;\r\n\tprivate String defaultValue = null;\r\n\tprivate ClassType type;\r\n\t\r\n\t/**\r\n\t * Create the attribute.\r\n\t * \r\n\t * @param attributeName the attribute name.\r\n\t * @param methodName the method name (if <code>null</code> then\r\n\t * \t\t\tthe method name is created implicitly based on\r\n\t * \t\t\tthe attribute name with the first character capitalized\r\n\t * \t\t\tand prefixed by \"set\".\r\n\t * @param type the type of the expected variable.\r\n\t * @param defaultValue the default value if exists (usually not provided).\r\n\t * \t\t\tThis default value is used only for some attribute types.\r\n\t */\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type, String defaultValue ){\r\n\t\tthis.attrName = attributeName;\r\n\t\tif( methodName == null ){\r\n\t\t\tthis.methodName = \"set\" + UIParser.capitalizeFirst(attributeName);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthis.methodName = methodName;\r\n\t\t}\r\n\t\tthis.type = type;\r\n\t\tthis.defaultValue = defaultValue;\r\n\t}\r\n\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type ){\r\n\t\tthis( attributeName, methodName, type, null );\r\n\t}\r\n\r\n\tpublic String getParameterIfExist( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\treturn( params == null ? null : params[0]);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the parameters for this element.\r\n\t * \r\n\t * @param e the element.\r\n\t * @return the list of the arguments or <code>null</code>\r\n\t * \t\tif there is no attribute for this definition.\r\n\t * @throws UnexpectedTag \r\n\t */\r\n\tpublic String[] getParameters( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = null;\r\n\t\t\r\n\t\tswitch( type ){\r\n\t\tcase TEXT :\r\n\t\t\tString txt = Parser.getTextContents(e).trim();\r\n\t\t\tif( txt.trim().length() == 0 ){\r\n\t\t\t\ttxt = Parser.getAttribute(e, \"text\");\r\n\t\t\t}\r\n\t\t\tif( txt != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(txt) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase BOOLEAN :\r\n\t\t\tBoolean b = Parser.getBooleanAttribute(e, attrName);\r\n\t\t\tif( b != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(b) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INTEGER :\r\n\t\t\tInteger i = Parser.getIntegerAttribute(e, attrName);\r\n\t\t\tif( i != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( i ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase PERCENT :\r\n\t\t\tDouble percent = Parser.getPercentageAttribute(e, attrName);\r\n\t\t\tif( percent != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( percent.doubleValue() ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase STRING :\r\n\t\t\tString s = Parser.getStringAttribute(e, attrName, defaultValue );\r\n\t\t\tif( s != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( s ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CHAR :\r\n\t\t\tString chars = Parser.getAttribute(e, attrName);\r\n\t\t\tif( chars != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( chars.charAt(0) ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase COLOR :\r\n\t\t\tColor color = Parser.getColorAttribute(e, attrName);\r\n\t\t\tif( color != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( color ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ALIGNMENT :\r\n\t\t\tString align = Parser.getAttribute(e, attrName);\r\n\t\t\tif( align != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = ALIGNS.get( align.trim().toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ICON :\r\n\t\t\tString iconName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( iconName != null ){\r\n\t\t\t\tString icon;\r\n\t\t\t\tif( iconName.startsWith(\"http:\" ) || iconName.startsWith(\"ftp:\" ) ){\r\n\t\t\t\t\ticon = \"new \" + ImageIcon.class.getName() + \"( new \" + URL.class.getName() + \"( \" + iconName + \") )\";\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ticon = \"(new javax.swing.ImageIcon(getClass().getResource(\" + JavaClass.toParam(iconName) + \")))\";\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { icon };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CURSOR :\r\n\t\t\tString cursorName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( cursorName != null ){\r\n\t\t\t\tString cursor = Cursor.class.getName() + \"getPredefinedCursor( \" + Cursor.class.getName() + cursorName + \") )\";\r\n\t\t\t\tparams = new String[] { cursor };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JSPLITPANE_ORIENTATION :\r\n\t\t\tString orientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.HORIZONTAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JLIST_ORIENTATION :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"hwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JList.HORIZONTAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"hwrap, vwrap or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase DIMENSION :\r\n\t\t\tString dim = Parser.getAttribute(e, attrName);\r\n\t\t\tif( dim != null ){\r\n\t\t\t\tString[] vector = dim.split(\",\");\r\n\t\t\t\tif( vector.length < 2 ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects 2 comma separated values.\" );\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint width = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\tint height = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Dimension(\" + width + \",\" + height +\")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INSETS :\r\n\t\t\tString insets = Parser.getAttribute(e, attrName);\r\n\t\t\tif( insets != null ){\r\n\t\t\t\tString[] vector = insets.split(\",\");\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint top = 0, left = 0, bottom = 0, right = 0;\r\n\t\t\t\t\t// if only one value, the inset is assumed for others.\r\n\t\t\t\t\tswitch( vector.length ){\r\n\t\t\t\t\tcase 1 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = bottom = right = top;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 2 :\r\n\t\t\t\t\t\tbottom = top = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tright = left = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 4 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbottom = Integer.parseInt( vector[2].trim() );\r\n\t\t\t\t\t\tright = Integer.parseInt( vector[3].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault :\r\n\t\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects only 1, 2 or 4 numeric values.\" );\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Insets(\" + top + \",\" + left + \",\" + bottom + \",\" + right + \")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase KEYSTROKE :\r\n\t\t\tString keystroke = Parser.getAttribute(e, attrName);\r\n\t\t\tif( keystroke != null ){\r\n\t\t\t\tKeyStroke ks = KeyStroke.getKeyStroke(keystroke);\r\n\t\t\t\tif( ks == null ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"Keystroke \\\"\" + keystroke + \"\\\" invalid\" );\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { \"javax.swing.KeyStroke.getKeyStroke(\" + JavaClass.toParam(keystroke) + \")\" };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase JTABLE_AUTO_RESIZE :\r\n\t\t\tString autoResizeMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( autoResizeMode != null ){\r\n\t\t\t\tif( autoResizeMode.equalsIgnoreCase(\"off\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_OFF\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"next\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_NEXT_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"subsequent\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"last\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_LAST_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"all\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_ALL_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"JTable \\\"autoResizeMode\\\" attribute not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase JLIST_SELECT_MODE :\r\n\t\t\tString selectMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( selectMode != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = LIST_SEL_MODE.get( selectMode.toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"value \\\"\" + selectMode + \"\\\" for attribute \" + attrName + \" is not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase VERTICAL_OR_HORIZONTAL :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.HORIZONTAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag ('\" + orientation + \"') provided.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tdefault :\r\n\t\t\tif( Parser.getAttribute(e, attrName) != null ){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Type \" + type + \" not yet supported.\" );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn params;\r\n\t}\r\n\t\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\tif( params != null ){\r\n\t\t\tjmethod.addCall( varName + \".\" + methodName, params );\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n}\r", "public class AttributesController {\r\n\tList<AttributeDefinition> list = new ArrayList<AttributeDefinition>();\r\n\tAttributesController parent = null;\r\n\r\n\tpublic AttributesController( AttributesController parent, AttributeDefinition[] arr ){\r\n\t\tthis.parent = parent;\r\n\t\tthis.list.addAll( Arrays.asList(arr) );\r\n\t}\r\n\r\n\tpublic AttributesController( AttributeDefinition[] arr ){\r\n\t\tthis(null,arr);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the parent\r\n\t */\r\n\tpublic AttributesController getParent() {\r\n\t\treturn parent;\r\n\t}\r\n\r\n\t/**\r\n\t * @param parent the parent to set\r\n\t */\r\n\tpublic void setParent(AttributesController parent) {\r\n\t\tthis.parent = parent;\r\n\t}\r\n\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tif( parent != null ){\r\n\t\t\tparent.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t\tfor( AttributeDefinition def : list ){\r\n\t\t\tdef.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t}\r\n\t\r\n}\r", "public final class Parser {\r\n\tpublic static final Map<String, Color> COLORS = new HashMap<String, Color>();\r\n\t\r\n\tstatic {\r\n\t\tCOLORS.put( \"black\", Color.BLACK );\r\n\t\tCOLORS.put( \"blue\", Color.BLUE );\r\n\t\tCOLORS.put( \"cyan\", Color.CYAN );\r\n\t\tCOLORS.put( \"darkgray\", Color.DARK_GRAY );\r\n\t\tCOLORS.put( \"gray\", Color.GRAY );\r\n\t\tCOLORS.put( \"green\", Color.GREEN );\r\n\t\tCOLORS.put( \"lightgray\", Color.LIGHT_GRAY );\r\n\t\tCOLORS.put( \"magenta\", Color.MAGENTA );\r\n\t\tCOLORS.put( \"orange\", Color.ORANGE );\r\n\t\tCOLORS.put( \"pink\", Color.PINK );\r\n\t\tCOLORS.put( \"red\", Color.RED );\r\n\t\tCOLORS.put( \"white\", Color.WHITE );\r\n\t\tCOLORS.put( \"yellow\", Color.YELLOW );\r\n\t}\r\n\t\r\n\t/**\r\n\t * The attribute for the variable name of the component.\r\n\t */\r\n\tpublic static final String ID_ATTRIBUTE = \"id\";\r\n\t\r\n\t/**\r\n\t * The attribute for the class name of the component. Usually,\r\n\t * the class name is a predefined class, but if the developper\r\n\t * wants to used an extended class rather than the normal class,\r\n\t * he can do it by changing this attribute. This attribute is available\r\n\t * for any component.\r\n\t * \r\n\t */\r\n\tpublic static final String CLASS_ATTRIBUTE = \"class\";\r\n\t\r\n\tprivate static Map<String, Integer> ids = new HashMap<String, Integer>();\r\n\r\n\t/**\r\n\t * Clear the IDs created before.\r\n\t */\r\n\tpublic static void clearIds(){\r\n\t\tids.clear();\r\n\t}\r\n\t\r\n\tpublic static synchronized String getUniqueId( String root ){\r\n\t\tInteger id = null;\r\n\t\tsynchronized( ids ){\r\n\t\t\tid = ids.get(root);\r\n\t\t\tif( id == null ){\r\n\t\t\t\tid = new Integer(1);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tid = new Integer( id.intValue() + 1 );\r\n\t\t\t}\r\n\t\t\tids.put(root, id); // Store the new value\r\n\t\t}\r\n\t\treturn root + id.toString();\r\n\t}\r\n\r\n\tpublic static Element getChildElement( Element root, String tagName ) {\r\n\t\tList<Element> list = getChildElements(root,tagName);\r\n\t\tswitch( list.size() ){\r\n\t\t\tcase 0:\r\n\t\t\t\treturn null;\r\n\t\t\t\t\r\n\t\t\tcase 1: \r\n\t\t\t\treturn list.get(0);\r\n\t\t\t\t\r\n\t\t\tdefault :\r\n\t\t\t\tthrow new IllegalArgumentException( \"Multiple <\" + tagName + \"> found. Only one expected.\" ); \r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElements( Element root, String tagName ){\r\n\t\tList<Element> selected = new LinkedList<Element>();\r\n\t\tList<Element> childs = getChildElements(root);\r\n\t\tfor( Element e : childs ){\r\n\t\t\tif( e.getTagName().equals(tagName) ){\r\n\t\t\t\tselected.add(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn selected;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve the elements contained in the parent element.\r\n\t * \r\n\t * @param e the parent element\r\n\t * @return the child elements.\r\n\t */\r\n\tpublic static List<Element> getChildElements( Element e ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\telements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElementsExcept( Element e, String ... list ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\tString nodeName = node.getNodeName();\r\n\t\t\t\tboolean toBeAdded = true;\r\n\t\t\t\tfor(int j = 0; j < list.length; j++){\r\n\t\t\t\t\tif( nodeName.equalsIgnoreCase(list[j]) ){\r\n\t\t\t\t\t\ttoBeAdded = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif( toBeAdded ) elements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\r\n\t/**\r\n\t * The attribute as a string.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute.\r\n\t * @param mandatory if the attribute is mandatory (if the attribute is\r\n\t * \t\tmandatory and not found or is empty, a {@link NullPointerException}\r\n\t * \t\tis thrown).\r\n\t * @return the string value or <code>null</code> if not exists or is\r\n\t * \t\tempty.\r\n\t */\r\n\tpublic static String getAttribute( Element e, String attributeName, boolean mandatory ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\tif( mandatory && value == null ){\r\n\t\t\tthrow new NullPointerException( \"<\" + e.getNodeName() + \">: attribute \\\"\" + attributeName + \"\\\" expected.\");\r\n\t\t}\r\n\t\treturn value;\r\n\t}\r\n\r\n\tpublic static String getStringAttribute( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\treturn (value == null ? defaultValue : value );\r\n\t}\r\n\r\n\tpublic static String getAttribute( Element e, String attributeName ){\r\n\t\treturn getAttribute(e, attributeName, false);\r\n\t}\r\n\r\n\t/**\r\n\t * Get the color attribute. The attribute returned is a \r\n\t * {@link Color} instance (or <code>null</code> if it is not\r\n\t * possible to decode).\r\n\t * \r\n\t * <p>\r\n\t * A color is analysed based on the color's name (yellow, cyan,\r\n\t * dark, etc.) or by the \"<code>#</code>\" character followed\r\n\t * by the color expressed in hexadecimal using the form RRGGBB.\r\n\t * For example, \"<code>#00ff00</code>\" is used for the green color.\r\n\t * </p>\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name for the color.\r\n\t * @return <code>null</code> is the attribute is empty or\r\n\t * \t\tdoes not exist or we are not able to decode the color,\r\n\t * \t\tthe color value.\r\n\t */\r\n\tpublic static Color getColorAttribute( Element e, String attributeName ){\r\n\t\tColor color = null;\r\n\t\tString s = getAttribute(e, attributeName, false);\r\n\t\tif( s != null && s.length() > 0 ){\r\n\t\t\tif( s.charAt(0) == '#' ){\r\n\t\t\t\t// RVB color...\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint rgb = Integer.parseInt( s.substring(1).trim(), 16 );\r\n\t\t\t\t\tcolor = new Color(rgb);\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\t// Error displayed below.\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// Use the color array.\r\n\t\t\t\tcolor = COLORS.get(s.toLowerCase());\r\n\t\t\t\tif( color == null ){\r\n\t\t\t\t\t// Last hope before we cancel!\r\n\t\t\t\t\tcolor = Color.getColor(s);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif( color == null ){\r\n\t\t\t\tSystem.err.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to a color.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn color;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Retrieve the class name for the tag or the defaulted one.\r\n\t * When an object is instantied, we use a default class \r\n\t * (a &lt;label&gt; will create a <code>JLabel</code> obejct)\r\n\t * but you can override the class with the \"class\" attribute\r\n\t * in the tag. This is a solution to provide more power\r\n\t * to an object.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param clazz the default class to use.\r\n\t * @return the class to be declared in the JAVA code.\r\n\t * \r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz ){\r\n\t\tString className = getAttribute(e, CLASS_ATTRIBUTE);\r\n\t\treturn( className == null ? clazz.getName() : className );\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Get the name of the the object. When a tag declares a\r\n\t * new object, this object can have a name (in this case, it\r\n\t * can be accessed by a derived class) or anonymous (the name\r\n\t * is created based on the <i>rootName</> parameter). In many\r\n\t * case, it is not necessary to declare a name except you have\r\n\t * to access the object in the derived class.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param rootName the default root naming in case the name is\r\n\t * \t\tcreated as an anomymous.\r\n\t * @return the name of the object.\r\n\t * @deprecated do not use anymore because you do not know if \r\n\t * \t\tthe variable is anonymous or not!\r\n\t * @see #addDeclaration(JavaClass, Element, Class) as replacement.\r\n\t */\r\n\tpublic static String getVariableName( Element e, String rootName ){\r\n\t\tString varName = getAttribute(e, ID_ATTRIBUTE);\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId(rootName);\r\n\t\t}\r\n\t\treturn varName;\t\t\r\n\t}\r\n\r\n\tpublic static String normalized( String s ){\r\n\t\tif( s == null ) return null;\r\n\t\ts = s.trim();\r\n\t\treturn ( s.length() == 0 ? null : s );\r\n\t}\r\n\t\r\n\tprivate static String cleanOf( String source ){\r\n\t\tint len = source.length();\r\n\t\tStringBuilder buf = new StringBuilder(len);\r\n\t\tboolean lastCharIsSpace = true;\r\n\t\tfor( int i = 0; i < len; i++ ){\r\n\t\t\tchar c = source.charAt(i);\r\n\t\t\tboolean isSpace = Character.isWhitespace(c);\r\n\t\t\tif( !isSpace ){\r\n\t\t\t\tlastCharIsSpace = false;\r\n\t\t\t\tbuf.append(c);\r\n\t\t\t}\r\n\t\t\telse if(!lastCharIsSpace){\r\n\t\t\t\tbuf.append(' ');\r\n\t\t\t\tlastCharIsSpace = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString().trim();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the text contents for a tag. Retrieve the text\r\n\t * enclosed between the beginning and the end of the\r\n\t * tag <i>excluding</i> the text of inner tags.\r\n\t * \r\n\t * <p>\r\n\t * &lt;p&gt;This is an &lt;emph>emphazed&lt;/p&gt; text.&lt;/code&gt;\r\n\t * will return \"This is an text.\"\r\n\t * </p>\r\n\t * \r\n\t * @param e the tag.\r\n\t * @return the text stored in the tag.\r\n\t */\r\n\tpublic static String getTextContents( Element e){\r\n\t\tif(e.hasAttribute(\"_text\")){\r\n\t\t\treturn e.getAttribute(\"_text\");\r\n\t\t}\r\n\r\n\t\t// Look in children\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tNodeList list = e.getChildNodes();\r\n\t\tfor( int i = 0; i < list.getLength(); i++ ){\r\n\t\t\tNode node = list.item(i);\r\n\t\t\tswitch( node.getNodeType() ){\r\n\t\t\t\tcase Node.TEXT_NODE :\r\n\t\t\t\t\tbuf.append( cleanOf( node.getNodeValue() ) );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.CDATA_SECTION_NODE :\r\n\t\t\t\t\tbuf.append( node.getNodeValue() );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.ELEMENT_NODE :\r\n\t\t\t\t\tElement elem = (Element)node;\r\n\t\t\t\t\tif( elem.getNodeName().equalsIgnoreCase(\"br\") ){\r\n\t\t\t\t\t\tbuf.append(\"\\n\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the boolean attribute.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name.\r\n\t * @param defaultValue the default value returned if the attribute does not\r\n\t * \t\texists or is not set to <code>true</code> or <code>false</code>.\r\n\t * @return the value of the attribute or the default value.\r\n\t */\r\n\tpublic static boolean getBooleanAttribute( Element e, String attributeName, boolean defaultValue ){\r\n\t\tBoolean b = getBooleanAttribute(e, attributeName);\r\n\t\tif( b == null ){\r\n\t\t\treturn defaultValue;\r\n\t\t}\r\n\t\treturn b.booleanValue();\r\n\t}\r\n\r\n\tpublic static Boolean getBooleanAttribute( Element e, String attributeName ){\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(true)) ) return true;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(false)) ) return false;\r\n\t\tSystem.out.println( \"<\" + e.getNodeName() + \"> is expected to have true/false for the attribute \\\"\" + attributeName + \"\\\" instead of \\\"\" + s + \"\\\"\" );\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic static Integer getIntegerAttribute( Element e, String attributeName ){\r\n\t\tInteger ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tret = Integer.parseInt(s);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static int getIntegerAttribute( Element e, String attributeName, int defaultValue ){\r\n\t\tInteger ret = getIntegerAttribute(e,attributeName);\r\n\t\treturn( ret == null ? defaultValue : ret.intValue() );\r\n\t}\r\n\r\n\t/**\r\n\t * Get the percentage value. The percentage value can be expressed\r\n\t * directly (with 0.250 for example) or with the percentage\r\n\t * character (25%) at your convenience.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute to extract.\r\n\t * @return the value expressed as a double (a range from\r\n\t * \t\t0.0 to 1.0� or <code>null</code> if no data available.\r\n\t * \r\n\t */\r\n\tpublic static Double getPercentageAttribute( Element e, String attributeName ){\r\n\t\tdouble factor = 1;\r\n\t\tDouble ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tif( s.endsWith(\"%\") ){\r\n\t\t\t\tfactor = 0.01;\r\n\t\t\t\ts = s.substring(0, s.indexOf(\"%\") ).trim();\r\n\t\t\t}\r\n\t\t\tret = new Double( Double.parseDouble(s) * factor);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, Class<?> clazz ){\r\n\t\tString className = getClassName( e, clazz, jclass );\r\n\t\treturn addDeclaration(jclass, e, className, ID_ATTRIBUTE );\r\n\t}\r\n\t\r\n\tpublic static String getSimpleName( String fullName ){\r\n\t\tint pos = fullName.lastIndexOf(\".\");\r\n\t\tif( pos > 0 ){\r\n\t\t\treturn fullName.substring(pos+1);\r\n\t\t}\r\n\t\treturn fullName;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, String className, String attributeName ){\r\n\t\tString modifier = \"protected\";\r\n\t\t\r\n\t\tString varName = (e == null ? null : getAttribute(e, attributeName));\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId( getSimpleName(className).toLowerCase() );\r\n\t\t\tmodifier = \"private\";\r\n\t\t}\r\n\r\n\t\tjclass.addAnonymousDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tjclass.register( varName, className );\r\n\t\treturn varName;\r\n\t}\r\n\r\n\t/**\r\n\t * Get the class name.\r\n\t * \r\n\t * @param e the element.\r\n\t * @param clazz the default class, this value is overrided if\r\n\t * a attribute {@link #CLASS_ATTRIBUTE} is found.\r\n\t * @param jclass the class on which we declare the import. \r\n\t * @return the name of the class to use to initialize the variables\r\n\t * \t\tin the sepcified class.\r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz, JavaClass jclass ){\r\n\t\tString className = (e == null ? null : Parser.getAttribute(e, CLASS_ATTRIBUTE));\r\n\t\tif( className == null ){\r\n\t\t\t// Only import standard classes. For classes defined by the user,\r\n\t\t\t// we must avoid use the import process to avoid issues on names.\r\n\t\t\tjclass.addImport(clazz);\r\n\t\t\tclassName = clazz.getSimpleName();\t\t\r\n\t\t}\r\n\t\treturn className;\r\n\t}\r\n\r\n\tpublic static void setDefaultAttributeValue( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = getAttribute(e, attributeName);\r\n\t\tif( value == null ){\r\n\t\t\te.setAttribute(attributeName, defaultValue);\r\n\t\t}\r\n\t}\r\n}\r", "public enum ClassType {\r\n\tTEXT,\r\n\tSTRING,\r\n\tCHAR,\r\n\tINTEGER,\r\n\tBOOLEAN,\r\n\tPERCENT,\r\n\tCOLOR,\r\n\tALIGNMENT,\r\n\tDIMENSION,\r\n\tINSETS,\r\n\tKEYSTROKE,\r\n\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\tJSPLITPANE_ORIENTATION,\r\n\tJLIST_ORIENTATION,\r\n\tICON,\r\n\tCURSOR,\r\n\tCOMPONENT,\r\n\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\tJLIST_SELECT_MODE,\r\n};\r", "@SuppressWarnings(\"serial\")\r\npublic class UnexpectedTag extends SAXException {\r\n\tpublic UnexpectedTag( Element e ){\r\n\t\tsuper(\"Tag <\" + e.getTagName() + \"> unexpected. XPath = \" + xpath(e) );\r\n\t}\r\n\r\n\tpublic UnexpectedTag( String text ){\r\n\t\tsuper(text);\r\n\t}\r\n\t\r\n\tpublic UnexpectedTag( Element e, String text ){\r\n\t\tsuper(\"XPath = \" + xpath(e) + \": \" + text );\r\n\t}\r\n\r\n\tpublic static String xpath(Element root ){\r\n\t\tString ret = \"\";\r\n\t\tNode e = root;\r\n\t\twhile( e != null ) {\r\n\t\t\tret = \"/\" + e.getNodeName() + ret;\r\n\t\t\te = e.getParentNode();\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n}\r", "public class JavaClass extends JavaCode {\r\n\tprivate String fullClassName = null;\r\n\tprivate String extClassName = null;\r\n\tprivate Set<String> implementInterfaces = new HashSet<String>(); \r\n\tprivate JavaType javaType = new JavaType();\r\n\tprivate JavaComments comments = null;\r\n\tprivate LinesOfCode declarations = new LinesOfCode();\r\n\tprivate Set<String> importSet = new HashSet<String>(); \r\n\tprivate Map<String, JavaMethod> methods = new HashMap<String, JavaMethod>();\r\n\tprivate LinesOfCode staticCode = new LinesOfCode();\r\n\tprivate Map<String,JavaClass> innerClasses = new HashMap<String, JavaClass>();\r\n\tprivate Properties props = new Properties();\r\n\tprivate Map<String,String> registered = new HashMap<String, String>();\r\n\r\n\tpublic void addStatic( JavaCode code ){\r\n\t\tstaticCode.addCode(code);\r\n\t}\r\n\r\n\tpublic void addStatic( String line ){\r\n\t\tstaticCode.addCode( new LineOfCode(line) );\r\n\t}\r\n\r\n\t/**\r\n\t * Add the interface. Note once the class implements\r\n\t * an interface, this interface is imported.\r\n\t * \r\n\t * @param iClass the interface class. \r\n\t */\r\n\tpublic void addInterface( Class<?> iClass ){\r\n\t\taddImport(iClass);\r\n\t\timplementInterfaces.add(iClass.getSimpleName());\r\n\t}\r\n\r\n\tpublic void addInterface( String iClass ){\r\n\t\timplementInterfaces.add(iClass);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the comments\r\n\t */\r\n\tpublic JavaComments getComments() {\r\n\t\treturn comments;\r\n\t}\r\n\r\n\t/**\r\n\t * @param comments the comments to set\r\n\t */\r\n\tpublic void setComments(JavaComments comments) {\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve a method based on its name. Note if\r\n\t * several methods having the same name\r\n\t * have been added to this class,\r\n\t * only the first one is returned.\r\n\t * \r\n\t * @param name the method name.\r\n\t * @return the method if one exists with the specified\r\n\t * \t\tname, if not return <code>null</code>.\r\n\t */\r\n\tpublic JavaMethod getMethod( String name ){\r\n\t\treturn methods.get(name);\r\n\t}\r\n\r\n\tpublic String addMethodIfNotExists( JavaMethod m ){\r\n\t\tif( getMethod( m.getName()) == null ){\r\n\t\t\treturn addMethod(m);\r\n\t\t}\r\n\t\treturn m.getName();\r\n\t}\r\n\r\n\tpublic String addMethod( JavaMethod m ){\r\n\t\tString root = m.getName();\r\n\t\tif( methods.containsKey(root) ){\r\n\t\t\tint i = 1;\r\n\t\t\twhile( methods.containsKey(m.getName()+\".\"+i) ){\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\troot = m.getName() + \".\" + i;\r\n\t\t}\r\n\t\tmethods.put( root, m);\r\n\t\treturn root;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Add an anonymous declaration. It means you have to\r\n\t * give all the declaration but the variable is not registred.\r\n\t * \r\n\t * @param lineOfCode the line of code to add in the \r\n\t * \t\tdeclaration part of the class.\r\n\t * @see #register(String, Class) for registring the\r\n\t * \t\tvariable (if necessary).\r\n\t */\r\n\tpublic void addAnonymousDeclaration( CharSequence lineOfCode ) {\r\n\t\tdeclarations.addCode(lineOfCode);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a declaration. \r\n\t * \r\n\t * @param varName the variable name;\r\n\t * @param type the Java type.\r\n\t * @param params the parameters for the initialization. If\r\n\t * \t\t<code>null</code>, there is no initialisation. A\r\n\t * \t\t<code>null</code> array (or no parameter) means\r\n\t * \t\tthe variable is created empty.\r\n\t */\r\n\tpublic void addDeclaration( String varName, JavaType type, String[] params ) {\r\n\t\t// jclass.addDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tbuf.append( type ).append(\" \").append(varName);\r\n\t\tif( params != null ){\r\n\t\t\tbuf.append( \" = new \" ).append( type.getClassName() ).append(\"(\");\r\n\t\t\tfor( int i = 0; i < params.length; i++ ){\r\n\t\t\t\tif( i > 1 ) buf.append(\", \");\r\n\t\t\t\tbuf.append( params[i] );\r\n\t\t\t}\r\n\t\t\tbuf.append(\")\");\r\n\t\t}\r\n\t\tbuf.append(\";\");\r\n\t\tdeclarations.addCode(buf.toString());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add the class specified as an import of\r\n\t * the current class. It simplifies the code\r\n\t * created.\r\n\t * \r\n\t * @param className the class name.\r\n\t * @see #addImport(Class)\r\n\t */\r\n\tpublic void addImport( String className ){\r\n\t\timportSet.add(className);\r\n\t}\r\n\r\n\t/**\r\n\t * Import a new class in the class. The class can\r\n\t * be referenced with its simple name. For example,\r\n\t * if you import the <code>java.util.List</code> class,\r\n\t * you will be able to refer to it with <code>List</code>\r\n\t * only.\r\n\t * \r\n\t * <p>You can import the same class multiple times:\r\n\t * the class name imported is registred to avoid\r\n\t * duplicate lines in the final code.\r\n\t * </p>\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t */\r\n\tpublic void addImport( Class<?> clazz ){\r\n\t\taddImport( clazz.getName() );\r\n\t}\r\n\r\n\t/**\r\n\t * Creates the class.\r\n\t * \r\n\t * @param name the class name (a full name including\r\n\t * \t\tthe package; if not the class will be created\r\n\t * \t\tin the default package).\r\n\t */\r\n\tpublic JavaClass( String name ){\r\n\t\tthis.fullClassName = name;\r\n\t}\r\n\t\r\n\tpublic JavaMethod getConstructor( JavaParam ... params ){\r\n\t\tJavaMethod constructor = new JavaMethod( this.getClassName() );\r\n\t\tconstructor.setReturnType(new JavaType(\"\"));\r\n\t\tconstructor.setParams(params);\r\n\t\taddMethod(constructor);\r\n\t\treturn constructor;\r\n\t}\r\n\t\r\n\tpublic String getClassName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? fullClassName : fullClassName.substring(pos+1) );\r\n\t}\r\n\r\n\t/**\r\n\t * Checks if a class has been imported.\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t * @return <code>true</code> if the class already\r\n\t * \t\texists in the import list, <code>false</code>\r\n\t * \t\tin the other cases.\r\n\t */\r\n\tpublic boolean isImported( Class<?> clazz ){\r\n\t\treturn importSet.contains(clazz.getName());\r\n\t}\r\n\t\r\n\tpublic void setExtend( Class<?> clazz ){\r\n\t\textClassName = (isImported( clazz ) ? clazz.getSimpleName() : clazz.getName());\r\n\t}\r\n\r\n\tpublic void setExtend( String clazzName ){\r\n\t\textClassName = clazzName;\r\n\t}\r\n\t\r\n\tpublic static String name2file( String s ){\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tfor(int i = 0; i < s.length(); i++ ){\r\n\t\t\tchar c = s.charAt(i);\r\n\t\t\tswitch( c ){\r\n\t\t\tcase '.' : buf.append( File.separator ); break;\r\n\t\t\tdefault : buf.append(c); break;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the package name for this class.\r\n\t * \r\n\t * @return the package name\r\n\t */\r\n\tpublic String getPackageName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? null : fullClassName.substring(0,pos) );\r\n\t}\r\n\r\n\tpublic void newAnonymousClass( String className, JavaClass clazz, String params ) throws IOException {\r\n\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Write the class on the disk.\r\n\t * \r\n\t * @param rootDir the root directory for the JAVA source\r\n\t * \t\tcode.\r\n\t * @return the path of the JAVA class. \r\n\t * @throws IOException if an i/O error occurred.\r\n\t */\r\n\tpublic String writeClass( String rootDir ) throws IOException {\r\n\t\tString packageName = getPackageName();\r\n\t\tString className = getClassName();\r\n\t\t\r\n\t\tString packageDir = \"\";\r\n\t\tif( packageName != null ){\r\n\t\t\tpackageDir = File.separator + name2file( packageName );\r\n\t\t}\r\n\t\tString fileName = rootDir + packageDir + File.separator + className + \".java\";\r\n\t\t\r\n\t\tWriter w = new OutputStreamWriter( new FileOutputStream(fileName) );\r\n\t\tif( packageName != null ){\r\n\t\t\tprintln( w, \"package \" + packageName + \";\" );\r\n\t\t}\r\n\t\t\r\n\t\t// Import classes\r\n\t\tString[] importArray = importSet.toArray(new String[0]);\r\n\t\tArrays.sort(importArray);\r\n\t\tString rootName = \"\";\r\n\t\tfor( String importLibraryName : importArray ){\r\n\t\t\tString[] subNames = importLibraryName.split(\"\\\\.\");\r\n\t\t\tif( !subNames[0].equals(rootName) ){\r\n\t\t\t\tprintln(w);\r\n\t\t\t\trootName = subNames[0];\r\n\t\t\t}\r\n\t\t\tprintln( w, \"import \" + importLibraryName + \";\" );\r\n\t\t}\r\n\t\tprintln(w);\r\n\r\n\t\twriteCode(w, 0,false);\r\n\t\tw.close();\r\n\t\treturn fileName;\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs,false);\r\n\t}\r\n\r\n\tpublic void writeAnonymous(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs, true);\r\n\t}\r\n\r\n\tpublic String toParam() {\r\n\t\ttry {\r\n\t\t\tStringWriter w = new StringWriter(); \r\n\t\t\twriteCode(w, 0, true);\r\n\t\t\tw.close();\r\n\t\t\treturn w.getBuffer().toString();\r\n\t\t}\r\n\t\tcatch(IOException ex ){\r\n\t\t\tthrow new OutOfMemoryError(\"I/O Error:\" + ex.getMessage());\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void writeCode(Writer w, int tabs, boolean anonymous) throws IOException {\r\n\t\t\r\n\t\tif( anonymous ){\r\n\t\t\tw.write(\"new \" + getClassName() + \"() \" );\r\n\t\t}\r\n\t\telse {\r\n\t\t\t// Comments\r\n\t\t\tif( comments != null ) comments.writeCode(w, tabs);\r\n\t\t\r\n\t\t\t// Class declaration\r\n\t\t\tjavaType.setClassName(\"class\");\r\n\t\t\tw.write( javaType + \" \" + getClassName() );\r\n\t\t\tif( extClassName != null ) {\r\n\t\t\t\tString extend = \"extends\";\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass<?> clazz = Class.forName(extClassName);\r\n\t\t\t\t\tif( clazz.isInterface() ){\r\n\t\t\t\t\t\textend = \"implements\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch(ClassNotFoundException ex){\r\n\t\t\t\t\t// Simply ignore in case we not found the class\r\n\t\t\t\t}\r\n\t\t\t\tw.write( \" \" + extend + \" \" + extClassName );\r\n\t\t\t}\r\n\r\n\t\t\tif( this.implementInterfaces.size() > 0 ){\r\n\t\t\t\t// Interfaces implemented.\r\n\t\t\t\tboolean first = true;\r\n\t\t\t\tfor(String className : this.implementInterfaces){\r\n\t\t\t\t\tw.write( first ? \" implements \" : \", \" );\r\n\t\t\t\t\tw.write(className);\r\n\t\t\t\t\tfirst = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tw.write( \" {\" + JavaCode.CRLF );\r\n\t\t\r\n\t\tdeclarations.writeCode(w, tabs + 1);\r\n\t\t\r\n\t\tif( staticCode.size() > 0 ){\r\n\t\t\tString prefix = (anonymous ? \"\" : \"static \");\r\n\t\t\tw.write( getTabulations(tabs+1) + prefix + \"{\" + JavaCode.CRLF );\r\n\t\t\tstaticCode.writeCode(w, tabs+2);\r\n\t\t\tw.write( getTabulations(tabs+1) + \"}\" + JavaCode.CRLF );\r\n\t\t}\r\n\r\n\t\tfor( JavaClass c : innerClasses.values() ){\r\n\t\t\tc.writeCode(w, tabs+1, false);\r\n\t\t}\r\n\r\n\t\t// Methods...\r\n\t\tfor( JavaMethod m : methods.values() ){\r\n\t\t\tprintln(w);\r\n\t\t\tm.writeCode(w, tabs+1);\r\n\t\t}\r\n\t\t\r\n\t\t// Class ending\r\n\t\tw.write( \"}\" + JavaCode.CRLF + JavaCode.CRLF );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Register an object. The registration of an object\r\n\t * is a simple way to mark the object to be owned\r\n\t * by the class. It is just a flag (no code is\r\n\t * associated). The registration is used to\r\n\t * register a group or some similar stuff.\r\n\t * \r\n\t * @param obj the name of the object to register.\r\n\t * @param clazz the class of the object.\r\n\t */\r\n\tpublic void register( String obj, Class<?> clazz ){\r\n\t\tregistered.put(obj, clazz.getName());\r\n\t}\r\n\r\n\tpublic void register( String obj, String className ){\r\n\t\tregistered.put(obj, className );\r\n\t}\r\n\r\n\tpublic boolean isRegistered( String obj ){\r\n\t\tString className = registered.get(obj);\r\n\t\treturn (className != null);\r\n\t}\r\n\t\r\n\tpublic void addInnerClass( JavaClass jclass ){\r\n\t\tinnerClasses.put( jclass.getClassName(), jclass );\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Dummy method: returns 0x0104 for the release\r\n\t * 1.5 of the JAVA classes.\r\n\t * \r\n\t * @return the version of the java classes.\r\n\t * \r\n\t */\r\n\tpublic int getVersion() {\r\n\t\treturn 0x0105;\r\n\t}\r\n\r\n /**\r\n * Set a property to this class. A proprty has no meaning and is\r\n * not used to construct the class. Nevertheless, it can be helpful\r\n * to store some global information during the construction of the\r\n * class. \r\n *\r\n * @param key the key to be placed into this property list.\r\n * @param value the value corresponding to <tt>key</tt>.\r\n * @see #getProperty\r\n */\r\n\tpublic void setProperty(String key, String value){\r\n\t\tprops.setProperty(key, value);\r\n\t}\r\n\r\n /**\r\n * Searches for the property with the specified key in this property list.\r\n * If the key is not found in this property list, the method returns\r\n * <code>null</code>.\r\n *\r\n * @param key the property key.\r\n * @return the value in this property list with the specified key value.\r\n * @see #setProperty\r\n */\r\n\tpublic String getProperty(String key){\r\n\t\treturn props.getProperty(key);\r\n\t}\r\n\t\r\n\tpublic void setModifiers( int modifiers ){\r\n\t\tjavaType.setAccess(modifiers);\r\n\t}\r\n}\r", "public abstract class JavaCode {\r\n\r\n\tpublic static final String TABULATION = \" \";\r\n\tpublic static final String CRLF = System.getProperty(\"line.separator\");\r\n\t\r\n\t/**\r\n\t * The method to write the code into a stream.\r\n\t * \r\n\t * @param writer a writer where the JAVA code is outputted.\r\n\t * @param tabs the number of tabulations.\r\n\t * @throws IOException if an I/O error occurs.\r\n\t */\r\n\tprotected abstract void writeCode( Writer writer, int tabs ) throws IOException;\r\n\t\r\n\t/**\r\n\t * Retrieve a string containing the required tabulations.\r\n\t * \r\n\t * @param tabs the number of tabulations.\r\n\t * @return the representation of the tabulations.\r\n\t */\r\n\tprotected static String getTabulations( int tabs ){\r\n\t\tStringBuilder buf = new StringBuilder( tabs * TABULATION.length() );\r\n\t\tfor(int i = 0; i < tabs; i++ ){\r\n\t\t\tbuf.append( TABULATION );\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Writes an empty line to the writer.\r\n\t * \r\n\t * @param w the writer.\r\n\t * @throws IOException if an I/O error occurs.\r\n\t */\r\n\tprotected static void println( Writer w ) throws IOException {\r\n\t\tw.write(CRLF);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Writes a string to the writer and goes to the next line.\r\n\t * \r\n\t * @param w the writer.\r\n\t * @throws IOException if an I/O error occurs.\r\n\t */\r\n\tprotected static void println( Writer w, String str ) throws IOException {\r\n\t\tw.write(str + CRLF);\r\n\t}\r\n\r\n\t/**\r\n\t * Return an overview of the current code.\r\n\t * \r\n\t */\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\r\n\t\ttry {\r\n\t\t\tPrintWriter w = new PrintWriter( out );\r\n\t\t\twriteCode(w, 0);\r\n\t\t} catch (IOException e) {\r\n\t\t\t// No I/O error is possible for a memory writer.\r\n\t\t}\r\n\t\t\r\n\t\tString ret;\r\n\t\tbyte[] array = out.toByteArray();\r\n\t\tif( array.length > 80 ){\r\n\t\t\tret = new String(array,0,72) + \"...\";\r\n\t\t}\r\n\t\telse {\r\n\t\t\tret = new String(array); \r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Convert a Color to its parameter expression.\r\n\t * The {@link Color} instance is transformed by\r\n\t * the initialisation of its RGB counterpart\r\n\t * (including the alpha if present).\r\n\t * \r\n\t * @param c the color to convert\r\n\t * @return a string compatible with a JAVA code\r\n\t * \t\tsource. \r\n\t */\r\n\tpublic static String toParam( Color c ){\r\n\t\tif( c == null ) return \"null\";\r\n\t\tStringBuilder buf = new StringBuilder( 30 );\r\n\t\tint red = c.getRed(); \r\n\t\tint green = c.getGreen();\r\n\t\tint blue = c.getBlue();\r\n\t\tint alpha = c.getAlpha();\r\n\t\tbuf.append(\"new \").append( Color.class.getName() ).append( \"(\" );\r\n\t\tbuf.append(red).append(\",\").append(green).append(\",\").append(blue);\r\n\t\tif( alpha > 0 ){\r\n\t\t\tbuf.append(\",\").append(alpha);\r\n\t\t}\r\n\t\tbuf.append(\")\");\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * A string is transferred to its JAVA counterpart.\r\n\t * \r\n\t * @param s the string.\r\n\t * @return a string compatible for a JAVA code source.\r\n\t */\r\n\tpublic static String toParam( CharSequence str ){\r\n\t\treturn str2java(str);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the JAVA representation of a character. This\r\n\t * representation is compatible with the JAVA specifications\r\n\t * for string and characters.\r\n\t * \r\n\t * <p>\r\n\t * NOTE: single quotes and double quotes are always returned\r\n\t * \tprefixed by the antislash character.\r\n\t * </p>\r\n\t * \r\n\t * @param c the character.\r\n\t * @return the character as a string or its expression\r\n\t * \t\tcompatible with JAVA (always a backslash followed\r\n\t * \t\tby the character or a Unicode sequence).\r\n\t */\r\n\tpublic static String getCharOf( char c ){\r\n\t\tswitch(c){\r\n\t\tcase '\\\"': return \"\\\\\\\"\";\r\n\t\tcase '\\'': return \"\\\\\\'\";\r\n\t\tcase '\\\\': return \"\\\\\";\r\n\t\tcase '\\b': return \"\\\\b\";\r\n\t\tcase '\\n': return \"\\\\n\";\r\n\t\tcase '\\r': return \"\\\\r\";\r\n\t\tcase '\\t': return \"\\\\t\";\r\n\t\tdefault:\r\n\t\t\tif( c < 32 || c > 127 ){\r\n\t\t\t\t// Use the UNICODE counterpart\r\n\t\t\t\tString hexa = Integer.toHexString(c);\r\n\t\t\t\twhile( hexa.length() < 4 ) hexa = \"0\" + hexa;\r\n\t\t\t\treturn \"\\\\u\" + hexa;\r\n\t\t\t}\r\n\r\n\t\t\t// Use a normal character.\r\n\t\t\treturn Character.toString(c);\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Convert a string to its JAVA counterpart.\r\n\t * \r\n\t * @param s a string.\r\n\t * @return a new string with the quotes values and\r\n\t * \t\tthe characters expressed in the respect of the\r\n\t * \t\tJAVA specification for sources. Return the\r\n\t * \t\ttext \"<code>null</code>\" if the string was a \r\n\t * \t\t<code>null</code> pointer.\r\n\t */\r\n\tpublic static String str2java( CharSequence s ){\r\n\t\tif( s == null ) return \"null\";\r\n\t\t\r\n\t\tint len = s.length();\r\n\t\tStringBuilder buf = new StringBuilder(len + 10);\r\n\t\tbuf.append('\\\"');\r\n\t\tint clen = 0;\r\n\t\tfor( int i = 0; i < len; i++ ){\r\n\t\t\tchar c = s.charAt(i);\r\n\t\t\tbuf.append(getCharOf(c));\r\n\t\t\tif( c == '\\n' || (clen++ > 120) ){\r\n\t\t\t\t// Split of the string on several lines... \r\n\t\t\t\tbuf.append(\"\\\"\\n + \\\"\");\r\n\t\t\t\tclen = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tbuf.append('\\\"');\r\n\t\treturn buf.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Converts a boolean to its JAVA counterpart.\r\n\t * \r\n\t * @param b a boolean value.\r\n\t * @return \"<code>null</code>\", <code>\"true\"</code>\r\n\t * \t\tor <code>\"false\"</code> depensing of the\r\n\t * \t\tvalue of <i>b</i>.\r\n\t */\r\n\tpublic static String toParam( Boolean b ){\r\n\t\tif( b == null ) return \"null\";\r\n\t\treturn b.toString();\r\n\t}\r\n\r\n\tpublic static String toParam( Double val ){\r\n\t\tif( val == null ) return \"null\";\r\n\t\treturn String.valueOf(val.doubleValue());\r\n\t}\r\n\r\n\tpublic static String toParam( int val ){\r\n\t\treturn String.valueOf(val);\r\n\t}\r\n\r\n\t/**\r\n\t * Return the character to its JAVA counterpart.\r\n\t * \r\n\t * @param c the character to convert.\r\n\t * @return The character inside simple quotes. If\r\n\t * \t\tthe character is below 32 or above 128, its\r\n\t * \t\tJAVA representation is returned.\r\n\t */\r\n\tpublic static String toParam( char c ){\r\n\t\treturn \"\\'\" + getCharOf(c) + \"\\'\";\r\n\t}\r\n\r\n\tpublic static String toParam( Integer i ){\r\n\t\tif( i == null ) return \"null\";\r\n\t\treturn i.toString();\r\n\t}\r\n\r\n}\r", "public class JavaMethod extends JavaBlock {\r\n\t// JavaBlock contents = new JavaBlock();\r\n\tJavaComments comments = new JavaComments();\r\n\tString name;\r\n\tJavaType returnType = new JavaType( \"void\" );\r\n\t\r\n\t/**\r\n\t * @return the returnType\r\n\t */\r\n\tpublic JavaType getReturnType() {\r\n\t\treturn returnType;\r\n\t}\r\n\r\n\t/**\r\n\t * @param returnType the returnType to set\r\n\t */\r\n\tpublic void setReturnType(JavaType returnType) {\r\n\t\tthis.returnType = returnType;\r\n\t}\r\n\r\n\tList<JavaParam> params = new ArrayList<JavaParam>();\r\n\t/**\r\n\t * @return the params\r\n\t */\r\n\tpublic JavaParam[] getParams() {\r\n\t\treturn params.toArray(new JavaParam[0]);\r\n\t}\r\n\r\n\tpublic JavaComments getComments(){\r\n\t\treturn this.comments;\r\n\t}\r\n\r\n\tpublic void setComments( JavaComments comments ){\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\tpublic void setComments( String comments ){\r\n\t\tthis.comments = new JavaComments(comments);\r\n\t}\r\n\r\n\t/**\r\n\t * @param params the params to set\r\n\t */\r\n\tpublic void setParams(JavaParam ... params) {\r\n\t\tthis.params = Arrays.asList( params );\r\n\t}\r\n\r\n\t\r\n\tpublic JavaMethod(){\r\n\t}\r\n\r\n\tpublic JavaMethod( String name ){\r\n\t\tthis();\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic JavaMethod( String name, JavaParam ... params ){\r\n\t\tthis(name);\r\n\t\tsetParams(params);\r\n\t}\r\n\r\n\r\n\r\n//\tpublic void addCode( JavaCode code ){\r\n//\t\tcontents.addCode(code);\r\n//\t}\r\n\r\n\t/**\r\n\t * @return the name\r\n\t */\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\t/**\r\n\t * @param name the name to set\r\n\t */\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer writer, int tabs) throws IOException {\r\n\t\tString tab = getTabulations(tabs);\r\n\t\tif( comments != null) comments.writeCode(writer, tabs);\r\n\t\twriter.write( tab + returnType + \" \" + getName() + \"(\" );\r\n\t\tboolean firstParam = true;\r\n\t\tfor( JavaParam param : params ){\r\n\t\t\tif( !firstParam ){\r\n\t\t\t\twriter.write(\", \");\r\n\t\t\t}\r\n\t\t\twriter.write( param.toString() );\r\n\t\t\tfirstParam = false;\r\n\t\t}\r\n\t\twriter.write( \")\" + CRLF );\r\n\t\tsuper.writeCode(writer, tabs);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a line comment in the method. The\r\n\t * comment starts with \"//\" and it is added\r\n\t * at the end of the current code. \r\n\t * \r\n\t * @param comment the comment line to add.\r\n\t * @see #setComments(JavaComments) to set\r\n\t * \t\tthe comments of the method. \r\n\t */\r\n\tpublic void addLineComment( String comment ){\r\n\t\tJavaComments cmt = new JavaComments();\r\n\t\tcmt.setJavaDoc(false);\r\n\t\tcmt.add(comment);\r\n\t\taddCode(cmt);\r\n\t}\r\n\r\n}\r" ]
import javax.swing.ImageIcon; import javax.swing.JFrame; import org.w3c.dom.Element; import com.oxande.xmlswing.AttributeDefinition; import com.oxande.xmlswing.AttributesController; import com.oxande.xmlswing.Parser; import com.oxande.xmlswing.AttributeDefinition.ClassType; import com.oxande.xmlswing.UnexpectedTag; import com.oxande.xmlswing.jcode.JavaClass; import com.oxande.xmlswing.jcode.JavaCode; import com.oxande.xmlswing.jcode.JavaMethod;
package com.oxande.xmlswing.components; /** * Implementation of a Frame. You should never use * directly this class as the normal implementation * comes from the {@link JFrameUI} class. * * @author wrey75 * */ public class FrameUI extends WindowUI { public static final AttributeDefinition[] PROPERTIES = { new AttributeDefinition( "title", "setTitle", ClassType.STRING ), new AttributeDefinition( "resizable", "setResizable", ClassType.BOOLEAN ), };
public static final AttributesController CONTROLLER = new AttributesController(WindowUI.CONTROLLER, PROPERTIES);
1
melloc/roguelike
engine/src/main/java/edu/brown/cs/roguelike/engine/proc/RandomMonsterGenerator.java
[ "public class Config {\n\n\tpublic enum ConfigType {\n\t\tMONSTER,WEAPON_ADJ,WEAPON_TYPE,KEY_BINDING\n\t}\n\n\tpublic static final String CFG_EXT = \".cfg\";\n\n\t/**\n\t * All of the required configuration files\n\t */\n\tpublic static final HashMap<ConfigType,String> REQUIRED_FILES = \n\t\t\tnew HashMap<ConfigType, String>();\n\n\tstatic {\n\t\tREQUIRED_FILES.put(ConfigType.MONSTER, \"monsters\");\n\t\tREQUIRED_FILES.put(ConfigType.WEAPON_ADJ, \"weapon_adjs\");\n\t\tREQUIRED_FILES.put(ConfigType.WEAPON_TYPE, \"weapon_types\");\n\t\tREQUIRED_FILES.put(ConfigType.KEY_BINDING, \"key_bindings\");\n\t}\n\n\tprivate File dir;\n\n\tpublic Config(String configDir) throws ConfigurationException {\n\t\tthis.dir = new File(configDir);\n\t\tvalidateDir();\n\t}\n\n\t/**\n\t * Superficially validates the config directory, making sure\n\t * that it contains all the required files, and that they are non-empty.\n\t * Does not validate their data. This is a simply fail-fast convenience\n\t * \n\t * Also validates the requiredFiles static array to make sure\n\t * there are no duplicates, as this will cause the rest of validation\n\t * to be inaccurate\n\t */\n\tprivate void validateDir() throws ConfigurationException {\n\n\t\tif (!dir.isDirectory()) \n\t\t\tthrow new ConfigurationException(\n\t\t\t\t\t\"Provided configuration directory \"\n\t\t\t\t\t\t\t+ dir.getAbsolutePath() + \" is not a directory\");\n\n\n\t\t// get all configuration files \n\t\tFile[] configFiles = dir.listFiles(new FilenameFilter() {\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\treturn name.toLowerCase().endsWith(CFG_EXT);\n\t\t\t}\n\t\t});\n\n\t\t// do we have all necessary config files?\n\t\tHashSet<String> filesPresent = new HashSet<String>();\n\n\t\tString missingFiles = \"\";\n\n\t\tfor (File f : configFiles) {\n\t\t\tString fileStr = f.getName().replaceAll(CFG_EXT, \"\");\n\t\t\tfilesPresent.add(fileStr);\n\t\t}\n\n\t\tfor (String f : REQUIRED_FILES.values()) {\n\t\t\tif (!filesPresent.contains(f)) missingFiles += f+\", \";\n\t\t}\n\n\t\t// if we're missing any config files, throw exception\n\t\tif (!missingFiles.isEmpty())\n\t\t\tthrow new ConfigurationException(\n\t\t\t\t\t\"missing configuration file(s): \" + missingFiles); \n\n\t}\n\n public <E> ArrayList<E> loadTemplate(Class<E> clazz, File file) throws ConfigurationException {\n\n\t\tObjectMapper om = new ObjectMapper();\n\n\t\tArrayList<E> ret = null;\n\n\t\ttry {\n\n\t\t\tTypeFactory t = TypeFactory.defaultInstance();\n\n\t\t\tret = om.readValue(\n\t\t\t\t\tfile, t.constructCollectionType(ArrayList.class,clazz));\n\n\t\t} catch (Exception e) {\n\t\t\tthrow new ConfigurationException(e);\n\t\t}\n\t\treturn ret;\n\t}\n\n\n\t/**\n\t * Build an array of MonsterTemplates used for the instantiation of \n\t * monsters\n\t * \n\t * @return ArrayList<MonsterTemplate> array of monster templates for\n\t * each monster in the configuration file\n\t * @throws ConfigurationException \n\t */\n\tpublic ArrayList<MonsterTemplate> loadMonsterTemplate() throws ConfigurationException {\n File file = new File(dir.getAbsolutePath() + \"/\" +\n REQUIRED_FILES.get(ConfigType.MONSTER).concat(CFG_EXT));\n return loadTemplate(MonsterTemplate.class, file);\n\t}\n\n\n\t/**\n * Builds an array of WeaponTemplates used for the instantion of Weapons \n * Weapon templates represent the type of weapon and its damage type\n * @throws ConfigurationException \n */\n public ArrayList<WeaponTemplate> loadWeaponTemplate() throws ConfigurationException {\n File file = new File(dir.getAbsolutePath() + \"/\" +\n REQUIRED_FILES.get(ConfigType.WEAPON_TYPE).concat(CFG_EXT));\n return loadTemplate(WeaponTemplate.class, file);\n }\n\n /**\n * Builds an array of WeaponNameTemplates used for the instantion of Weapons \n */\n public ArrayList<WeaponNameTemplate> loadWeaponNameTemplate() throws ConfigurationException {\n File file = new File(dir.getAbsolutePath() + \"/\" +\n REQUIRED_FILES.get(ConfigType.WEAPON_ADJ).concat(CFG_EXT));\n return loadTemplate(WeaponNameTemplate.class, file);\n }\n\n /**\n * Build an array of ContextTemplates used for generating keybindings\n * \n * @return ArrayList<ContextTemplate> array of context templates for\n * each context that exists in the game.\n * @throws ConfigurationException \n */\n public ArrayList<ContextTemplate> loadContextTemplate() throws ConfigurationException {\n File file = new File(dir.getAbsolutePath() + \"/\" +\n REQUIRED_FILES.get(ConfigType.KEY_BINDING).concat(CFG_EXT));\n return loadTemplate(ContextTemplate.class, file);\n }\n\n}", "public class ConfigurationException extends Exception {\n\t\n\t/**\n\t * Generated \n\t */\n\tprivate static final long serialVersionUID = 5399497813931843528L;\n\n\tpublic ConfigurationException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n\tpublic ConfigurationException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}", "public class MonsterTemplate {\n\tpublic final String name;\n\tpublic final char character;\n\tpublic final Color color;\n\tpublic final int startHp;\n\tpublic final int attack;\n\tpublic final int defense;\n\tpublic final int tier;\n\tpublic final int moveCost;\n\n\t@JsonCreator\n\tpublic MonsterTemplate(\n\t\t\t@JsonProperty(\"name\") String name, \n\t\t\t@JsonProperty(\"char\") char character,\n\t\t\t@JsonProperty(\"color\") String color, \n\t\t\t@JsonProperty(\"startHp\") int startHp,\n\t\t\t@JsonProperty(\"attack\") int attack,\n\t\t\t@JsonProperty(\"defense\") int defense,\n\t\t\t@JsonProperty(\"tier\") int tier,\n\t\t\t@JsonProperty(\"moveCost\") int moveCost) {\n\t\tthis.name = name;\n\t\tthis.character = character;\n\t\t\n\t\t// parse color\n\t\tString c = color.toLowerCase();\n\t\t\n\t\tif (c.equals(\"black\")) { this.color = Color.BLACK; }\n\t\telse if (c.equals(\"blue\")) { this.color = Color.BLUE; }\n\t\telse if (c.equals(\"cyan\")) { this.color = Color.CYAN; }\n\t\telse if (c.equals(\"green\")) { this.color = Color.GREEN; }\n\t\telse if (c.equals(\"magenta\")) { this.color = Color.MAGENTA; }\n\t\telse if (c.equals(\"red\")) { this.color = Color.RED; }\n\t\telse if (c.equals(\"white\")) { this.color = Color.WHITE; }\n\t\telse if (c.equals(\"yellow\")) { this.color = Color.YELLOW; }\n\t\telse { this.color = Color.DEFAULT; } \n\n\t\tthis.startHp = startHp;\n\t\tthis.attack = attack;\n\t\tthis.defense = defense;\n\t\tthis.tier = tier;\n\t\tthis.moveCost = moveCost;\n\t}\n\t\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + character;\n\t\tresult = prime * result + ((color == null) ? 0 : color.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\tresult = prime * result + startHp;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tMonsterTemplate other = (MonsterTemplate) obj;\n\t\tif (character != other.character)\n\t\t\treturn false;\n\t\tif (color == null) {\n\t\t\tif (other.color != null)\n\t\t\t\treturn false;\n\t\t} else if (!color.equals(other.color))\n\t\t\treturn false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\tif (startHp != other.startHp)\n\t\t\treturn false;\n\t\t\n\t\tif (attack != other.attack)\n\t\t\treturn false;\n\t\tif (defense != other.defense)\n\t\t\treturn false;\n\t\tif (tier != other.tier)\n\t\t\treturn false;\n\t\t\n\t\treturn true;\n\t}\n\t\n\t\n}", "public class Monster extends Combatable {\n\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 78534419381534560L;\n\t\n\t// The Level I'm in\n\tprivate Level level;\n\tprivate final int moveCost;\n\tprivate Action nextAction;\n\t\n\t// My brainz\n\tprivate FSM<MonsterInput> brainz;\n\t\n\tList<String> categories = null;\n\t{\n\t\tcategories = new ArrayList<String>();\n\t\tcategories.add(\"monster\");\n\t}\n\n\tpublic final int tier;\n\tpublic Monster(char c, Color color, Level level) {\n\t\tthis.character = c;\n\t\tthis.color = color;\n\t\tnextAction = null;\n\t\tthis.moveCost = 10;\n\t\tbuildBrainz();\n\t\ttier = 1;\n\t}\n\t\n\tpublic Monster(MonsterTemplate mt, Level level) {\n\t\tthis.level = level;\n\t\tthis.character = mt.character;\n\t\tthis.color = mt.color;\n\t\tthis.HP = mt.startHp;\n\t\tthis.startHP = mt.startHp;\n\t\tthis.stats = new Stats(mt.attack,mt.defense); \n\t\tbaseStats = stats;\n\t\tthis.team = 0;\n\t\tthis.name = mt.name;\n\t\tthis.moveCost = mt.moveCost;\n\t\tthis.tier = mt.tier;\n\t\tbuildBrainz();\n\t}\n\t\n\tprivate void buildBrainz() {\n\t\tbrainz = new FSM<MonsterInput>();\n\t\t\n\t\tIdle idleState = new Idle(this);\n\t\tChasing chaseState = new Chasing(this, moveCost);\n\t\t\n\t\tPlayerInSpace chasePlayer = new PlayerInSpace(chaseState, this);\n\t\t// PlayerNotInSpace giveUp = new PlayerNotInSpace(idleState, this);\n\t\t\n\t\tidleState.addTransition(chasePlayer);\n\t\t// chaseState.addTransition(giveUp);\n\t\t\n\t\tbrainz.setStartState(idleState);\n\t}\n\n\t@Override\n\tprotected void die() {\n\t\tthis.location.setEntity(null);\n\t\tthis.manager.call(Event.DEATH);\n\t}\n\n\t@Override\n\tprotected void onKillEntity(Combatable combatable) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\tpublic List<String> getCategories() {\n\t\treturn categories;\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn name;\n\t}\n\t\n\tpublic Level getLevel() { return this.level; }\n\t\n\tpublic void setNextAction(Action nextAction) {\n\t\tthis.nextAction = nextAction;\n\t}\n\t\n\t/**\n\t * TODO: Make FSM responsible for generating next actions\n\t */\n\t@Override\n\tprotected Action generateNextAction() {\n\t\tbrainz.update(new MonsterInput(level));\n\t\treturn this.nextAction;\n\t}\n}", "public class Level implements Saveable, Artist {\n\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 1187760172149150039L;\n\n\tprivate static final int TIER_STEP_SIZE = 5;\n\n\tpublic final Tile[][] tiles;\n\tprivate List<Room> rooms;\n\tprivate List<Hallway> hallways;\n\tprotected EntityManager manager = new EntityManager();\n\tprivate int depth; //The depth of the level\n\tpublic HashSet<Room> revealedRooms = new HashSet<Room>();\n\t\n\tpublic Tile upStairs;\n\tpublic Tile downStairs;\n\t\n\tpublic int getTier() {\n\t\t return (1 + (this.depth/TIER_STEP_SIZE));\n\t}\n\t\n\tpublic int getTierDiff() {\n\t\t return this.depth + 1 - TIER_STEP_SIZE*(getTier()-1);\n\t}\n\t\n\t/**\n\t * @return The entity manager for this {@link Level}.\n\t */\n\tpublic EntityManager getManager() {\n\t\treturn manager;\n\t}\n\n\tpublic void revealRoom(Room r) {\n\t\tif(revealedRooms.contains(r))\n\t\t\treturn;\n\t\t\n\t\tfor(int i = r.min.x-1; i<=r.max.x+1; i++) {\n\t\t\tfor(int j = r.min.y-1; j<=r.max.y+1; j++) {\n\t\t\t\ttiles[i][j].setReveal(true);\n\t\t\t}\n\t\t}\n\t\trevealedRooms.add(r);\n\t}\n\n\tpublic Level(Tile[][] tiles, List<Room> rooms, List<Hallway> hallways) {\n\t\tthis.tiles = tiles;\n\t\tfor (Tile[] tiles2 : tiles)\n\t\t\tfor (Tile tile : tiles2)\n\t\t\t\ttile.setLevel(this);\n\t\tthis.rooms = rooms;\n\t\tthis.hallways = hallways;\n\t}\n\n\tpublic Tile[][] getTiles() { return this.tiles; }\n\tpublic List<Room> getRooms() { return this.rooms; }\n\tpublic List<Hallway> getHallways() { return this.hallways; }\t\n\tpublic int getDepth(){return depth;}\n\n\tpublic void setDepth(int depth) {this.depth = depth;}\n\n\t/*** BEGIN Saveable ***/\n\n\tprivate UUID id;\n\n\t/** initialize id **/\n\t{\n\t\tthis.id = UUID.randomUUID();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tLevel other = (Level) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (id.equals(other.id))\n\t\t\t// return true if ids are the same\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic UUID getId() {\n\t\treturn this.id;\n\t}\n\n\t/*** END Saveable ***/\n\n\tpublic List<Tile> getNeighbors(Tile current) {\n\t\tList<Tile> neighbors = new LinkedList<Tile>();\n\n\t\tif(current.getLocation().x != 0) {\n\t\t\tneighbors.add(tiles[current.getLocation().x-1][current.getLocation().y]);\n\t\t}\n\t\tif(current.getLocation().x != tiles.length) {\n\t\t\tneighbors.add(tiles[current.getLocation().x+1][current.getLocation().y]);\n\t\t}\n\t\tif(current.getLocation().y != 0) {\n\t\t\tneighbors.add(tiles[current.getLocation().x][current.getLocation().y-1]);\n\t\t}\n\t\tif(current.getLocation().y != tiles[0].length) {\n\t\t\tneighbors.add(tiles[current.getLocation().x][current.getLocation().y+1]);\n\t\t}\n\t\treturn neighbors;\n\t}\n\n\tpublic void revealAround(Tile t) {\n\t\tfor(int i = t.location.x-1; i<=t.location.x+1;i++) {\n\t\t\tfor(int j = t.location.y-1; j<=t.location.y+1;j++) {\n\t\t\t\ttiles[i][j].setReveal(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**Removes the player from the world and returns it\n\t * Allows for world to be simulated while the player is not there.\n\t * @return The main character of the level\n\t */\n\tpublic MainCharacter removePlayer() {\n\t\tList<EntityActionManager> mains = manager.getEntity(\"main\");\n\t\tif(mains.size() >0) {\n\t\t\tMainCharacter mc = (MainCharacter) mains.get(0).getEntity();\n\t\t\tmc.getLocation().setEntity(null);\n\t\t\tmanager.unregister(mc);\n\t\t\treturn mc;\n\t\t}\n\t\telse\n\t\t\treturn null;\n\t}\n\n\t/**Places the character onto the map on the stairs indicated by the boolean argument\n\t * @param mc The main character to place\n\t *\n\t * @param up: If true, place on the down stairs, else, the up stairs\n\t */\n\tpublic void placeCharacter(MainCharacter mc, boolean up) {\n\t\t\n\t\tEntity current = (up ? upStairs.getEntity() : downStairs.getEntity());\n\t\tif(current != null) {\n\t\t\tRandomGen rand = new RandomGen(System.nanoTime());\n\t\tRoom r = this.rooms.get(rand.getRandom(rooms.size()));\n\t\tboolean placedMonster = false;\n\t\tdo {\n\t\t\tint mX = rand.getRandom(r.min.x, r.max.x);\n\t\t\tint mY = rand.getRandom(r.min.y, r.max.y);\n\t\t\tTile t = tiles[mX][mY];\n\t\t\tif(t.getEntity() == null) {\n\t\t\t\tt.setEntity(current);\n\t\t\t\tcurrent.setLocation(t);\n\t\t\t\tplacedMonster = true;\n\t\t\t}\n\t\t}\n\t\twhile(!placedMonster);\n\t\t}\n\t\t\n\t\tif(up)\n\t\t\tupStairs.setEntity(mc);\n\t\telse\n\t\t\tdownStairs.setEntity(mc);\n\t\t\n\t\tLinkedList<String> attr = new LinkedList<String>();\n\t\tmanager.register(mc);\n\t}\n\n\tpublic void doDraw(ScreenWriter sw) {\n\t\tTile t;\n\t\tfor (int c = 0; c < tiles.length; c++) {\n\t\t\tfor (int r = tiles[0].length - 1; r >= 0; r--) { // flip y\n\t\t\t\tt = tiles[c][r];\n\t\t\t\tsw.setForegroundColor(t.getColor());\n\t\t\t\tsw.drawString(c, r,\n\t\t\t\t\t\tString.valueOf(t.getCharacter()),\n\t\t\t\t\t\tScreenCharacterStyle.Bold);\n\t\t\t}\n\t\t}\n\t}\n\n}", "public class Room implements Space, Saveable {\r\n\t\r\n\t/**\r\n\t * Generated\r\n\t */\r\n\tprivate static final long serialVersionUID = -760167898015853500L;\r\n\t\r\n\tprotected List<Room> connectedRooms; //The rooms directly connected to this room\r\n\r\n\tpublic Vec2i min; //Min point of room, excluding walls\r\n\tpublic Vec2i max; //Max point of room, excluding walls\r\n\t\r\n\tpublic List<Room> getConnectedRooms() {return this.connectedRooms;}\r\n\tpublic void addRoom(Room room) {connectedRooms.add(room);}\r\n\t\r\n\t\r\n\t\r\n\tpublic Room(Vec2i min, Vec2i max) {\r\n\t\tthis.min = min;\r\n\t\tthis.max = max;\r\n\t\tthis.connectedRooms = new ArrayList<Room>();\r\n\t}\r\n\t\r\n\tpublic boolean containsTile(Tile t) {\r\n\t\treturn (t.location.x >= min.x && t.location.x <= max.x && t.location.y >= min.y && t.location.y <= max.y);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void connectToHallway(Hallway h) {\r\n\t\tfor(Room r : h.getRooms()) {\r\n\t\t\tthis.addRoom(r);\r\n\t\t\th.addRoom(this);\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\t@Override\r\n\tpublic boolean needDoor() {\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t/*** BEGIN Saveable ***/\r\n\r\n\tprivate UUID id;\r\n\t\r\n\t/** initialize id **/\r\n\t{\r\n\t\tthis.id = UUID.randomUUID();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tRoom other = (Room) obj;\r\n\t\tif (id == null) {\r\n\t\t\tif (other.id != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (id.equals(other.id))\r\n\t\t\t// return true if ids are the same\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic UUID getId() {\r\n\t\treturn this.id;\r\n\t}\r\n\r\n}\r", "public class Tile extends AStarNode<Tile> implements Saveable, Drawable {\r\n\t\r\n\t// The Space I belong to\r\n\tprotected Space space;\r\n\r\n\tprotected Vec2i location = null;\r\n\tprotected Level level = null;\r\n\tprotected boolean reveal = false;\r\n\r\n\t/**Allows you to reveal/hide a tile**/\r\n\tpublic void setReveal(boolean r) {\r\n\t\tthis.reveal = r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Generated\r\n\t */\r\n\tprivate static final long serialVersionUID = -4972149313921847289L;\r\n\r\n\tpublic Tile(TileType type) {\r\n\t\tthis.type = type;\r\n\t}\r\n\t\r\n\tpublic Tile(TileType type, Space space) {\r\n\t\tthis.type = type;\r\n\t\tthis.space = space;\r\n\t}\r\n\t\r\n\tprivate LinkedList<Stackable> stackables = new LinkedList<Stackable>();\r\n\r\n\t/**\r\n\t * @return the location\r\n\t */\r\n\tpublic Vec2i getLocation() {\r\n\t\treturn location;\r\n\t}\r\n\t\r\n\tpublic Space getSpace() { return space; }\r\n\tpublic void setSpace(Space space) { this.space = space; }\r\n\r\n\t/**\r\n\t * @param location the location to set\r\n\t */\r\n\tpublic void setLocation(Vec2i location) {\r\n\t\tthis.location = location;\r\n\t}\r\n\r\n\t/**\r\n\t *\r\n\t */\r\n\tpublic Direction dirTo(Tile other) {\r\n\t\tVec2i otherLoc = other.getLocation();\r\n\t\tif (location.x < otherLoc.x)\r\n\t\t\treturn Direction.RIGHT;\r\n\t\telse if (location.x > otherLoc.x)\r\n\t\t\treturn Direction.LEFT;\r\n\t\telse if (location.y < otherLoc.y)\r\n\t\t\treturn Direction.DOWN;\r\n\t\telse \r\n\t\t\treturn Direction.UP;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the level\r\n\t */\r\n\tpublic Level getLevel() {\r\n\t\treturn level;\r\n\t}\r\n\r\n\t/**\r\n\t * @param level the level to set\r\n\t */\r\n\tpublic void setLevel(Level level) {\r\n\t\tthis.level = level;\r\n\t}\r\n\r\n\tpublic LinkedList<Stackable> getStackables() {\r\n\t\treturn stackables;\r\n\t}\r\n\t\r\n\tprivate Entity entity;\r\n\r\n\tpublic Entity getEntity() {\r\n\t\treturn entity;\r\n\t}\r\n\r\n\tpublic void setEntity(Entity entity) {\r\n\t\tif (entity != null)\r\n\t\t\tentity.setLocation(this);\r\n\t\tthis.entity = entity;\r\n\t}\r\n\r\n\r\n\tpublic boolean isPassable() {\r\n\t\tif (entity != null)\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t\treturn type.isPassable();\r\n\t}\r\n\r\n\tprivate TileType type;\r\n\r\n\tpublic TileType getType() {\r\n\t\treturn type;\r\n\t}\r\n\r\n\tpublic void setType(TileType type) {\r\n\t\tthis.type = type;\r\n\t}\r\n\t\r\n @Override\r\n public String toString() {\r\n return \"Tile\" + location.toString();\r\n }\r\n\r\n\tpublic boolean getReveal() {\r\n\t\treturn this.reveal;\r\n\t}\r\n\r\n\t@Override\r\n\tprotected int getHScore(Tile goal) {\r\n\t\treturn 10*calcManhattan(goal);\r\n\t}\r\n\t\r\n\t@Override \r\n\tpublic ArrayList<Tile> getNeighbors() {\r\n\t\t\r\n\t\tList<Tile> trueNeighbors = level.getNeighbors(this);\r\n\t\t\r\n\t\tArrayList<Tile> passableNeighbors = new ArrayList<Tile>();\r\n\t\t\r\n\t\tfor (Tile t : trueNeighbors) \r\n\t\t\tif ( t.getType().passable ) passableNeighbors.add(t);\r\n\t\t\r\n\t\treturn passableNeighbors;\r\n\t}\r\n\t\r\n\t// Convenience method to calculate the Manhattan distance\r\n\tprotected int calcManhattan(Tile goal) {\r\n\t\t\r\n\t\tint rows = Math.abs(location.y-goal.location.y);\r\n\t\tint cols = Math.abs(location.x-goal.location.x);\r\n\t\t\r\n\t\treturn rows + cols;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int distance(Tile neighbor) {\r\n\t\tint penalty = 0;\r\n\t\t\r\n\t\tEntity occupant = neighbor.getEntity();\r\n\t\t\r\n\t\t// Don't move into other Monsters, silly\r\n\t\tif (occupant != null && !(occupant instanceof MainCharacter)) penalty = 100; \r\n\t\t\r\n\t\treturn 10 + penalty;\r\n\t}\r\n\r\n\t/*** BEGIN Saveable ***/\r\n\r\n\tprivate UUID id;\r\n\t\r\n\t/** initialize id **/\r\n\t{\r\n\t\tthis.id = UUID.randomUUID();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tTile other = (Tile) obj;\r\n\t\tif (id == null) {\r\n\t\t\tif (other.id != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (id.equals(other.id))\r\n\t\t\t// return true if ids are the same\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic UUID getId() {\r\n\t\treturn this.id;\r\n\t}\r\n\r\n\r\n\tpublic char getCharacter() {\r\n\t\treturn getCurrent().getCharacter();\r\n\t}\r\n\r\n\tpublic Color getColor() {\r\n\t\treturn getCurrent().getColor();\r\n\t}\r\n\r\n\tprotected Drawable getCurrent() {\r\n\t\tif(this.reveal == false && !(entity instanceof MainCharacter)) {\r\n\t\t\treturn TileType.HIDDEN;\r\n\t\t}\r\n\t\tif (this.entity != null)\r\n\t\t\treturn entity;\r\n\t\telse if(stackables.size() > 0)\r\n\t\t\treturn stackables.getFirst();\r\n\t\telse\r\n\t\t\treturn getType();\r\n\t}\r\n\r\n\r\n\r\n}\r" ]
import java.util.ArrayList; import edu.brown.cs.roguelike.engine.config.Config; import edu.brown.cs.roguelike.engine.config.ConfigurationException; import edu.brown.cs.roguelike.engine.config.MonsterTemplate; import edu.brown.cs.roguelike.engine.entities.Monster; import edu.brown.cs.roguelike.engine.level.Level; import edu.brown.cs.roguelike.engine.level.Room; import edu.brown.cs.roguelike.engine.level.Tile;
package edu.brown.cs.roguelike.engine.proc; public class RandomMonsterGenerator implements MonsterGenerator { ArrayList<MonsterTemplate> templates; RandomGen rand = new RandomGen(System.nanoTime()); @Override public void populateLevel(Level level) throws ConfigurationException { int roomNum; Config c = new Config("../config"); templates = c.loadMonsterTemplate(); for (int i = 0 ; i < getMonsterCount(); i++) { roomNum = rand.getRandom(level.getRooms().size()); Room r = level.getRooms().get(roomNum); addMonster(level,r,getRandomMonster(level)); } }
private Monster getRandomMonster(Level level) {
3
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/BringCommand.java
[ "public class PlayerTeleportBringEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Bring {\n\n /**\n * PlayerTeleportBringEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportBringEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n}", "public class PlayerTeleportPreEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Pre {\n\n /**\n * PlayerTeleportPreEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportPreEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n\n}", "public class TeleportationService {\n\n public static final TeleportationService instance = new TeleportationService();\n private final Map<Transaction, Timestamp> transactions = new ConcurrentHashMap<>();\n private final int expires;\n\n /**\n * TeleportationService constructor\n */\n private TeleportationService() {\n expires = DestinationsConfig.getTeleportRequestExpiration();\n this.startCleanupTask();\n }\n\n /**\n * TeleportationService.Transaction class\n */\n private class Transaction {\n private Player caller;\n private Player target;\n\n /**\n * @return Player\n */\n Player getCaller() {\n return this.caller;\n }\n\n /**\n * @return Player\n */\n Player getTarget() {\n return this.target;\n }\n\n /**\n * CallModel constructor\n *\n * @param caller Player\n * @param target Player\n */\n Transaction(Player caller, Player target) {\n Preconditions.checkNotNull(caller);\n Preconditions.checkNotNull(target);\n\n this.caller = caller;\n this.target = target;\n }\n }\n\n /**\n * Start the teleportationCleanupTask\n */\n private void startCleanupTask() {\n Sponge.getScheduler().createTaskBuilder()\n .interval(1, TimeUnit.SECONDS)\n .name(\"teleportationCleanupTask\")\n .execute(this::cleanup)\n .submit(Destinations.getInstance());\n }\n\n /**\n * Cleanup teleportation transactions\n */\n private void cleanup() {\n Timestamp now = new Timestamp(System.currentTimeMillis());\n\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (now.after(call.getValue())) {\n this.expiredNotification(call.getKey().getCaller(), call.getKey().getTarget());\n this.transactions.remove(call.getKey());\n }\n }\n }\n\n /**\n * Send teleportation request expiration notices to players\n *\n * @param caller Player\n * @param target Player\n */\n private void expiredNotification(Player caller, Player target) {\n Optional<Player> optionalCaller = Sponge.getServer().getPlayer(caller.getUniqueId());\n Optional<Player> optionalTarget = Sponge.getServer().getPlayer(target.getUniqueId());\n\n optionalCaller.ifPresent(player -> player.sendMessage(MessagesUtil.warning(player, \"call.request_expire_to\", target.getName())));\n optionalTarget.ifPresent(player -> player.sendMessage(MessagesUtil.warning(player, \"call.request_expire_from\", caller.getName())));\n }\n\n /**\n * Add a call transaction\n *\n * @param caller Player\n * @param target Player\n */\n public void call(Player caller, Player target) {\n Transaction call = new Transaction(caller, target);\n Timestamp expireTime = new Timestamp(System.currentTimeMillis() + this.expires * 1000);\n this.transactions.put(call, expireTime);\n }\n\n /**\n * Remove a call transaction\n *\n * @param caller Player\n * @param target Player\n */\n public void removeCall(Player caller, Player target) {\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getCaller().getUniqueId().equals(caller.getUniqueId())\n && call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n this.transactions.remove(call.getKey());\n }\n }\n }\n\n /**\n * Get the first caller from this player's current calls\n *\n * @param target Player\n * @return Player\n */\n public Player getFirstCaller(Player target) {\n Player caller = null;\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n caller = call.getKey().getCaller();\n }\n }\n\n return caller;\n }\n\n /**\n * Get the total number of current callers\n *\n * @param target Player\n * @return int\n */\n public int getNumCallers(Player target) {\n int callers = 0;\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n callers++;\n }\n }\n\n return callers;\n }\n\n /**\n * Get the current list of callers\n *\n * @param target Player\n * @return List<String>\n */\n public List<String> getCalling(Player target) {\n List<String> list = new ArrayList<>();\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())) {\n list.add(call.getKey().getCaller().getName());\n }\n }\n\n return list;\n }\n\n /**\n * Get whether or not a Player is currently waiting for a call reply\n *\n * @param caller Player\n * @param target Player\n * @return bool\n */\n public boolean isCalling(Player caller, Player target) {\n\n for (Map.Entry<Transaction, Timestamp> call : this.transactions.entrySet()) {\n if (call.getKey().getTarget().getUniqueId().equals(target.getUniqueId())\n && call.getKey().getCaller().getUniqueId().equals(caller.getUniqueId())) {\n return true;\n }\n }\n\n return false;\n }\n}", "public class FormatUtil {\n\t\n\tpublic static final int COMMAND_WINDOW_LENGTH = 53;\n\t\n\t// Message Levels\n\tpublic static final TextColor SUCCESS = TextColors.GREEN;\n\tpublic static final TextColor WARN = TextColors.GOLD;\n\tpublic static final TextColor ERROR = TextColors.RED;\n\tpublic static final TextColor INFO = TextColors.WHITE;\n\tpublic static final TextColor DIALOG = TextColors.GRAY;\n\t\n\t// Object Levels\n\tpublic static final TextColor OBJECT = TextColors.GOLD;\n\tpublic static final TextColor DELETED_OBJECT = TextColors.RED;\n\t\n\t// Links\n\tpublic static final TextColor CANCEL = TextColors.RED;\n\tpublic static final TextColor DELETE = TextColors.RED;\n\tpublic static final TextColor CONFIRM = TextColors.GREEN;\n\tpublic static final TextColor GENERIC_LINK = TextColors.DARK_AQUA;\n\t\n\t//Other\n\tpublic static final TextColor HEADLINE = TextColors.DARK_GREEN;\n\t\n\tpublic static Text empty() {\n\t\t\n\t\tText.Builder text = Text.builder();\n\t\tfor (int i = 0; i < 20; i++) {\n\t\t\ttext.append(Text.NEW_LINE);\n\t\t}\n\t\t\n\t\treturn text.build();\n\t\t\n\t}\n\t\n\tpublic static String getFill(int length, char fill) {\n\t\treturn new String(new char[length]).replace('\\0', fill);\n\t}\n\t\n\tpublic static String getFill(int length) {\n\t\treturn new String(new char[length]).replace('\\0', ' ');\n\t}\n\t\n\tpublic FormatUtil(){\n\t}\n\n}", "public class MessagesUtil {\n\n /**\n * Get the message associated with this key, for this player's locale\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text get(Player player, String key, Object... args) {\n ResourceBundle messages = PlayerCache.instance.getResourceCache(player);\n return messages.containsKey(key) ? Text.of(String.format(messages.getString(key), args)) : Text.EMPTY;\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a success (green).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text success(Player player, String key, Object... args) {\n return Text.of(TextColors.GREEN, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a warning (gold).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text warning(Player player, String key, Object... args) {\n return Text.of(TextColors.GOLD, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as an error (red).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text error(Player player, String key, Object... args) {\n return Text.of(TextColors.RED, get(player, key, args));\n }\n\n}" ]
import com.github.mmonkey.destinations.events.PlayerTeleportBringEvent; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.teleportation.TeleportationService; import com.github.mmonkey.destinations.utilities.FormatUtil; import com.github.mmonkey.destinations.utilities.MessagesUtil; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextStyles; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList;
package com.github.mmonkey.destinations.commands; public class BringCommand implements CommandExecutor { public static final String[] ALIASES = {"bring", "tpaccept", "tpyes"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.tpa") .description(Text.of("/bring [player] or /tpaccept [player] or /tpyes [player]")) .extendedDescription(Text.of("Teleports a player that has issued a call request to your current location.")) .executor(new BringCommand()) .arguments(GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.player(Text.of("player"))))) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } Player target = (Player) src; Player caller = args.getOne("player").isPresent() ? (Player) args.getOne("player").get() : null; if (caller == null) { int numCallers = TeleportationService.instance.getNumCallers(target); switch (numCallers) { case 0: target.sendMessage(MessagesUtil.error(target, "bring.empty")); return CommandResult.success(); case 1: Player calling = TeleportationService.instance.getFirstCaller(target); return executeBring(calling, target); default: return listCallers(target, args); } } if (TeleportationService.instance.isCalling(caller, target)) { return executeBring(caller, target); } target.sendMessage(MessagesUtil.error(target, "bring.not_found", caller.getName())); return CommandResult.success(); } private CommandResult listCallers(Player target, CommandContext args) { List<String> callList = TeleportationService.instance.getCalling(target); List<Text> list = new CopyOnWriteArrayList<>(); callList.forEach(caller -> list.add(getBringAction(caller))); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); paginationService.builder().title(MessagesUtil.get(target, "bring.title")).contents(list).padding(Text.of("-")).sendTo(target); return CommandResult.success(); } private CommandResult executeBring(Player caller, Player target) { TeleportationService.instance.removeCall(caller, target); Sponge.getGame().getEventManager().post(new PlayerTeleportPreEvent(caller, caller.getLocation(), caller.getRotation()));
Sponge.getGame().getEventManager().post(new PlayerTeleportBringEvent(caller, target.getLocation(), target.getRotation()));
0
GoogleCloudPlatform/healthcare-api-dicom-fuse
src/main/java/com/google/dicomwebfuse/dao/spec/InstancePathBuilder.java
[ "public static final String DATASETS = \"/datasets/\";", "public static final String DICOM_STORES = \"/dicomStores/\";", "public static final String DICOM_WEB = \"/dicomWeb\";", "public static final String INSTANCES = \"/instances/\";", "public static final String LOCATIONS = \"/locations/\";", "public static final String PROJECTS = \"/projects/\";", "public static final String SERIES = \"/series/\";", "public static final String STUDIES = \"/studies/\";", "public class DicomFuseException extends Exception {\n\n private int statusCode;\n\n public DicomFuseException(String message) {\n super(message);\n }\n\n public DicomFuseException(String message, Exception e) {\n super(message, e);\n }\n\n public DicomFuseException(Exception e) {\n super(e);\n }\n\n public DicomFuseException(String message, int statusCode) {\n super(message);\n this.statusCode = statusCode;\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n}" ]
import static com.google.dicomwebfuse.dao.Constants.DATASETS; import static com.google.dicomwebfuse.dao.Constants.DICOM_STORES; import static com.google.dicomwebfuse.dao.Constants.DICOM_WEB; import static com.google.dicomwebfuse.dao.Constants.INSTANCES; import static com.google.dicomwebfuse.dao.Constants.LOCATIONS; import static com.google.dicomwebfuse.dao.Constants.PROJECTS; import static com.google.dicomwebfuse.dao.Constants.SERIES; import static com.google.dicomwebfuse.dao.Constants.STUDIES; import com.google.dicomwebfuse.exception.DicomFuseException;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.dicomwebfuse.dao.spec; public class InstancePathBuilder implements PathBuilder { private QueryBuilder queryBuilder; public InstancePathBuilder(QueryBuilder queryBuilder) { this.queryBuilder = queryBuilder; } @Override
public String toPath() throws DicomFuseException {
8
Gikkman/Java-Twirk
src/main/java/com/gikk/twirk/types/usernotice/DefaultUsernoticeBuilder.java
[ "public interface TagMap extends Map<String, String>{\n //***********************************************************\n\t// \t\t\t\tPUBLIC\n\t//***********************************************************\n\t/**Fetches a certain field value that might have been present in the tag.\n\t * If the field was not present in the tag, or the field's value was empty,\n\t * this method returns <code>NULL</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if there was any. <code>NULL</code> otherwise\n\t */\n\tpublic String getAsString(String identifier);\n\n\t/**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into an <code>int</code>. If the field was not present in the tag,\n\t * or the field's value was empty, this method returns <code>-1</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and an int. <code>-1</code> otherwise\n\t */\n\tpublic int getAsInt(String identifier);\n\n /**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into a <code>long</code>. If the field was not present in the tag,\n\t * or the field's value was empty, this method returns <code>-1</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and a long. <code>-1</code> otherwise\n\t */\n long getAsLong(String identifier);\n\n\t/**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into a <code>boolean</code>. For parsing purpose, <code>1</code> is interpreted\n\t * as <code>true</code>, anything else as <code>false</code>.\n\t * If the field was not present in the tag, or the field's value was empty, this method returns <code>false</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and could be parsed to a boolean. <code>false</code> otherwise\n\t */\n\tpublic boolean getAsBoolean(String identifier);\n\n /**Creates a new TagMap using the default TagMap implementation.\n *\n * @param tag\n * @return the default tag map\n */\n static TagMap getDefault(String tag){\n return new TagMapImpl(tag);\n }\n}", "public class TwitchTags {\n\n\t/**Denotes the message's unique ID\n\t */\n\tpublic static final String ID\t\t\t= \"id\";\n\n\t/**Denotes the user's unique ID\n\t */\n\tpublic static final String USER_ID \t\t= \"user-id\";\n\n\t/**The users display name (on Twitch). Escaped like the following:<br><br><table style=\"width:500\"><tr>\n\t *<td><b>CHARACTER\t\t</b></td><td><b>ESCAPED BY</b></td><tr>\n\t *<td>; (semicolon)\t</td><td>\\: (backslash and colon)</td><tr>\n\t *<td>SPACE\t\t\t</td><td>\\s </td><tr>\n\t *<td>\\\t\t\t\t</td><td>\\\\ </td><tr>\n\t *<td>CR\t\t\t</td><td>\\r </td><tr>\n\t *<td>LF\t\t\t</td><td>\\n </td><tr>\n\t *<td>all others\t</td><td>the character itself</td></tr></table>\n\t */\n\tpublic static final String DISPLAY_NAME\t= \"display-name\";\n\n\t/**Denotes badges this message has. Can be:<br>\n\t * {@code staff, admin, global_mod, moderator, subscriber, turbo } and/or {@code bits}\n\t */\n\tpublic static final String BADGES \t\t= \"badges\";\n\n /**Denotes the number of bits that was cheered in this message\n */\n public static final String BITS = \"bits\";\n\n\t/**Denotes the users color. This comes as a hexadecimal value. Can be empty if never set by the user\n\t */\n\tpublic static final String COLOR \t\t= \"color\";\n\n\t/**Denotes if the user is a subscriber or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_SUB \t\t= \"subscriber\";\n\n\t/**Denotes if the user is a moderator or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_MOD \t\t= \"mod\";\n\n\t/**Denotes if the user has turbo or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_TURBO \t= \"turbo\";\n\n\t/**Is either <code>empty, mod, global_mod, admin</code> or <code>staff</code>.\n\t* <li>The broadcaster can have any of these, including empty.\n\t*/\n\tpublic static final String USERTYPE \t= \"user-type\";\n\n\t/**Contains information to replace text in the message with the emote images and <b>can be empty</b>. The format is as follows:<br><br>\n\t * <code>emote_id:first_index-last_index,another_first-another_last/another_emote_id:first_index-last_index</code><br><br>\n\t *\n\t * <code>emote_id</code> is the number to use in this URL: <code>http://static-cdn.jtvnw.net/emoticons/v1/:emote_id/:size</code> (<i>size is 1.0, 2.0 or 3.0</i>)<br><br>\n\t *\n\t * Emote indexes are simply character indexes. <code>ACTION</code> does not count and indexing starts from the first character that is part of the user's \"actual message\".<br>\n\t * Both start and end is inclusive. If the message is \"Kappa\" (emote id 25), start is from character 0 (K) to character 4 (a).\n\t */\n\tpublic static final String EMOTES\t\t = \"emotes\";\n\n\t/** Contains your emote set, which you can use to request a subset of <a href=\"https://github.com/justintv/Twitch-API/blob/master/v3_resources/chat.md#get-chatemoticon_images\">/chat/emoticon_images</a>\n\t * <li>Always contains at least {@code 0}\n\t * <li>Ex: <code>https://api.twitch.tv/kraken/chat/emoticon_images?emotesets=0,33,50,237,793,2126,3517,4578,5569,9400,10337,12239</code>\n\t */\n\tpublic static final String EMOTE_SET\t= \"emote-sets\";\n\n\t/** The user's login name. Can be different from the user's display name\n\t */\n\tpublic final static String LOGIN_NAME \t= \"login\";\n\n\t/** Identifies what kind of notice it was.\n\t */\n\tpublic final static String MESSAGE_ID \t= \"msg-id\";\n\n\t/** The message printed in chat along with this notice.\n\t */\n\tpublic final static String SYSTEM_MESSAGE = \"system-msg\";\n\n\t/** The number of cumulative months the user has subscribed for in a resub notice.\n\t */\n\tpublic final static String PARAM_MONTHS = \"msg-param-cumulative-months\";\n\n\t/** The number of consecutive months the user has subscribed for in a resub notice.\n\t */\n\tpublic final static String PARAM_STREAK = \"msg-param-streak-months\";\n\n\t/** Denotes if the user share the streak or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic final static String PARAM_SHARE_STREAK = \"msg-param-should-share-streak\";\n\n /** The type of subscription plan being used.\n * Valid values: Prime, 1000, 2000, 3000. 1000, 2000, and 3000 refer to the\n * first, second, and third levels of paid subscriptions,\n * respectively (currently $4.99, $9.99, and $24.99).\n */\n public final static String PARAM_SUB_PLAN = \"msg-param-sub-plan\";\n\n /** The display name of the subscription plan. This may be a default name or\n * one created by the channel owner.\n */\n public static String PARAM_SUB_PLAN_NAME = \"msg-param-sub-plan-name\";\n\n\t/** Denotes the room's ID which the message what sent to. Each room's ID is unique\n\t */\n\tpublic static final String ROOM_ID \t\t= \"room-id\";\n\n\t/** <code>broadcaster-lang</code> is the chat language when <a href=\"https://blog.twitch.tv/your-channel-your-chat-your-language-80306ab98a59#.i4rpk1gn1\">broadcaster language mode</a> is enabled, and empty otherwise. <br>\n\t * A few examples would be en for English, fi for Finnish and es-MX for Mexican variant of Spanish\n\t */\n\tpublic static final String ROOM_LANG \t= \"broadcaster-lang\";\n\n\t/** Messages with more than 9 characters must be unique. 0 means disabled, 1 enabled\n\t */\n\tpublic static final String R9K_ROOM \t= \"r9k\";\n\n\t/** Only subscribers and moderators can chat. 0 disabled, 1 enabled.\n\t */\n\tpublic static final String SUB_ONLY_ROOM= \"subs-only\";\n\n\t/** Only followers can chat. -1 disabled, 0 all followers can chat, > 0 only users following for at least the specified number of minutes can chat.\n\t */\n\tpublic static final String FOLLOWERS_ONLY_ROOM = \"followers-only\";\n\n\t/** Emote-only mode. If enabled, only emotes are allowed in chat. Valid values: 0 (disabled) or 1 (enabled).\n\t */\n\tpublic static final String EMOTE_ONLY_ROOM = \"emote-only\";\n\n\t/** Determines how many seconds chatters without moderator privileges must wait between sending messages\n\t */\n\tpublic static final String SLOW_DURATION= \"slow\";\n\n\t/** The duration of the timeout in seconds. The tag is omitted on permanent bans.\n\t */\n\tpublic static final String BAN_DURATION = \"ban-duration\";\n\n\t/** The reason the moderator gave for the timeout or ban.\n\t */\n\tpublic static final String BAN_REASON = \"ban-reason\";\n\n /** The UNIX timestamp a message reached the Twitch server\n */\n public static final String TMI_SENT_TS = \"tmi-sent-ts\";\n\n /** The number of viewers which participates in a raid\n */\n public static final String PARAM_VIEWER_COUNT = \"msg-param-viewerCount\";\n\n /** The login name of the user initiating a raid\n */\n public static final String PARAM_LOGIN_NAME = \"msg-param-login\";\n\n /** The display name of a user initiating a raid\n */\n public static final String PARAM_DISPLAY_NAME = \"msg-param-displayName\";\n\n /** The name of the ritual this notice is for. Valid value: new_chatter\n */\n public static String PARAM_RITUAL_NAME = \"msg-param-ritual-name\";\n\n /** The display name of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_NAME = \"msg-param-recipient-name\";\n\n /** The display name of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_DISPLAY_NAME = \"msg-param-recipient-display-name\";\n\n /** The user ID of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_ID = \"msg-param-recipient-id\";\n}", "public interface Emote {\n\t/** Fetches the emotes ID as String. This became necessary after Twitch start\n\t * including other characters than numbers in emote IDs\n\t *\n\t * @return The emotes ID\n\t */\n\tString getEmoteIDString();\n\t\n\t/** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>\n\t * \n\t * For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>\n\t * <li> (0,5)\n\t * <li> (15,20)\n\t * </ul>\n\t * \n\t * @return The indices this emote takes up in the associated message\n\t */\n\tLinkedList<EmoteIndices> getIndices();\n\t\n\t/** The emote's pattern. For example: 'Kappa'\n\t * \n\t * @return The emote's pattern\n\t */\n\tString getPattern();\n\t\n\t/**Emote images can be downloaded from Twitch's server, and come in three\n\t * sizes. Use this method to get the address for the emote.\n\t * \n\t * @param imageSize Emotes comes in three sizes. Specify which size you want\n\t * @return The address for the emote's image\n\t */\n\tString getEmoteImageUrl(EMOTE_SIZE imageSize);\n\t\n\t/**Class for representing the beginning and end of an emote occurrence within a message\n\t * \n\t * @author Gikkman\n\t */\t\n\tclass EmoteIndices{\n\t\tpublic final int beingIndex;\n\t\tpublic final int endIndex;\n\t\t\n\t\tpublic EmoteIndices(int begin, int end){\n\t\t\tthis.beingIndex = begin;\n\t\t\tthis.endIndex = end;\n\t\t}\n\t\t\n\t\tpublic String toString(){\n\t\t\treturn \"(\" +beingIndex + \",\" + endIndex + \")\";\n\t\t}\n\t}\n}", "public interface TwitchMessage extends AbstractEmoteMessage {\n\n\t/**Retrieves this message's tag segment. Should always starts with a @. Note that the\n\t * Tag segment will look vastly different for different Twitch commands, and some won't\n\t * even have a tag.\n\t *\n\t * @return The tag segment, or {@code \"\"} if no tag was present\n\t */\n\tpublic String getTag();\n\n\t/**Retrieves the message's prefix.<br><br>\n\t *\n\t * A typical Twitch message looks something line this:<br>\n\t * <code>:[email protected] COMMAND #channel :message</code> <br><br>\n\t *\n\t * The prefix is the part before the first space. It usually only contains data about the sender of\n\t * the message, but it might sometimes contain other information (PING messages for example just have PING as\n\t * their prefix).<br><br>\n\t *\n\t * @return The messages prefix\n\t */\n\tpublic String getPrefix();\n\n\t/**Retrieves the message's command.<br>\n\t * The command tells us what action triggered this message being sent.<br><br>\n\t *\n\t * @return The message's command\n\t */\n\tpublic String getCommand();\n\n\t/**Retrieves the message's target.<br>\n\t * The target tells us whom the message is intended towards. It can be a user,\n * a channel, or something else (though mostly the channel).\n * <p>\n\t * This segment is not always present.\n\t *\n\t * @return The message's target, or {@code \"\"} if no target\n\t */\n\tpublic String getTarget();\n\n\t/**Retrieves the message's content.<br>\n\t * The content is the commands parameters. Most often, this is the actual chat message, but it may be many\n\t * other things for other commands.<br><br>\n\t *\n\t * This segment is not always present.\n\t *\n\t * @return The message's content, or {@code \"\"} if no content\n\t */\n\tpublic String getContent();\n\n /**Tells whether this message was a cheer event or not.\n *\n * @return {@code true} if the message contains bits, <code>false</code> otherwise\n */\n public boolean isCheer();\n\n /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.\n\t * The list might be empty, if the message contained no cheers.\n *\n\t * @return List of emotes (might be empty)\n\t */\n public List<Cheer> getCheers();\n\n /**Fetches the total number of bits that this message contained.\n * This method is short-hand for:\n * <pre>\n * int bits = 0;\n * for(Cheer c : getCheers())\n * bits += c.getBits();\n * return bits;\n * </pre>\n * @return number of bits\n */\n public int getBits();\n\n /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.\n * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.\n */\n public TagMap getTagMap();\n}", "public interface Raid {\n\n /**Fetches the display name of the user whom initiated the raid.\n *\n * @return the display name of the raid initiator\n */\n public String getSourceDisplayName();\n\n /**Fetches the login name of the user whom initiated the raid. This will\n * also give you the name of the channel which the raid originated from.\n *\n * @return the login name of the raid initiator\n */\n public String getSourceLoginName();\n\n\n /**Fetches the number of users participating in the raid.\n *\n * @return number of raiders\n */\n public int getRaidCount();\n}", "public interface Ritual {\n /**Fetches the name of the Ritual\n *\n * @return the ritual name\n */\n public String getRitualName();\n}", "public interface Subscription {\n public SubscriptionPlan getSubscriptionPlan();\n\n /**Get the number of month's the subscription's been active. New subscriptions\n * return 1, whilst re-subscriptions tells which month was just activated.\n *\n * @return number of months\n */\n public int getMonths();\n\n /**Get the number of month's the subscription's been active consecutive.\n *\n * @return number of months\n */\n public int getStreak();\n\n /** Returns if user decide to share the streak, this decide if the value of {@code getStreak} its zero or another.\n *\n * @return {@code true} if user share the streak\n */\n public boolean isSharedStreak();\n\n /**Returns the name of the purchased subscription plan. This may be a\n * default name or one created by the channel owner.\n *\n * @return display name of the subscription plan\n */\n public String getSubscriptionPlanName();\n\n /**Returns whether this was a new sub or a re-sub.\n *\n * @return {@code true} if this was a re-subscription\n */\n public boolean isResub();\n\n /**Tells whether this is a subscription gift or not.\n *\n * @return {@code true} if this was a gift\n */\n public boolean isGift();\n\n /**Retrieves the SubscriptionGift item, which holds information about the\n * gift and the recipiant of the gift. The Optional object wraps the\n * SubscriptionGift object (as an alternative to returning {@code null}).\n *\n * @return the subscription gift, wrapped in a {@link Optional}\n */\n public Optional<SubscriptionGift> getSubscriptionGift();\n}" ]
import com.gikk.twirk.types.TagMap; import com.gikk.twirk.types.TwitchTags; import com.gikk.twirk.types.emote.Emote; import com.gikk.twirk.types.twitchMessage.TwitchMessage; import com.gikk.twirk.types.usernotice.subtype.Raid; import com.gikk.twirk.types.usernotice.subtype.Ritual; import com.gikk.twirk.types.usernotice.subtype.Subscription; import java.util.List;
package com.gikk.twirk.types.usernotice; class DefaultUsernoticeBuilder implements UsernoticeBuilder{ String rawLine; List<Emote> emotes; String messageID; int roomID; long sentTimestamp; String systemMessage; Subscription subscription; Raid raid; Ritual ritual; String message; @Override public Usernotice build(TwitchMessage message) { this.rawLine = message.getRaw(); this.emotes = message.getEmotes();
TagMap map = message.getTagMap();
0
huyongli/TigerVideo
TigerVideoPlayer/src/main/java/cn/ittiger/player/ui/VideoControllerView.java
[ "public final class PlayerManager implements IPlayer.PlayCallback {\n private static final String TAG = \"PlayerManager\";\n private static volatile PlayerManager sPlayerManager;\n private AbsSimplePlayer mPlayer;\n private PlayStateObservable mPlayStateObservable;\n private String mVideoUrl;\n private int mObserverHash = -1;\n private int mScreenState = ScreenState.SCREEN_STATE_NORMAL;\n private Config mConfig;\n\n private PlayerManager(Config config) {\n\n mConfig = config;\n createPlayer();\n\n mPlayStateObservable = new PlayStateObservable();\n }\n\n private void createPlayer() {\n\n mPlayer = mConfig.getPlayerFactory().create();\n mPlayer.setPlayCallback(this);\n }\n\n public Config getConfig() {\n\n return mConfig;\n }\n\n /**\n * 加载配置\n * @param config\n */\n public static void loadConfig(Config config) {\n\n if(sPlayerManager == null) {\n sPlayerManager = new PlayerManager(config);\n }\n }\n\n public static PlayerManager getInstance() {\n\n if(sPlayerManager == null) {\n synchronized (PlayerManager.class) {\n if(sPlayerManager == null) {\n //加载默认配置\n loadConfig(new Config.Builder().build());\n }\n }\n }\n if(sPlayerManager.mPlayer == null) {\n synchronized (PlayerManager.class) {\n if(sPlayerManager.mPlayer == null) {\n sPlayerManager.createPlayer();\n }\n }\n }\n return sPlayerManager;\n }\n\n public void removeTextureView() {\n\n if(mPlayer.getTextureView() != null &&\n mPlayer.getTextureView().getParent() != null) {\n ((ViewGroup)mPlayer.getTextureView().getParent()).removeView(mPlayer.getTextureView());\n setTextureView(null);\n if(mPlayer.getTextureView() != null) {\n Utils.log(\"remove TextureView:\" + mPlayer.getTextureView().toString());\n }\n }\n }\n\n public void setTextureView(TextureView textureView) {\n\n if(textureView != null) {\n Utils.log(\"set TextureView:\" + textureView.toString());\n }\n mPlayer.setTextureView(textureView);\n }\n\n /**\n * 待播放视频是否已经缓存\n * @param videoUrl\n * @return\n */\n boolean isCached(String videoUrl) {\n\n if(mConfig.isCacheEnable() && mConfig.getCacheProxy().isCached(videoUrl)) {\n return true;\n }\n return false;\n }\n\n /**\n * 获取正在播放的视频地址,必须在stop或release方法调用之前获取\n * @return\n */\n public String getVideoUrl() {\n\n return mVideoUrl;\n }\n\n public void start(String url, int observerHash) {\n\n bindPlayerView(url, observerHash);\n\n onPlayStateChanged(PlayState.STATE_LOADING);\n Utils.log(String.format(\"start loading video, hash=%d, url=%s\", mObserverHash, mVideoUrl));\n String wrapperUrl = url;\n if(mConfig.isCacheEnable()) {\n wrapperUrl = mConfig.getCacheProxy().getProxyUrl(url);\n }\n mPlayer.start(wrapperUrl);\n }\n\n void bindPlayerView(String url, int observerHash) {\n\n this.mVideoUrl = url;\n this.mObserverHash = observerHash;\n }\n\n public void play() {\n\n Utils.log(String.format(\"play video, hash=%d, url=%s\", mObserverHash, mVideoUrl));\n mPlayer.play();\n onPlayStateChanged(PlayState.STATE_PLAYING);\n }\n\n public void resume() {\n\n if(getState() == PlayState.STATE_PAUSE) {\n Utils.log(String.format(\"resume video, hash=%d, url=%s\", mObserverHash, mVideoUrl));\n play();\n }\n }\n\n public void pause() {\n\n if(getState() == PlayState.STATE_PLAYING) {\n Utils.log(String.format(\"pause video, hash=%d, url=%s\", mObserverHash, mVideoUrl));\n mPlayer.pause();\n onPlayStateChanged(PlayState.STATE_PAUSE);\n } else {\n Utils.log(String.format(\"pause video for state: %d, hash=%d, url=%s\", getState(), mObserverHash, mVideoUrl));\n }\n }\n\n public void stop() {\n\n Utils.log(String.format(\"stop video, hash=%d, url=%s\", mObserverHash, mVideoUrl));\n onPlayStateChanged(PlayState.STATE_NORMAL);\n mPlayer.stop();\n removeTextureView();\n mObserverHash = -1;\n mVideoUrl = null;\n mScreenState = ScreenState.SCREEN_STATE_NORMAL;\n }\n\n public void release() {\n\n Utils.log(\"release player\");\n mPlayer.setState(PlayState.STATE_NORMAL);\n removeTextureView();\n mPlayer.release();\n mPlayer = null;\n mObserverHash = -1;\n mVideoUrl = null;\n mScreenState = ScreenState.SCREEN_STATE_NORMAL;\n }\n\n /**\n * 界面上是否存在视频播放\n * @return\n */\n public boolean hasViewPlaying() {\n\n return mObserverHash != -1;\n }\n\n /**\n * 判断视频播放时是否需要自己处理返回键事件\n * @return\n */\n public boolean onBackPressed() {\n\n boolean consume = ScreenState.isNormal(mScreenState);\n if(consume == false) {\n mPlayStateObservable.notify(new BackPressedMessage(mScreenState, mObserverHash, mVideoUrl));\n return true;\n }\n return false;\n }\n\n public boolean isPlaying() {\n\n return mPlayer.isPlaying();\n }\n\n /**\n * 指定View是否在播放视频\n * @param viewHash\n * @return\n */\n boolean isViewPlaying(int viewHash) {\n\n return mObserverHash == viewHash;\n }\n\n public int getCurrentPosition() {\n\n return mPlayer.getCurrentPosition();\n }\n\n public void seekTo(int position) {\n\n if(isPlaying()) {\n onPlayStateChanged(PlayState.STATE_PLAYING_BUFFERING_START);\n }\n mPlayer.seekTo(position);\n }\n\n public int getState() {\n\n return sPlayerManager.mPlayer.getState();\n }\n\n @Override\n public void onError(String error) {\n\n Utils.log(\"error video, error= \" + error == null ? \"null\" : error + \", url=\" + mVideoUrl);\n if(!TextUtils.isEmpty(error)) {\n Log.d(TAG, error);\n }\n mPlayer.stop();\n changeUIState(PlayState.STATE_ERROR);\n }\n\n @Override\n public void onComplete() {\n\n changeUIState(PlayState.STATE_AUTO_COMPLETE);\n }\n\n @Override\n public void onPlayStateChanged(int state) {\n\n changeUIState(state);\n }\n\n @Override\n public void onDurationChanged(int duration) {\n\n mPlayStateObservable.notify(new DurationMessage(mObserverHash, mVideoUrl, duration));\n }\n\n void addObserver(Observer observer) {\n\n mPlayStateObservable.addObserver(observer);\n }\n\n void removeObserver(Observer observer) {\n\n mPlayStateObservable.deleteObserver(observer);\n }\n\n private void changeUIState(int state) {\n\n mPlayer.setState(state);\n\n mPlayStateObservable.notify(new UIStateMessage(mObserverHash, mVideoUrl, state));\n }\n\n public void setScreenState(int screenState) {\n\n mScreenState = screenState;\n }\n\n class PlayStateObservable extends Observable {\n\n private void setObservableChanged() {\n\n this.setChanged();\n }\n\n public void notify(Message message) {\n\n setObservableChanged();\n notifyObservers(message);\n }\n }\n}", "public interface FullScreenToggleListener {\r\n\r\n /**\r\n * 开始进入全屏\r\n */\r\n void onStartFullScreen();\r\n\r\n /**\r\n * 开始推出全屏\r\n */\r\n void onExitFullScreen();\r\n}\r", "public interface UIStateChangeListener {\r\n\r\n /**\r\n * UI状态更新为Normal状态,即初始状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUINormalState(int screenState);\r\n\r\n /**\r\n * UI状态更新为Loading状态,即视频加载状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUILoadingState(int screenState);\r\n\r\n /**\r\n * UI状态更新为Playing状态,即视频播放状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUIPlayingState(int screenState);\r\n\r\n /**\r\n * UI状态更新为Pause状态,即视频暂停播放状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUIPauseState(int screenState);\r\n\r\n /**\r\n * UI状态更新为SeekBuffer状态,即拖动进度条后导致的加载loading\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUISeekBufferingState(int screenState);\r\n\r\n /**\r\n * UI状态更新为Complete状态,即视频播放结束状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUICompleteState(int screenState);\r\n\r\n /**\r\n * UI状态更新为Error状态,即视频播放错误状态\r\n * @param screenState 当前屏幕状态{@link cn.ittiger.player.state.ScreenState}\r\n */\r\n void onChangeUIErrorState(int screenState);\r\n}\r", "public interface VideoControllerViewListener {\r\n\r\n /**\r\n * 开始更新视频播放进度\r\n */\r\n void startVideoProgressUpdate();\r\n\r\n /**\r\n * 停止更新视频播放进度\r\n */\r\n void stopVideoProgressUpdate();\r\n\r\n /**\r\n * 视频时长发生变化时的回调处理\r\n * @param duration\r\n */\r\n void onVideoDurationChanged(int duration);\r\n}\r", "public interface VideoTouchListener {\n\n /**\n * 显示所有的播放状态视图(底部控制条(与进度条显示与否互斥),播放暂停按钮,全屏时的头部等)\n */\n void showAllPlayStateView();\n\n /**\n * 隐藏所有的播放状态视图(底部控制条(与进度条显示与否互斥),播放暂停按钮,全屏时的头部等)\n */\n void hideAllPlayStateView();\n}", "public final class ScreenState {\n /**\n * 正常播放状态\n */\n public static final int SCREEN_STATE_NORMAL = 1;\n /**\n * 全屏播放状态\n */\n public static final int SCREEN_STATE_FULLSCREEN = 2;\n /**\n * 小窗口播放状态\n */\n public static final int SCREEN_STATE_SMALL_WINDOW = 3;\n\n public static boolean isFullScreen(int screenState) {\n\n return screenState == SCREEN_STATE_FULLSCREEN;\n }\n\n public static boolean isSmallWindow(int screenState) {\n\n return screenState == SCREEN_STATE_SMALL_WINDOW;\n }\n\n public static boolean isNormal(int screenState) {\n\n return screenState == SCREEN_STATE_NORMAL;\n }\n}", "public class Utils {\n private static final String UNKNOWN_SIZE = \"00:00\";\n\n /**\n * 转换视频时长(s)为时分秒的展示格式\n * @param miliseconds 视频总时长,单位毫秒\n * @return\n */\n public static String formatVideoTimeLength(long miliseconds) {\n\n int seconds = (int) (miliseconds / 1000);\n\n String formatLength;\n if(seconds == 0) {\n formatLength = UNKNOWN_SIZE;\n } else if(seconds < 60) {//小于1分钟\n formatLength = \"00:\" + (seconds < 10 ? \"0\" + seconds : seconds);\n } else if(seconds < 60 * 60) {//小于1小时\n long sec = seconds % 60;\n long min = seconds / 60;\n formatLength = (min < 10 ? \"0\" + min : String.valueOf(min)) + \":\" +\n (sec < 10 ? \"0\" + sec : String.valueOf(sec));\n } else {\n long hour = seconds / 3600;\n long min = seconds % 3600 / 60;\n long sec = seconds % 3600 % 60;\n formatLength = (hour < 10 ? \"0\" + hour : String.valueOf(hour)) + \":\" +\n (min < 10 ? \"0\" + min : String.valueOf(min)) + \":\" +\n (sec < 10 ? \"0\" + sec : String.valueOf(sec));\n }\n return formatLength;\n }\n\n public static void showViewIfNeed(View view) {\n\n if(view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) {\n view.setVisibility(View.VISIBLE);\n }\n }\n\n public static void hideViewIfNeed(View view) {\n\n if(view.getVisibility() == View.VISIBLE) {\n view.setVisibility(View.GONE);\n }\n }\n\n public static boolean isViewShown(View view) {\n\n return view.getVisibility() == View.VISIBLE;\n }\n\n public static boolean isViewHide(View view) {\n\n return view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE;\n }\n\n public static void log(String message) {\n\n Log.d(\"__VideoPlayer__\", message);\n }\n\n public static void logTouch(String message) {\n\n Log.d(\"__GestureTouch__\", message);\n }\n\n /**\n * Get activity from context object\n *\n * @param context context\n * @return object of Activity or null if it is not Activity\n */\n public static Activity getActivity(Context context) {\n if (context == null) return null;\n\n if (context instanceof Activity) {\n return (Activity) context;\n } else if (context instanceof ContextWrapper) {\n return getActivity(((ContextWrapper) context).getBaseContext());\n }\n\n return null;\n }\n\n /**\n * 返回屏幕宽度Px\n *\n * @param context\n * @return int\n */\n public static int getWindowWidth(Context context) {\n\n int screenWidthPixels = 0;\n\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n Point outPoint = new Point();\n display.getRealSize(outPoint);\n screenWidthPixels = outPoint.x;\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {\n Point outPoint = new Point();\n display.getSize(outPoint);\n screenWidthPixels = outPoint.x;\n } else {\n screenWidthPixels = display.getWidth();\n }\n return screenWidthPixels;\n }\n\n /**\n * 返回屏幕高度\n *\n * @param context\n * @return int\n */\n public static int getWindowHeight(Context context) {\n\n DisplayMetrics dm = new DisplayMetrics();\n ((Activity) context).getWindowManager().getDefaultDisplay()\n .getMetrics(dm);\n return dm.heightPixels;\n }\n\n /**\n * 应用缓存目录,可以通过手机中的清除缓存把数据清除掉\n *\n * @param context\n * @return\n */\n public static String getCacheDir(Context context) {\n\n return context.getExternalCacheDir().getAbsolutePath() + \"/VideoCache\";\n }\n\n /**\n * 判断网络连接是否有效(此时可传输数据)。\n * <p>需添加权限 {@code <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>}</p>\n * 如果未添加此权限则返回true\n *\n * @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。\n */\n public static boolean isConnected(Context context) {\n try {\n NetworkInfo net = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();\n return net != null && net.isConnected();\n } catch(Exception e) {\n return true;\n }\n }\n}" ]
import android.content.Context; import android.os.Build; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import cn.ittiger.player.PlayerManager; import cn.ittiger.player.R; import cn.ittiger.player.listener.FullScreenToggleListener; import cn.ittiger.player.listener.UIStateChangeListener; import cn.ittiger.player.listener.VideoControllerViewListener; import cn.ittiger.player.listener.VideoTouchListener; import cn.ittiger.player.state.ScreenState; import cn.ittiger.player.util.Utils;
package cn.ittiger.player.ui; /** * 底部播放控制视图 * @author: ylhu * @time: 2017/12/12 */ public class VideoControllerView extends RelativeLayout implements UIStateChangeListener, View.OnClickListener, VideoControllerViewListener, VideoTouchListener, SeekBar.OnSeekBarChangeListener { private static final int PROGRESS_UPDATE_INTERNAL = 300; private static final int PROGRESS_UPDATE_INITIAL_INTERVAL = 100; protected View mVideoControllerInternalView; /** * 底部 视频当前播放时间 */ protected TextView mVideoPlayTimeView; /** * 底部 视频总时长 */ protected TextView mVideoTotalTimeView; /** * 底部 视频播放进度 */ protected SeekBar mVideoPlaySeekBar; /** * 底部 全屏播放按钮 */ protected ImageView mVideoFullScreenButton; /** * 控制条不显示后,显示播放进度的进度条(不可点击) */ protected ProgressBar mBottomProgressBar; /** * 当前屏幕播放状态 */
protected int mCurrentScreenState = ScreenState.SCREEN_STATE_NORMAL;
5
bit-man/SwissArmyJavaGit
javagit/src/main/java/edu/nyu/cs/javagit/client/cli/CliGitAdd.java
[ "public final class JavaGitConfiguration {\n\n /*\n * The path to our git binaries. Default to null, which means that the git command is available\n * via the system PATH environment variable.\n */\n private static File gitPath = null;\n\n /*\n * The version string fpr the locally-installed git binaries.\n */\n private static GitVersion gitVersion = null;\n\n /**\n * Constructor - private because this is an all-static class.\n */\n private JavaGitConfiguration() {\n\n }\n\n /**\n * Sets the {@link #gitVersion} field.\n * <br/>\n * This function gets called in one of two ways:\n * <br/>\n * 1) When client code sets the path to the git binaries explicitly by calling {@link #setGitPath(java.io.File)},\n * this function is used to determine if the path is usable or not. In this case, the\n * <code>File</code> path argument will be the new path to the git binaries.\n * <br/>\n * 2) When client code calls {@link #getGitVersion()} and the path has not been set explicitly, we\n * call this function to figure out the version. In this case, the <code>File</code> path\n * argument will be null.\n *\n *\n * @param path\n * <code>File</code> object representing the directory containing the git binaries. If\n * null, the previously-set path is used (if any). It must contain either an absolute\n * path, or a valid path relative to the current working directory.\n * @throws JavaGitException\n * Thrown if git is not found at the provided path.\n */\n private static void determineGitVersion(File path) throws JavaGitException {\n\n /*\n * If they already set the path explicitly, or are in the process of doing so (via the path\n * argument), make sure to prefix the git call with it. If they didn't, assume it's blank.\n */\n String gitPrefix = \"\";\n if (path != null) {\n // We got a path passed in as an argument.\n gitPrefix = path.getAbsolutePath() + File.separator;\n } else if (gitPath != null) {\n // They didn't pass in a path, but previously set it explicitly via setGitPath.\n gitPrefix = getGitCommandPrefix();\n }\n\n String gitCommand = gitPrefix + \"git\";\n if (!(gitPrefix.equals(\"\"))) {\n // If we've got a full path to the git binary here, ensure it actually exists.\n if (!(new File(gitCommand).exists())) {\n throw new JavaGitException(100002, ExceptionMessageMap.getMessage(\"100002\"));\n }\n }\n\n List<String> commandLine = new ArrayList<String>();\n commandLine.add(gitCommand);\n commandLine.add(\"--version\");\n\n // Now run the actual git version command.\n try {\n // We're passing in a working directory of null, which is \"don't care\" to runCommand\n gitVersion = (GitVersion) ProcessUtilities.runCommand(null, commandLine,\n new GitVersionParser());\n } catch (Exception e) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n\n String version = gitVersion.toString();\n if (!(isValidVersionString(version))) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n\n }\n\n /**\n * Return the complete string necessary to invoke git on the command line. Could be an absolute\n * path to git, or if the path was never set explicitly, just \"git\".\n * \n * @return <code>String</code> containing the path to git, ending with the git executable's name\n * itself.\n */\n public static String getGitCommand() {\n return getGitCommandPrefix() + \"git\";\n }\n\n /**\n * Return an absolute path capable of being dropped in front of the command-line git invocation.\n * If the path hasn't been set explicitly, just return the empty string and assume git is in this\n * process' PATH environment variable.\n * \n * @return The <code>String</code> that points to the git executable.\n */\n public static String getGitCommandPrefix() {\n return ((gitPath == null) ? \"\" : (gitPath.getAbsolutePath() + File.separator));\n }\n\n /**\n * Accessor method for the <code>File</code> object representing the path to git. If the git\n * path is never set explicitly, this will return null.\n * \n * @return <code>File</code> object pointing at the directory containing git.\n */\n public static File getGitPath() {\n return gitPath;\n }\n\n /**\n * Returns the version number of the underlying git binaries. If this method is called and we\n * don't know the version yet, it tries to figure it out. (The version gets set if\n * {@link #setGitPath(File) setGitPath} was previously called.)\n * \n * @return The git version <code>String</code>.\n */\n public static String getGitVersion() throws JavaGitException {\n return getGitVersionObject().toString();\n }\n\n\n public static GitVersion getGitVersionObject() throws JavaGitException {\n // If the version hasn't been found yet, let's do some lazy initialization here.\n if (gitVersion == null) {\n determineGitVersion(gitPath);\n }\n\n return gitVersion;\n }\n\n /**\n * Judge the validity of a given git version string. This can be difficult to do, as there seems\n * to be no deliberately-defined git version format. So, here we do a minimal sanity check for two\n * things: 1. The first character in the version is a number. 2. There's at least one period in\n * the version string.\n * \n * @param version\n * @return true if the version passed as argument is valid\n */\n private static boolean isValidVersionString(String version) {\n /*\n * Git version strings can vary, so let's do a minimal sanity check for two things: 1. The first\n * character in the version is a number. 2. There's at least one period in the version string.\n * \n * TODO (rs2705): Make this more sophisticated by parsing out a major/minor version number, and\n * ensuring it's >= some minimally-required version.\n */\n try {\n Integer.parseInt(version.substring(0, 1));\n } catch (NumberFormatException e) {\n // First character in the version string was not a valid number!\n return false;\n }\n\n if (version.indexOf(\".\") == -1) {\n // The version string doesn't contain a period!\n return false;\n }\n\n return true;\n }\n\n /**\n * Called when client code wants to explicitly tell us where to find git on their filesystem. If\n * never called, we assume that git is in a directory in the PATH environment variable for this\n * process. Passing null as the path argument will unset an explicitly-set path and revert to\n * looking for git in the PATH.\n * \n * @param path\n * <code>File</code> object representing the directory containing the git binaries. It\n * must contain either an absolute path, or a valid path relative to the current working\n * directory.\n * @throws IOException\n * Thrown if the provided path does not exist.\n * @throws JavaGitException\n * Thrown if git does not exist at the provided path, or the provided path is not a\n * directory.\n */\n public static void setGitPath(File path) throws IOException, JavaGitException {\n if (path != null) {\n CheckUtilities.checkFileValidity(path);\n\n if (!(path.isDirectory())) {\n throw new JavaGitException(020002, ExceptionMessageMap.getMessage(\"020002\") + \" { path=[\"\n + path.getPath() + \"] }\");\n }\n }\n\n try {\n determineGitVersion(path);\n } catch (Exception e) {\n // The path that was passed in doesn't work. Catch any errors and throw this one instead.\n throw new JavaGitException(100002, ExceptionMessageMap.getMessage(\"100002\") + \" { path=[\"\n + path.getPath() + \"] }\", e);\n }\n\n // Make sure we're hanging onto an absolute path.\n gitPath = (path != null) ? path.getAbsoluteFile() : null;\n }\n\n /**\n * Convenience method for setting the path with a <code>String</code> instead of a\n * <code>File</code>.\n * \n * TODO (rs2705): Enforce the requirement below that the path be absolute. Is there a simple way\n * to do this in an OS-independent fashion?\n * \n * @param path\n * Absolute path to git binaries installed on the system. The path must be absolute since\n * it needs to persist for the life of the client code, even if the working directory\n * changes. Throws a NullPointerException if path is null, or an IllegalArgumentException\n * if it's the empty string.\n * @throws IOException\n * Thrown if the provided path does not exist.\n * @throws JavaGitException\n * Thrown if we cannot find git at the path provided.\n */\n public static void setGitPath(String path) throws IOException, JavaGitException {\n CheckUtilities.checkStringArgument(path, \"path\");\n setGitPath(new File(path));\n }\n\n /*\n * <code>GitVersionParser</code> parses the output of the <code>git --version</code> command.\n * It is also used to determine if the git binaries are accessible via the command line.\n * \n * TODO (rs2705): Write unit tests for this class.\n */\n private static class GitVersionParser implements IParser {\n // The version of git that we parse out.\n private String version = \"\";\n\n // Whether or not we saw a valid version string.\n private boolean parsedCorrectly = true;\n\n // We only care about parsing the first line of our input - watch that here.\n private boolean sawLine = false;\n\n /**\n * Returns the <code>GitVersion</code> object that's essentially just a wrapper around\n * the git version number.\n * \n * @return The response object containing the version number.\n */\n public CommandResponse getResponse() throws JavaGitException {\n if (!(parsedCorrectly)) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n return new GitVersion(version);\n }\n\n /**\n * Parses the output of <code>git --version</code>. Expects to see: \"git version XYZ\".\n * \n * @param line\n * <code>String</code> containing the line to be parsed.\n */\n public void parseLine(String line) {\n if (!(sawLine)) {\n sawLine = true;\n parsedCorrectly = (line.trim().indexOf(\"git version \") == 0);\n if (parsedCorrectly) {\n version = line.replaceAll(\"git version \", \"\");\n }\n }\n }\n\n public void processExitCode(int code) {\n }\n \n }\n\n}", "public abstract class GitAddResponse implements CommandResponse {\n\n /**\n * List of files added to the index by &lt;git-add&gt; command.\n */\n protected List<File> filePathsList;\n\n /**\n * Initially set to true as git-add many times does not generate any output at all. If output is\n * generated then it needs to be set to false. This can be used as a tester whether any output was\n * generated or not.\n */\n protected boolean noOutput;\n\n protected List<ResponseString> comments;\n\n protected boolean dryRun;\n\n /**\n * Constructor\n */\n public GitAddResponse() {\n filePathsList = new ArrayList<File>();\n comments = new ArrayList<ResponseString>();\n noOutput = true;\n dryRun = false;\n }\n\n /**\n * Gets the number of files added.\n * \n * @return size of list.\n */\n public int getFileListSize() {\n return filePathsList.size();\n }\n\n public File get(int index) throws IndexOutOfBoundsException {\n if (index < filePathsList.size() && index >= 0) {\n return filePathsList.get(index);\n }\n throw new IndexOutOfBoundsException(index + \" is out of range\");\n }\n\n public boolean noOutput() {\n return noOutput;\n }\n\n public boolean dryRun() {\n return dryRun;\n }\n\n public boolean comment() {\n return (comments.size() > 0);\n }\n\n public int nubmerOfComments() {\n return comments.size();\n }\n\n public ResponseString getComment(int index) {\n CheckUtilities.checkIntInRange(index, 0, comments.size());\n return (comments.get(index));\n }\n\n /**\n * For saving errors, warnings and comments related information in the response object. Currently\n * it has only two fields -\n * <ul>\n * <li>Error, warning or general comment string</li>\n * <li>Line number where the string appeared in output</li>\n * <ul>\n */\n public static class ResponseString {\n final String comment;\n final int lineNumber;\n\n public ResponseString(int lineNumber, String comment) {\n this.lineNumber = lineNumber;\n this.comment = comment;\n }\n\n public int getLineNumber() {\n return lineNumber;\n }\n\n public String comment() {\n return comment;\n }\n\n }\n}", "public class GitAddResponseImpl extends GitAddResponse {\n\n /**\n * Sets the value of no output flag.\n * \n * @param noOutput\n * true if there was no output generated. This is a helper flag that tells the consumer\n * of <code>GitAddResponse</code> that there was no resulting output for executed\n * &lt;git-add&gt; command.\n */\n public void setNoOutput(boolean noOutput) {\n this.noOutput = noOutput;\n }\n\n /**\n * Sets the flag if dry run flag need to be used\n * \n * @param dryRun\n * true if dry run should be used, otherwise false.\n */\n public void setDryRun(boolean dryRun) {\n this.dryRun = dryRun;\n }\n\n /**\n * Sets the non-error message generated in the output of the &lt;git-add&gt; command.\n * \n * @param lineNumber\n * line number at which the message appeared in output.\n * @param commentString\n * message itself.\n */\n public void setComment(int lineNumber, String commentString) {\n ResponseString comment = new ResponseString(lineNumber, commentString);\n comments.add(comment);\n }\n\n /**\n * Adds a file and action to the list.\n * \n * @param file\n * File to be added to the <code>List</code>.\n */\n public void add(File file) {\n filePathsList.add(file);\n }\n\n}", "public class CheckUtilities {\n\n /**\n * Checks that the specified filename exists. This assumes that the above check for string\n * validity has already been run and the path/filename is neither null or of size 0.\n * \n * @param filename\n * File or directory path\n */\n public static void checkFileValidity(String filename) throws IOException {\n File file = new File(filename);\n if (!file.exists()) {\n throw new IOException(ExceptionMessageMap.getMessage(\"020001\") + \" { filename=[\" + filename\n + \"] }\");\n }\n }\n\n /**\n * Checks that the specified file exists.\n * \n * @param file\n * File or directory path\n */\n public static void checkFileValidity(File file) throws IOException {\n if (!file.exists()) {\n throw new IOException(ExceptionMessageMap.getMessage(\"020001\") + \" { filename=[\"\n + file.getName() + \"] }\");\n }\n }\n\n /**\n * Checks that the int to check is greater than <code>lowerBound</code>. If the int to check is\n * not greater than <code>lowerBound</code>, an <code>IllegalArgumentException</code> is\n * thrown.\n * \n * @param toCheck\n * The int to check.\n * @param lowerBound\n * The lower bound to check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkIntArgumentGreaterThan(int toCheck, int lowerBound, String variableName) {\n if (lowerBound >= toCheck) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000004\") + \" { toCheck=[\"\n + toCheck + \"], lowerBound=[\" + lowerBound + \"], variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Performs a null check on the specified object. If the object is null, a\n * <code>NullPointerException</code> is thrown.\n * \n * @param obj\n * The object to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkNullArgument(Object obj, String variableName) {\n if (null == obj) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000003\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List&lt;?&gt;</code> argument to make sure it is not null, has length > 0, and\n * none of its elements are null. If the <code>List&lt;?&gt;</code> or any contained instance is\n * null, a <code>NullPointerException</code> is thrown. If the <code>List&lt;?&gt;</code> or\n * any contained instance has length zero, an <code>IllegalArgumentException</code> is thrown.\n * \n * @param list\n * The list to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkNullListArgument(List<?> list, String variableName) {\n // TODO (jhl388): Write a unit test for this method.\n if (null == list) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000005\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (list.size() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000005\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n for (int i = 0; i < list.size(); i++) {\n checkNullArgument(list.get(i), variableName);\n }\n }\n\n /**\n * Checks that two lists are equal, specifically: they are both null or the both contain the same\n * elements.\n * \n * @param l1\n * The first list to check.\n * @param l2\n * The second list to check.\n * @return True if one of the following conditions hold:\n * <ol>\n * <li>Both lists are null</li>\n * <li>a) Neither list is null; b) for each element in list 1 an equivalent element\n * exists in list 2; and c) for each element in list 2, an equivalent element exists in\n * list 1</li>\n * </ol>\n */\n public static boolean checkListsEqual(List<?> l1, List<?> l2) {\n \n // TODO (jhl388): write a test case for this method.\n \n if (null != l1 && null == l2) {\n return false;\n }\n \n if (null == l1 && null != l2) {\n return false;\n }\n \n if (null != l1) {\n for (Object e : l1) {\n if (!l2.contains(e)) {\n return false;\n }\n }\n \n for (Object e : l2) {\n if (!l1.contains(e)) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Checks to see if two objects are equal. The Object.equal() method is used to check for\n * equality.\n * \n * @param o1\n * The first object to check.\n * @param o2\n * The second object to check.\n * @return True if the two objects are equal. False if the objects are not equal.\n */\n public static boolean checkObjectsEqual(Object o1, Object o2) {\n if (null != o1 && !o1.equals(o2)) {\n return false;\n }\n\n if (null == o1 && null != o2) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Checks a <code>String</code> argument to make sure it is not null and contains one or more\n * characters. If the <code>String</code> is null, a <code>NullPointerException</code> is\n * thrown. If the <code>String</code> has length zero, an <code>IllegalArgumentException</code>\n * is thrown.\n * \n * @param str\n * The string to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkStringArgument(String str, String variableName) {\n if (null == str) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000001\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (str.length() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000001\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List&lt;String&gt;</code> argument to make sure it is not null, none of its\n * elements are null, and all its elements contain one or more characters. If the\n * <code>List&lt;String&gt;</code> or a contained <code>String</code> is null, a\n * <code>NullPointerException</code> is thrown. If the <code>List&lt;String&gt;</code> or a\n * contained <code>String</code> has length zero, an <code>IllegalArgumentException</code> is\n * thrown.\n * \n * @param str\n * The <code>List&lt;String&gt;</code> to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkStringListArgument(List<String> str, String variableName) {\n if (null == str) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000002\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (str.size() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000002\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n for (int i = 0; i < str.size(); i++) {\n checkStringArgument(str.get(i), variableName);\n }\n }\n\n /**\n * Checks if two unordered lists are equal.\n * \n * @param l1\n * The first list to test.\n * @param l2\n * The second list to test.\n * @return True if:\n * <ul>\n * <li>both lists are null or</li>\n * <li>both lists are the same length, there exists an equivalent object in l2 for all\n * objects in l1, and there exists an equivalent object in l1 for all objects in l2</li>\n * </ul>\n * False otherwise.\n */\n public static boolean checkUnorderedListsEqual(List<?> l1, List<?> l2) {\n if (null == l1 && null != l2) {\n return false;\n }\n\n if (null != l1 && null == l2) {\n return false;\n }\n\n if (l1.size() != l2.size()) {\n return false;\n }\n\n for (Object o : l1) {\n if (!l2.contains(o)) {\n return false;\n }\n }\n\n for (Object o : l2) {\n if (!l1.contains(o)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if the index provided to list is within the range i.e. positive and less than the size of\n * the <List>. If the index is less than 0 or greater than equal to the size of the list then\n * <code>IndexOutOfBoundsException</code> is thrown.\n * \n * @param list\n * <List> for which the index is being verified.\n * @param index\n * Index in the list.\n */\n public static void checkIntIndexInListRange(List<?> list, int index) {\n checkIntInRange(index, 0, list.size());\n }\n\n /**\n * A general range check utility for checking whether a given &lt;integer&gt; value is between a\n * given start and end indexes. This is a helper method for other methods such as\n * checkIntIndexInListRange or can also be used independently by external objects.\n * \n * @param index\n * Given index that is being checked for validity between start and end.\n * @param start\n * index should be greater than or equal to start.\n * @param end\n * index should be less than end.\n */\n public static void checkIntInRange(int index, int start, int end) {\n if (index < start) {\n throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage(\"000006\") + \" { index=[\"\n + index + \"], start=[\" + start + \"], end=[\" + end + \"] }\");\n }\n if (index >= end) {\n throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage(\"000006\") + \" { index=[\"\n + index + \"], start=[\" + start + \"], end=[\" + end + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List</code> argument to make sure that all the <code>Ref</code> in the list \n * are of same <code>refType</code> type. If there is a mismatch \n * <code>IllegalArgumentException</code> is thrown.\n * \n * @param list\n * The <code>List</code> to check.\n * @param type\n * The <code>refType</code> check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void validateListRefType(List<Ref> list, Ref.RefType type, String variableName) {\n // TODO (ns1344): Write a unit test for this method.\n checkNullListArgument(list, variableName);\n for (Ref ref : list) {\n validateArgumentRefType(ref, type, variableName);\n }\n }\n\n /**\n * Checks a <code>Ref</code> argument to make sure that it is of given <code>refType</code> type.\n * If not <code>IllegalArgumentException</code> is thrown.\n * \n * @param name\n * The argument to check.\n * @param type\n * The <code>refType</code> to check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void validateArgumentRefType(Ref name, Ref.RefType type, String variableName) {\n checkNullArgument(name, variableName);\n if (name.getRefType() != type) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"100000\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n \n /**\n * Checks a <code>File</code> argument to make sure that it is a directory. If not \n * <code>IllegalArgumentException</code> is thrown.\n * \n * @param fileName\n * The <code>File</code> to be checked.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkDirectoryArgument(File fileName, String variableName) {\n checkNullArgument(fileName, variableName);\n if (!fileName.isDirectory()) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000007\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n}", "public class ExceptionMessageMap {\n\n private static Map<String, String> MESSAGE_MAP;\n\n static {\n MESSAGE_MAP = new HashMap<String, String>();\n\n MESSAGE_MAP.put(\"000001\", \"000001: A String argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000002\", \"000002: A List<String> argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000003\", \"000003: An Object argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000004\",\n \"000004: The int argument is not greater than the lower bound (lowerBound < toCheck).\");\n MESSAGE_MAP.put(\"000005\",\n \"000005: An List<?> argument was not specified or is empty but is required.\");\n MESSAGE_MAP.put(\"000006\",\n \"000006: The int argument is outside the allowable range (start <= index < end).\");\n MESSAGE_MAP.put(\"000007\",\"000007: The argument should be a directory.\");\n\n MESSAGE_MAP.put(\"000100\", \"000100: Invalid option combination for git-commit command.\");\n MESSAGE_MAP.put(\"000110\", \"000110: Invalid option combination for git-add command.\");\n MESSAGE_MAP.put(\"000120\", \"000120: Invalid option combination for git-branch command.\");\n MESSAGE_MAP.put(\"000130\", \"000130: Invalid option combination for git-checkout command.\");\n \n MESSAGE_MAP.put(\"020001\", \"020001: File or path does not exist.\");\n MESSAGE_MAP.put(\"020002\", \"020002: File or path is not a directory.\");\n\n MESSAGE_MAP.put(\"020100\", \"020100: Unable to start sub-process.\");\n MESSAGE_MAP.put(\"020101\", \"020101: Error reading input from the sub-process.\");\n\n MESSAGE_MAP.put(\"100000\", \"100000: Incorrect refType type.\");\n MESSAGE_MAP.put(\"100001\", \"100001: Error retrieving git version.\");\n MESSAGE_MAP.put(\"100002\", \"100002: Invalid path to git specified.\");\n\n MESSAGE_MAP.put(\"401000\", \"401000: Error calling git-add.\");\n MESSAGE_MAP.put(\"401001\", \"401001: Error fatal pathspec error while executing git-add.\");\n\n MESSAGE_MAP.put(\"410000\", \"410000: Error calling git-commit.\");\n\n MESSAGE_MAP.put(\"404000\", \"404000: Error calling git-branch. \");\n\n MESSAGE_MAP.put(\"424000\", \"424000: Error calling git-mv. \");\n\n MESSAGE_MAP.put(\"424001\", \"424001: Error calling git-mv for dry-run. \");\n\n MESSAGE_MAP.put(\"420001\", \"420001: Error calling git log\");\n\n MESSAGE_MAP.put(\"432000\", \"432000: Error calling git-reset.\");\n\n MESSAGE_MAP.put(\"418000\", \"418000: Error calling git init.\");\n\n MESSAGE_MAP.put(\"434000\", \"434000: Error calling git-rm.\");\n\n MESSAGE_MAP.put(\"406000\", \"406000: Error calling git-checkout\");\n MESSAGE_MAP.put(\"406001\", \"406001: Error not a treeIsh RefType\");\n\n MESSAGE_MAP.put(\"438000\", \"438000: Error calling git-status\");\n\n MESSAGE_MAP.put(\"442001\", \"442001: No git, or wrong, major version number.\");\n MESSAGE_MAP.put(\"442002\", \"442002: No git, or wrong, minor version number.\");\n MESSAGE_MAP.put(\"442003\", \"442003: No git, or wrong, major release version number.\");\n MESSAGE_MAP.put(\"442004\", \"442004: Wrong minor release version number.\");\n }\n\n /**\n * Gets the error message for the specified code.\n * \n * @param code\n * The error code for which to get the associated error message.\n * @return The error message for the specified code.\n */\n public static String getMessage(String code) {\n String str = MESSAGE_MAP.get(code);\n if (null == str) {\n return \"NO MESSAGE FOR ERROR CODE. { code=[\" + code + \"] }\";\n }\n return str;\n }\n\n}" ]
import edu.nyu.cs.javagit.api.JavaGitConfiguration; import edu.nyu.cs.javagit.api.JavaGitException; import edu.nyu.cs.javagit.api.commands.GitAddOptions; import edu.nyu.cs.javagit.api.commands.GitAddResponse; import edu.nyu.cs.javagit.client.GitAddResponseImpl; import edu.nyu.cs.javagit.client.IGitAdd; import edu.nyu.cs.javagit.utilities.CheckUtilities; import edu.nyu.cs.javagit.utilities.ExceptionMessageMap; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;
if (options.ignoreErrors()) { command.add("--ignore-errors"); } } if (paths != null && paths.size() > 0) { for (File file : paths) { command.add(file.getPath()); } } return command; } /** * Parser class that implements <code>IParser</code> for implementing a parser for * &lt;git-add&gt; output. */ public static class GitAddParser implements IParser { private int lineNum; private GitAddResponseImpl response; private boolean error = false; private List<Error> errorList; public GitAddParser() { lineNum = 0; response = new GitAddResponseImpl(); } public void parseLine(String line) { if (line == null || line.length() == 0) { return; } lineNum++; if (isError(line)) { error = true; errorList.add(new Error(lineNum, line)); } else if (isComment(line)) response.setComment(lineNum, line); else processLine(line); } private boolean isError(String line) { if (line.trim().startsWith("fatal") || line.trim().startsWith("error")) { if (errorList == null) { errorList = new ArrayList<Error>(); } return true; } return false; } private boolean isComment(String line) { if (line.startsWith("Nothing specified") || line.contains("nothing added") || line.contains("No changes") || line.contains("Maybe you wanted to say") || line.contains("usage")) { return true; } return false; } /** * Lines that start with "add" have the second token as the name of the file added by * &lt;git-add&gt. * * @param line */ private void processLine(String line) { if (line.startsWith("add")) { StringTokenizer st = new StringTokenizer(line); if (st.nextToken().equals("add") && st.hasMoreTokens()) { String extractedFileName = filterFileName(st.nextToken()); if (extractedFileName != null && extractedFileName.length() > 0) { File file = new File(extractedFileName); response.add(file); } } } else { processSpaceDelimitedFilePaths(line); } } private void processSpaceDelimitedFilePaths(String line) { if (!line.startsWith("\\s+")) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { File file = new File(st.nextToken()); response.add(file); } } } public String filterFileName(String token) { if (token.length() > 0 && enclosedWithSingleQuotes(token)) { int firstQuote = token.indexOf("'"); int nextQuote = token.indexOf("'", firstQuote + 1); if (nextQuote > firstQuote) { return token.substring(firstQuote + 1, nextQuote); } } return null; } public boolean enclosedWithSingleQuotes(String token) { return token.matches("'.*'"); } public void processExitCode(int code) { } /** * Gets a <code>GitAddResponse</code> object containing the info generated by &lt;git-add&gt; command. * If there was an error generated while running &lt;git-add&gt; then it throws an exception. * * @return GitAddResponse object containing &lt;git-add&gt; response. * @throws JavaGitException If there are any errors generated by &lt;git-add&gt; command. */ public GitAddResponse getResponse() throws JavaGitException { if (error) {
throw new JavaGitException(401000, ExceptionMessageMap.getMessage("401000") +
4
ToxicBakery/Screenshot-Redaction
app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
[ "public class CopyBus extends ADefaultBus<ICopyConfiguration> {\n\n private static volatile CopyBus instance;\n\n public static CopyBus getInstance() {\n if (instance == null) {\n synchronized (CopyBus.class) {\n if (instance == null) {\n instance = new CopyBus();\n }\n }\n }\n\n return instance;\n }\n\n}", "public class CopyToSdCard {\n\n public void copy(@NonNull ICopyConfiguration copy) {\n Observable.just(copy)\n .observeOn(Schedulers.io())\n .subscribeOn(Schedulers.io())\n .subscribe(new CopyAction());\n }\n\n public interface ICopyConfiguration {\n\n InputStream getCopyStream() throws IOException;\n\n File getTarget() throws IOException;\n\n long getSize() throws IOException;\n\n }\n\n}", "public interface ICopyConfiguration {\n\n InputStream getCopyStream() throws IOException;\n\n File getTarget() throws IOException;\n\n long getSize() throws IOException;\n\n}", "public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {\n\n private static final String FOLDER = \"wordlists\";\n\n private final Context context;\n private final int rawRes;\n private final File baseDir;\n\n public WordListRawResourceCopyConfiguration(@NonNull Context context,\n @RawRes int rawRes) {\n\n this.context = context.getApplicationContext();\n this.rawRes = rawRes;\n\n baseDir = new File(context.getExternalFilesDir(null), FOLDER);\n\n try {\n FileUtils.forceMkdir(baseDir);\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to create required directory \" + baseDir, e);\n }\n }\n\n @Override\n public InputStream getCopyStream() throws IOException {\n return context.getResources()\n .openRawResource(rawRes);\n }\n\n @Override\n public File getTarget() throws IOException {\n String resourceEntryName = context.getResources()\n .getResourceEntryName(rawRes);\n\n return new File(baseDir, resourceEntryName);\n }\n\n @Override\n public long getSize() throws IOException {\n InputStream inputStream = context.getResources()\n .openRawResource(rawRes);\n\n long fileSize = inputStream.available();\n inputStream.close();\n\n return fileSize;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o != null\n && o instanceof WordListRawResourceCopyConfiguration) {\n\n WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;\n return rawRes == other.rawRes\n && baseDir.equals(other.baseDir);\n }\n\n return false;\n }\n\n}", "public interface IDictionary {\n\n /**\n * Determine if a word should be redacted.\n *\n * @param word the word in question\n * @return true if the word should be redacted\n */\n boolean shouldRedact(@NonNull String word);\n\n /**\n * The name of the dictionary.\n *\n * @return a string resource representation of the dictionary name.\n */\n @StringRes\n int getName();\n\n /**\n * A constant UUID of the dictionary.\n *\n * @return a constant UUID\n */\n @NonNull\n String getUUID();\n\n}" ]
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.util.Log; import com.ToxicBakery.app.screenshot_redaction.R; import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus; import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard; import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration; import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration; import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary; import org.mapdb.DB; import org.mapdb.DBMaker; import java.io.IOException; import java.util.Locale; import java.util.Set; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl; public class DictionaryEnglishNames implements IDictionary { private static final String TAG = "DictionaryEnglishNames"; private static DictionaryEnglishNames instance; @VisibleForTesting final ICopyConfiguration copyConfiguration; private final CopyBus copyBus; private Set<String> words; DictionaryEnglishNames(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english_names);
3
ketao1989/ourea
ourea-spring/src/main/java/com/taocoder/ourea/spring/consumer/ConsumerProxyFactoryBean.java
[ "public class Constants {\n\n public static final String ZK_PATH_PREFIX = \"/ourea\";\n\n public static final String PATH_SEPARATOR = \"/\";\n\n public static final String GROUP_KEY = \"group\";\n\n public static final String VERSION_KEY = \"version\";\n\n public static final String INTERFACE_KEY = \"interface\";\n\n public static final String INVOKER_KEY = \"invoker\";\n\n public static final String DEFAULT_INVOKER_PROVIDER = \"provider\";\n\n public static final String DEFAULT_INVOKER_CONSUMER = \"consumer\";\n\n public static final String DEFAULT_GROUP_NAME = \"ourea\";\n\n public static final String DEFAULT_VERSION_VALUE = \"1.0.0\";\n\n public static final int DEFAULT_WEIGHT_VALUE = 0;\n\n public static final int DEFAULT_TIMEOUT_VALUE = 1000;\n\n public static final int DEFAULT_THRIFT_PORT = 1000;\n}", "public class PropertiesUtils {\n\n public static Properties load(String fileName) {\n\n InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);\n return load(is);\n }\n\n public static Properties load(InputStream is) {\n\n Properties properties = new Properties();\n try {\n properties.load(is);\n } catch (IOException e) {\n e.printStackTrace();\n throw new IllegalArgumentException(e.getMessage());\n }\n return properties;\n }\n\n}", "public class ThriftClientConfig {\n\n /**\n * 服务组,不同组之间不能服务交互\n */\n private String group = Constants.DEFAULT_GROUP_NAME;\n\n /**\n * 服务版本,不同版本之间不能交互\n */\n private String version = Constants.DEFAULT_VERSION_VALUE;\n\n /**\n * 超时时间\n */\n private int timeout = Constants.DEFAULT_TIMEOUT_VALUE;\n\n /**\n * 服务重试次数,默认重试一次\n */\n private int retryTimes = 1;\n\n /**\n * 服务client的负载策略\n */\n private ILoadBalanceStrategy loadBalanceStrategy = new RoundRobinLoadBalanceStrategy();\n\n public String getGroup() {\n return group;\n }\n\n public void setGroup(String group) {\n this.group = group;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n public void setTimeout(int timeout) {\n this.timeout = timeout;\n }\n\n public int getRetryTimes() {\n return retryTimes;\n }\n\n public void setRetryTimes(int retryTimes) {\n this.retryTimes = retryTimes;\n }\n\n public ILoadBalanceStrategy getLoadBalanceStrategy() {\n return loadBalanceStrategy;\n }\n\n public void setLoadBalanceStrategy(ILoadBalanceStrategy loadBalanceStrategy) {\n this.loadBalanceStrategy = loadBalanceStrategy;\n }\n}", "public class ZkConfig {\n\n /**\n * zk ip:port,\n */\n private String zkAddress;\n\n /**\n * zk 超时时间\n */\n private int zkTimeout = 3000;\n\n /**\n * 重试之间初始等待时间\n */\n private int baseSleepTimeMs = 10;\n\n /**\n * 重试之间最长等待时间\n */\n private int maxSleepTimeMs = 1000;\n\n /**\n * 重试次数\n */\n private int maxRetries = 3;\n\n public ZkConfig() {\n }\n\n public ZkConfig(String zkAddress) {\n this.zkAddress = zkAddress;\n }\n\n public void setZkAddress(String zkAddress) {\n this.zkAddress = zkAddress;\n }\n\n public String getZkAddress() {\n return zkAddress;\n }\n\n public int getZkTimeout() {\n return zkTimeout;\n }\n\n public void setZkTimeout(int zkTimeout) {\n this.zkTimeout = zkTimeout;\n }\n\n public int getBaseSleepTimeMs() {\n return baseSleepTimeMs;\n }\n\n public void setBaseSleepTimeMs(int baseSleepTimeMs) {\n this.baseSleepTimeMs = baseSleepTimeMs;\n }\n\n public int getMaxSleepTimeMs() {\n return maxSleepTimeMs;\n }\n\n public void setMaxSleepTimeMs(int maxSleepTimeMs) {\n this.maxSleepTimeMs = maxSleepTimeMs;\n }\n\n public int getMaxRetries() {\n return maxRetries;\n }\n\n public void setMaxRetries(int maxRetries) {\n this.maxRetries = maxRetries;\n }\n\n}", "public class ConsumerProxyFactory {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerProxyFactory.class);\n\n /**\n * 正常的业务需求,是保证全局的thrift client 单例的,因为构造client成本是很重的. 这里的,key为class_group_version\n */\n private static final ConcurrentHashMap<String, Object> SERVICE_CLIENT_CONCURRENT_HASH_MAP = new ConcurrentHashMap<String, Object>();\n\n private static final Joiner CLIENT_KEY_JOINER = Joiner.on(\"_\");\n\n private static final Object SERVICE_CLIENT_LOCK = new Object();\n\n public <T> T getProxyClient(Class<T> clientClazz, ZkConfig zkConfig) {\n return getProxyClient(clientClazz, new ThriftClientConfig(), zkConfig);\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> T getProxyClient(Class<T> clientClazz, ThriftClientConfig config, ZkConfig zkConfig) {\n\n String clientKey = CLIENT_KEY_JOINER.join(clientClazz.getCanonicalName(), config.getGroup(),\n config.getVersion());\n T client = (T) SERVICE_CLIENT_CONCURRENT_HASH_MAP.get(clientKey);\n\n if (client == null) {\n synchronized (SERVICE_CLIENT_LOCK) {\n client = (T) SERVICE_CLIENT_CONCURRENT_HASH_MAP.get(clientKey);\n if (client == null) {\n\n long start = System.currentTimeMillis();\n final ServiceInfo serviceInfo = new ServiceInfo(clientClazz, config.getVersion(),\n config.getGroup());\n\n client = (T) Proxy.newProxyInstance(ConsumerProxyFactory.class.getClassLoader(),\n new Class[] { clientClazz }, new ConsumerProxy(serviceInfo, zkConfig, config));\n SERVICE_CLIENT_CONCURRENT_HASH_MAP.putIfAbsent(clientKey, client);\n LOGGER.info(\"build thrift client succ.cost:{},clientConfig:{},zkConfig:{}\",\n System.currentTimeMillis() - start, config, zkConfig);\n }\n }\n }\n return client;\n }\n\n}", "public interface ILoadBalanceStrategy {\n\n /**\n * 从众多连接池子中选择其中一个池子.\n * \n * @param invokeConns\n * @return\n */\n public InvokeConn select(List<InvokeConn> invokeConns, Invocation invocation);\n}", "public class RoundRobinLoadBalanceStrategy extends AbstractLoadBalanceStrategy {\n\n private static final ConcurrentHashMap<String, Integer> current = new ConcurrentHashMap<String, Integer>();\n\n @Override\n protected InvokeConn doSelect(List<InvokeConn> invokeConns, Invocation invocation) {\n\n String key = invocation.getInterfaceName() + invocation.getMethodName();\n Integer cur = current.get(key);\n\n if (cur == null || cur >= Integer.MAX_VALUE - 1) {\n cur = 0;\n }\n current.putIfAbsent(key, cur + 1);\n\n try {\n return invokeConns.get(cur % invokeConns.size());\n }catch (IndexOutOfBoundsException e){\n return invokeConns.get(0);\n }\n\n }\n}", "public class ConfigUtils {\n\n public static ZkConfig buildConfig(Properties properties){\n\n assertEmpty(\"zkAddress\", properties.getProperty(\"zkAddress\"));\n ZkConfig zkConfig = new ZkConfig(properties.getProperty(\"zkAddress\"));\n\n if (StringUtils.isNoneEmpty(properties.getProperty(\"baseSleepTimeMs\"))){\n zkConfig.setBaseSleepTimeMs(Integer.parseInt(properties.getProperty(\"baseSleepTimeMs\")));\n }\n\n if (StringUtils.isNoneEmpty(properties.getProperty(\"maxRetries\"))){\n zkConfig.setMaxRetries(Integer.parseInt(properties.getProperty(\"maxRetries\")));\n }\n\n if (StringUtils.isNoneEmpty(properties.getProperty(\"maxSleepTimeMs\"))){\n zkConfig.setMaxSleepTimeMs(Integer.parseInt(properties.getProperty(\"maxSleepTimeMs\")));\n }\n\n if (StringUtils.isNoneEmpty(properties.getProperty(\"zkTimeout\"))){\n zkConfig.setZkTimeout(Integer.parseInt(properties.getProperty(\"zkTimeout\")));\n }\n\n return zkConfig;\n }\n\n public static void assertEmpty(String key, String val) {\n if (StringUtils.isBlank(val)) {\n throw new IllegalArgumentException(key + \"value do not can be empty.\");\n }\n }\n}" ]
import com.taocoder.ourea.core.common.Constants; import com.taocoder.ourea.core.common.PropertiesUtils; import com.taocoder.ourea.core.config.ThriftClientConfig; import com.taocoder.ourea.core.config.ZkConfig; import com.taocoder.ourea.core.consumer.ConsumerProxyFactory; import com.taocoder.ourea.core.loadbalance.ILoadBalanceStrategy; import com.taocoder.ourea.core.loadbalance.RoundRobinLoadBalanceStrategy; import com.taocoder.ourea.spring.ConfigUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.io.Resource; import java.util.Properties;
/* * Copyright (c) 2015 taocoder.com. All Rights Reserved. */ package com.taocoder.ourea.spring.consumer; /** * @author tao.ke Date: 16/5/1 Time: 下午2:18 */ public class ConsumerProxyFactoryBean implements FactoryBean<ConsumerProxyFactory>, InitializingBean, ApplicationListener<ApplicationEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerProxyFactoryBean.class); /** * zk配置 */
private ZkConfig zkConfig;
3
DanielShum/MaterialAppBase
app/src/main/java/com/daililol/material/appbase/example/ExampleNavigationDrawerActivity.java
[ "public abstract class BaseNavigationDrawerActivity extends BaseFragmentActivity implements DrawerListener,\nAdapterView.OnItemClickListener{\n\n\n /**\n * An activity will be created like this\n * -------------------------------------- ---------------------------------------\n * | __ | | | |\n * | == Action bar | | | |\n * | | | | |\n * |------------------------------------| | |-------|\n * | | | Navigation Drawer | |\n * | | | Header | |\n * | | | | |\n * | | > | | |\n * | | > |-----------------------------| |\n * | | > | _ | |\n * | | > | |_| Navigation item 1 | |\n * | | |_____________________________| |\n * | | | _ | |\n * | THE | | |_| Navigation item 2 | |\n * | CONTENT | |_____________________________| |\n * | VIEW | | _ | |\n * | | | |_| Navigation item 3 | |\n * | | |_____________________________| |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * | | | | |\n * -------------------------------------- --------------------------------------\n */\n\n\tprivate RelativeLayout statusBar;\n\tprivate Toolbar toolbar;\n\tprivate ActionBar actionBar;\n\tprivate RelativeLayout customizedContentViewHolder;\n\tprivate View versionAdaptiveActionbarShawdow;\n\t\n\tprivate DrawerLayout navigationDrawer;\n\tprivate ExtendableListView navigationListView;\n\tprivate BaseNavigationDrawerListAdapter navigationListAdapter;\n\t\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState){\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\tsetContentView(R.layout.base_navigation_drawer_activity);\n\t\t\n\t\tnavigationDrawer = (DrawerLayout) findViewById(R.id.baseNavigationDrawer);\n\t\tnavigationListView = (ExtendableListView) findViewById(R.id.baseNavigationList);\n\t\t\n\t\tstatusBar = (RelativeLayout) findViewById(R.id.baseStatusBar);\n\t\ttoolbar = (Toolbar) findViewById(R.id.baseToolbar);\n\t\tcustomizedContentViewHolder = (RelativeLayout) findViewById(R.id.customizedContentViewHolder);\n\t\tversionAdaptiveActionbarShawdow = (View) findViewById(R.id.baseVersionAdaptiveActionbarShadow);\n\t\t\n\t\tnavigationListView.getLayoutParams().width = DeviceUtil.getScreenSize(this).x - Converter.dp2px(this, 56);\n\t\tnavigationDrawer.setDrawerListener(this);\n\t\tnavigationDrawer.setDrawerShadow(R.drawable.rectangle_left_to_right_shadaw, Gravity.LEFT);\n\t\tnavigationListView.setOnItemClickListener(this);\n\n\t\tView navigationDrawerHeaderView = setupNavigationDrawerHeader();\n\t\tif (navigationDrawerHeaderView != null) navigationListView.addHeaderView(navigationDrawerHeaderView);\n\n navigationListAdapter = new BaseNavigationDrawerListAdapter(this);\n navigationListView.setAdapter(navigationListAdapter);\n setupNavigationDrawerItem(navigationListView, navigationListAdapter);\n\n\t\tif (Build.VERSION.SDK_INT >= 21) versionAdaptiveActionbarShawdow.setVisibility(View.GONE);\n setSupportActionBar(toolbar);\n actionBar = getSupportActionBar();\n \n \n setActionbarThemeColor();\n\t\tthis.requestHomeIcon(DrawableUtil.getDrawable(this, R.drawable.ic_menu_black_24dp));\n \n \n\t\tsetupContentView(customizedContentViewHolder, setupContentVew());\n onActivityCreated(savedInstanceState);\n\t}\n\t\n\t\n\t/**\n\t * This will be called after onCreate \n\t * @param savedInstanceState\n\t */\n\tabstract protected void onActivityCreated(Bundle savedInstanceState);\n\t\n\tabstract protected int setupContentVew();\n\tabstract protected Drawable setupThemeColor();\n\tabstract protected void onMenuItemSelected(MenuItem menu);\n\tabstract protected void setupNavigationDrawerItem(ExtendableListView listView, BaseNavigationDrawerListAdapter navigationListAdapter);\n\n /**\n *\n * @return the returned view will be set to the navigation head.\n */\n abstract protected View setupNavigationDrawerHeader();\n\n /**\n *\n * @param adapterView\n * @param itemView\n * @param position\n * @return true the selected item highlight, false otherwise.\n */\n\tabstract protected boolean navigationOnItemClickListener(AdapterView<?> adapterView, View itemView, int position);\n\t\n\t/**\n\t * \n\t * @param menu\n\t * @param inflater\n\t * @return return false will show no menu items.\n\t */\n\tabstract protected boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater);\n\t\n\n\tpublic void toggleNavigation(){\n\t\tif (navigationDrawer.isDrawerOpen(Gravity.LEFT)){\n\t\t\tnavigationDrawer.closeDrawer(Gravity.LEFT);\n\t\t}else{\n\t\t\tnavigationDrawer.openDrawer(Gravity.LEFT);\n\t\t}\n\t}\n\t\n\tprivate void setupContentView(RelativeLayout customizedContentViewHolder, int customizedContentView){\n if (customizedContentView == 0) return;\n\t\tView view = LayoutInflater.from(this).inflate(customizedContentView, null);\n\t\tcustomizedContentViewHolder.addView(view);\n\t}\n\t\n\tprotected void requestHomeIcon(Drawable drawable){\n\t\tgetActionbar().setHomeAsUpIndicator(drawable);\n\t\t\n\t\tgetActionbar().setDisplayHomeAsUpEnabled(true);\n\t}\n\t\n\tprotected void requestBackIcon(Drawable drawable){\n\t\tgetActionbar().setHomeAsUpIndicator(drawable);\n\t\tgetActionbar().setDisplayHomeAsUpEnabled(true);\n\t}\n\t\n\tprotected Toolbar getToolBar(){\n\t\treturn toolbar;\n\t}\n\t\n\tprotected ActionBar getActionbar(){\n\t\treturn actionBar;\n\t}\n\n\tprotected ExtendableListView getNavigationListView(){\n\t\treturn navigationListView;\n\t}\n\n\tprotected BaseNavigationDrawerListAdapter getNavigationListAdapter(){\n\t\treturn navigationListAdapter;\n\t}\n\n\t/**\n\t * \n\t * @param title\n\t * @param color specify the actionbar actual title color, can not be color resourceId.\n\t */\n\tprotected void setActionbarTitle(CharSequence title, int color){\n\t\tgetActionbar().setTitle(title);\n\t\tgetToolBar().setTitleTextColor(color);\n\t}\n\t\n\t\n\t@SuppressLint(\"NewApi\") \n\t@SuppressWarnings(\"deprecation\")\n\tprivate void setActionbarThemeColor(){\n\t\tDrawable drawable = setupThemeColor();\n\t\tif (drawable == null) drawable = DrawableUtil.getDrawable(this, R.color.base_theme_blue);\n\t\tif (Build.VERSION.SDK_INT >= 16){\n\t\t\tgetToolBar().setBackground(drawable);\n\t\t\tstatusBar.setBackground(drawable);\n\t\t}else{\n\t\t\tgetToolBar().setBackgroundDrawable(drawable);\n\t\t\tstatusBar.setBackgroundDrawable(drawable);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {\n\t\t// TODO Auto-generated method stub\n\t\tif (navigationOnItemClickListener(arg0, arg1, arg2)){\n navigationListAdapter.setSelectedPosition(arg2 - navigationListView.getHeaderViewsCount());\n }\n\n toggleNavigation();\n\t}\n\t\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n \t\n \tif (item.getItemId() == android.R.id.home){\n \t\ttoggleNavigation();\n \t}\n \tonMenuItemSelected(item);\n return super.onOptionsItemSelected(item);\n }\n\t\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n onCreateOptionsMenu(menu, getMenuInflater());\n return true;\n }\n \n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event){\n \tif (keyCode == KeyEvent.KEYCODE_BACK){\n \t\tsuper.onKeyDown(keyCode, event);\n \t\tif (navigationDrawer.isDrawerOpen(Gravity.LEFT)) {\n \t\t\tnavigationDrawer.closeDrawer(Gravity.LEFT);\n \t\t\treturn false;\n \t\t}else{\n \t\t\treturn true;\n \t\t}\n \t\t\n \t}\n \t\n \treturn super.onKeyDown(keyCode, event);\n }\n\n}", "public class BaseNavigationDrawerListAdapter extends BaseAdapter{\n\n\tprivate Context context;\n\tprivate ArrayList<MenuItem> menuList;\n private int selectedItem = -1;\n\t\n\t\n\tpublic void addItem(String text, Drawable icon, MenuItem.Type type){\n\t\tmenuList.add(new MenuItem(text, icon, type));\n\t\tthis.notifyDataSetChanged();\n\t}\n\n /**\n * Set -1 to dishighlight selected item\n * @param position\n */\n\tpublic void setSelectedPosition(int position){\n selectedItem = position;\n notifyDataSetChanged();\n }\n\n\tpublic BaseNavigationDrawerListAdapter(Context context){\n\t\tthis.context = context;\n\t\tthis.menuList = new ArrayList<MenuItem>();\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\t// TODO Auto-generated method stub\n\t\treturn menuList.size();\n\t}\n\n\t@Override\n\tpublic Object getItem(int position) {\n\t\t\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic long getItemId(int position) {\n\t\t\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\n\t\tMenuItem.Type type = menuList.get(position).type;\n\n\t\tif (type == MenuItem.Type.DIVIDER){\n AbsListView.LayoutParams convertViewParams = new AbsListView.LayoutParams(\n AbsListView.LayoutParams.MATCH_PARENT, Converter.dp2px(context, 17));\n convertView = new LinearLayout(context);\n convertView.setLayoutParams(convertViewParams);\n convertView.setBackgroundColor(Color.WHITE);\n ((LinearLayout)convertView).setOrientation(LinearLayout.VERTICAL);\n ((LinearLayout)convertView).setGravity(Gravity.CENTER);\n\n LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.MATCH_PARENT, Converter.dp2px(context, 1));\n View divider = new View(context);\n divider.setLayoutParams(dividerParams);\n divider.setBackgroundColor(ContextCompat.getColor(context, R.color.base_divider_grey));\n\n ((LinearLayout)convertView).addView(divider);\n\n return convertView;\n\t\t}\n\n if (type == MenuItem.Type.BLANK_DIVEDER){\n AbsListView.LayoutParams convertViewParams = new AbsListView.LayoutParams(\n AbsListView.LayoutParams.MATCH_PARENT, Converter.dp2px(context, 8));\n convertView = new View(context);\n convertView.setLayoutParams(convertViewParams);\n convertView.setBackgroundColor(Color.WHITE);\n return convertView;\n }\n\n convertView = LayoutInflater.from(context).inflate(R.layout.base_item_for_navigation_drawer, null);\n ViewHolder viewHolder = new ViewHolder(convertView);\n\n if (selectedItem == position){\n viewHolder.backgroundView.setSelected(true);\n viewHolder.backgroundView.setBackgroundResource(R.color.base_ui_selected_holo_light);\n }else{\n viewHolder.backgroundView.setSelected(false);\n viewHolder.backgroundView.setBackgroundColor(Color.TRANSPARENT);\n }\n\n\t\tMenuItem menuItem = menuList.get(position);\n\t\tviewHolder.textView.setText(menuItem.text);\n\t\tif (menuItem.icon != null){\n\t\t\tviewHolder.imageView.setVisibility(View.VISIBLE);\n\t\t\tviewHolder.imageView.setImageDrawable(menuItem.icon);\n\t\t}else{\n\t\t\tviewHolder.imageView.setVisibility(View.GONE);\n\t\t}\n\t\t\n\t\treturn convertView;\n\t}\n\t\n\tprivate class ViewHolder{\n public RelativeLayout backgroundView;\n\t\tpublic TextView textView;\n\t\tpublic ImageView imageView;\n\t\t\n\t\tpublic ViewHolder(View convertView){\n this.backgroundView = (RelativeLayout)convertView.findViewById(R.id.backgroundView);\n\t\t\tthis.textView = (TextView)convertView.findViewById(R.id.text);\n\t\t\tthis.imageView = (ImageView)convertView.findViewById(R.id.icon);\n\t\t\tconvertView.setTag(this);\n\t\t}\n\t}\n\t\n\tpublic static class MenuItem{\n\n\t\tpublic static enum Type{\n\t\t\tDIVIDER,\n BLANK_DIVEDER,\n\t\t\tMENU_ITEM\n\t\t}\n\n\t\tpublic Type type;\n\t\tpublic String text;\n\t\tpublic Drawable icon;\n\t\t\n\t\tpublic MenuItem(String text, Drawable icon, Type type){\n\t\t\tthis.type = type;\n\t\t\tthis.text = text;\n\t\t\tthis.icon = icon;\n\t\t}\n\t}\n\n}", "public class Converter {\r\n\t\r\n\tpublic static int dp2px(Context context, float dp){\r\n\t\treturn (int)(dp * context.getResources().getDisplayMetrics().density);\r\n\t}\r\n\r\n\tpublic static int px2dp(Context context, float px){\r\n\t\treturn (int)(px / context.getResources().getDisplayMetrics().density);\r\n\t}\r\n}\r", "public class DrawableUtil {\r\n\t\r\n\tpublic static Drawable changeDrawableColor(Drawable drawable, int destinationColor){\r\n\t\tdrawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY);\r\n\t\treturn drawable;\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"deprecation\")\r\n\t@SuppressLint(\"NewApi\")\r\n\tpublic static Drawable getDrawable(Context context, int resourceId){\r\n\r\n\t\tif (Build.VERSION.SDK_INT >= 21){\r\n\t\t\treturn context.getDrawable(resourceId);\r\n\t\t}else{\r\n\t\t\treturn context.getResources().getDrawable(resourceId);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static Drawable getDrawable(Context context, int resourceId, int convertToColor){\r\n\t\tDrawable drawable = getDrawable(context, resourceId);\r\n\t\treturn changeDrawableColor(drawable, convertToColor);\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic static ColorStateList createColorStateListAPI21(int normal) { \r\n int[] colors = new int[] {normal}; \r\n int[][] states = new int[1][]; \r\n states[0] = new int[] {}; \r\n ColorStateList colorList = new ColorStateList(states, colors); \r\n return colorList; \r\n }\r\n\t\r\n\tpublic static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { \r\n int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; \r\n int[][] states = new int[7][]; \r\n states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; \r\n states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; \r\n states[2] = new int[] { android.R.attr.state_selected };\r\n states[3] = new int[] { android.R.attr.state_focused }; \r\n states[4] = new int[] { android.R.attr.state_window_focused }; \r\n states[5] = new int[] { android.R.attr.state_enabled }; \r\n states[6] = new int[] {}; \r\n ColorStateList colorList = new ColorStateList(states, colors); \r\n return colorList; \r\n }\r\n\r\n\tpublic static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){\r\n\t\tDrawable drawableNormal = getDrawable(context, normalResourceId);\r\n\t\tDrawable drawableActive = getDrawable(context, activeResourceId);\r\n\t\treturn createStateListDrawable(context, drawableNormal, drawableActive,\r\n\t\t\t\tdrawableActive, drawableActive, drawableNormal);\r\n\t}\r\n\r\n\tpublic static StateListDrawable createStateListDrawable(Context contet, \r\n\t\t\tDrawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){\r\n\t\t\r\n\t\tStateListDrawable drawableList = new StateListDrawable();\r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); \r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused);\r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_selected }, selected); \r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_focused }, focused); \r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); \r\n\t\tdrawableList.addState(new int[] { android.R.attr.state_enabled }, normal); \r\n\t\tdrawableList.addState(new int[] {}, normal); \r\n \r\n\t\treturn drawableList;\r\n\t\t\r\n\r\n\t}\r\n\r\n}\r", "public class ExtendableListView extends ListView{\r\n\r\n\tpublic ExtendableListView(Context context){\r\n\t\tthis(context, null);\r\n\t}\r\n\tpublic ExtendableListView(Context context, AttributeSet attrs) {\r\n\t\tsuper(context, attrs);\r\n\t\t// TODO Auto-generated constructor stub\r\n\t}\r\n\r\n}\r" ]
import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.os.Message; import android.support.v4.app.FragmentTransaction; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.LinearLayout; import com.daililol.material.appbase.base.BaseNavigationDrawerActivity; import com.daililol.material.appbase.component.BaseNavigationDrawerListAdapter; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DrawableUtil; import com.daililol.material.appbase.widget.ExtendableListView;
package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/20/15. */ public class ExampleNavigationDrawerActivity extends BaseNavigationDrawerActivity{ @Override protected void onActivityCreated(Bundle savedInstanceState) { FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragmentReplacement, new ExampleListViewFragment()).commit(); } @Override protected int setupContentVew() { return R.layout.example_navigation_drawer_activity; } @Override protected Drawable setupThemeColor() { return null; } @Override protected void onMenuItemSelected(MenuItem menu) { } @Override
protected void setupNavigationDrawerItem(ExtendableListView listView, BaseNavigationDrawerListAdapter navigationListAdapter) {
1
andrewflynn/bettersettlers
app/src/main/java/com/nut/bettersettlers/fragment/dialog/ExpansionDialogFragment.java
[ "public class MainActivity extends FragmentActivity {\n\tprivate static final String STATE_SHOW_GRAPH = \"STATE_SHOW_GRAPH\";\n\tprivate static final String STATE_SHOW_PLACEMENTS = \"STATE_SHOW_PLACEMENTS\";\n\tprivate static final String STATE_THEFT_ORDER = \"STATE_THEFT_ORDER\";\n\tprivate static final String STATE_EXP_THEFT_ORDER = \"STATE_EXP_THEFT_ORDER\";\n\tprivate static final String STATE_TITLE_ID = \"STATE_TITLE_ID\";\n\t\n\tprivate static final Bundle GET_PRICES_BUNDLE;\n\tstatic {\n\t\tArrayList<String> priceItems = new ArrayList<>();\n\t\tpriceItems.add(MapContainer.NEW_WORLD.id); // Any normal map should do\n\t\tpriceItems.add(IabConsts.BUY_ALL);\n\t\t\n\t\tGET_PRICES_BUNDLE = new Bundle();\n\t\tGET_PRICES_BUNDLE.putStringArrayList(IabConsts.GET_SKU_DETAILS_ITEM_LIST, priceItems);\n\t}\n\n\tpublic static final int BUY_INTENT_REQUEST_CODE = 101;\n\t\n\tprivate MapFragment mMapFragment;\n\tprivate GraphFragment mGraphFragment;\n\n\tprivate View mTitle;\n\tprivate int mTitleId;\n\t\n\tprivate Set<String> mOwnedMaps = new HashSet<>();\n\t\n\t// Stupid onActivityResult is called before onStart()\n\t// http://stackoverflow.com/q/10114324/452383\n\t// https://code.google.com/p/android/issues/detail?id=17787\n\tprivate boolean mShowFogIsland = false;\n\t\n\tprivate String mSinglePrice = null;\n\tprivate String mBuyAllPrice = null;\n\t\n\tIInAppBillingService mService;\n\tprivate ServiceConnection mServiceConn = new ServiceConnection() {\n\t\t@Override\n\t\tpublic void onServiceDisconnected(ComponentName name) {\n\t\t\tmService = null;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void onServiceConnected(ComponentName name, IBinder service) {\n\t\t\tmService = IInAppBillingService.Stub.asInterface(service);\n\t\t\t\n try {\n int response = mService.isBillingSupported(IabConsts.API_VERSION, getPackageName(), IabConsts.ITEM_TYPE_INAPP);\n if (response == IabConsts.BILLING_RESPONSE_RESULT_OK) {\n \tBetterLog.w(\"IAB v\" + IabConsts.API_VERSION + \" is supported\");\n \t\t\t\tmMapFragment.setShowSeafarers(true);\n \tnew InitIabTask().execute();\n } else {\n \tBetterLog.w(\"IAB v\" + IabConsts.API_VERSION + \" not supported\");\n \t\t\t\tmMapFragment.setShowSeafarers(true);\n }\n } catch (RemoteException e) {\n \tBetterLog.w(\"Exception while querying for IABv3 support.\");\n }\n\t\t}\n\t};\n\t\n\tprivate class InitIabTask extends AsyncTask<Void, Void, Void> {\n\t\t@Override\n\t\tprotected Void doInBackground(Void... params) {\n\t\t\ttry {\n\t\t\t\trestoreTransactions();\n\t\t\t\tsetPrices();\n\t\t\t} catch (RemoteException e) {\n\t\t\t\tBetterLog.w(\"RemoteException \", e);\n\t\t\t}\n\t\t\t\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tprivate void restoreTransactions() throws RemoteException {\n\t\t\tBetterLog.d(\"RestoreTransactions\");\n\t \tBundle ownedItems = mService.getPurchases(IabConsts.API_VERSION, getPackageName(),\n\t \t\t\tIabConsts.ITEM_TYPE_INAPP, null);\n\t \n\t int response = getResponseCodeFromBundle(ownedItems);\n\t BetterLog.d(\"Owned items response: \" + String.valueOf(response));\n\t if (response != IabConsts.BILLING_RESPONSE_RESULT_OK\n\t || !ownedItems.containsKey(IabConsts.RESPONSE_INAPP_ITEM_LIST)\n\t || !ownedItems.containsKey(IabConsts.RESPONSE_INAPP_PURCHASE_DATA_LIST)\n\t || !ownedItems.containsKey(IabConsts.RESPONSE_INAPP_SIGNATURE_LIST)) {\n\t \tBetterLog.w(\"Error querying owned items. Response: \" + response);\n\t \treturn;\n\t }\n\n\t List<String> purchaseDataList = ownedItems.getStringArrayList(IabConsts.RESPONSE_INAPP_PURCHASE_DATA_LIST);\n\t List<String> signatureList = ownedItems.getStringArrayList(IabConsts.RESPONSE_INAPP_SIGNATURE_LIST);\n\t \n\t for (int i = 0; i < purchaseDataList.size(); i++) {\n \t \tverifyAndAddPurchase(purchaseDataList.get(i), signatureList.get(i), true /* restore */);\n\t }\n\t\t}\n\t}\n\t\n\tprivate void setPrices() throws RemoteException {\n\t\tBundle details = mService.getSkuDetails(IabConsts.API_VERSION, getPackageName(),\n\t\t\t\tIabConsts.ITEM_TYPE_INAPP, GET_PRICES_BUNDLE);\n\n if (!details.containsKey(IabConsts.RESPONSE_GET_SKU_DETAILS_LIST)) {\n \tBetterLog.d(\"Could not fetch prices\");\n \treturn;\n }\n\n ArrayList<String> responseList = details.getStringArrayList(IabConsts.RESPONSE_GET_SKU_DETAILS_LIST);\n \n for (String response : responseList) {\n \tSkuDetails item;\n\t\t\ttry {\n\t\t\t\titem = new SkuDetails(response);\n\t\t\t} catch (JSONException e) {\n\t\t\t\tBetterLog.w(\"Could not parse JSON response for finding prices\");\n\t\t\t\treturn;\n\t\t\t}\n \t\n \tif (IabConsts.BUY_ALL.equals(item.sku)) {\n \t\tmBuyAllPrice = item.price;\n \t} else {\n \t\tmSinglePrice = item.price;\n \t}\n }\n\t}\n\t\n\tpublic String getSinglePrice() {\n\t\treturn mSinglePrice;\n\t}\n\t\n\tpublic String getBuyAllPrice() {\n\t\treturn mBuyAllPrice;\n\t}\n\n\tprivate void consumePurchase(Purchase purchase) {\n\t\tBetterLog.d(\"ConsumePurchase\");\n\t\ttry {\n\t\t\tmService.consumePurchase(IabConsts.API_VERSION, getPackageName(), purchase.token);\n\t\t} catch (RemoteException e) {\n\t\t\tBetterLog.e(\"Could not consume purchase\");\n\t\t}\n\t}\n\t\n\tprivate void verifyAndAddPurchase(String purchaseData, String signature, boolean restore) {\n\t\tBetterLog.d(\"VerifyAndAddPurchase: \" + restore);\n\t\tif (Security.verifyPurchase(purchaseData, signature)) {\n\t\t\tBetterLog.d(\"Passed security\");\n\t\t\tPurchase purchase;\n\t\t\ttry {\n\t\t\t\tpurchase = new Purchase(purchaseData, signature);\n\t\t\t} catch (JSONException e) {\n\t\t\t\tBetterLog.e(\"Unable to parse returned JSON. Not adding item\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// If it's prod, ID=SKU\n\t\t\t// If we're testing, ID is stored in devPayload\n \t\tString itemId = Consts.TEST_STATIC_IAB ? purchase.developerPayload : purchase.sku;\n\t\t\tBetterLog.d(\"Purchasing \" + itemId);\n \t\t\n\t\t\tmOwnedMaps.add(itemId);\n\n \t\t// If we're testing IAB, consume all purchases immediately so we can test infinitely\n \tif (Consts.TEST_CONSUME_ALL_PURCHASES) {\n \t\tconsumePurchase(purchase);\n \t}\n\t\t\t\n\t\t\t// If we're restoring all purchases, don't do anything special\n\t\t\tif (restore) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// Else show the map they chose, and maybe Fog Island help\n\t\t\tif (getMapFragment() != null && !itemId.equals(IabConsts.BUY_ALL)) {\n\t\t\t\tgetMapFragment().sizeChoice(MapSize.getMapSizeByProductId(itemId));\n\t\t\t}\n\t\t\t\n\t\t\t// Show Fog Island if we need to (and we're not restoring all maps)\n\t\t\t// Note the comment on mShowFogIsland (we need to wait until after onStart() before\n\t\t\t// showing the fragment\n\t\t\tif (MapContainer.THE_FOG_ISLAND.id.equals(itemId)) {\n\t\t\t\tmShowFogIsland = true;\n\t\t\t}\n \t}\n\t}\n\t\n\tpublic void purchaseItem(MapContainer map) {\n\t\tpurchaseItem(map.id);\n\t}\n\t\n\tpublic void purchaseItem(String id) {\n\t\tBetterLog.i(\"Buying \" + id);\n\t\t\n\t\t// If it's prod, use real ID and no devPayload\n\t\t// If we're testing, use fake product id and store ID in devPayload\n\t\tString sku = Consts.TEST_STATIC_IAB ? IabConsts.FAKE_PRODUCT_ID : id;\n\t\tString devPayload = Consts.TEST_STATIC_IAB ? id : null;\n\t\t\n \tBundle buyIntentBundle;\n \ttry {\n\t\t\tbuyIntentBundle = mService.getBuyIntent(IabConsts.API_VERSION, getPackageName(), sku,\n\t\t\t\t\tIabConsts.ITEM_TYPE_INAPP, devPayload);\n\t\t} catch (RemoteException e) {\n\t\t\tBetterLog.w(\"RemoteException\", e);\n\t\t\treturn;\n\t\t}\n\n\t\tint response = getResponseCodeFromBundle(buyIntentBundle);\n\t\tif (response != IabConsts.BILLING_RESPONSE_RESULT_OK) {\n\t\t\tBetterLog.e(\"Bad response: \" + response);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tPendingIntent buyIntent = buyIntentBundle.getParcelable(IabConsts.RESPONSE_BUY_INTENT);\n\t\tif (buyIntent == null) {\n\t\t\tBetterLog.w(\"Item has already been purchased\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tstartIntentSenderForResult(buyIntent.getIntentSender(), BUY_INTENT_REQUEST_CODE,\n\t\t\t\t\tnew Intent(), 0, 0, 0);\n\t\t} catch (SendIntentException e) {\n\t\t\tBetterLog.e(\"Error sending intent\", e);\n\t\t}\n\t}\n\n\t\n\t// Workaround to bug where sometimes response codes come as Long instead of Integer\n\tprivate int getResponseCodeFromBundle(Bundle b) {\n Object o = b.get(IabConsts.RESPONSE_CODE);\n if (o == null) {\n BetterLog.i(\"Bundle with null response code, assuming OK (known issue)\");\n return IabConsts.BILLING_RESPONSE_RESULT_OK;\n } else if (o instanceof Integer) {\n \treturn ((Integer)o).intValue();\n } else if (o instanceof Long) {\n \treturn (int)((Long)o).longValue();\n } else {\n \tBetterLog.e(\"Unexpected type for bundle response code.\");\n \tBetterLog.e(o.getClass().getName());\n throw new RuntimeException(\"Unexpected type for bundle response code: \" + o.getClass().getName());\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n \tswitch (requestCode) {\n \tcase BUY_INTENT_REQUEST_CODE:\n \t\t// Verify/consume the purchase\n \t\tif (data == null) {\n \t\t\tBetterLog.w(\"Null data. Returning\");\n \t\t\treturn;\n \t\t}\n \t\n String purchaseData = data.getStringExtra(IabConsts.RESPONSE_INAPP_PURCHASE_DATA);\n String dataSignature = data.getStringExtra(IabConsts.RESPONSE_INAPP_SIGNATURE);\n \n if (resultCode == RESULT_OK) {\n \tBetterLog.d(\"Successful return code from purchase activity.\");\n \tverifyAndAddPurchase(purchaseData, dataSignature, false /* restore */);\n } else if (resultCode == RESULT_CANCELED) {\n \tBetterLog.w(\"Purchase canceled\");\n } else {\n \tBetterLog.w(\"Purchase failed\");\n }\n \t\tbreak;\n \t}\n }\n\n\t/** Called when the activity is going to disappear. */\n\t@Override\n\tpublic void onSaveInstanceState(Bundle outState) {\n\t\tBetterLog.d(\"MainActivity.onSaveInstanceState\");\n\t\t\n\t\tif (mGraphFragment.isVisible()) {\n\t\t\toutState.putBoolean(STATE_SHOW_GRAPH, true);\n\t\t} else if (mMapFragment.isVisible()) {\n\t\t\tif (mMapFragment.showingPlacements()) {\n\t\t\t\toutState.putBoolean(STATE_SHOW_PLACEMENTS, true);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (mMapFragment != null && mMapFragment.getCatanMap().theftOrder != null\n\t\t\t\t&& !mMapFragment.getCatanMap().theftOrder.isEmpty()) {\n\t\t\tif (mMapFragment.getCatanMap().name.equals(\"new_world\")) {\n\t\t\t\toutState.putIntegerArrayList(STATE_THEFT_ORDER, mMapFragment.getCatanMap().theftOrder);\n\t\t\t}\n\t\t\tif (mMapFragment.getCatanMap().name.equals(\"new_world_exp\")) {\n\t\t\t\toutState.putIntegerArrayList(STATE_EXP_THEFT_ORDER, mMapFragment.getCatanMap().theftOrder);\n\t\t\t}\n\t\t}\n\t\t\n\t\toutState.putInt(STATE_TITLE_ID, mTitleId);\n\t\tsuper.onSaveInstanceState(outState);\n\t}\n\t\n\t/** Called when the activity is first created. */\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\tsetContentView(R.layout.main);\n\t\t\n\t\tmMapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);\n\t\tmGraphFragment = (GraphFragment) getSupportFragmentManager().findFragmentById(R.id.graph_fragment);\n\n\t\tmTitle = findViewById(R.id.title_text);\n\t\tif (savedInstanceState != null && savedInstanceState.getInt(STATE_TITLE_ID) != 0) {\n\t\t\tsetTitleButtonText(savedInstanceState.getInt(STATE_TITLE_ID));\n\t\t} else {\n\t\t\tsetTitleButtonText(MapSize.STANDARD.titleDrawableId);\n\t\t}\n\t\t\n\t\tImageView infoButton = (ImageView) findViewById(R.id.info_button);\n\t\tinfoButton.setOnClickListener(new OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tAboutDialogFragment.newInstance().show(getSupportFragmentManager(), \"AboutDialog\");\n\t\t\t\tAnalytics.track(MainActivity.this, Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.INFO);\n\t\t\t}\n\t\t});\n\n\t\tboolean showGraph = false;\n\t\tboolean showPlacements = false;\n\t\tif (savedInstanceState != null && savedInstanceState.getBoolean(STATE_SHOW_GRAPH)) {\n\t\t\tshowGraph = true;\n\t\t} else if (savedInstanceState != null && savedInstanceState.getBoolean(STATE_SHOW_PLACEMENTS)) {\n\t\t\tshowPlacements = true;\n\t\t}\n\n\t\tif (showGraph) {\n\t\t\tshowGraphFragment();\n\t\t} else {\n\t\t\tshowMapFragment();\n\t\t\tif (showPlacements) {\n\t\t\t\tgetMapFragment().showPlacements(false);\n\t\t\t} else {\n\t\t\t\tgetMapFragment().hidePlacements(false);\n\t\t\t}\n\t\t}\n\t\t\n\t\tmOwnedMaps.add(MapContainer.HEADING_FOR_NEW_SHORES.id);\n\n\t\t// IAB\n Intent serviceIntent = new Intent(IabConsts.BIND_ACTION);\n serviceIntent.setPackage(IabConsts.VENDING_PACKAGE);\n\t\tbindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);\n\t}\n\t\n\t@Override\n\tpublic void onResumeFragments() {\n\t\tsuper.onResumeFragments();\n\t\t\n\t\tif (mShowFogIsland) {\n\t\t\tmShowFogIsland = false;\n\n\t\t\tSharedPreferences prefs = getSharedPreferences(Consts.SHARED_PREFS_NAME, Context.MODE_PRIVATE);\n\t\t\tboolean shownWhatsNew = prefs.getBoolean(Consts.SHARED_PREFS_KEY_FOG_ISLAND_HELP, false);\n\t\t\tif (!shownWhatsNew) {\n\t\t\t\tFogIslandHelpDialogFragment.newInstance().show(getSupportFragmentManager(), \"TheFogIslandHelpDialog\");\n\t\t\t\tSharedPreferences.Editor prefsEditor = prefs.edit();\n\t\t\t\tprefsEditor.putBoolean(Consts.SHARED_PREFS_KEY_FOG_ISLAND_HELP, true);\n\t\t\t\tprefsEditor.apply();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\t// IAB\n\t\tif (mService != null) {\n\t\t\tunbindService(mServiceConn);\n\t\t\tmService = null;\n\t\t}\n\t}\n \n public void setTitleButtonText(final int resId) {\n \trunOnUiThread(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t \tmTitle.setBackgroundResource(resId);\n\t\t\t}\n\t\t});\n \tmTitleId = resId;\n }\n \n public Set<String> getOwnedMaps() {\n \treturn mOwnedMaps;\n }\n \n public MapFragment getMapFragment() {\n \treturn (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);\n }\n \n public GraphFragment getGraphFragment() {\n \treturn (GraphFragment) getSupportFragmentManager().findFragmentById(R.id.graph_fragment);\n }\n \n public void showMapFragment() {\n\t\tFragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n\t\t//ft.setCustomAnimations(R.anim.long_slide_in_left, R.anim.long_slide_out_right);\n\t\tft.hide(mGraphFragment);\n\t\tft.show(mMapFragment);\n\t\tft.commit();\n }\n \n public void showGraphFragment() {\n\t\tFragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n\t\t//ft.setCustomAnimations(R.anim.long_slide_in_right, R.anim.long_slide_out_left);\n\t\tft.hide(mMapFragment);\n\t\tft.show(mGraphFragment);\n\t\tft.addToBackStack(\"GraphFragment\");\n\t\tft.commit();\n\n\t\t\n\t\tAnalytics.trackView(this, Analytics.VIEW_ROLL_TRACKER);\n }\n}", "public enum MapSize implements Parcelable {\n\tSTANDARD(new Standard(), \"standard\", R.drawable.title_settlers, \"standard\"),\n\tLARGE(new Large(), \"large\", R.drawable.title_settlers, \"large\"),\n\tXLARGE(new XLarge(), \"xlarge\", R.drawable.title_settlers, \"xlarge\"),\n\t\n\tHEADING_FOR_NEW_SHORES(new HeadingForNewShores(), \"heading_for_new_shores\",\n\t\t\tR.drawable.title_heading_for_new_shores, \"seafarers.heading_for_new_shores\"),\n\tTHE_FOUR_ISLANDS(new TheFourIslands(), \"the_four_islands\",\n\t\t\tR.drawable.title_the_four_islands, \"seafarers.the_four_islands\"),\n\tTHE_FOG_ISLAND(new TheFogIsland(), \"the_fog_island\",\n\t\t\tR.drawable.title_the_fog_island, \"seafarers.the_fog_island\"),\n\tTHROUGH_THE_DESERT(new ThroughTheDesert(), \"through_the_desert\",\n\t\t\tR.drawable.title_through_the_desert, \"seafarers.through_the_desert\"),\n\tTHE_FORGOTTEN_TRIBE(new TheForgottenTribe(), \"the_forgotten_tribe\",\n\t\t\tR.drawable.title_the_forgotten_tribe, \"seafarers.the_forgotten_tribe\"),\n\tCLOTH_FOR_CATAN(new ClothForCatan(), \"cloth_for_catan\",\n\t\t\tR.drawable.title_cloth_for_catan, \"seafarers.cloth_for_catan\"),\n\tTHE_PIRATE_ISLANDS(new ThePirateIslands(), \"the_pirate_islands\",\n\t\t\tR.drawable.title_the_pirate_islands, \"seafarers.the_pirate_islands\"),\n\tTHE_WONDERS_OF_CATAN(new TheWondersOfCatan(), \"the_wonders_of_catan\",\n\t\t\tR.drawable.title_the_wonders_of_catan, \"seafarers.the_wonders_of_catan\"),\n\tNEW_WORLD(new NewWorld(), \"new_world\", R.drawable.title_new_world, \"seafarers.new_world\"),\n\n\tHEADING_FOR_NEW_SHORES_EXP(new HeadingForNewShoresExp(), \"heading_for_new_shores_exp\",\n\t\t\tR.drawable.title_heading_for_new_shores, null),\n\tTHE_FOUR_ISLANDS_EXP(new TheFourIslandsExp(), \"the_four_islands_exp\",\n\t\t\tR.drawable.title_the_four_islands, null),\n\tTHE_FOG_ISLAND_EXP(new TheFogIslandExp(), \"the_fog_island_exp\",\n\t\t\tR.drawable.title_the_fog_island, null),\n\tTHROUGH_THE_DESERT_EXP(new ThroughTheDesertExp(), \"through_the_desert_exp\",\n\t\t\tR.drawable.title_through_the_desert, null),\n\tTHE_FORGOTTEN_TRIBE_EXP(new TheForgottenTribeExp(), \"the_forgotten_tribe_exp\",\n\t\t\tR.drawable.title_the_forgotten_tribe, null),\n\tCLOTH_FOR_CATAN_EXP(new ClothForCatanExp(), \"cloth_for_catan_exp\",\n\t\t\tR.drawable.title_cloth_for_catan, null),\n\tTHE_PIRATE_ISLANDS_EXP(new ThePirateIslandsExp(), \"the_pirate_islands_exp\",\n\t\t\tR.drawable.title_the_pirate_islands, null),\n\tTHE_WONDERS_OF_CATAN_EXP(new TheWondersOfCatanExp(), \"the_wonders_of_catan_exp\",\n\t\t\tR.drawable.title_the_wonders_of_catan, null),\n\tNEW_WORLD_EXP(new NewWorldExp(), \"new_world_exp\", R.drawable.title_new_world, null);\n\n\tprivate static final Map<String, MapSize> PRODUCT_ID_MAP = new HashMap<>();\n\tstatic {\n\t\tfor (MapSize size : MapSize.values()) {\n\t\t\tPRODUCT_ID_MAP.put(size.productId, size);\n\t\t}\n\t}\n\tpublic static MapSize getMapSizeByProductId(String id) {\n\t\treturn PRODUCT_ID_MAP.get(id);\n\t}\n\t\n\tpublic final CatanMapProvider mapProvider;\n\tpublic final String title;\n\tpublic final int titleDrawableId;\n\tpublic final String productId;\n\t\n\tMapSize(CatanMapProvider mapProvider, String title, int titleDrawableId, String productId) {\n\t\tthis.mapProvider = mapProvider;\n\t\tthis.title = title;\n\t\tthis.titleDrawableId = titleDrawableId;\n\t\tthis.productId = productId;\n\t}\n\n public static final Parcelable.Creator<MapSize> CREATOR = new Parcelable.Creator<MapSize>() {\n public MapSize createFromParcel(Parcel in) {\n return MapSize.values()[in.readInt()];\n }\n\n public MapSize[] newArray(int size) {\n return new MapSize[size];\n }\n };\n\t\n\t@Override\n\tpublic int describeContents() {\n return 0;\n }\n\n\t@Override\n public void writeToParcel(Parcel out, int flags) {\n\t\tout.writeInt(ordinal());\n }\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn title;\n\t}\n}", "public enum MapSizePair implements Parcelable {\n\tSTANDARD(MapSize.STANDARD, null, R.drawable.map_standard_button),\n\tLARGE(MapSize.LARGE, null, R.drawable.map_large_button),\n\tXLARGE(MapSize.XLARGE, null, R.drawable.map_xlarge_button),\n\t\n\tHEADING_FOR_NEW_SHORES(MapSize.HEADING_FOR_NEW_SHORES,\n\t\t\tMapSize.HEADING_FOR_NEW_SHORES_EXP,\n\t\t\tR.drawable.sea_heading_for_new_shores),\n\tTHE_FOUR_ISLANDS(MapSize.THE_FOUR_ISLANDS,\n\t\t\tMapSize.THE_FOUR_ISLANDS_EXP,\n\t\t\tR.drawable.sea_the_four_islands_button, R.drawable.sea_the_four_islands_bw_button),\n\tTHE_FOG_ISLAND(MapSize.THE_FOG_ISLAND,\n\t\t\tMapSize.THE_FOG_ISLAND_EXP,\n\t\t\tR.drawable.sea_the_fog_island_button, R.drawable.sea_the_fog_island_bw_button),\n\tTHROUGH_THE_DESERT(MapSize.THROUGH_THE_DESERT,\n\t\t\tMapSize.THROUGH_THE_DESERT_EXP,\n\t\t\tR.drawable.sea_through_the_desert_button, R.drawable.sea_through_the_desert_bw_button),\n\tTHE_FORGOTTEN_TRIBE(MapSize.THE_FORGOTTEN_TRIBE,\n\t\t\tMapSize.THE_FORGOTTEN_TRIBE_EXP,\n\t\t\tR.drawable.sea_the_forgotten_tribe_button, R.drawable.sea_the_forgotten_tribe_bw_button),\n\tCLOTH_FOR_CATAN(MapSize.CLOTH_FOR_CATAN,\n\t\t\tMapSize.CLOTH_FOR_CATAN_EXP,\n\t\t\tR.drawable.sea_cloth_for_catan_button, R.drawable.sea_cloth_for_catan_bw_button),\n\tTHE_PIRATE_ISLANDS(MapSize.THE_PIRATE_ISLANDS,\n\t\t\tMapSize.THE_PIRATE_ISLANDS_EXP,\n\t\t\tR.drawable.sea_the_pirate_islands_button, R.drawable.sea_the_pirate_islands_bw_button),\n\tTHE_WONDERS_OF_CATAN(MapSize.THE_WONDERS_OF_CATAN,\n\t\t\tMapSize.THE_WONDERS_OF_CATAN_EXP,\n\t\t\tR.drawable.sea_the_wonders_of_catan_button, R.drawable.sea_the_wonders_of_catan_bw_button),\n\tNEW_WORLD(MapSize.NEW_WORLD,\n\t\t\tMapSize.NEW_WORLD_EXP,\n\t\t\tR.drawable.sea_new_world_button, R.drawable.sea_new_world_bw_button);\n\t\n\tpublic final MapSize reg;\n\tpublic final MapSize exp;\n\tpublic final int buttonResId;\n\tpublic final int bwButtonResId;\n\n\tMapSizePair(MapSize reg, MapSize exp) {\n\t\tthis(reg, exp, 0, 0);\n\t}\n\tMapSizePair(MapSize reg, MapSize exp, int buttonResId) {\n\t\tthis(reg, exp, buttonResId, 0);\n\t}\n\tMapSizePair(MapSize reg, MapSize exp, int buttonResId, int bwButtonResId) {\n\t\tthis.reg = reg;\n\t\tthis.exp = exp;\n\t\tthis.buttonResId = buttonResId;\n\t\tthis.bwButtonResId = bwButtonResId;\n\t}\n\n public static final Parcelable.Creator<MapSizePair> CREATOR = new Parcelable.Creator<MapSizePair>() {\n public MapSizePair createFromParcel(Parcel in) {\n return MapSizePair.values()[in.readInt()];\n }\n\n public MapSizePair[] newArray(int size) {\n return new MapSizePair[size];\n }\n };\n\t\n\t@Override\n\tpublic int describeContents() {\n return 0;\n }\n\n\t@Override\n public void writeToParcel(Parcel out, int flags) {\n\t\tout.writeInt(ordinal());\n }\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn name();\n\t}\n}", "public class MapFragment extends Fragment {\n\tprivate static final String STATE_MAP_SIZE = \"MAP_SIZE\";\n\tprivate static final String STATE_MAP_TYPE = \"MAP_TYPE\";\n\tprivate static final String STATE_RESOURCES = \"MAP_RESOURCES\";\n\tprivate static final String STATE_PROBABILITIES = \"PROBABILITIES\";\n\tprivate static final String STATE_UNKNOWNS = \"UNKNOWNS\";\n\tprivate static final String STATE_UNKNOWN_PROBABILITIES = \"UNKNOWN_PROBABILITIES\";\n\tprivate static final String STATE_HARBORS = \"HARBORS\";\n\tprivate static final String STATE_PLACEMENT_BOOKMARK = \"PLACEMENT_BOOKMARK\";\n\tprivate static final String STATE_PLACEMENT_MAX = \"PLACEMENT_MAX\";\n\tprivate static final String STATE_PLACEMENTS = \"PLACEMENTS\";\n\tprivate static final String STATE_ORDERED_PLACEMENTS = \"ORDERED_PLACEMENTS\";\n\t\n\tprivate MapView mMapView;\n\n\tprivate ImageView mPlacementsButton;\n\tprivate LinearLayout mPlacementsContainer;\n\tprivate ImageView mRefreshButton;\n\tprivate ImageView mRefreshDownButton;\n\n\tprivate MapSize mMapSize;\n\tprivate int mMapType;\n\tprivate ArrayList<Harbor> mHarborList = new ArrayList<>();\n\tprivate ArrayList<Resource> mResourceList = new ArrayList<>();\n\tprivate ArrayList<Integer> mProbabilityList = new ArrayList<>();\n\tprivate ArrayList<Resource> mUnknownsList = new ArrayList<>();\n\tprivate ArrayList<Integer> mUnknownProbabilitiesList = new ArrayList<>();\n\tprivate ArrayList<Integer> mPlacementsList = new ArrayList<>();\n\tprivate SparseArray<ArrayList<String>> mOrderedPlacementsList = new SparseArray<>();\n\tprivate int mPlacementBookmark = -1;\n\tprivate int mPlacementMax;\n\t\n\tprivate boolean mShowSeafarers = false;\n\n\t///////////////////////////////\n\t// Fragment method overrides //\n\t///////////////////////////////\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n\t\tsuper.onCreateView(inflater, container, savedInstanceState);\n\t\tView view = inflater.inflate(R.layout.map, container, false);\n\t\tmMapView = (MapView) view.findViewById(R.id.map_view);\n\t\t\n\t\tImageView settingsButton = (ImageView) view.findViewById(R.id.settings_button);\n\t\tsettingsButton.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override public void onClick(View v) {\n\t\t\t\tFragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();\n\t\t\t ft.addToBackStack(null);\n\t\t \tMapsDialogFragment.newInstance().show(ft, \"MapsDialogFragment\");\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.SETTINGS);\n\t\t\t}\n\t\t});\n\t\t\n\t\tmPlacementsButton = (ImageView) view.findViewById(R.id.placements_button);\n\t\tmPlacementsButton.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override public void onClick(View v) {\n\t\t \tif (showingPlacements()) {\n\t\t \t\thidePlacements(true);\n\t\t \t} else {\n\t\t \t\tshowPlacements(true);\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.USE_PLACEMENTS);\n\t\t \t}\n\t\t\t}\n\t\t});\n\t\t\n\t\tmPlacementsContainer = (LinearLayout) view.findViewById(R.id.placements_container);\n\t\t\n\t\tImageView placementsLeftButton = (ImageView) view.findViewById(R.id.placements_left_button);\n\t\tplacementsLeftButton.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override public void onClick(View v) {\n\t\t\t\tprevPlacement();\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.PREV_PLACEMENTS);\n\t\t\t}\n\t\t});\n\t\t\n\t\tImageView placementsRightButton = (ImageView) view.findViewById(R.id.placements_right_button);\n\t\tplacementsRightButton.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override public void onClick(View v) {\n\t\t\t\tnextPlacement();\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.NEXT_PLACEMENTS);\n\t\t\t}\n\t\t});\n\t\t\n\t\tmRefreshButton = (ImageView) view.findViewById(R.id.refresh_button);\n\t\tmRefreshButton.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tasyncMapShuffle();\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.SHUFFLE_MAP);\n\t\t\t}\n\t\t});\n\t\tmRefreshDownButton = (ImageView) view.findViewById(R.id.refresh_down_button);\n\n\t\t// Set initial state of placement buttons\n\t\tif (showingPlacements()) {\n\t\t\tshowPlacements(false);\n\t\t} else {\n\t\t\thidePlacements(false);\n\t\t}\n\t\t\n\t\treturn view;\n\t}\n\n\t/** Called when the activity is going to disappear. */\n\t@Override\n\tpublic void onSaveInstanceState(Bundle outState) {\n\t\tsuper.onSaveInstanceState(outState);\n\n\t\toutState.putParcelable(STATE_MAP_SIZE, mMapSize);\n\t\toutState.putInt(STATE_MAP_TYPE, mMapType);\n\t\toutState.putParcelableArrayList(STATE_RESOURCES, mResourceList);\n\t\toutState.putParcelableArrayList(STATE_UNKNOWNS, mUnknownsList);\n\t\toutState.putIntegerArrayList(STATE_PROBABILITIES, mProbabilityList);\n\t\toutState.putIntegerArrayList(STATE_UNKNOWN_PROBABILITIES, mUnknownProbabilitiesList);\n\t\toutState.putIntegerArrayList(STATE_PLACEMENTS, mPlacementsList);\n\t\toutState.putBundle(STATE_ORDERED_PLACEMENTS, Util.sparseArrayArrayListToBundle(mOrderedPlacementsList));\n\t\toutState.putParcelableArrayList(STATE_HARBORS, mHarborList);\n\t\toutState.putInt(STATE_PLACEMENT_BOOKMARK, mPlacementBookmark);\n\t\toutState.putInt(STATE_PLACEMENT_MAX, mPlacementMax);\n\t}\n\t\n\t@Override\n\tpublic void onActivityCreated(Bundle savedInstanceState) {\n\t\tsuper.onActivityCreated(savedInstanceState);\n\t\tBetterLog.d(\"MapFragment.onActivityCreated() \" + savedInstanceState);\n\t\t\n\t\t// If savedInstanceState == null, this is the first time the activity is created (not a rotation)\n\t\tif (savedInstanceState == null) {\n\t\t\t// Show what's new if we need to\n\t\t\tSharedPreferences prefs = getActivity().getSharedPreferences(Consts.SHARED_PREFS_NAME, Context.MODE_PRIVATE);\n\t\t\tboolean shownWhatsNew = prefs.getBoolean(Consts.SHARED_PREFS_KEY_WHATS_NEW_HELP, false);\n\t\t\tif (!shownWhatsNew) {\n\t\t\t\tWelcomeDialogFragment.newInstance().show(getFragmentManager(), \"WelcomeDialog\");\n\t\t\t\tSharedPreferences.Editor prefsEditor = prefs.edit();\n\t\t\t\tprefsEditor.putBoolean(Consts.SHARED_PREFS_KEY_WHATS_NEW_HELP, true);\n\t\t\t\tprefsEditor.apply();\n\t\t\t}\n\t\t\t\n\t\t\tmMapSize = MapSize.STANDARD;\n\t\t\tmMapType = MapType.FAIR;\n\t\t\tasyncMapShuffle();\n\t\t\trecordView();\n\t\t} else { // we have state from a rotation, use it\n\t\t\tif (savedInstanceState.containsKey(STATE_MAP_SIZE)) {\n\t\t\t\tmMapSize = savedInstanceState.getParcelable(STATE_MAP_SIZE);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_MAP_TYPE)) {\n\t\t\t\tmMapType = savedInstanceState.getInt(STATE_MAP_TYPE);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_RESOURCES)) {\n\t\t\t\tmResourceList = savedInstanceState.getParcelableArrayList(STATE_RESOURCES);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_UNKNOWNS)) {\n\t\t\t\tmUnknownsList = savedInstanceState.getParcelableArrayList(STATE_UNKNOWNS);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_PROBABILITIES)) {\n\t\t\t\tmProbabilityList = savedInstanceState.getIntegerArrayList(STATE_PROBABILITIES);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_UNKNOWN_PROBABILITIES)) {\n\t\t\t\tmUnknownProbabilitiesList = savedInstanceState.getIntegerArrayList(STATE_UNKNOWN_PROBABILITIES);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_PLACEMENTS)) {\n\t\t\t\tmPlacementsList = savedInstanceState.getIntegerArrayList(STATE_PLACEMENTS);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_ORDERED_PLACEMENTS)) {\n\t\t\t\tmOrderedPlacementsList = Util.bundleToSparseArrayArrayList(savedInstanceState.getBundle(STATE_ORDERED_PLACEMENTS));\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_HARBORS)) {\n\t\t\t\tmHarborList = savedInstanceState.getParcelableArrayList(STATE_HARBORS);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_PLACEMENT_BOOKMARK)) {\n\t\t\t\tmPlacementBookmark = savedInstanceState.getInt(STATE_PLACEMENT_BOOKMARK);\n\t\t\t}\n\t\t\tif (savedInstanceState.containsKey(STATE_PLACEMENT_MAX)) {\n\t\t\t\tmPlacementMax = savedInstanceState.getInt(STATE_PLACEMENT_MAX);\n\t\t\t}\n\t\t\t\n\t\t\trefreshView();\n\t\t}\n\t}\n \n private void showProgressBar() {\n \tif (mRefreshButton.getVisibility() == View.VISIBLE) {\n \tgetActivity().runOnUiThread(new Runnable() {\n \t\t\t@Override\n \t\t\tpublic void run() {\n \t \t\tmRefreshDownButton.setVisibility(View.VISIBLE);\n \t \t\tmRefreshButton.setVisibility(View.INVISIBLE);\n \t\t\t}\n \t\t});\n \t}\n }\n \n private void killProgressBar() {\n \tif (mRefreshDownButton.getVisibility() == View.VISIBLE) {\n \tgetActivity().runOnUiThread(new Runnable() {\n \t\t\t@Override\n \t\t\tpublic void run() {\n \t \t\tmRefreshDownButton.setVisibility(View.INVISIBLE);\n \t \t\tmRefreshButton.setVisibility(View.VISIBLE);\n \t\t\t}\n \t\t});\n \t}\n }\n \n public void hidePlacements(boolean animate) {\n\t\tmPlacementsButton.setImageDrawable(getResources().getDrawable(R.drawable.main_placements));\n\t\t\n \tif (animate) {\n \t\tAnimation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.placements_out);\n \t\tanimation.setAnimationListener(new AnimationListener() {\n \t\t\t@Override public void onAnimationStart(Animation animation) {}\n \t\t\t@Override public void onAnimationRepeat(Animation animation) {}\n \t\t\t@Override public void onAnimationEnd(Animation animation) {\n \t\t\t\ttogglePlacements(false);\n \t\t\t\tmPlacementsContainer.setVisibility(View.GONE);\n \t\t\t}\n \t\t});\n \t\tmPlacementsContainer.startAnimation(animation);\n \t} else {\n\t\t\ttogglePlacements(false);\n\t\t\tmPlacementsContainer.setVisibility(View.GONE);\n \t}\n }\n \n public void showPlacements(boolean animate) {\n\t\tmPlacementsButton.setImageDrawable(getResources().getDrawable(R.drawable.main_placements_down));\n\t\tmPlacementsContainer.setVisibility(View.VISIBLE);\n\t\t\n \tif (animate) {\n \t\tAnimation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.placements_in);\n \t\tanimation.setAnimationListener(new AnimationListener() {\n \t\t\t@Override public void onAnimationStart(Animation animation) {}\n \t\t\t@Override public void onAnimationRepeat(Animation animation) {}\n \t\t\t@Override public void onAnimationEnd(Animation animation) {\n \t\t\t\ttogglePlacements(true);\n \t\t\t}\n \t\t});\n \t\tmPlacementsContainer.startAnimation(animation);\n \t} else {\n \t\ttogglePlacements(true);\n \t}\n }\n\n\t//////////////////////////\n\t// Async generate tasks //\n\t//////////////////////////\n private abstract class ShuffleAsyncTask extends AsyncTask<Void, Void, Void> {\n\t\t@Override\n\t\tprotected void onPreExecute() {\n\t\t\tshowProgressBar();\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Void doInBackground(Void... params) {\n\t\t\t// MapLogic\n\t\t\tmapChanges();\n\t\t\t\n\t\t\t// PlacementLogic\n\t\t\tPair<ArrayList<Integer>, SparseArray<ArrayList<String>>> placementPair =\n\t\t\t PlacementLogic.getBestPlacements(getCatanMap(), mResourceList, mProbabilityList, mHarborList);\n\t\t\tmPlacementsList = placementPair.first;\n\t\t\tmOrderedPlacementsList = placementPair.second;\n\t\t\t\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onPostExecute(Void result) {\n\t\t\trefreshView();\n\t\t\tkillProgressBar();\n\t\t}\n\t\t\n\t\tprotected abstract void mapChanges();\n }\n \n\tprivate class ShuffleMapAsyncTask extends ShuffleAsyncTask {\n\t\t@Override\n\t\tprotected void mapChanges() {\n\t\t\t// Refresh New World maps\n\t\t\tif (mMapSize.title.equals(\"new_world\")) {\n\t\t\t\tmMapSize = MapSize.NEW_WORLD;\n\t\t\t\tmMapSize.mapProvider.refresh(getActivity());\n\t\t\t}\n\t\t\tif (mMapSize.title.equals(\"new_world_exp\")) {\n\t\t\t\tmMapSize = MapSize.NEW_WORLD_EXP;\n\t\t\t\tmMapSize.mapProvider.refresh(getActivity());\n\t\t\t}\n\t\t\tmProbabilityList = MapLogic.getProbabilities(getCatanMap(), mMapType);\n\t\t\tmUnknownProbabilitiesList = MapLogic.getUnknownProbabilities(getCatanMap());\n\t\t\tmResourceList = MapLogic.getResources(getCatanMap(), mMapType, mProbabilityList);\n\t\t\tmUnknownsList = MapLogic.getUnknowns(getCatanMap(), mUnknownProbabilitiesList);\n\t\t\tmHarborList = MapLogic.getHarbors(getCatanMap(), mMapType, mResourceList, mProbabilityList);\n\t\t}\n\t}\n public void asyncProbsShuffle() {\n \tnew ShuffleProbabilitiesAsyncTask().execute();\n }\n\n\tprivate class ShuffleProbabilitiesAsyncTask extends ShuffleAsyncTask {\n\t\t@Override\n\t\tprotected void mapChanges() {\n\t\t\tmProbabilityList = MapLogic.getProbabilities(getCatanMap(), mMapType, mResourceList);\n\t\t\tmUnknownProbabilitiesList = MapLogic.getUnknownProbabilities(getCatanMap());\n\t\t\tmUnknownsList = MapLogic.getUnknowns(getCatanMap(), mUnknownProbabilitiesList);\n\t\t}\n\t}\n public void asyncHarborsShuffle() {\n \tnew ShuffleHarborsAsyncTask().execute();\n }\n\n\tprivate class ShuffleHarborsAsyncTask extends ShuffleAsyncTask {\n\t\t@Override\n\t\tprotected void mapChanges() {\n\t\t\tmHarborList = MapLogic.getHarbors(getCatanMap(), mMapType, mResourceList, mProbabilityList);\n\t\t}\n\t}\n public void asyncMapShuffle() {\n \tnew ShuffleMapAsyncTask().execute();\n }\n\n\t//////////////////////////\n\t// Map helper functions //\n\t////////////////////////// \n\tprivate void refreshView() {\n\t\tif (mResourceList.isEmpty() || mProbabilityList.isEmpty() || mHarborList.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tmMapView.setMapSize(mMapSize);\n\t\t\n\t\tfillResourceProbabilityAndHarbors();\n\t\tfillPlacements();\n\t\tmMapView.setReady();\n\t\tmMapView.invalidate(); // Force refresh\n\t}\n\n\tprivate void fillResourceProbabilityAndHarbors() {\n\t\tResource[][] resourceBoard = new Resource[BOARD_RANGE_X + 1][BOARD_RANGE_Y + 1];\n\t\tResource[][] uResourceBoard = new Resource[BOARD_RANGE_X + 1][BOARD_RANGE_Y + 1];\n\t\tint[][] probabilityBoard = new int[BOARD_RANGE_X + 1][BOARD_RANGE_Y + 1];\n\t\tint[][] uProbabilityBoard = new int[BOARD_RANGE_X + 1][BOARD_RANGE_Y + 1];\n\t\tHarbor[][] harborBoard = new Harbor[BOARD_RANGE_X + 1][BOARD_RANGE_Y + 1];\n\t\tfor (int i = 0; i < getCatanMap().landGrid.length; i++) {\n\t\t\tPoint point = getCatanMap().landGrid[i];\n\t\t\tresourceBoard[point.x][point.y] = mResourceList.get(i);\n\t\t\tprobabilityBoard[point.x][point.y] = mProbabilityList.get(i);\n\t\t}\n\t\tfor (int i = 0; i < getCatanMap().waterGrid.length; i++) {\n\t\t\tPoint point = getCatanMap().waterGrid[i];\n\t\t\tharborBoard[point.x][point.y] = mHarborList.get(i);\n\t\t}\n\t\tfor (int i = 0; i < getCatanMap().unknownGrid.length; i++) {\n\t\t\tPoint point = getCatanMap().unknownGrid[i];\n\t\t\tuResourceBoard[point.x][point.y] = mUnknownsList.get(i);\n\t\t\tuProbabilityBoard[point.x][point.y] = mUnknownProbabilitiesList.get(i);\n\t\t}\n\n\t\tmMapView.setLandAndWaterResources(resourceBoard, harborBoard, uResourceBoard);\n\t\tmMapView.setProbabilities(probabilityBoard, uProbabilityBoard);\n\t\tmMapView.setHarbors(mHarborList);\n\t\tmMapView.setPlacementBookmark(mPlacementBookmark);\n\t}\n\n\tprivate void fillPlacements() {\n\t\tmMapView.setOrderedPlacements(mPlacementsList);\n\t\tmMapView.setPlacements(mOrderedPlacementsList);\n\t\t\n\t\tmPlacementMax = mOrderedPlacementsList.size() - 1;\n\t\t//BetterLog.v(\"mOrderedPlacementList: \" + mOrderedPlacementList);\n\t\t//BetterLog.v(\"mPlacementList: \" + mPlacementList);\n\t}\n\t\n\tpublic boolean showingPlacements() {\n\t\treturn mPlacementBookmark >= 0;\n\t}\n\t\n\tpublic void nextPlacement() {\n\t\tmPlacementBookmark = (mPlacementBookmark == mPlacementMax) ? mPlacementBookmark : mPlacementBookmark + 1;\n\t\trefreshView();\n\t}\n\t\n\tpublic void prevPlacement() {\n\t\tmPlacementBookmark = mPlacementBookmark == 0 ? 0 : mPlacementBookmark - 1;\n\t\trefreshView();\n\t}\n\t\n\tpublic CatanMap getCatanMap() {\n\t\treturn mMapSize.mapProvider.get();\n\t}\n\tpublic int getMapType() {\n\t\treturn mMapType;\n\t}\n\t\n\tpublic boolean getShowSeafarers() {\n\t\treturn mShowSeafarers;\n\t}\n\n\tpublic void setShowSeafarers(boolean showSeafarers) {\n\t\tmShowSeafarers = showSeafarers;\n\t}\n\t\n\tprivate void recordView() {\n Analytics.trackView(getActivity(), String.format(\n Analytics.VIEW_MAP_FORMAT, mMapSize.title, MapType.getString(mMapType)));\n\t}\n\t\n\tpublic void typeChoice(int type) {\n\t\tif (mMapType != type) {\n\t\t\tmMapType = type;\n\t\t\tasyncMapShuffle();\n\t\t\trecordView();\n\t\t}\n\t}\n\t\n\tpublic void sizeChoice(MapSize mapSize) {\n\t\t// Only Settlers maps can have traditional\n\t\tif (mMapType == MapType.TRADITIONAL\n\t\t\t\t&& (mapSize != MapSize.STANDARD && mapSize != MapSize.LARGE && mapSize != MapSize.XLARGE)) {\n\t\t\tmMapType = MapType.FAIR;\n\t\t}\n\t\t\n\t\tif (mMapSize != mapSize) {\n\t\t\tmMapSize = mapSize;\n\t\t\tasyncMapShuffle();\n\t\t\tMainActivity mainActivity = (MainActivity) getActivity();\n\t\t\tmainActivity.setTitleButtonText(mapSize.titleDrawableId);\n\t\t\trecordView();\n\t\t}\n\t}\n\t\n\tpublic void togglePlacements(boolean on) {\n\t\tif (on) {\n Analytics.track(getActivity(), Analytics.CATEGORY_MAIN, Analytics.ACTION_BUTTON,\n Analytics.USE_PLACEMENTS);\n\t\t\tif (mPlacementBookmark < 0) {\n\t\t\t\tmPlacementBookmark = 0;\n\t\t\t}\n\t\t} else {\n\t\t\tmPlacementBookmark = -1;\n\t\t}\n\t\trefreshView();\n\t}\n}", "public final class Analytics {\n\tprivate Analytics() {}\n\n\tpublic static final String CATEGORY_MAIN = \"main\";\n\tpublic static final String CATEGORY_MAPS_MENU = \"maps_menu\";\n\tpublic static final String CATEGORY_MENU_MENU = \"menu_menu\";\n\tpublic static final String CATEGORY_SETTLERS_MENU = \"seafarers_menu\";\n\tpublic static final String CATEGORY_SEAFARERS_MENU = \"seafarers_menu\";\n\tpublic static final String CATEGORY_EXPANSION_MENU = \"expansion_menu\";\n\tpublic static final String CATEGORY_ABOUT_MENU = \"about_menu\";\n\tpublic static final String CATEGORY_ROLL_TRACKER = \"roll_tracker\";\n\n\tpublic static final String ACTION_BUTTON = \"button\";\n\tpublic static final String ACTION_LONG_PRESS_BUTTON = \"long_press_button\";\n\tpublic static final String ACTION_PURCHASE_OFFER = \"purchase_offer\";\n\t\n\tpublic static final String INFO = \"info\";\n\tpublic static final String RATE_US = \"rate_us\";\n\n\tpublic static final String SETTINGS = \"settings\";\n\tpublic static final String USE_PLACEMENTS = \"placements\";\n\tpublic static final String NEXT_PLACEMENTS = \"next\";\n\tpublic static final String PREV_PLACEMENTS = \"prev\";\n\tpublic static final String SHUFFLE_MAP = \"shuffle_map\";\n\t\n\tpublic static final String SEE_SETTLERS = \"settlers\";\n\tpublic static final String SEE_SEAFARERS = \"seafarers\";\n\tpublic static final String SEE_MORE = \"more\";\n\n\tpublic static final String USE_ROLL_TRACKER = \"roll_tracker\";\n\tpublic static final String SHUFFLE_PROBABILITIES = \"shuffle_probabilities\";\n\tpublic static final String SHUFFLE_HARBORS = \"shuffle_harbors\";\n\n\tpublic static final String EXPANSION_SMALL = \"expansion_small\";\n\tpublic static final String EXPANSION_LARGE = \"expansion_large\";\n\n\tpublic static final String DELETE = \"delete\";\n\n\t// Arg 1: MapSize\n\t// Arg 2: MapType\n\tpublic static final String VIEW_MAP_FORMAT = \"/map/%s/%s\";\n\tpublic static final String VIEW_ROLL_TRACKER = \"/roll_tracker\";\n\tpublic static final String VIEW_INFO = \"/info\";\n\tpublic static final String VIEW_MAPS_MENU = \"/main_menu\";\n\tpublic static final String VIEW_EXPANSIONS_MENU = \"/expansions_menu\";\n\tpublic static final String VIEW_MORE_MENU = \"/more_menu\";\n\tpublic static final String VIEW_SETTLERS_MENU = \"/settlers_menu\";\n\tpublic static final String VIEW_SEAFARERS_MENU = \"/seafarers_menu\";\n\n private static final Object sLock = new Object();\n private static volatile Tracker sTracker = null;\n\n public static void track(Context context, String category, String action) {\n getTracker(context).send(getEvent(category, action, null /* action */, 0L /* value */));\n }\n\n public static void track(Context context, String category, String action, String label) {\n getTracker(context).send(getEvent(category, action, label, 0L /* value */));\n }\n\n public static void track(Context context, String category, String action, String label,\n long value) {\n getTracker(context).send(getEvent(category, action, label, value));\n }\n\n public static void trackView(Context context, String view) {\n Tracker tracker = getTracker(context);\n tracker.setScreenName(view);\n tracker.send(new HitBuilders.AppViewBuilder().build());\n }\n\n private static Map<String, String> getEvent(String category, String action, String label,\n long value) {\n HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder()\n .setCategory(category)\n .setAction(action);\n if (label != null) {\n builder.setLabel(label);\n }\n if (value != 0L) {\n builder.setValue(value);\n }\n return builder.build();\n }\n\n private static Tracker getTracker(Context context) {\n if (sTracker == null) {\n synchronized (sLock) {\n if (sTracker == null) {\n sTracker = GoogleAnalytics.getInstance(context.getApplicationContext())\n .newTracker(R.xml.global_tracker);\n }\n }\n }\n return sTracker;\n }\n}", "public final class Consts {\n\tprivate Consts() {}\n\n\t///////////////////////////////////////////\n\t// All of these should be false for release\n\tpublic static final boolean TEST_STATIC_IAB = false;\n\tpublic static final boolean TEST_CONSUME_ALL_PURCHASES = false;\n\t\n\tpublic static final boolean DEBUG_MAP = false;\n\tpublic static final boolean DEBUG_MAP_WITH_RED = false;\n //\n\t///////////////////////////////////////////\n\t\n\tpublic static final String LAUNCH_MAP_ACTION = \"com.nut.bettersettlers.action.LAUNCH_MAP\";\n\tpublic static final String PLAY_STORE_URL = \"https://play.google.com/store/apps/details?id=com.nut.bettersettlers\";\n\n\tpublic static final String SHARED_PREFS_NAME = \"Preferences\";\n\tpublic static final String SHARED_PREFS_KEY_WHATS_NEW_HELP = \"ShownWhatsNewVersion21\";\n\tpublic static final String SHARED_PREFS_KEY_FOG_ISLAND_HELP = \"TheFogIsland\";\n\t\n\t/**\n\t * Mapping between the numbers that are shown (rolled on the dice) and the probability of each\n\t * being rolled.\n\t */\n\tpublic static final int[] PROBABILITY_MAPPING = {\n\t\t0, // 0\n 0, // 1\n 1, // 2\n 2, // 3\n 3, // 4\n 4, // 5\n 5, // 6\n 0, // 7\n 5, // 8\n 4, // 9\n 3, // 10\n 2, // 11\n 1 // 12\n\t};\n\t\n\tpublic static final int BOARD_RANGE_X = 22;//19;\n\tpublic static final int BOARD_RANGE_HALF_X = 11;//9;\n\tpublic static final int BOARD_RANGE_Y = 13;//11;\n\tpublic static final int BOARD_RANGE_HALF_Y = 7;//6;\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import com.nut.bettersettlers.R; import com.nut.bettersettlers.activity.MainActivity; import com.nut.bettersettlers.data.MapSize; import com.nut.bettersettlers.data.MapSizePair; import com.nut.bettersettlers.fragment.MapFragment; import com.nut.bettersettlers.util.Analytics; import com.nut.bettersettlers.util.Consts;
package com.nut.bettersettlers.fragment.dialog; public class ExpansionDialogFragment extends DialogFragment { private static final String SIZE_KEY = "SIZE"; private MapSizePair mMapSizePair; public static ExpansionDialogFragment newInstance(MapSizePair sizePair) { ExpansionDialogFragment f = new ExpansionDialogFragment(); Bundle args = new Bundle(); args.putParcelable(SIZE_KEY, sizePair); f.setArguments(args); f.setStyle(STYLE_NO_TITLE, 0); return f; } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Analytics.trackView(getActivity(), Analytics.VIEW_EXPANSIONS_MENU); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.expansion, container, false); mMapSizePair = getArguments().getParcelable(SIZE_KEY); ImageView smallButton = (ImageView) view.findViewById(R.id.expansion_small_item); smallButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.track(getActivity(), Analytics.CATEGORY_EXPANSION_MENU, Analytics.ACTION_BUTTON, Analytics.EXPANSION_SMALL); choice(mMapSizePair.reg); } }); ImageView largeButton = (ImageView) view.findViewById(R.id.expansion_large_item); largeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.track(getActivity(), Analytics.CATEGORY_EXPANSION_MENU, Analytics.ACTION_BUTTON, Analytics.EXPANSION_LARGE); choice(mMapSizePair.exp); } }); getDialog().getWindow().getAttributes().windowAnimations = R.style.FadeDialogAnimation; return view; } private void choice(MapSize size) {
final MainActivity mainActivity = (MainActivity) getActivity();
0
OlgaKuklina/GitJourney
app/src/main/java/com/oklab/gitjourney/activities/MainActivity.java
[ "public class DeleteUserAuthorizationAsyncTask extends AsyncTask<String, Integer, Boolean> {\n private static final String TAG = DeleteUserAuthorizationAsyncTask.class.getSimpleName();\n private final Activity activity;\n private UserSessionData currentSessionData;\n\n public DeleteUserAuthorizationAsyncTask(Activity activity) {\n this.activity = activity;\n }\n\n @Override\n protected Boolean doInBackground(String... args) {\n try {\n HttpURLConnection connect = (HttpURLConnection) new URL(activity.getString(R.string.url_disconnect, currentSessionData.getId())).openConnection();\n connect.setRequestMethod(\"DELETE\");\n String authentication = \"token \" + currentSessionData.getToken();\n connect.setRequestProperty(\"Authorization\", authentication);\n connect.connect();\n int responseCode = connect.getResponseCode();\n\n Log.v(TAG, \"responseCode = \" + responseCode);\n if (responseCode == 204) {\n return true;\n }\n } catch (IOException e) {\n Log.v(TAG, \"\", e);\n }\n return false;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SharedPreferences prefs = activity.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);\n String sessionDataStr = prefs.getString(\"userSessionData\", null);\n currentSessionData = UserSessionData.createUserSessionDataFromString(sessionDataStr);\n }\n\n @Override\n protected void onPostExecute(Boolean result) {\n super.onPostExecute(result);\n SharedPreferences prefs = activity.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);\n SharedPreferences.Editor e = prefs.edit();\n e.remove(\"userSessionData\");\n e.apply();\n Intent intent = new Intent(activity, AuthenticationActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n activity.startActivity(intent);\n activity.finish();\n }\n}", "public class GitHubUserProfileDataEntry extends GitHubUsersDataEntry implements Parcelable {\n\n public static final Creator<GitHubUserProfileDataEntry> CREATOR = new Creator<GitHubUserProfileDataEntry>() {\n @Override\n public GitHubUserProfileDataEntry createFromParcel(Parcel in) {\n return new GitHubUserProfileDataEntry(in);\n }\n\n @Override\n public GitHubUserProfileDataEntry[] newArray(int size) {\n return new GitHubUserProfileDataEntry[size];\n }\n };\n private final String location;\n private final String name;\n private final String company;\n private final String blogURI;\n private final String email;\n private final String bio;\n private final int publicRepos;\n private final int publicGists;\n private final int followers;\n private final int following;\n private final Calendar createdAt;\n\n public GitHubUserProfileDataEntry(String name, String imageUri, String profileUri, String location, String login, String company, String blogURI, String email, String bio, int publicRepos, int publicGists, int followers, int following, Calendar createdAt) {\n super(login, imageUri, profileUri);\n this.location = location;\n this.name = name;\n this.company = company;\n this.email = email;\n this.blogURI = blogURI;\n this.bio = bio;\n this.publicRepos = publicRepos;\n this.publicGists = publicGists;\n this.followers = followers;\n this.following = following;\n this.createdAt = createdAt;\n }\n\n protected GitHubUserProfileDataEntry(Parcel in) {\n super(in);\n location = in.readString();\n name = in.readString();\n company = in.readString();\n email = in.readString();\n blogURI = in.readString();\n bio = in.readString();\n publicRepos = in.readInt();\n publicGists = in.readInt();\n followers = in.readInt();\n following = in.readInt();\n long date = in.readLong();\n String timeZone = in.readString();\n createdAt = Calendar.getInstance(TimeZone.getTimeZone(timeZone));\n createdAt.setTimeInMillis(date);\n }\n\n public String getLocation() {\n return location;\n }\n\n public String getName() {\n return name;\n }\n\n public String getCompany() {\n return company;\n }\n\n public String getBlogURI() {\n return blogURI;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getBio() {\n return bio;\n }\n\n public int getPublicRepos() {\n return publicRepos;\n }\n\n public int getPublicGists() {\n return publicGists;\n }\n\n public int getFollowers() {\n return followers;\n }\n\n public int getFollowing() {\n return following;\n }\n\n public Calendar getCreatedAt() {\n return createdAt;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int i) {\n super.writeToParcel(parcel, i);\n parcel.writeString(location);\n parcel.writeString(name);\n parcel.writeString(company);\n parcel.writeString(email);\n parcel.writeString(blogURI);\n parcel.writeString(bio);\n parcel.writeInt(publicRepos);\n parcel.writeInt(publicGists);\n parcel.writeInt(followers);\n parcel.writeInt(following);\n parcel.writeLong(createdAt.getTimeInMillis());\n parcel.writeString(createdAt.getTimeZone().getID());\n }\n}", "public class UserSessionData {\n\n private final String id;\n private final String credentials;\n private final String token;\n private final String login;\n\n\n public UserSessionData(String id, String credentials, String token, String login) {\n this.id = id;\n this.credentials = credentials;\n this.token = token;\n this.login = login;\n }\n\n public static UserSessionData createUserSessionDataFromString(String data) {\n if (data == null || data.isEmpty()) {\n return null;\n }\n String[] array = data.split(\";\");\n return new UserSessionData(array[0], array[1], array[2], array[3]);\n }\n\n public String getLogin() {\n return login;\n }\n\n public String getId() {\n return id;\n }\n\n public String getCredentials() {\n return credentials;\n }\n\n public String getToken() {\n return token;\n }\n\n @Override\n public String toString() {\n return id + \";\" + credentials + \";\" + token + \";\" + login;\n }\n}", "public class ContributionsByDateListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, SwipeRefreshLayout.OnRefreshListener {\n private static final String TAG = ContributionsByDateListFragment.class.getSimpleName();\n private RecyclerView recyclerView;\n private SwipeRefreshLayout swipeRefreshLayout;\n private ContributionsByDateAdapter contributionsListAdapter;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public ContributionsByDateListFragment() {\n }\n\n public static ContributionsByDateListFragment newInstance() {\n Log.v(TAG, \" ContributionsByDateListFragment newInstance \");\n ContributionsByDateListFragment fragment = new ContributionsByDateListFragment();\n Bundle args = new Bundle();\n fragment.setArguments(args);\n fragment.setRetainInstance(true);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n Log.v(TAG, \"onCreateView savedInstanceState = \" + savedInstanceState);\n View v = inflater.inflate(R.layout.fragment_contributions_list, container, false);\n recyclerView = (RecyclerView) v.findViewById(R.id.c_items_list_recycler_view);\n swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.c_swipe_refresh_layout);\n return v;\n }\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n Log.v(TAG, \"onActivityCreated\");\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);\n recyclerView.setLayoutManager(linearLayoutManager);\n swipeRefreshLayout.setOnRefreshListener(this);\n getLoaderManager().initLoader(0, null, this);\n }\n\n @Override\n public void onRefresh() {\n recyclerView.setAdapter(null);\n getLoaderManager().initLoader(0, null, this);\n }\n\n @Override\n public Loader<Cursor> onCreateLoader(int id, Bundle args) {\n return ContributionsDataLoader.newAllItemsLoader(getContext());\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\n contributionsListAdapter = new ContributionsByDateAdapter(this.getContext(), data);\n contributionsListAdapter.setHasStableIds(true);\n recyclerView.setAdapter(contributionsListAdapter);\n swipeRefreshLayout.setRefreshing(false);\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> loader) {\n\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n * <p/>\n * See the Android Training lesson <a href=\n * \"http://developer.android.com/training/basics/fragments/communicating.html\"\n * >Communicating with Other Fragments</a> for more information.\n */\n public interface OnListFragmentInteractionListener {\n // TODO: Update argument type and name\n // void onListFragmentInteraction(DummyItem item);\n }\n}", "public class MainViewFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {\n\n private static final String TAG = MainViewFragment.class.getSimpleName();\n private static final String ARG_SECTION_NUMBER = \"section_number\";\n String monthName;\n private ContributionsListAdapter contributionsListAdapter;\n private GridView gridView;\n private ScrollView scrollView;\n private Calendar calendar = (Calendar) Calendar.getInstance().clone();\n private TextView monthTitle;\n\n\n public MainViewFragment() {\n setRetainInstance(true);\n }\n\n /**\n * Returns a new instance of this fragment for the given section\n * number.\n */\n public static MainViewFragment newInstance(int sectionNumber) {\n MainViewFragment fragment = new MainViewFragment();\n Bundle args = new Bundle();\n args.putInt(ARG_SECTION_NUMBER, sectionNumber);\n fragment.setArguments(args);\n fragment.adjustCalendar();\n return fragment;\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n getLoaderManager().initLoader(0, null, this);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setRetainInstance(true);\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View v = inflater.inflate(R.layout.fragment_main, container, false);\n gridView = (GridView) v.findViewById(R.id.gridview);\n scrollView = (ScrollView) v.findViewById(R.id.contributions_activity_container);\n monthTitle = (TextView) v.findViewById(R.id.month_title);\n monthTitle.setText(monthName);\n return v;\n }\n\n private void adjustCalendar() {\n int offset = getArguments().getInt(ARG_SECTION_NUMBER);\n calendar.add(Calendar.MONTH, -offset);\n SimpleDateFormat month_date = new SimpleDateFormat(\"MMMM, yyyy\", Locale.getDefault());\n monthName = month_date.format(calendar.getTime());\n }\n\n @Override\n public Loader<Cursor> onCreateLoader(int id, Bundle args) {\n int numberOfDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n Calendar newCalendar = (Calendar) calendar.clone();\n newCalendar.set(Calendar.DAY_OF_MONTH, 1);\n newCalendar.set(Calendar.HOUR_OF_DAY, 0);\n newCalendar.set(Calendar.MINUTE, 0);\n newCalendar.set(Calendar.SECOND, 0);\n Log.v(TAG, \"numberOfDays = \" + numberOfDays);\n long minDate = newCalendar.getTimeInMillis();\n newCalendar.set(Calendar.DAY_OF_MONTH, numberOfDays);\n newCalendar.set(Calendar.HOUR_OF_DAY, 23);\n newCalendar.set(Calendar.MINUTE, 59);\n newCalendar.set(Calendar.SECOND, 59);\n long maxDate = newCalendar.getTimeInMillis();\n return ContributionsDataLoader.newRangeLoader(getContext(), minDate, maxDate);\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\n Log.v(TAG, \"loader finished \" + data.getCount());\n contributionsListAdapter = new ContributionsListAdapter(this.getContext(), getArguments().getInt(ARG_SECTION_NUMBER), data);\n gridView.setAdapter(contributionsListAdapter);\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> loader) {\n\n }\n}", "public class GitHubUserProfileDataParser implements Parser<GitHubUserProfileDataEntry> {\n private static final String TAG = GitHubUserProfileDataParser.class.getSimpleName();\n private static final String PATTERN = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n\n @Override\n public GitHubUserProfileDataEntry parse(JSONObject jsonObject) throws JSONException {\n GitHubUserProfileDataEntry entry = parseItem(jsonObject);\n return entry;\n }\n\n private GitHubUserProfileDataEntry parseItem(JSONObject object) throws JSONException {\n if (object == null) {\n return null;\n }\n Log.v(TAG, \"login = \" + object.getString(\"login\"));\n Log.v(TAG, \"JSONObject = \" + object);\n String login = \"\";\n if (!object.getString(\"login\").isEmpty()) {\n login = object.getString(\"login\");\n }\n String avatarUrl = \"\";\n if (!object.getString(\"avatar_url\").isEmpty()) {\n avatarUrl = object.getString(\"avatar_url\");\n }\n String profileUri = \"\";\n if (!object.getString(\"url\").isEmpty()) {\n profileUri = object.getString(\"url\");\n }\n Log.v(TAG, \"location = \" + object.getString(\"location\"));\n Log.v(TAG, \"JSONObject = \" + object);\n String location = \"\";\n if (!object.getString(\"location\").isEmpty()) {\n location = object.getString(\"location\");\n }\n String name = \"\";\n if (!object.getString(\"name\").isEmpty() && object.getString(\"name\") != null && !object.getString(\"name\").equals(\"null\")) {\n name = object.getString(\"name\");\n } else {\n name = object.getString(\"login\");\n }\n String company = \"\";\n if (!object.getString(\"company\").isEmpty()) {\n company = object.getString(\"company\");\n }\n String blogURI = \"\";\n if (!object.getString(\"blog\").isEmpty()) {\n blogURI = object.getString(\"blog\");\n }\n String email = \"\";\n if (!object.getString(\"email\").isEmpty()) {\n email = object.getString(\"email\");\n }\n String bio = \"\";\n if (!object.getString(\"bio\").isEmpty()) {\n bio = object.getString(\"bio\");\n }\n int publicRepos = 0;\n if (object.has(\"public_repos\")) {\n publicRepos = object.getInt(\"public_repos\");\n }\n int privateRepos = 0;\n if (object.has(\"total_private_repos\")) {\n privateRepos = object.getInt(\"total_private_repos\");\n }\n int publicGists = 0;\n if (object.has(\"public_gists\")) {\n publicGists = object.getInt(\"public_gists\");\n }\n int followers = 0;\n if (object.has(\"followers\")) {\n followers = object.getInt(\"followers\");\n }\n int following = 0;\n if (object.has(\"following\")) {\n following = object.getInt(\"following\");\n }\n\n Calendar createdAt = null;\n if (!object.getString(\"created_at\").isEmpty()) {\n String date = object.getString(\"created_at\");\n SimpleDateFormat format = new SimpleDateFormat(PATTERN, Locale.getDefault());\n format.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n Date entryDate = null;\n try {\n entryDate = format.parse(date);\n createdAt = Calendar.getInstance();\n createdAt.setTime(entryDate);\n } catch (ParseException e) {\n Log.v(TAG, \"\", e);\n }\n }\n return new GitHubUserProfileDataEntry(name, avatarUrl, profileUri, location, login, company, blogURI, email, bio, publicRepos + privateRepos, publicGists, followers, following, createdAt);\n }\n}", "public interface Parser<T> {\n T parse(JSONObject jsonObject) throws JSONException;\n}", "public class TakeScreenshotService {\n\n private static final String TAG = TakeScreenshotService.class.getSimpleName();\n private final Activity activity;\n\n public TakeScreenshotService(Activity activity) {\n this.activity = activity;\n }\n\n public void takeScreenShot() {\n View v1 = activity.getWindow().getDecorView().getRootView();\n v1.setDrawingCacheEnabled(true);\n Bitmap myBitmap = v1.getDrawingCache();\n String filePath = saveBitmap(myBitmap);\n v1.setDrawingCacheEnabled(false);\n if (filePath != null) {\n sendMail(filePath);\n }\n }\n\n private String saveBitmap(Bitmap bitmap) {\n Utils.verifyStoragePermissions(activity);\n String filePath = Environment.getExternalStorageDirectory()\n + File.separator + activity.getString(R.string.local_path);\n File imagePath = new File(filePath);\n FileOutputStream stream;\n try {\n stream = new FileOutputStream(imagePath);\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);\n stream.flush();\n stream.close();\n return filePath;\n } catch (IOException e) {\n Log.e(TAG, \"\", e);\n return null;\n }\n }\n\n private void sendMail(String path) {\n Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\n emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,\n activity.getString(R.string.screenshot_msg_title));\n emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,\n activity.getString(R.string.screenshot_msg_extra_text));\n emailIntent.setType(activity.getString(R.string.content_type));\n Uri myUri = Uri.parse(activity.getString(R.string.content_path) + path);\n emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);\n activity.startActivity(Intent.createChooser(emailIntent, activity.getString(R.string.screenshot_msg_desc)));\n }\n}", "public final class Utils {\n public static final String SHARED_PREF_NAME = \"com.ok.lab.GitJourney\";\n public static final String DMY_DATE_FORMAT_PATTERN = \"dd-MM-yyyy\";\n private static final int REQUEST_EXTERNAL_STORAGE = 1;\n private static String[] PERMISSIONS_STORAGE = {\n Manifest.permission.READ_EXTERNAL_STORAGE,\n Manifest.permission.WRITE_EXTERNAL_STORAGE\n };\n\n private Utils() {\n\n }\n\n public static void verifyStoragePermissions(Activity activity) {\n // Check if we have write permission\n int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);\n Log.e(\"TAG\", \"verifyStoragePermissions\");\n if (permission != PackageManager.PERMISSION_GRANTED) {\n // We don't have permission so prompt the user\n ActivityCompat.requestPermissions(\n activity,\n PERMISSIONS_STORAGE,\n REQUEST_EXTERNAL_STORAGE\n );\n }\n }\n\n public static DateFormat createDateFormatterWithTimeZone(Context context, String pattern) {\n SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);\n boolean timeZone = sharedPref.getBoolean(\"timezone_switch\", true);\n SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.getDefault());\n if (timeZone) {\n formatter.setTimeZone(TimeZone.getDefault());\n } else {\n String customTimeZone = sharedPref.getString(\"timezone_list\", TimeZone.getDefault().getID());\n formatter.setTimeZone(TimeZone.getTimeZone(customTimeZone));\n }\n return formatter;\n }\n\n public static String getStackTrace(Exception e) {\n StringWriter writer = new StringWriter();\n PrintWriter printer = new PrintWriter(writer);\n e.printStackTrace(printer);\n printer.close();\n return writer.toString();\n }\n}" ]
import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; 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.ImageView; import com.google.firebase.analytics.FirebaseAnalytics; import com.oklab.gitjourney.R; import com.oklab.gitjourney.adapters.FirebaseAnalyticsWrapper; import com.oklab.gitjourney.asynctasks.DeleteUserAuthorizationAsyncTask; import com.oklab.gitjourney.asynctasks.UserProfileAsyncTask; import com.oklab.gitjourney.data.GitHubUserProfileDataEntry; import com.oklab.gitjourney.data.UpdaterService; import com.oklab.gitjourney.data.UserSessionData; import com.oklab.gitjourney.fragments.ContributionsByDateListFragment; import com.oklab.gitjourney.fragments.MainViewFragment; import com.oklab.gitjourney.parsers.GitHubUserProfileDataParser; import com.oklab.gitjourney.parsers.Parser; import com.oklab.gitjourney.services.TakeScreenshotService; import com.oklab.gitjourney.utils.Utils;
}); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override protected void onStart() { super.onStart(); firebaseAnalytics.setCurrentScreen(this, "MainActivityFirebaseAnalytics"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, Integer.toString(item.getItemId())); bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "MainActivityNavigationItemSelected"); firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle); if (id == R.id.github_events) { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } else if (id == R.id.profile) { String currentSessionData = prefs.getString("userSessionData", null); if (currentSessionData != null) { Intent intent = new Intent(this, GeneralActivity.class); startActivity(intent); return true; } } else if (id == R.id.personal) { String currentSessionData = prefs.getString("userSessionData", null); if (currentSessionData != null) { Parser<GitHubUserProfileDataEntry> parser = new GitHubUserProfileDataParser(); userProfileAsyncTask = new UserProfileAsyncTask<GitHubUserProfileDataEntry>(this, this, parser); userProfileAsyncTask.execute(); return true; } } else if (id == R.id.settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } else if (id == R.id.sing_out) { new DeleteUserAuthorizationAsyncTask(this).execute(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void OnProfilesLoaded(GitHubUserProfileDataEntry dataEntry) { Log.v(TAG, "OnProfilesLoaded "); userProfileAsyncTask = null; String currentSessionData = prefs.getString("userSessionData", null); UserSessionData userSessionData = UserSessionData.createUserSessionDataFromString(currentSessionData); Intent intent = new Intent(this, UserProfileActivity.class); intent.putExtra("profile", dataEntry); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); if (userProfileAsyncTask != null) { userProfileAsyncTask.cancel(true); } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class CalendarYearPagerAdapter extends FragmentPagerAdapter { public CalendarYearPagerAdapter(FragmentManager fm) { super(fm); } @Override public android.support.v4.app.Fragment getItem(int position) { Log.v(TAG, "position - " + position); // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below).
return MainViewFragment.newInstance(position);
4
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/ServerForge.java
[ "public class Player{\n private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>();\n private EntityPlayer entityPlayer;\n private InventoryBase inventory;\n\n public enum GameMode{\n SURVIVAL,\n CREATIVE,\n ADVENTURE\n }\n\n private Player(EntityPlayer entityPlayer){\n this.entityPlayer = entityPlayer;\n inventory = new InventoryBase(this.entityPlayer.inventory);\n }\n\n public static Player get(EntityPlayer player){\n Player c = playerEntities.get(player.getUniqueID());\n if(c == null){\n Player np = new Player(player);\n playerEntities.put(player.getUniqueID(), np);\n return np;\n }else{\n return c;\n }\n }\n\n /**\n * Returns the name of this player\n * @return The name of this player\n */\n public String getName(){\n return entityPlayer.getCommandSenderName();\n }\n\n /**\n * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode\n * @return The player's UUID\n */\n public UUID getUUID(){\n return entityPlayer.getUniqueID();\n }\n\n /**\n * Teleports the player to the specified location\n * @param x The x coordinate of the location to teleport the player to\n * @param y The y coordinate of the location to teleport the player to\n * @param z The z coordinate of the location to teleport the player to\n */\n public void teleport(double x, double y, double z){\n entityPlayer.setPosition(x, y, z);\n EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer);\n mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch);\n }\n\n /**\n * Sets the yaw and pitch of the player's camera\n * @param yaw The yaw to set for this player\n * @param pitch The pitch to set for this player\n */\n public void setCameraAngles(float yaw, float pitch){\n EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer);\n mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch);\n }\n\n /**\n * Sends the message passed into this method to the player's chat box\n * @param message The message to send to the player\n */\n public void sendMessage(String message){\n entityPlayer.addChatMessage(new ChatComponentText(message));\n }\n\n /**\n * Returns the value for the permission of this player\n * @param permission the permission to lookup\n * @return the value of the permission\n */\n public boolean getPermission(String permission) {\n return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission);\n }\n\n public InventoryBase getInventory(){\n return inventory;\n }\n\n /**\n * Sets this player's current gamemode\n * @param mode the new gamemode\n */\n public void setGameMode(GameMode mode){\n EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer);\n switch(mode){\n case SURVIVAL:\n mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL);\n break;\n case CREATIVE:\n mpPlayer.setGameType(WorldSettings.GameType.CREATIVE);\n break;\n case ADVENTURE:\n mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE);\n break;\n }\n }\n\n /**\n * Returns this player's current world\n * @return This player's current world\n */\n public ServerForgeWorld getWorld(){\n return ServerForgeWorld.get(entityPlayer.dimension);\n }\n\n /**\n * Returns the current X coordinate of this player\n * @return The current X coordinate of this player\n */\n public double getX(){\n return entityPlayer.getPlayerCoordinates().posX;\n }\n\n /**\n * Returns the current Y coordinate of this player\n * @return The current Y coordinate of this player\n */\n public double getY(){\n return entityPlayer.getPlayerCoordinates().posY;\n }\n\n /**\n * Returns the current Z coordinate of this player\n * @return The current Z coordinate of this player\n */\n public double getZ(){\n return entityPlayer.getPlayerCoordinates().posZ;\n }\n\n}", "public interface ServerForgeCommand {\n\n /**\n * Called when a command is executed\n * @param sender An object representing the player, console, or command block that sent the command\n * @param args The arguments of the command\n */\n public void onCommand(CommandSender sender, String[] args);\n\n}", "public class EventManager{\n private ArrayList<EventListenerWrapper> listeners;\n\n public void onServerStart(){\n ServerForge.info(\"Starting events\");\n listeners = new ArrayList<EventListenerWrapper>();\n ServerForge.info(\"Starting forge listener\");\n DefaultEventListener defaultEventListener = new DefaultEventListener(this);\n MinecraftForge.EVENT_BUS.register(defaultEventListener);\n }\n\n /**\n * Registers an event listener to have it's methods called when an event is fired\n * @param listener The listener to register\n */\n public void registerEventListener(EventListener listener){\n EventListenerWrapper wrapper = new EventListenerWrapper(listener);\n listeners.add(wrapper);\n }\n\n /**\n * Fires an event\n * @param o The event to fire\n */\n public void fireEvent(Object o){\n for(EventListenerWrapper wrapper : listeners){\n wrapper.callEvent(o);\n }\n }\n\n}", "public class PluginLoader{\n private ArrayList<PluginFile> pluginFile;\n private ArrayList<PluginWrapper> pluginWrapper;\n private URLClassLoader loader;\n private File pluginsFolder;\n\n public void onServerStart(){\n pluginsFolder = new File(\"./plugins\");\n\n try {\n if (!pluginsFolder.isDirectory()) {\n Files.move(pluginsFolder, new File(\"./plugins-file\"));\n pluginsFolder.delete();\n }\n\n if (!pluginsFolder.exists()) {\n pluginsFolder.mkdir();\n }\n }catch(IOException e){\n e.printStackTrace();\n System.exit(0);\n }\n\n pluginFile = new ArrayList<PluginFile>();\n pluginWrapper = new ArrayList<PluginWrapper>();\n ArrayList<URL> pluginURL = new ArrayList<URL>();\n\n ServerForge.info(\"Loading plugins...\");\n for(File file : pluginsFolder.listFiles()){\n ServerForge.info(\"Loading \" + file.getAbsolutePath());\n if(file.getName().endsWith(\".jar\") || (!file.isDirectory())){\n PluginFile pFile = new PluginFile(file);\n\n if(pFile.getName() == null) {\n ServerForge.error(\"Plugin \" + file.getAbsolutePath() + \" does not have a name set, please add the name to plugindata.txt\");\n }else if(pFile.getMainClass() == null){\n ServerForge.error(\"Plugin \" + file.getAbsolutePath() + \" does not have a mainClass set, please add the name to plugindata.txt\");\n }else{\n pluginFile.add(pFile);\n pluginURL.add(pFile.getURL());\n ServerForge.info(\"Loaded \" + pFile.getName());\n }\n }else{\n ServerForge.info(\"Skipping \" + file.getAbsolutePath() + \" not a plugin.\");\n }\n }\n ServerForge.info(\"Plugins loaded\");\n\n loader = new URLClassLoader(pluginURL.toArray(new URL[pluginURL.size()]), getClass().getClassLoader());\n\n ServerForge.info(\"Starting plugins\");\n for(PluginFile pFile : pluginFile){\n try {\n startPlugin(pFile, loader);\n }catch(ClassNotFoundException e){\n ServerForge.error(\"Failed to load plugin \" + pFile.getName() + \". Can not load main class \" + pFile.getMainClass() + \".\");\n e.printStackTrace();\n }catch(InstantiationException e){\n ServerForge.error(\"Failed to load plugin \" + pFile.getName() + \". Can not instantiate main class \" + pFile.getMainClass() + \". (\" + e.getClass().getCanonicalName() + \")\");\n e.printStackTrace();\n }catch(IllegalAccessException e){\n ServerForge.error(\"Failed to load plugin \" + pFile.getName() + \". Can not instantiate main class \" + pFile.getMainClass() + \". (\" + e.getClass().getCanonicalName() + \")\");\n e.printStackTrace();\n }catch(ClassCastException e){\n ServerForge.error(\"Failed to load plugin \" + pFile.getName() + \". Can not instantiate main class is not instanceof \" + ServerForgePlugin.class.getCanonicalName() + \".\");\n e.printStackTrace();\n }catch(NullPointerException e){\n ServerForge.error(\"Failed to load plugin \" + pFile.getName() + \". Could not load main class \" + ServerForgePlugin.class.getCanonicalName() + \". (nullpointerexception)\");\n e.printStackTrace();\n }\n }\n\n ServerForge.info(\"Starting ServerForgePlugin\");\n ServerForgeDefaultPlugin plugin = new ServerForgeDefaultPlugin();\n\n PluginWrapper wrapper = new PluginWrapper(plugin, \"ServerForgePlugin\");\n pluginWrapper.add(wrapper);\n\n plugin.onServerStart();\n\n ServerForge.info(\"ServerForgePlugin started\");\n }\n\n private void startPlugin(PluginFile pFile, ClassLoader loader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException, NullPointerException{\n ServerForge.info(\"Starting \" + pFile.getName());\n String mainClass = pFile.getMainClass();\n\n if(loader == null){\n System.out.println(\"Classloader null?!\");\n }\n\n Class<?> pluginClass = loader.loadClass(mainClass);\n Object instance = pluginClass.newInstance();\n ServerForgePlugin plugin = ((ServerForgePlugin) instance);\n PluginWrapper wrapper = new PluginWrapper(plugin, pFile.getName());\n pluginWrapper.add(wrapper);\n\n plugin.onServerStart();\n\n ServerForge.info(pFile.getName() + \" started\");\n }\n\n /**\n * Returns a list of all plugins in their wrappers\n * @return A list of all plugins in their wrappers\n */\n public ArrayList<PluginWrapper> getPlugins(){\n return pluginWrapper;\n }\n\n public File getPluginsFolder(){\n return pluginsFolder;\n }\n\n}", "public class PermissionsManager{\n private ArrayList<PermissionsHandler> handlerIndex;\n\n public void onServerStart(){\n handlerIndex = new ArrayList<PermissionsHandler>();\n }\n\n /**\n * Registers the specified permissionhandler in the system\n * @param permissionsHandler The permissionhandler to be registered\n */\n public void registerPermissionsHandler(PermissionsHandler permissionsHandler){\n handlerIndex.add(permissionsHandler);\n }\n\n //using entityplayermp to encourage use of the method in the src.john01dav.serverforge.api.Player class\n public boolean getPermission(EntityPlayerMP playerMP, String permission){\n Player player = Player.get(playerMP);\n\n for(PermissionsHandler handler : handlerIndex){\n if(handler.isPermissionSet(player, permission)){\n return handler.getPermission(player, permission);\n }\n }\n\n return false;\n }\n\n\n}" ]
import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLServerStartingEvent; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.EventManager; import src.john01dav.serverforge.loader.PluginLoader; import src.john01dav.serverforge.permissions.PermissionsManager; import java.util.ArrayList;
package src.john01dav.serverforge; @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") public class ServerForge{ public static final String VERSION = "PRE-ALPHA 0.0.1"; private EventManager eventManager; private PermissionsManager permissionsManager; private PluginLoader pluginLoader; private FMLServerStartingEvent serverStartingEvent; @Mod.Instance("ServerForge") public static ServerForge instance; public static void info(String info){ System.out.println("[SERVERFORGE INFO]: " + info); } public static void error(String error){ System.out.println("[SERVERFORGE ERROR]: " + error); } @Mod.EventHandler public void serverStartingEvent(FMLServerStartingEvent e){ info("Starting ServerForge..."); this.serverStartingEvent = e; eventManager = new EventManager(); eventManager.onServerStart(); permissionsManager = new PermissionsManager(); permissionsManager.onServerStart(); pluginLoader = new PluginLoader(); pluginLoader.onServerStart(); this.serverStartingEvent = null; info("ServerForge started"); } /** * Registers a command for use in the server, can only be called from onServerStart() or it's submethods * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") * @param command The command object to register * @param aliases Array containing the aliases for this command */
public void registerCommand(String name, ServerForgeCommand command, String[] aliases){
1
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/RedQueryBuilder.java
[ "public class Select extends Query implements ColumnResolver {\n\n private final Button add = new Button(\"Add condition\");\n\n private final XWidget<Expression> xcondition = new XWidget<Expression>();\n\n private HashMap<Expression, Object> currentGroup;\n\n private int currentGroupRowId;\n\n private ObjectArray<Expression> expressions;\n private final ObjectArray<TableFilter> filters = ObjectArray.newInstance();\n // private ObjectArray<SelectOrderBy> orderList;\n private ObjectArray<Expression> group;\n private boolean[] groupByExpression;\n private int[] groupIndex;\n private Expression having;\n\n private boolean isQuickAggregateQuery;\n private final Session session;\n private int visibleColumnCount;\n\n private final VerticalPanel vp = new VerticalPanel();\n\n private final CommandListBox what;\n\n public Select(final Session session2) {\n super(session2);\n session = session2;\n session.setSelect(this);\n\n initWidget(vp);\n\n what = new CommandListBox(this);\n what.addStyleName(\"rqbWhat\"); // XXX to be removed\n what.addStyleName(\"rqbFrom\");\n what.setVisible(session.getConfig().getFrom().isVisible());\n vp.add(what);\n\n vp.add(add);\n add.addClickHandler(new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n addFirstCondition();\n fireDirty();\n }\n });\n List items = new ArrayList();\n CommandWithLabel prompt = new PromptCommand();\n what.setValue(prompt);\n items.add(prompt);\n\n // XXX 00 What is SQL 92 case sensitivity rule\n\n for (Table t : session.getDatabase().getMainSchema().getTables()) {\n if (!t.isHidden()) {\n items.add(new TableCommand(t));\n }\n }\n\n what.setAcceptableValues(items);\n\n vp.add(xcondition);\n }\n\n // XXX scope for testing\n public Comparison addFirstCondition() {\n Comparison c = new Comparison(session);\n addCondition(c);\n return c;\n }\n\n class TableCommand extends CommandWithLabel {\n private final Table table;\n TableCommand(Table t) {\n super(t);\n table = t;\n }\n @Override\n public void execute() {\n updateTable(table);\n }\n }\n\n class PromptCommand extends CommandWithLabel {\n PromptCommand() {\n super(\"Please select\");\n }\n\n @Override\n public void execute() {\n updateTable(null);\n }\n }\n\n\n /**\n * Add a condition to the list of conditions.\n *\n * @param cond\n * the condition to add\n */\n public void addCondition(Expression cond) {\n Expression condition = getCondition();\n if (condition == null) {\n condition = cond;\n } else {\n condition = new ConditionAndOr(session, ConditionAndOr.AND, cond, condition);\n }\n setCondition(condition);\n }\n\n private void setCondition(Expression condition) {\n xcondition.setValue(condition);\n }\n\n /**\n * Add a table to the query.\n *\n * @param filter\n * the table to add\n * @param isTop\n * if the table can be the first table in the query plan\n */\n public void addTableFilter(TableFilter filter, boolean isTop) {\n // Oracle doesn't check on duplicate aliases\n // String alias = filter.getAlias();\n // if(filterNames.contains(alias)) {\n // throw Message.getSQLException(\n // ErrorCode.DUPLICATE_TABLE_ALIAS, alias);\n // }\n // filterNames.add(alias);\n\n filters.add(filter);\n\n }\n\n public int getColumnCount() {\n return visibleColumnCount;\n }\n\n public Expression getCondition() {\n return xcondition.getValue();\n }\n\n public HashMap<Expression, Object> getCurrentGroup() {\n return currentGroup;\n }\n\n public int getCurrentGroupRowId() {\n return currentGroupRowId;\n }\n\n public ObjectArray<Expression> getExpressions() {\n return expressions;\n }\n\n public ObjectArray<TableFilter> getFilters() {\n return filters;\n }\n\n public String getSQL(List args) {\n\n StatementBuilder buff = new StatementBuilder(\"SELECT \");\n // if (distinct) {\n // buff.append(\"DISTINCT \");\n // }\n if (expressions != null) {\n for (int i = 0; i < expressions.size(); i++) {\n buff.appendExceptFirst(\", \");\n buff.append(expressions.get(i).getSQL(args));\n }\n }\n buff.append(\"\\nFROM \");\n TableFilter filter = null;\n if (filters.size() > 0) {\n filter = filters.get(0);\n }\n if (filter != null) {\n buff.resetCount();\n int i = 0;\n do {\n buff.appendExceptFirst(\"\\n\");\n buff.append(filter.getSQL(i++ > 0, args));\n filter = filter.getJoin();\n } while (filter != null);\n } else {\n buff.resetCount();\n int i = 0;\n for (TableFilter f : filters) {\n buff.appendExceptFirst(\"\\n\");\n buff.append(f.getSQL(i++ > 0, args));\n }\n }\n if (xcondition.getValue() != null) {\n buff.append(\"\\nWHERE \").append(xcondition.getValue().getSQL(args));\n }\n // if (groupIndex != null) {\n // buff.append(\"\\nGROUP BY \");\n // buff.resetCount();\n // for (int gi : groupIndex) {\n // Expression g = exprList[gi];\n // g = g.getNonAliasExpression();\n // buff.appendExceptFirst(\", \");\n // buff.append(StringUtils.unEnclose(g.getSQL()));\n // }\n // }\n // if (group != null) {\n // buff.append(\"\\nGROUP BY \");\n // buff.resetCount();\n // for (Expression g : group) {\n // buff.appendExceptFirst(\", \");\n // buff.append(StringUtils.unEnclose(g.getSQL()));\n // }\n // }\n // if (having != null) {\n // // could be set in addGlobalCondition\n // // in this case the query is not run directly, just getPlanSQL is\n // // called\n // Expression h = having;\n // buff.append(\"\\nHAVING \").append(StringUtils.unEnclose(h.getSQL()));\n // } else if (havingIndex >= 0) {\n // Expression h = exprList[havingIndex];\n // buff.append(\"\\nHAVING \").append(StringUtils.unEnclose(h.getSQL()));\n // }\n // if (sort != null) {\n // buff.append(\"\\nORDER BY \").append(sort.getSQL(exprList,\n // visibleColumnCount));\n // }\n // if (orderList != null) {\n // buff.append(\"\\nORDER BY \");\n // buff.resetCount();\n // for (SelectOrderBy o : orderList) {\n // buff.appendExceptFirst(\", \");\n // buff.append(StringUtils.unEnclose(o.getSQL()));\n // }\n // }\n // if (limitExpr != null) {\n // buff.append(\"\\nLIMIT \").append(StringUtils.unEnclose(limitExpr.getSQL()));\n // if (offsetExpr != null) {\n // buff.append(\" OFFSET \").append(StringUtils.unEnclose(offsetExpr.getSQL()));\n // }\n // }\n // if (isForUpdate) {\n // buff.append(\"\\nFOR UPDATE\");\n // }\n // if (isQuickAggregateQuery) {\n // buff.append(\"\\n/* direct lookup */\");\n // }\n // if (isDistinctQuery) {\n // buff.append(\"\\n/* distinct */\");\n // }\n // if (sortUsingIndex) {\n // buff.append(\"\\n/* index sorted */\");\n // }\n // if (isGroupQuery) {\n // if (isGroupSortedQuery) {\n // buff.append(\"\\n/* group sorted */\");\n // }\n // }\n return buff.toString();\n }\n\n // public ListBox getWhat() {\n // return what;\n // }\n\n // public HashSet<Table> getTables() {\n // HashSet<Table> set = New.hashSet();\n // for (TableFilter filter : filters) {\n // set.add(filter.getTable());\n // }\n // return set;\n // }\n\n /**\n * Check if this is an aggregate query with direct lookup, for example a\n * query of the type SELECT COUNT(*) FROM TEST or SELECT MAX(ID) FROM TEST.\n *\n * @return true if a direct lookup is possible\n */\n public boolean isQuickAggregateQuery() {\n return isQuickAggregateQuery;\n }\n\n @Override\n public BaseSqlWidget remove(Expression e) {\n if (getCondition() == e) {\n setCondition(null);\n return this;\n }\n throw new IllegalArgumentException();\n }\n\n @Override\n public void replace(Expression e0, Expression e1) {\n if (getCondition() == e0) {\n setCondition(e1);\n }\n }\n\n public void setExpressions(ObjectArray<Expression> p) {\n this.expressions = p;\n }\n\n // public void mapColumns(ColumnResolver resolver, int level) throws\n // SQLException {\n // for (Expression e : expressions) {\n // e.mapColumns(resolver, level);\n // }\n // if (condition != null) {\n // condition.mapColumns(resolver, level);\n // }\n // }\n //\n // public void setEvaluatable(TableFilter tableFilter, boolean b) {\n // for (Expression e : expressions) {\n // e.setEvaluatable(tableFilter, b);\n // }\n // if (condition != null) {\n // condition.setEvaluatable(tableFilter, b);\n // }\n // }\n\n public void setGroupBy(ObjectArray<Expression> p) {\n this.group = p;\n }\n\n public void setHaving(Expression p) {\n this.having = p;\n }\n\n public void updateTable(Table tt) {\n if (tt == null) {\n filters.clear();\n } else if (getFilters().size() == 0) {\n TableFilter filter = new TableFilter(session, tt, TableFilter\n .newAlias(), Select.this);\n addTableFilter(filter, true); // XXX really is true?\n } else {\n getFilters().get(0).setTable(tt);\n }\n expressions = null; // XXX 03 bit harsh?\n setCondition(null);\n\n session.getMsgBus().fireEvent(new TableEvent());\n }\n\n @Override\n public void onDirty() {\n garbageCollectFilters();\n\n add.setVisible(getCondition() == null && this.getFilters().size() > 0);\n\n if (getFilters().size() > 0) {\n what.setValue(new TableCommand(getFilters().get(0).getTable()));\n }\n }\n\n public void garbageCollectFilters() {\n if (filters.size() > 1) {\n // XXX identity?\n final Set<TableFilter> used = new HashSet<TableFilter>();\n used.add(null);\n Visitor counter = new VisitorBase() {\n @Override\n public void handle(BaseSqlWidget w) {\n if (w instanceof ExpressionColumn) {\n ExpressionColumn ec = (ExpressionColumn) w;\n TableFilter tf = ec.getTableFilter();\n if (used.add(tf)) {\n if (tf.getJoinCondition() != null) {\n tf.getJoinCondition().traverse(this);\n }\n }\n }\n }\n };\n\n if (getCondition() != null) {\n getCondition().traverse(counter);\n }\n\n boolean removed;\n do {\n removed = false;\n TableFilter prev = filters.get(0);\n TableFilter x = prev.getJoin();\n while (x != null) {\n if (!used.contains(x)) {\n // look for used in all other filters?\n int i = filters.indexOf(x);\n if (i > 0) {\n filters.remove(i);\n }\n // XXX why is this the case?\n // just when comma seperated?\n prev.setJoin(x.getJoin());\n removed = true;\n }\n prev = x;\n x = x.getJoin();\n }\n } while (removed);\n\n }\n }\n\n @Override\n public void acceptChildren(Visitor callback) {\n Expression condition = getCondition();\n if (condition != null) {\n condition.traverse(callback);\n }\n }\n\n @Override\n public Column resolveColumn(String alias, String columnName) {\n for (TableFilter tf : getFilters()) {\n if (alias == null || alias.equals(tf.getAlias())) {\n Column c = tf.getTable().getColumn(columnName);\n if (c != null) {\n return c;\n }\n // XXX if alias != null should blowup?\n // XXX should blowup if find more than one?\n }\n\n //if (alias.equals(tf.getAlias())) {\n // return tf.getTable().getColumn(columnName);\n //}\n }\n // XXX log? Window.alert(\"Unable to find \" + alias + \".\" + columnName);\n return null;\n }\n\n public TableFilter getTableFilter(String alias) {\n if (alias == null) {\n return getFilters().get(0);\n }\n\n for (TableFilter tf : getFilters()) {\n if (alias.equals(tf.getAlias())) {\n return tf;\n }\n }\n return null;\n }\n\n // public void addGlobalCondition(Parameter param, int columnId, int\n // comparisonType) throws SQLException {\n // addParameter(param);\n // Expression col = expressions.get(columnId);\n // col = col.getNonAliasExpression();\n // Expression comp = new Comparison(session, comparisonType, col, param);\n // comp = comp.optimize(session);\n // boolean addToCondition = true;\n // if (isGroupQuery) {\n // addToCondition = false;\n // for (int i = 0; groupIndex != null && i < groupIndex.length; i++) {\n // if (groupIndex[i] == columnId) {\n // addToCondition = true;\n // break;\n // }\n // }\n // if (!addToCondition) {\n // if (havingIndex >= 0) {\n // having = expressions.get(havingIndex);\n // }\n // if (having == null) {\n // having = comp;\n // } else {\n // having = new ConditionAndOr(ConditionAndOr.AND, having, comp);\n // }\n // }\n // }\n // if (addToCondition) {\n // if (condition == null) {\n // condition = comp;\n // } else {\n // condition = new ConditionAndOr(ConditionAndOr.AND, condition, comp);\n // }\n // }\n // }\n\n // public String getFirstColumnAlias(Session s) {\n // if (SysProperties.CHECK) {\n // if (visibleColumnCount > 1) {\n // Message.throwInternalError(\"\" + visibleColumnCount);\n // }\n // }\n // Expression expr = expressions.get(0);\n // if (expr instanceof Alias) {\n // return expr.getAlias();\n // }\n // Mode mode = s.getDatabase().getMode();\n // String name = s.getNextSystemIdentifier(getSQL());\n // expr = new Alias(expr, name, mode.aliasColumnName);\n // expressions.set(0, expr);\n // return expr.getAlias();\n // }\n //\n\n}", "public class Session {\n\n private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {\n @Override\n public String quote(String id) {\n return \"\\\"\" + id + \"\\\"\";\n }\n };\n\n public void setIdentifierEscaper(IdentifierEscaper p) {\n identifierEscaper = p;\n }\n\n /**\n * Add double quotes around an identifier if required.\n *\n * @param s the identifier\n * @return the quoted identifier\n */\n public static String quoteIdentifier(String s) {\n return identifierEscaper.quote(s);\n }\n\n // XXX need commandBuilder and select?\n private CommandBuilder commandBuilder;\n\n private Select select;\n\n private Configuration config;\n\n private final ValueRegistry valueRegistry = new ValueRegistry();\n\n private final Database database;\n\n private final HandlerManager msgbus;\n\n\n // XXX 00 remove one of these constructors\n public Session(Configuration config2) {\n this(config2.getDatabase());\n this.config = config2;\n }\n\n @Deprecated\n public Session(Database database2) {\n database = database2;\n msgbus = new HandlerManager(this);\n }\n\n public Configuration getConfig() {\n return config;\n }\n\n public CommandBuilder getCommandBuilder() {\n return commandBuilder;\n }\n\n public void setCommandBuilder(CommandBuilder p) {\n commandBuilder = p;\n }\n\n public Database getDatabase() {\n return database;\n }\n\n\n public HandlerManager getMsgBus() {\n return msgbus;\n }\n\n\n\n public void setSelect(Select p) {\n select = p;\n }\n\n public Column resolveColumn(String alias, String columnName) {\n return select.resolveColumn(alias, columnName);\n }\n\n public ObjectArray<TableFilter> getFilters() {\n return select.getFilters();\n }\n\n public TableFilter getTableFilter(Table t) {\n for (TableFilter tf : select.getFilters()) {\n if (tf.getTable().equals(t)) {\n return tf;\n }\n }\n return null;\n }\n\n public TableFilter createTableFilter(Table t) {\n TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);\n select.addTableFilter(tf, true); // XXX really is true?\n return tf;\n }\n\n public TableFilter getOrCreateTableFilter(Table t) {\n TableFilter tf = getTableFilter(t);\n if (tf == null) {\n tf = createTableFilter(t);\n }\n return tf;\n }\n\n //public Table getTable(String alias) {\n // return select.getTable(alias);\n //}\n\n public Table getRootTable() {\n // XXX maybe if no table then grab default?\n // or should select always have one table?\n // or ui shouldn't offer condition button till table?\n return select.getFilters().get(0).getTable();\n }\n\n public ValueRegistry getValueRegistry() {\n return valueRegistry;\n }\n}", "public class TableEvent extends GwtEvent<TableEventHandler> {\n public static final Type<TableEventHandler> TYPE = new Type<TableEventHandler>();\n\n // XXX only for root table changing?\n public TableEvent() {\n }\n\n @Override\n public Type<TableEventHandler> getAssociatedType() {\n return TYPE;\n }\n\n @Override\n protected void dispatch(TableEventHandler handler) {\n handler.onTable(this);\n }\n}", "public interface TableEventHandler extends EventHandler {\n void onTable(TableEvent e);\n}", "public class ExpressionColumn extends Expression implements TableEventHandler {\n private Database database;\n private final String schemaName;\n private String tableAlias;\n private String columnName;\n\n private final HorizontalPanel hp = new HorizontalPanel();\n\n public ExpressionColumn(Session session2, String schemaName2,\n String tableAlias2, String columnName2) {\n super(session2);\n this.schemaName = schemaName2;\n this.tableAlias = tableAlias2;\n this.columnName = columnName2;\n\n initWidget(hp);\n\n reg2 = getSession().getMsgBus().addHandler(TableEvent.TYPE, this);\n }\n\n public void selectConstraintRef(ConstraintReferential ref) {\n TableFilter targetTf = JoinHelper.getOrCreateFor(getSession(), ref);\n this.tableAlias = targetTf.getAlias();\n this.columnName = targetTf.getTable().getColumns().iterator().next()\n .getName();\n\n }\n\n public void updateColumn(String alias, Column col2) {\n this.tableAlias = alias;\n this.columnName = col2.getName();\n }\n\n private final HandlerRegistration reg2;\n\n @Override\n public void onUnload() {\n super.onUnload();\n if (reg2 != null) {\n reg2.removeHandler();\n }\n }\n\n public Column getColumn() {\n return getSession().resolveColumn(tableAlias, getColumnName());\n }\n\n public String getColumnName() {\n return columnName;\n }\n\n public String getQualifiedColumnName() {\n if (tableAlias == null) {\n return getColumnName();\n }\n return tableAlias + \".\" + getColumnName();\n }\n\n @Override\n public void onDirty() {\n hp.clear();\n\n TableFilter tf = null;\n for (TableFilter tf2 : getSession().getFilters()) {\n if (StringUtils.equals(tableAlias, tf2.getAlias())) {\n tf = tf2;\n break;\n } else if (tf == null) {\n tf = tf2;\n }\n }\n\n Object hotValue = getColumn();\n\n Command hotCommand = null;\n while (tf != null) {\n final CommandListBox ght = new CommandListBox(this);\n hp.insert(ght, 0);\n List<Command> items = new ArrayList();\n// hotCommand = new ClearCommand();\n// items.add(hotCommand);\n\n for (Constraint c : tf.getTable().getConstraints()) {\n if (c instanceof ConstraintReferential) {\n ConstraintReferential cr = (ConstraintReferential) c;\n if (!cr.isHidden()) {\n Command command = new ConstraintCommand(cr);\n if (cr == hotValue) {\n hotCommand = command;\n }\n items.add(command);\n }\n }\n }\n\n for (Column c : tf.getTable().getColumns()) {\n if (!c.isHidden()) {\n Command command = new ColumnCommand(tf.getAlias(), c);\n if (c == hotValue) {\n hotCommand = command;\n }\n items.add(command);\n }\n }\n\n ght.setValue(hotCommand);\n ght.setAcceptableValues(items);\n\n JoinHelper thing = JoinHelper.getParent(tf);\n if (thing != null) {\n tf = thing.getParent();\n hotValue = thing.getConstraint();\n } else {\n tf = null;\n }\n }\n }\n\n @Override\n public String getSQL(List args) {\n String sql;\n // if (column != null) {\n // sql = column.getSQL();\n // } else {\n sql = Session.quoteIdentifier(\"\" + getColumnName());\n // }\n if (tableAlias != null) {\n sql = Session.quoteIdentifier(tableAlias) + \".\" + sql;\n }\n // if (schemaName != null) {\n // sql = Parser.quoteIdentifier(schemaName) + \".\" + sql;\n // }\n return sql;\n }\n\n @Override\n public void onTable(TableEvent e) {\n // Window.alert(\"Changed table\");\n }\n\n public TableFilter getTableFilter() {\n // return resolver == null ? null : resolver.getTableFilter();\n for (TableFilter tf2 : getSession().getFilters()) {\n\n if (StringUtils.equals(tableAlias, tf2.getAlias())) {\n return tf2;\n }\n }\n return null; // XXX or blowup?\n }\n\n// private class ClearCommand extends Command2 {\n// ClearCommand() {\n// super(\"Please select...\");\n// }\n//\n// @Override\n// public void execute() {\n// // TOxDO 00 a Select \"PLease select\" for column and goes bang. in getSql?\n// // really want this at all? Ever selected? Defaults to first column...\n// // A) Default to first column and get rid of this\n// // B) Don't default and make this work ok\n// updateColumn(null, null);\n// }\n// }\n\n private class ColumnCommand extends CommandWithLabel {\n private final String alias;\n private final Column column;\n\n ColumnCommand(String a, Column c) {\n super(c);\n assert (c != null);\n this.alias = a;\n this.column = c;\n }\n\n @Override\n public void execute() {\n updateColumn(alias, column);\n }\n }\n\n private class ConstraintCommand extends CommandWithLabel {\n private final ConstraintReferential constraintReferential;\n\n ConstraintCommand(ConstraintReferential constraintReferential2) {\n super(constraintReferential2);\n this.constraintReferential = constraintReferential2;\n }\n\n @Override\n public void execute() {\n selectConstraintRef(constraintReferential);\n }\n }\n}" ]
import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.SimplePanel; import com.redspr.redquerybuilder.core.client.command.CommandBuilder; import com.redspr.redquerybuilder.core.client.command.dml.Select; import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.engine.TableEvent; import com.redspr.redquerybuilder.core.client.engine.TableEventHandler; import com.redspr.redquerybuilder.core.client.expression.ExpressionColumn; import com.redspr.redquerybuilder.core.client.table.TableFilter; import com.redspr.redquerybuilder.core.client.util.ObjectArray; import com.redspr.redquerybuilder.core.shared.meta.Column;
/******************************************************************************* * Copyright (c) 2010-2013 Redspr Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sam Hough - initial API and implementation *******************************************************************************/ package com.redspr.redquerybuilder.core.client; public class RedQueryBuilder implements EntryPoint { private void createCommandBuilder(final Configuration config, String sql, List args) throws Exception { final Session session = new Session(config); final CommandBuilder builder = new CommandBuilder(session, sql, args); session.getMsgBus().addHandler(TableEvent.TYPE, new TableEventHandler() { @Override public void onTable(TableEvent e) { if (session.getFilters().size() > 0) { config.fireOnTableChange(session.getFilters()); // XXX need to do distinct? ObjectArray expr = ObjectArray.newInstance(); TableFilter tf = session.getFilters().get(0); String alias = tf.getAlias(); for (Column col : tf.getTable().getColumns()) { expr.add(new ExpressionColumn(session, null, alias, col.getName())); } builder.getSelect().setExpressions(expr); } else { builder.getSelect().setExpressions(null); } } });
builder.addValueChangeHandler(new ValueChangeHandler<Select>() {
0
mszubert/2048
src/main/java/put/ci/cevo/games/serializers/NTuplesSerializer.java
[ "public class NTuple {\n\n\tprivate final int numValues;\n\tprivate final int[] locations;\n\tprivate final double[] LUT;\n\n\t/**\n\t * Watch out: Locations are margin-based (not 0-based)\n\t */\n\tpublic NTuple(int numValues, int[] locations, double[] weights) {\n\t\tPreconditions.checkArgument(locations.length > 0);\n\t\tPreconditions.checkArgument(weights.length == computeNumWeights(numValues, locations.length));\n\t\t// I do not copy this arrays, because some of them may be shared among NTuples (symmetry expander)!\n\t\tthis.numValues = numValues;\n\t\tthis.locations = locations;\n\t\tthis.LUT = weights;\n\t}\n\n\tpublic static NTuple newWithRandomWeights(int numValues, int[] locations, double minWeight, double maxWeight,\n\t\t\tRandomDataGenerator random) {\n\t\tPreconditions.checkArgument(locations.length > 0);\n\t\tdouble[] weights = new double[NTuple.computeNumWeights(numValues, locations.length)];\n\n\t\tweights = RandomUtils.randomDoubleVector(weights.length, minWeight, maxWeight, random);\n\n\t\treturn new NTuple(numValues, locations, weights);\n\t}\n\n\t/**\n\t * Copy constructor\n\t */\n\tpublic NTuple(NTuple template) {\n\t\tthis(template.numValues, template.locations.clone(), template.LUT.clone());\n\t}\n\n\tpublic double valueFor(Board board) {\n\t\treturn LUT[address(board)];\n\t}\n\n\tpublic int address(Board board) {\n\t\tint address = 0;\n\t\tfor (int location : locations) {\n\t\t\taddress *= numValues;\n\t\t\t// Here we assume that board values are in [-1, numValues-2] range\n\t\t\taddress += board.getValue(location); // HACKED. Above no longer true\n\t\t}\n\t\treturn address;\n\t}\n\n\t/**\n\t * @param address\n\t * @return actual values e.g. [-1, 0, 1] for a given address (5). Could be static in principle\n\t */\n\tpublic int[] valuesFromAddress(int address) {\n\t\tint[] val = new int[getSize()];\n\t\tfor (int i = getSize() - 1; i >= 0; --i) {\n\t\t\tval[i] = address % numValues - 1;\n\t\t\taddress = address / numValues;\n\t\t}\n\t\tthrow new RuntimeException();// HACK\n\t\t// return val;\n\t}\n\n\t/**\n\t * weights are not cloned, because I use this method for sharing weights among ntuples. Right, this could be done\n\t * better (TODO)\n\t */\n\tpublic double[] getWeights() {\n\t\treturn LUT;\n\t}\n\n\tpublic int getNumWeights() {\n\t\treturn LUT.length;\n\t}\n\n\tpublic int[] getLocations() {\n\t\treturn locations.clone();\n\t}\n\n\tpublic int getSize() {\n\t\treturn locations.length;\n\t}\n\n\tpublic int getNumValues() {\n\t\treturn numValues;\n\t}\n\n\tstatic int computeNumWeights(int numValues, int numFields) {\n\t\treturn (int) (Math.pow(numValues, numFields) + 0.5);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn new HashCodeBuilder().append(locations).append(LUT).append(numValues).toHashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tNTuple other = (NTuple) obj;\n\t\treturn new EqualsBuilder().append(locations, other.locations).append(LUT, other.LUT)\n\t\t\t.append(numValues, other.numValues).isEquals();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"loc=[\" + Joiner.on(\",\").join(ArrayUtils.toObject(locations)) + \"]\";\n\t}\n\n\tpublic String toStringDetailed() {\n\t\tString s = \"loc=[\" + Joiner.on(\",\").join(ArrayUtils.toObject(locations)) + \"]\\n\";\n\t\tfor (int i = 0; i < getNumWeights(); ++i) {\n\t\t\tint[] values = valuesFromAddress(i);\n\t\t\ts += \" \" + Joiner.on(\",\").join(ArrayUtils.toObject(values)) + \":\\t\" + String.format(\"%5.1f\", LUT[i]) + \"\\n\";\n\t\t}\n\t\treturn s;\n\t}\n}", "public class NTuples implements Iterable<NTuple>, Serializable, RealFunction {\n\n\t/** A class helping in building NTuples object */\n\tpublic static class Builder {\n\t\tprivate final List<NTuple> tuples = new ArrayList<NTuple>();\n\n\t\tprivate final SymmetryExpander expander;\n\n\t\tpublic Builder(SymmetryExpander expander) {\n\t\t\tthis.expander = expander;\n\t\t}\n\n\t\tpublic void add(NTuple tuple) {\n\t\t\ttuples.add(tuple);\n\t\t}\n\n\t\tpublic NTuples build() {\n\t\t\treturn new NTuples(tuples, expander);\n\t\t}\n\t}\n\n\tprivate static final long serialVersionUID = -3843856387088040436L;\n\n\t// AllNTuples contain tuples equal to mainNTuples (those are different objects, but are exactly equal).\n\t// Moreover, the weights (LUT) are shared between allNTuples and mainNTuples.\n\tprivate final List<NTuple> allNTuples;\n\tprivate final List<NTuple> mainNTuples;\n\n\tprivate final SymmetryExpander symmetryExpander;\n\n\t/** No symmetry */\n\tpublic NTuples(List<NTuple> tuples) {\n\t\tthis(tuples, new IdentitySymmetryExpander());\n\t}\n\n\tpublic NTuples(NTuples ntuples) {\n\t\tthis(ntuples.mainNTuples, ntuples.symmetryExpander);\n\t}\n\n\t/** Creates a n-tuples system where each tuple from tuples is expanded by expander */\n\tpublic NTuples(List<NTuple> tuples, SymmetryExpander expander) {\n\t\t// Defensive copy\n\t\tmainNTuples = new ArrayList<NTuple>();\n\t\tfor (NTuple tuple : tuples) {\n\t\t\tmainNTuples.add(new NTuple(tuple));\n\t\t}\n\t\tthis.allNTuples = new ArrayList<>();\n\t\tfor (NTuple mainTuple : mainNTuples) {\n\t\t\tList<NTuple> symmetric = createSymmetric(mainTuple, expander);\n\t\t\tassert symmetric.get(0).equals(mainTuple);\n\t\t\tallNTuples.addAll(symmetric);\n\t\t}\n\t\tthis.symmetryExpander = expander;\n\t}\n\n\tpublic NTuples add(NTuples other) {\n\t\treturn new NTuples(concat(getAll(), other.getAll()));\n\t}\n\n\tpublic List<NTuple> getMain() {\n\t\treturn mainNTuples;\n\t}\n\n\tpublic List<NTuple> getAll() {\n\t\treturn allNTuples;\n\t}\n\n\tpublic NTuple getTuple(int idx) {\n\t\treturn allNTuples.get(idx);\n\t}\n\n\tpublic int totalWeights() {\n\t\treturn weights().length;\n\t}\n\n\tpublic double[] weights() {\n\t\tDoubleArrayList weights = new DoubleArrayList();\n\t\tfor (NTuple tuple : mainNTuples) {\n\t\t\tweights.add(tuple.getWeights());\n\t\t}\n\t\treturn weights.toArray();\n\t}\n\n\tpublic SymmetryExpander getSymmetryExpander() {\n\t\treturn symmetryExpander;\n\t}\n\n\t@Override\n\tpublic Iterator<NTuple> iterator() {\n\t\treturn allNTuples.iterator();\n\t}\n\n\tpublic int size() {\n\t\treturn allNTuples.size();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(allNTuples);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tNTuples other = (NTuples) obj;\n\t\treturn allNTuples.equals(other.allNTuples);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"NTuples [mainNTuples=\" + mainNTuples + \", symmetryExpander=\" + symmetryExpander + \"]\";\n\t}\n\n\t@Override\n\tpublic double getValue(double[] input) {\n\t\tDefaultNTupleEvaluator evaluator = new DefaultNTupleEvaluator();\n\n\t\treturn evaluator.evaluate(this, new Game2048Board(input));\n\t}\n\n\t@Override\n\tpublic void update(double[] input, double expectedValue, double learningRate) {\n\t\tDefaultNTupleEvaluator evaluator = new DefaultNTupleEvaluator();\n\n\t\tdouble val = evaluator.evaluate(this, new Game2048Board(input));\n\n\t\tdouble error = expectedValue - val;\n\n\t\tdouble delta = error * learningRate;\n\n Game2048Board board = new Game2048Board(input);\n\t\tfor (NTuple tuple : getAll()) {\n\t\t\ttuple.getWeights()[tuple.address(board)] += delta;\n\t\t}\n\t}\n}", "public interface SymmetryExpander {\r\n\r\n\t/**\r\n\t * Returns an array of locations expanded by the inherent symmetry of the board. The expanded locations can (and\r\n\t * should sometimes, e.g. for the middle locations in Othello). Have to always return the same number of symmetries.\r\n\t *\r\n\t * @return the first element has to be the original location.\r\n\t **/\r\n\tpublic int[] getSymmetries(int location);\r\n\r\n\t/**\r\n\t * Number of symmetric expansions for the given symmetry expander. >0\r\n\t */\r\n\tpublic int numSymmetries();\r\n}\r", "public class SerializationException extends Exception {\n\n\tprivate static final long serialVersionUID = 2369185289909583646L;\n\n\tpublic SerializationException() {\n\t\tsuper();\n\t}\n\n\tpublic SerializationException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic SerializationException(String message, Throwable e) {\n\t\tsuper(message, e);\n\t}\n}", "public interface SerializationInput extends AutoCloseable {\n\n\tint readInt() throws IOException;\n\n\tlong readLong() throws IOException;\n\n\tString readString() throws IOException;\n\n\tdouble readDouble() throws IOException;\n\n\tint available() throws IOException;\n}", "public final class SerializationManager {\n\n\tprivate static final Logger logger = Logger.getLogger(SerializationManager.class);\n\n\tprivate final Map<Type, ObjectSerializer<? extends Object>> defaultSerializers = new HashMap<>();\n\tprivate final Map<Integer, ObjectSerializer<? extends Object>> deserializers = new HashMap<>();\n\n\t/**\n\t * Instantiate only using {@link SerializationManagerFactory#create()}\n\t */\n\tprotected SerializationManager() {\n\t\t// forbid direct construction\n\t}\n\n\tpublic SerializationManager(Iterable<ObjectSerializer<?>> serializers) throws SerializationException {\n\t\tfor (ObjectSerializer<?> serializer : serializers) {\n\t\t\tregister(serializer);\n\t\t}\n\t}\n\n\t/**\n\t * Registers serializer and deserializer. A warning is logged if serializer for the same type already existed\n\t */\n\tpublic <T> void register(ObjectSerializer<T> serializer) throws SerializationException {\n\t\tregisterSerializer(serializer);\n\t\tregisterDeserializer(serializer);\n\t}\n\n\t/**\n\t * Used to register old serializers. They will be used only for deserialization, never for serialization.\n\t */\n\tpublic <T> void registerAdditional(ObjectSerializer<T> serializer) throws SerializationException {\n\t\tregisterDeserializer(serializer);\n\t}\n\n\t/**\n\t * Allows to override any automatically registered serializers. Use with caution!\n\t */\n\tpublic <T> void registerOverride(ObjectSerializer<T> serializer) {\n\t\tObjectSerializer<?> previousSerializer = defaultSerializers\n\t\t\t.put(getSerializerObjectType(serializer), serializer);\n\t\tObjectSerializer<?> previousDeserializer = deserializers.put(serializer.getUniqueSerializerId(), serializer);\n\n\t\tif (previousSerializer != null) {\n\t\t\tlogger.warn(\"Overriding serializer: \" + previousSerializer + \" with: \" + serializer);\n\t\t}\n\t\tif (previousDeserializer != null) {\n\t\t\tlogger.warn(\"Overriding deserializer: \" + previousDeserializer + \" with: \" + serializer);\n\t\t}\n\t}\n\n\t/**\n\t * Unregister a serializer (and a deserializer). Unregistration is based on Serializer's id and generic param type.\n\t */\n\tpublic <T> void unregister(ObjectSerializer<T> serializer) {\n\t\tdefaultSerializers.remove(getSerializerObjectType(serializer));\n\t\tdeserializers.remove(serializer.getUniqueSerializerId());\n\t}\n\n\t/**\n\t * Serialize object to output\n\t */\n\tpublic <T> void serialize(T object, SerializationOutput output) throws SerializationException {\n\t\tPreconditions.checkNotNull(object);\n\t\tserialize(object, resolveSerializer(object.getClass()), output);\n\t}\n\n\tpublic <T> void serializeStream(Iterable<T> object, SerializationOutput output) throws SerializationException {\n\t\tfor (T o : object) {\n\t\t\tserialize(o, output);\n\t\t}\n\t}\n\n\t/**\n\t * Serialize object to a file using {@link SerializationManager#serialize(Object, File)} and wrap all exceptions\n\t * into a {@link RuntimeException}.\n\t */\n\tpublic <T> void serializeWrapExceptions(T object, File file) {\n\t\ttry {\n\t\t\tserialize(object, file);\n\t\t} catch (SerializationException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Serialize object to file with BinarySerializator.\n\t */\n\tpublic <T> void serialize(T object, File file) throws SerializationException {\n\t\tPreconditions.checkNotNull(object);\n\t\ttry (BinarySerializationOutput output = new BinarySerializationOutput(openOutputStream(file))) {\n\t\t\tserialize(object, output);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SerializationException(\"Cound to close file: \" + file.toString(), e);\n\t\t}\n\t}\n\n\t/**\n\t * Deserialize object from input and return it\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T deserialize(SerializationInput input) throws SerializationException {\n\t\ttry {\n\t\t\tint id = input.readInt();\n\t\t\tObjectSerializer<?> deserializer = deserializers.get(id);\n\t\t\tif (deserializer == null) {\n\t\t\t\tthrow new SerializationException(\"Deserializator with id \" + id + \" was not registered\");\n\t\t\t}\n\t\t\treturn (T) deserializer.load(this, input);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SerializationException(\"Failed to deserialize object\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Deserialize object from a file using {@link SerializationManager#deserialize(File)} and wrap all exceptions into\n\t * a {@link RuntimeException}.\n\t */\n\tpublic <T> T deserializeWrapExceptions(File file) {\n\t\ttry {\n\t\t\treturn deserialize(file);\n\t\t} catch (SerializationException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Deserialize object from file with BinarySerializator\n\t */\n\tpublic <T> T deserialize(File file) throws SerializationException {\n\t\ttry (BinarySerializationInput input = new BinarySerializationInput(openInputStream(file))) {\n\t\t\treturn deserialize(input);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SerializationException(\"Could not deserialize from file: \" + file.toString(), e);\n\t\t}\n\t}\n\n\t/**\n\t * Serialize with a explicitly given serializer. Just for testing.\n\t */\n\t<T> void serialize(T object, ObjectSerializer<T> serializer, SerializationOutput output)\n\t\t\tthrows SerializationException {\n\t\ttry {\n\t\t\toutput.writeInt(serializer.getUniqueSerializerId());\n\t\t\tserializer.save(this, object, output);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SerializationException(\"Could not serialize object\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Attempts to resolve a serializer by the class name. In case a dedicated serializer is not found, all of\n\t * interfaces implemented by the target class are scanned for registered default serializers. However, when multiple\n\t * top-level interface serializers are found, an exception is thrown as there is currently no way to accurately\n\t * choose the right one.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> ObjectSerializer<T> resolveSerializer(Class<? extends Object> clazz) throws SerializationException {\n\t\tObjectSerializer<T> serializer = (ObjectSerializer<T>) defaultSerializers.get(clazz);\n\t\tif (serializer != null) {\n\t\t\treturn serializer;\n\t\t}\n\t\tList<ObjectSerializer<T>> matchingSerializers = Lists.newArrayList();\n\t\tfor (Class<?> implementedInterface : getAllInterfaces(clazz)) {\n\t\t\tserializer = (ObjectSerializer<T>) defaultSerializers.get(implementedInterface);\n\t\t\tif (serializer != null) {\n\t\t\t\tmatchingSerializers.add(serializer);\n\t\t\t}\n\t\t}\n\t\tif (matchingSerializers.size() == 1) {\n\t\t\treturn matchingSerializers.iterator().next();\n\t\t}\n\t\tthrow new SerializationException(\"No serializer has been registered for type: \" + clazz\n\t\t\t+ \". Matching default interface serializers found: \" + matchingSerializers);\n\t}\n\n\tprivate <T> void registerSerializer(ObjectSerializer<T> serializer) {\n\t\tType type = getSerializerObjectType(serializer);\n\n\t\tif (defaultSerializers.containsKey(defaultSerializers.containsKey(type))) {\n\t\t\tlogger.warn(\"Registering serializer \" + serializer.getClass().getName()\n\t\t\t\t+ \" which overrides previously registered serializer for class \" + type);\n\t\t}\n\t\tdefaultSerializers.put(type, serializer);\n\t}\n\n\tprivate <T> void registerDeserializer(ObjectSerializer<T> serializer) throws SerializationException {\n\t\tif (deserializers.containsKey(serializer.getUniqueSerializerId())) {\n\t\t\tthrow new SerializationException(\"Cannot register \" + serializer.getClass().getName()\n\t\t\t\t+ \" because other serializer with this Id has been already registered for deserialization\");\n\t\t}\n\t\tdeserializers.put(serializer.getUniqueSerializerId(), serializer);\n\t}\n\n\t/**\n\t * Returns type of T in ObjectSerializer<T>\n\t */\n\tprivate <T> Class<?> getSerializerObjectType(ObjectSerializer<T> serializer) {\n\t\treturn TypeResolver.resolveRawArgument(ObjectSerializer.class, serializer.getClass());\n\t}\n}", "public interface SerializationOutput extends AutoCloseable {\n\tvoid writeInt(int value) throws IOException;\n\n\tvoid writeLong(long value) throws IOException;\n\n\tvoid writeString(String value) throws IOException;\n\n\tvoid writeDouble(double value) throws IOException;\n}" ]
import java.io.IOException; import java.util.List; import put.ci.cevo.games.encodings.ntuple.NTuple; import put.ci.cevo.games.encodings.ntuple.NTuples; import put.ci.cevo.games.encodings.ntuple.expanders.SymmetryExpander; import put.ci.cevo.util.serialization.ObjectSerializer; import put.ci.cevo.util.serialization.SerializationException; import put.ci.cevo.util.serialization.SerializationInput; import put.ci.cevo.util.serialization.SerializationManager; import put.ci.cevo.util.serialization.SerializationOutput; import put.ci.cevo.util.serialization.serializers.AutoRegistered;
package put.ci.cevo.games.serializers; @AutoRegistered(defaultSerializer = true) public final class NTuplesSerializer implements ObjectSerializer<NTuples> { @Override public void save(SerializationManager manager, NTuples object, SerializationOutput output) throws IOException, SerializationException { manager.serialize(object.getMain(), output); manager.serialize(object.getSymmetryExpander(), output); } @Override
public NTuples load(SerializationManager manager, SerializationInput input) throws IOException,
4
jboz/plantuml-builder
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
[ "public enum AssociationType {\n\n LINK(\"-\"),\n DIRECTION(\"-->\"),\n BI_DIRECTION(\"<->\"),\n INHERITANCE(\"<|--\");\n\n private String symbol;\n\n AssociationType(String symbol) {\n this.symbol = symbol;\n }\n\n @Override\n public String toString() {\n return symbol;\n }\n}", "public enum Cardinality {\n\n NONE(\"\"),\n MANY(\"*\"),\n ONE(\"1\");\n\n private String symbol;\n\n Cardinality(String symbol) {\n this.symbol = symbol;\n }\n\n @Override\n public String toString() {\n return symbol;\n }\n}", "public class SimpleAttribute implements Attribute {\n\n private String type;\n private String name;\n\n public SimpleAttribute(String name, String type) {\n this.type = type;\n this.name = name;\n }\n\n @Override\n public Optional<String> getTypeName() {\n return Optional.ofNullable(type);\n }\n\n @Override\n public String getName() {\n return name;\n }\n}", "public interface Clazz extends Comparable<Clazz> {\n\n public String getName();\n\n public Type getType();\n\n default public Optional<Link> getLink() {\n return Optional.empty();\n }\n\n public List<? extends Attribute> getAttributes();\n\n default public List<? extends Method> getMethods() {\n return new ArrayList<>();\n }\n\n default public Optional<List<String>> getStereotypes() {\n return Optional.empty();\n }\n\n default public Optional<String> getBackgroundColor() {\n return Optional.empty();\n }\n\n default public Optional<String> getBorderColor() {\n return Optional.empty();\n }\n\n default public void validate() {\n Validate.notNull(getName(), \"Class name must be defined !\");\n Validate.notNull(getType(), String.format(\"Class '%s' type must be defined !\", getName()));\n }\n\n @Override\n default int compareTo(Clazz clazz) {\n return getName().compareTo(clazz.getName());\n }\n\n default boolean hasContent() {\n return !getAttributes().isEmpty() || !getMethods().isEmpty();\n }\n\n enum Type {\n INTERFACE(\"interface\"),\n ENUM(\"enum\"),\n CLASS(\"class\"),\n ABSTRACT(\"abstract class\");\n\n private String name;\n\n Type(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n }\n}", "public class SimpleClazz implements Clazz {\n\n private String name;\n private Type type;\n private List<Attribute> attributes = new ArrayList<>();\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public Type getType() {\n return type;\n }\n\n @Override\n public List<Attribute> getAttributes() {\n return attributes;\n }\n\n public static SimpleClazz create(String name, Type type, Attribute... attributes) {\n SimpleClazz c = new SimpleClazz();\n c.name = name;\n c.type = type;\n Stream.of(attributes).forEach(c.attributes::add);\n return c;\n }\n}" ]
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType; import ch.ifocusit.plantuml.classdiagram.model.Cardinality; import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute; import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz; import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz; import org.junit.Test; import static org.fest.assertions.Assertions.*;
/*- * Plantuml builder * * Copyright (C) 2017 Focus IT * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package ch.ifocusit.plantuml; public class PlantUmlBuilderTest { private static final String CR = PlantUmlBuilder.NEWLINE; @Test public void buildInterface() { final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build(); assertThat(diagram).isEqualTo("interface \"Vehicule\"" + CR + CR); } @Test public void buildClassNoField() { final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Wheel", Clazz.Type.CLASS)).build(); assertThat(diagram).isEqualTo("class \"Wheel\"" + CR + CR); } @Test public void buildClassWithManyFields() { final String diagram = new PlantUmlBuilder() .addType(SimpleClazz.create("Car", Clazz.Type.CLASS, new SimpleAttribute("brand", "String"), new SimpleAttribute("wheels", "Collection<Wheel>"))) .build(); assertThat(diagram).isEqualTo("class \"Car\" {" + CR + " brand : String" + CR + " wheels : Collection<Wheel>" + CR + "}" + CR + CR); } @Test public void buildEnum() { final String diagram = new PlantUmlBuilder() .addType(SimpleClazz.create("Devise", Clazz.Type.ENUM, new SimpleAttribute("CHF", null), new SimpleAttribute("EUR", null), new SimpleAttribute("USD", null))) .build(); assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR + " CHF" + CR + " EUR" + CR + " USD" + CR + "}" + CR + CR); } @Test public void buildAssociations() throws Exception { String diagram = new PlantUmlBuilder()
.addAssociation("Vehicule", "Car", AssociationType.INHERITANCE)
0
asrulhadi/wap
src/java/org/homeunix/wap/XSS/OutputAnalysisXSS.java
[ "public class LinesToCorrect {\n String nameFile;\n Map<Integer, String> MapLinesToCorrect;\n Map<Integer, String[]> MapLinesToCorrectArray;\n\n \n public LinesToCorrect (String filename){\n this.nameFile = filename;\n MapLinesToCorrect = new LinkedHashMap<Integer, String>();\n }\n\n public LinesToCorrect (String filename, Boolean array){\n this.nameFile = filename;\n MapLinesToCorrectArray = new LinkedHashMap<Integer, String[]>();\n }\n \n public Map getMapLinesToCorrect (){\n return MapLinesToCorrect;\n }\n\n public Map getMapLinesToCorrectArray (){\n return MapLinesToCorrectArray;\n }\n \n public String getNameFile(){\n return nameFile;\n }\n \n}", "public class GlobalDataApp {\n /**\n * args Flags\n * index 0: presence of -a\n * analysis without automatic correction\n * index 1: presence of -p\n * analysis of a project\n * index 2: presence of files\n * analysis of one or more php files\n * index 3: presence of -sqli\n * SQLI analysis\n * index 4: presence of -out\n * stdout forward to output file\n * index 5: presence of -s\n * show only global summary\n * index 6: presence of -ci\n * RFI/LFI/DT SCD, OS, Eval analysis \n * index 7: presence of -xss\n * XSS Reflected, Store and DOM??\n * index 8: presence of --dbms <dbms>\n * select DBMS: db2, PostgreSQL, MySQL. If not specify any, MySQL is selected\n * -dbms mysql; -dbms bd2; -dbms pg\n * index 9: presence of -all\n * presence of all types of detection\n */\n public static int args_flags[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n public static int numAnalysis = 0;\n public static String dbms = \"mysql\";\n public static Classifier cf_lr;\n public static Classifier cf_rt;\n public static Classifier cf_svm;\n public static Classifier cf_jrip;\n public static JRip jrip;\n public static Boolean isWindows = false;\n\n /*\n * Load dataset and build classifier to data mining\n */\n public static Classifier loadClassifier(String nameClassifier) throws IOException{ \n Classifier javaml = null;\n \n /* Load the data set */\n // VERSAO FINAL\n Dataset data;\n if (nameClassifier.equals(\"svm\") == true)\n data = FileHandler.loadDataset(new File(\"data\" + File.separator + \"dataset_balanced.data\"), 15, \",\");\n else\n data = FileHandler.loadDataset(new File(\"data\" + File.separator + \"dataset.data\"), 15, \",\");\n \n \n //Dataset data = FileHandler.loadDataset(new File(\"..\" + File.separator + \"data\" + File.separator + \"dataset.data\"), 15, \",\");\n \n // Create Weka classifier\n if (nameClassifier.equals(\"lr\") == true){\n Logistic lr = new weka.classifiers.functions.Logistic();\n lr.setDebug(false);\n lr.setMaxIts(-1);\n lr.setRidge(1.0E-8);\n\n // Wrap Weka classifier in bridge \n Classifier javaml_lr = new WekaClassifier(lr);\n \n // Build the classifier \n javaml_lr.buildClassifier(data);\n javaml = javaml_lr;\n }\n \n // Create Weka classifier\n if (nameClassifier.equals(\"rt\") == true){\n RandomTree rt = new weka.classifiers.trees.RandomTree();\n rt.setKValue(0);\n rt.setDebug(false);\n rt.setMaxDepth(0);\n rt.setMinNum(1.0);\n rt.setSeed(1);\n \n // Wrap Weka classifier in bridge \n Classifier javaml_rt = new WekaClassifier(rt);\n \n // Build the classifier \n javaml_rt.buildClassifier(data);\n javaml = javaml_rt;\n }\n \n // Create Weka classifier\n if (nameClassifier.equals(\"jrip\") == true){\n jrip = new weka.classifiers.rules.JRip();\n jrip.setCheckErrorRate(true);\n jrip.setDebug(false);\n jrip.setFolds(3);\n jrip.setMinNo(2.0);\n jrip.setOptimizations(2);\n jrip.setSeed(1);\n jrip.setUsePruning(true);\n \n \n // Wrap Weka classifier in bridge \n Classifier javaml_jrip = new WekaClassifier(jrip);\n \n // Build the classifier \n javaml_jrip.buildClassifier(data);\n javaml = javaml_jrip;\n } \n\n // Create Weka classifier\n if (nameClassifier.equals(\"svm\") == true){\n // SMOTE filter applied to dataset\n /*\n SMOTE smote = new weka.filters.supervised.instance.SMOTE();\n smote.setClassValue(\"Yes\");\n smote.setNearestNeighbors(5);\n smote.setPercentage(100.0);\n smote.setRandomSeed(1);\n */\n \n //kernel\n PolyKernel kernel = new weka.classifiers.functions.supportVector.PolyKernel();\n kernel.setCacheSize(250007);\n kernel.setExponent(1.0); \n \n SMO svm = new weka.classifiers.functions.SMO();\n svm.setBuildLogisticModels(false);\n svm.setC(1.0);\n svm.setChecksTurnedOff(false);\n svm.setDebug(false);\n svm.setEpsilon(1.0E-12);\n svm.setNumFolds(-1);\n svm.setRandomSeed(1);\n svm.setToleranceParameter(0.001);\n //svm.setFilterType(0);\n svm.setKernel(kernel);\n \n // Wrap Weka classifier in bridge \n Classifier javaml_svm = new WekaClassifier(svm);\n \n // Build the classifier \n javaml_svm.buildClassifier(data);\n javaml = javaml_svm;\n } \n \n return javaml;\n }\n}", "public class ManageFiles{\n private File f;\n\n // *** CONSTRUCTORS\n public ManageFiles (String filename){\n //super(filename);\n f = new File(filename);\n }\n\n\n // *** METHODS\n /*\n * give base directory of te file\n */\n public File getBaseDir(){\n File baseDir = new File(f.getParent());\n return baseDir;\n }\n \n /*\n * Give just the name of the file\n */\n public File getFileName(){\n File f1 = new File (f.getName());\n return f1;\n }\n\n /*\n * Give all name of the file (path and name)\n */\n public File getAllFile(){\n File f1 = new File(this.getBaseDir().toString(),this.getFileName().toString());\n return f1;\n }\n\n /*\n * Verify if file exist\n */\n public Boolean existFile(String filename){\n if (f.exists())\n return true;\n else{\n //String s = \"File or directory not found... \" + filename;\n //System.out.println(s);\n return false;\n }\n }\n\n /*\n * Verify if directory exist\n */\n public Boolean existDirectory(String filename){\n if (f.isDirectory() && f.exists())\n return true;\n else{\n //String s = \"File or directory not found... \" + filename;\n //System.out.println(s);\n return false;\n }\n }\n \n /*\n * Verify if extension of file is php, Php or PHP\n */\n public Boolean validExtension(String filename, int IsSearchFile){\n // .inc include file\n // faltam: .tpl template; .cgi script Perl/C\n String Extensions[] = {\".php\", \".phps\", \".php3\", \".php4\", \".php5\", \".phtml\", \".inc\", \".phpsec\"};\n List<String> ValidExtensionsPhp = Arrays.asList(Extensions);\n\n int dotPos = filename.lastIndexOf(\".\");\n if(dotPos == -1)\n return false;\n else{\n String extensionFile = (filename.substring(dotPos)).toLowerCase();\n //if (extension.equals(\".php\") == false && extension.equals(\".PHP\") == false && extension.equals(\".Php\") == false){\n //if (extension.equalsIgnoreCase(\".php\") == false){\n if (ValidExtensionsPhp.contains(extensionFile) == false){\n if (IsSearchFile == 0){\n String s = \"Type of file not permited... \\n\" + extensionFile;\n System.out.println(s);\n }\n return false;\n }\n else\n return true;\n }\n\n }\n\n /*\n * Search php files in directory specified by user.\n * This method is recursive\n */\n public void searchPhpFiles(List lista){\n File l[] = this.getAllFile().listFiles();\n for(int i=0; i<l.length; i++){\n if (l[i].isFile() == true){\n ManageFiles aux = new ManageFiles(l[i].toString());\n if (aux.validExtension(l[i].toString(), 1) == true){\n lista.add(l[i].toString());\n }\n }\n if (l[i].isDirectory() == true){\n ManageFiles aux = new ManageFiles(l[i].toString());\n aux.searchPhpFiles(lista);\n }\n\n }\n }\n\n /*\n * Search the index.php file in list of files of the project directory\n */\n public void searchIndexPhp(List<String> lista){ \n for(int i=0; i<lista.size(); i++){\n String au = lista.get(i).toString();\n String[] a;\n if (GlobalDataApp.isWindows.booleanValue() == true)\n a = au.split(Pattern.quote(File.separator));\n else\n a = au.split(File.separator);\n String[] b = (a[(a.length)-1].toUpperCase()).split(\".PHP\"); \n if(b[0].equalsIgnoreCase(\"INDEX\") == true){\n String aux = lista.get(0).toString();\n lista.set(0, lista.get(i).toString());\n lista.set(i, aux);\n break;\n }\n }\n }\n\n public String composePathFile(String s, File baseDir) throws IOException{\n String final_file = \"\";\n\n if (s.startsWith(\"\\\"\") || s.startsWith(\"\\'\"))\n s = s.substring(1, s.length()-1);\n \n File ff = new File(s);\n File base;\n if (ff.exists() == false){ // Se a path do file nao e' passada toda no include \n String a[];\n if (GlobalDataApp.isWindows.booleanValue() == true)\n a = s.split(Pattern.quote(File.separator));\n else\n a = s.split(File.separator);\n base = new File(baseDir.toString());\n File b[] = base.listFiles();\n\n if (a.length == 0){ // se passou somente path sem file no include\n String ss = \"File not specified in \\\"include\\\" instruction\";\n System.out.println(ss);\n }\n else {\n int cont = 0;\n for (String aux : a){\n if (aux.equals(\"..\") == true)\n cont++;\n }\n if (cont == 0){\n if (a[0].equals(\".\") == true){ // se passou o file relativo a base.dir\n String aux = s.substring(2);\n final_file = base.toString() + File.separator + aux;\n }\n else // se passou no include uma path de subdirs de base.dir\n final_file = base.toString() + File.separator + s;\n }\n else{ // se passou no include uma path de subdirs atras de base.dir\n String[] c;\n if (GlobalDataApp.isWindows.booleanValue() == true)\n c = base.toString().split(Pattern.quote(File.separator));\n else\n c = base.toString().split(File.separator);\n \n //String c[] = base.toString().split(File.separator);\n String d = File.separator;\n int i;\n for (i=0; i < c.length - cont; i++)\n d = d + c[i] + File.separator;\n\n for (i = cont; i < a.length - 1; i++)\n d = d + a[i] + File.separator;\n\n final_file = d + a[a.length-1];\n } // if (cont == 0){\n } // if (a.length == 0)\n }\n else {// if (ff.exists())\n final_file = s;\n }\n \n if (final_file.isEmpty() == false){\n //System.out.println(\"File not found...\");\n //else{\n ff = new File(final_file);\n if (ff.exists() == false){\n //System.out.println(\"File not found...\" + final_file);\n final_file = \"\";\n }\n }\n \n return final_file;\n }\n\n public int getNumberLinesFile() throws FileNotFoundException{\n String line = \"\";\n int count = 0;\n Scanner fscanner = new Scanner(new FileReader(this.f.toString()));\n while (fscanner.hasNextLine()) {\n line = fscanner.nextLine();\n count += 1;\n }\n fscanner.close();\n return count;\n }\n\n public String getLineOfCode(int line){\n String codeLine = \"\";\n Scanner fscanner = null;\n try {\n fscanner = new Scanner(new FileReader(this.f.toString()));\n\n\n for (int jj=1; jj<=line;jj++){\n codeLine = fscanner.nextLine();\n }\n \n String aux = codeLine;\n codeLine = \"\";\n while (aux.lastIndexOf(';') == -1){\n if (codeLine.isEmpty() == true)\n codeLine += aux.trim();\n else\n codeLine += \" \" + aux.trim();\n aux = fscanner.nextLine();\n }\n\n if (codeLine.isEmpty())\n codeLine = aux;\n else\n codeLine += \" \" + aux.trim();\n\n fscanner.close();\n } catch (Exception e){} \n\n return codeLine;\n }\n\n /*\n * clean html code from a given file\n */\n public String cleanHTML(String f) throws FileNotFoundException, IOException{\n String[] filename;\n if (GlobalDataApp.isWindows.booleanValue() == true)\n filename = f.split(Pattern.quote(File.separator));\n else\n filename = f.split(File.separator); \n \n //String[] filename = f.split(File.separator);\n String[] filename_parts = filename[filename.length-1].split(\"[.]\");\n\n InputStream in = new FileInputStream(f);\n Scanner fscanner = new Scanner(in);\n String temp_file = this.getBaseDir().toString() + File.separator + filename_parts[0] + \"_000.\" +filename_parts[1];\n File out = new File(temp_file);\n FileWriter outFile = new FileWriter(out);\n\n String aux[], auxx = null;\n Boolean firstOpen_bodyString = false;\n Boolean close_bodyString = false;\n Boolean more_bodyString = false;\n int lineLastClose = 0;\n \n Pattern open = Pattern.compile(\"<[?]\"+\"php\");\n Pattern open1 = Pattern.compile(\"<[?]\");\n Pattern close = Pattern.compile(\"[?]>\");\n Matcher matcher_open;\n Matcher matcher_open1;\n Matcher matcher_close;\n\n String s = null, s1 = null, codeLine;\n int countLines = 0, blankLines = 0;\n \n for (; fscanner.hasNextLine();) {\n codeLine = fscanner.nextLine();\n countLines++; \n matcher_open = open.matcher(codeLine);\n matcher_open1 = open1.matcher(codeLine);\n matcher_close = close.matcher(codeLine);\n\n if ((matcher_open.find() || matcher_open1.find()) && !matcher_close.find()){ \n if (firstOpen_bodyString == false){\n firstOpen_bodyString=true;\n close_bodyString = false;\n outFile.write(codeLine+\"\\n\");\n }\n else{\n more_bodyString = true;\n close_bodyString = false;\n if (matcher_open.find())\n aux = open.split(codeLine);\n else\n aux = open1.split(codeLine);\n\n if (aux.length <= 1)\n outFile.write(\"\\n\");\n else{\n if (aux[1].startsWith(\"php\")){\n aux = aux[1].split(\"php\");\n try{\n outFile.write(aux[1] + \"\\n\");\n }catch (Exception e) {\n outFile.write(\"\\n\");\n }\n }\n else{\n if (aux[1].startsWith(\" \")){\n try{\n outFile.write(aux[1] + \"\\n\");\n }catch (Exception e) {\n outFile.write(\"\\n\");\n } \n }\n }\n }\n }\n }\n else{ \n if (matcher_open.find() || matcher_open1.find()) {\n lineLastClose = countLines;\n if (matcher_open.find())\n aux = open.split(codeLine);\n else\n aux = open1.split(codeLine);\n \n if (aux[1].startsWith(\"php \"))\n auxx = aux[1].substring(3);\n else\n auxx = aux[1];\n\n aux = close.split(auxx);\n if (!aux[0].endsWith(\";\"))\n aux[0] = aux[0] + \";\"; \n \n if (firstOpen_bodyString == false){\n // s = \"<?php \" + aux[0] + \" ?>\" + \"\\n\";\n s = \"<?php \" + aux[0];\n outFile.write(s + \"\\n\");\n firstOpen_bodyString = true;\n close_bodyString = true;\n }\n else{\n more_bodyString = false;\n close_bodyString = true;\n outFile.write(aux[0] + \"\\n\");\n }\n }\n else{\n if(matcher_close.find()){\n lineLastClose = countLines;\n //if (more_bodyString == true)\n more_bodyString = false;\n //else\n close_bodyString = true;\n\n aux = close.split(codeLine);\n try{\n outFile.write(aux[0] + \"\\n\");\n } catch (Exception e) {\n outFile.write(\"\\n\");\n }\n\n }\n else{\n if ((more_bodyString == true || close_bodyString == false) && firstOpen_bodyString == true)\n outFile.write(codeLine+\"\\n\");\n else{\n outFile.write(\"\\n\");\n blankLines++;\n }\n }\n }\n }\n }\n\n\n fscanner.close();\n outFile.close();\n\n // Para escrever a tag end_php na linha que aparece por ultimo\n in = new FileInputStream(temp_file);\n fscanner = new Scanner(in);\n String final_file = this.getBaseDir().toString() + File.separator + filename_parts[0] + \"_0.\" +filename_parts[1];\n out = new File(final_file);\n outFile = new FileWriter(out); \n countLines = 0;\n for (; fscanner.hasNextLine();) {\n codeLine = fscanner.nextLine();\n countLines++;\n if (countLines == lineLastClose)\n outFile.write(codeLine + \"?>\\n\");\n else\n outFile.write(codeLine + \"\\n\");\n } \n fscanner.close();\n outFile.close();\n File t = new File(temp_file);\n t.delete();\n \n \n if (countLines == blankLines){\n out = new File(final_file);\n outFile = new FileWriter(out);\n outFile.write(\"<?php\\n\");\n outFile.write(\"?>\\n\");\n outFile.close();\n }\n return final_file;\n } \n \n \n /*\n * Replace reserved words in variable names to keyword_00\n */\n public String keywordTo00(String ori, String html_clear) throws FileNotFoundException, IOException{\n String final_file = ori;\n\n // KeyWords\n String ReservedWords[] = {\"case\", \"if\", \"array\", \"list\", \"else\", \"elseif\", \"for\", \"foreach\", \"while\", \"do\",\n \"switch\", \"default\", \"function\", \"global\", \"and\", \"or\", \"xor\", \"instanceof\", \"return\", //};\n \"print\", \"public\"};\n List<String> KeyWords = Arrays.asList(ReservedWords);\n\n InputStream in = new FileInputStream(html_clear);\n Scanner fscanner = new Scanner(in);\n\n ArrayList<String> al = new ArrayList<String>();\n while( fscanner.hasNext() ) {\n String all = fscanner.nextLine();\n al.add(all);\n }\n fscanner.close();\n\n File out = new File(final_file);\n FileWriter outFile = new FileWriter(out);\n\n Pattern p = Pattern.compile(\"[a-zA-Z_0-9]\");\n Matcher mat;\n boolean b;\n String linef;\n int nline;\n\n for (String aux : KeyWords){\n nline = 0;\n for( String line : al ) {\n linef = \"\";\n if (line.contains(aux) == true){\n int indOf=0;\n while (indOf != -1){\n indOf = line.indexOf(aux);\n if (indOf != -1){\n if (indOf != 0){\n String[] a = line.split(aux);\n if (line.charAt(indOf-1) == '$'){\n try{\n char c = line.charAt(indOf + aux.length());\n mat = p.matcher(Character.toString(c));\n if (mat.matches() == false){\n linef = linef + a[0] + aux + \"_00\";\n }\n else\n linef = linef + a[0] + aux;\n } catch (Exception e){}\n line = line.substring(indOf + aux.length());\n }\n else{\n line = line.substring(indOf + aux.length());\n linef = linef + a[0] + aux;\n }\n }\n else{\n linef += aux;\n line = line.substring(aux.length());\n }\n\n }\n else\n linef += line;\n }\n al.set(nline, linef);\n }\n nline++;\n }\n }\n\n for( String line : al ) {\n outFile.write(line+\"\\n\");\n }\n outFile.close();\n\n return final_file;\n }\n\n /*\n * Process inverse of keywordTo00, ie, Replace keyword_00 to keyword\n */\n public void keywordFrom00(String html_clear) throws FileNotFoundException, IOException{\n // KeyWords_00\n String ReservedWords[] = {\"case_00\", \"if_00\", \"array_00\", \"list_00\", \"else_00\", \"elseif_00\", \"for_00\", \"foreach_00\",\n \"while_00\", \"do_00\", \"switch_00\", \"default_00\", \"function_00\", \"global_00\", \"and_00\",\n \"or_00\", \"xor_00\", \"instanceof_00\", \"return_00\", \"print_00\", \"public_00\"};\n List<String> KeyWords = Arrays.asList(ReservedWords);\n\n InputStream in = new FileInputStream(html_clear);\n Scanner fscanner = new Scanner(in);\n\n ArrayList<String> al = new ArrayList<String>();\n while( fscanner.hasNext() ) {\n String all = fscanner.nextLine();\n al.add(all);\n }\n fscanner.close();\n\n File out = new File(html_clear + \"_tmp\");\n FileWriter outFile = new FileWriter(out);\n\n Pattern p = Pattern.compile(\"[a-zA-Z_0-9]\");\n Matcher mat;\n boolean b;\n String linef;\n int nline;\n\n for (String aux : KeyWords){\n nline = 0;\n for( String line : al ) {\n linef = \"\";\n if (line.contains(aux) == true){\n int indOf=0;\n while (indOf != -1){\n indOf = line.indexOf(aux);\n if (indOf != -1){\n if (indOf != 0){\n String[] a = line.split(aux);\n if (line.charAt(indOf-1) == '$'){\n char c = line.charAt(indOf + aux.length());\n mat = p.matcher(Character.toString(c));\n if (mat.matches() == false){\n linef = linef + a[0] + aux.substring(0, aux.length()-4);\n }\n else\n linef = linef + a[0] + aux;\n line = line.substring(indOf + aux.length());\n }\n else{\n line = line.substring(indOf + aux.length());\n linef = linef + a[0] + aux;\n }\n }\n }\n else\n linef += line;\n }\n al.set(nline, linef);\n }\n nline++;\n }\n }\n\n for( String line : al ) {\n outFile.write(line+\"\\n\");\n }\n outFile.close();\n\n //Renomear file html_clear_tmp to html_clear\n File bb = new File(html_clear);\n out.renameTo(bb);\n }\n\n /*\n * replace the html code removed on begin of the process\n */\n public void putHtml(String ori, String html_clear) throws FileNotFoundException, IOException{\n InputStream in_ori = new FileInputStream(ori);\n Scanner fscanner_ori = new Scanner(in_ori);\n InputStream in_html = new FileInputStream(html_clear);\n Scanner fscanner_html = new Scanner(in_html);\n File out = new File(html_clear + \"_tmp\");\n FileWriter outFile = new FileWriter(out);\n\n int nline_html = 1;\n int nline_ori = 1;\n String line;\n while( fscanner_html.hasNext() ) {\n line = fscanner_html.nextLine();\n if (line.isEmpty() == false){\n outFile.write(line+\"\\n\");\n }\n else{\n for(int i = nline_ori; i<nline_html; i++)\n fscanner_ori.nextLine();\n line = fscanner_ori.nextLine();\n outFile.write(line+\"\\n\");\n nline_ori = nline_html+1;\n }\n nline_html++;\n }\n\n while( fscanner_ori.hasNext() ) {\n line = fscanner_ori.nextLine();\n outFile.write(line+\"\\n\");\n }\n fscanner_ori.close();\n fscanner_html.close();\n outFile.close();\n\n //Renomear file html_clear_tmp to html_clear\n File bb = new File(html_clear);\n out.renameTo(bb);\n\n }\n \n // copia file php em analise para Newfiles para podermos introduzir as correcoes no codigo\n public void copyFileToNewfiles(String targetDir, String targetName) throws FileNotFoundException, IOException{ \n InputStream source = new FileInputStream(this.getAllFile().toString());\n Scanner fscanner_source = new Scanner(source);\n File out = null;\n if (targetName == null){\n try{\n int ind = this.getAllFile().toString().lastIndexOf(File.separator);\n String s = this.getAllFile().toString().substring(0, ind);\n File dir = new File(targetDir + s);\n dir.mkdirs(); \n out = new File(targetDir + this.getAllFile().toString());\n } catch (Exception e) {}\n }\n else{\n try{\n int ind = targetName.lastIndexOf(File.separator);\n String s = targetName.substring(0, ind);\n File dir = new File(targetDir + s);\n dir.mkdirs(); \n out = new File(targetDir + targetName);\n } catch (Exception e) {}\n }\n \n FileWriter outFile = new FileWriter(out);\n String line;\n while( fscanner_source.hasNext() ) {\n line = fscanner_source.nextLine();\n outFile.write(line+\"\\n\");\n }\n fscanner_source.close();\n outFile.close();\n }\n \n // copia file php de improvements para Newfiles. Sao os files de codigo php para sanitizar inputs\n public void copyFileImprovement(String targetDir) throws FileNotFoundException, IOException{ \n File dest = new File(targetDir);\n dest.mkdirs();\n File src = new File(this.getAllFile().toString());\n\n // Copy files\n String[] l = src.list();\n for(int i=0; i < l.length; i++){\n InputStream source = new FileInputStream(src + File.separator + l[i]);\n Scanner fscanner_source = new Scanner(source);\n\n //File out = new File(src + File.separator + l[i] + \"_temp\");\n File out = new File(dest + File.separator + l[i]);\n FileWriter outFile = new FileWriter(out);\n String line;\n while( fscanner_source.hasNext() ) {\n line = fscanner_source.nextLine();\n outFile.write(line+\"\\n\");\n }\n fscanner_source.close();\n outFile.close();\n }\n }\n \n // Delete a no empty directory\n public Boolean deleteDir(File directory) {\n if (directory.isDirectory()) {\n String[] subDirs = directory.list();\n for (int i=0; i<subDirs.length; i++) {\n boolean success = deleteDir(new File(directory, subDirs[i]));\n if (!success) {\n return false;\n }\n }\n }\n\n // The directory is now empty so delete it\n return directory.delete();\n } \n}", "public class ListVulners {\n String nameFile;\n List<Vulner> LVulners;\n\n /* CONSTRUCTOR */\n public ListVulners(String f) {\n this.nameFile = f;\n LVulners = new ArrayList<Vulner>();\n }\n\n\n /* METHODS */\n public List getListOfVulners(){\n return LVulners;\n }\n\n public String getFilename(){\n return this.nameFile;\n }\n}", "public class SymbolTable implements Scope{\n String name;\n //Map<String, Symbol> symbols;\n List<Symbol> symbols;\n Boolean haveFunctions;\n Boolean haveClasses;\n List<String> includeFiles;\n Map <String, Symbol> aliases;\n Map <String, Symbol> globalVars;\n MethodTableCalls methodCallInstance; // para somente os StaticMemberAccees diferentes de self e parent\n MethodTaintedTable methTaintedInstance; // para somente os StaticMemberAccees diferentes de self e parent\n\n\n // *** CONSTRUCTORS\n public SymbolTable(String name) {\n this.name = name;\n //symbols = new LinkedHashMap<String, Symbol>();\n symbols = new ArrayList<Symbol>();\n haveFunctions = false;\n haveClasses = false;\n includeFiles = new ArrayList<String>();\n this.aliases = new LinkedHashMap<String, Symbol>();\n this.globalVars = new LinkedHashMap<String, Symbol>();\n\n // cria a tabela para as st dos StaticMemberAccees que serao chamados diferentes de self e parent\n methodCallInstance = new MethodTableCalls(name);\n\n // cria a tainted table para as chamadas dos StaticMemberAccees diferentes de self e parent\n methTaintedInstance = new MethodTaintedTable(name);\n }\n\n // *** METHODS\n\n // Satisfy Scope interface\n public String getScopeName() {\n \t//return \"global\";\n return name;\n }\n\n // am I nested in another?\n public Scope getEnclosingScope() {\n \treturn null;\n }\n\n /*\n * Give the Map that contain the Symbols of main Map\n * This symbols are root symbol the scopes CallSymbol (for Callfunction\n * or assign instrutions) or MethodSymbol (for user function definition)\n */\n public List getMembers() {\n return symbols;\n }\n\n /*\n * Give the root Symbol of the scope. In another words, give the symbol\n * that create a new scope.\n * Here, in main table of symbols, don't exist root symbol.\n */\n public Symbol getScopeSymbol() {\n \treturn null;\n }\n\n /*\n * Tell if file have functions definied by the programmer\n */\n public Boolean getHaveFunctions() {\n \treturn haveFunctions;\n }\n\n /*\n * Tell if file have classes definied by the programmer\n */\n public Boolean getHaveClasses() {\n \treturn haveClasses;\n }\n\n /*\n * Give the list of the include files that the analysed file have\n */\n public List<String> getIncludeFiles() {\n \treturn includeFiles;\n }\n\n /*\n * Give the Map of the alises defined inthe symbolTable\n */\n public Map getAliases(){\n return this.aliases;\n }\n\n public Map getGlobalVarsOfSymbolTable() {\n return globalVars;\n }\n\n public MethodTableCalls getMethodCallInstance() {\n return this.methodCallInstance;\n }\n\n public MethodTaintedTable getMethodTaintedInstance() {\n return this.methTaintedInstance;\n }\n \n public String getInstanceNameFromAliases(String s, InstanceTable instTab){\n String instName = \"\";\n boolean found = false;\n while (found == false){\n if (instTab.containsInstance(s) == true){\n instName = s;\n found = true;\n }\n else{\n if (this.getAliases().containsKey(s)){\n Symbol sym = (Symbol) this.getAliases().get(s);\n s = sym.getName();\n }\n }\n }\n return instName;\n }\n\n /*\n * Return a specific symbol\n */\n public Symbol getSymbolOfListSymbols(String symName){\n Symbol sym_final = null;\n Iterator <Symbol> it = this.getMembers().iterator();\n Symbol sym;\n for (;it.hasNext();){\n sym = it.next();\n if (sym.getName().equals(symName) == true){\n sym_final = sym;\n break;\n }\n }\n return sym_final;\n }\n\n /*\n * Tells if the symbols list contains a gived symbol\n */\n public Boolean containsSymbol(String symName){\n Iterator <Symbol> it = this.getMembers().iterator();\n Symbol sym;\n Boolean haveSymbol = false;\n for (;it.hasNext();){\n sym = it.next();\n if (sym.getName().equals(symName) == true){\n haveSymbol = true;\n break;\n }\n }\n return haveSymbol;\n }\n\n /*\n * Insert a root symbol (new scope) in main Map.\n */\n public void define(Symbol sym, Scope scp, Boolean IsVariableSymbol) {\n symbols.add(sym);\n sym.setRootScope(scp);\n sym.setScope(this);\n sym.setIsVariableSymbol(IsVariableSymbol);\n }\n\n /*\n * Set true if the analysed file have functions defined by user\n */\n public void setHaveFunctions(){\n haveFunctions = true;\n }\n\n /*\n * Set true if the analysed file have classes defined by user\n */\n public void setHaveClasses(){\n haveClasses = true;\n }\n \n public void setGlobalVarSymbolTable(String varName, Symbol gvar) {\n globalVars.put(varName, gvar);\n }\n\n /*\n * Set true if the analysed file have functions defined by user\n */\n public void setAllSymbols(List<Symbol> syms){\n symbols.addAll(syms);\n }\n \n /*\n * Set true if the analysed file have functions defined by user\n */\n public void setAllIncludeFiles(List<String> incs){\n includeFiles.addAll(incs);\n } \n\n /*\n * Not relevant here!\n */\n //public Boolean resolve(String name, TaintedTable mts, UntaintedTable mus) {\n public void resolveSymbol(Scope scp, Symbol sy, TaintedTable mts, UntaintedTable mus, String file){\n \t//return symbols.get(name);\n // return true;\n }\n\n\n public Boolean resolve(Symbol symb, TaintedTable mts, UntaintedTable mus) {\n return true;\n }\n \n /*\n * Move include file symbolTable from mst to mift\n */\n public void mvIncludeFiles(List fileList) throws IOException{\n for(Iterator <String> it1 = this.getIncludeFiles().iterator(); it1.hasNext();){\n String s = it1.next();\n if(GlobalDataApp.args_flags[3] == 1){\n if (GlobalDataSqli.MainSymbolTable.containsKey(s) == true){\n GlobalDataSqli.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataSqli.MainSymbolTable.get(s));\n GlobalDataSqli.MainSymbolTable.remove(s);\n }\n else{\n if (GlobalDataSqli.MainIncludeFilesTable.containsKey(s) == false){\n try {\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(s, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n \n // build walker tree to SQLI\n buildWalkerTree_sqli sqli = new buildWalkerTree_sqli(nodes, s, GlobalDataSqli.MainSymbolTable, GlobalDataSqli.MainIncludeFilesTable,\n GlobalDataSqli.MainFunctionsTable, GlobalDataSqli.MainFunctionsTaintedTable,\n GlobalDataSqli.MainTaintedTable, GlobalDataSqli.mus, GlobalDataSqli.MainLinesToCorrect,\n GlobalDataSqli.MainClassesTable, GlobalDataSqli.MainInstancesTable, fileList);\n \n GlobalDataSqli.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataSqli.MainSymbolTable.get(s));\n GlobalDataSqli.MainSymbolTable.remove(s);\n } catch (RecognitionException ex) {\n Logger.getLogger(SymbolTable.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }\n\n SymbolTable st_aux = GlobalDataSqli.MainIncludeFilesTable.get(s);\n if (st_aux.getIncludeFiles().isEmpty() == false){\n st_aux.mvIncludeFiles(fileList);\n }\n }\n\n if(GlobalDataApp.args_flags[6] == 1){\n if (GlobalDataCodeInj.MainSymbolTable.containsKey(s) == true){\n GlobalDataCodeInj.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataCodeInj.MainSymbolTable.get(s));\n GlobalDataCodeInj.MainSymbolTable.remove(s);\n }\n else{\n if (GlobalDataCodeInj.MainIncludeFilesTable.containsKey(s) == false){\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(s, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n\n // build walker tree to SQLI\n buildWalkerTree_CodeInj ci = new buildWalkerTree_CodeInj(nodes, s, GlobalDataCodeInj.MainSymbolTable, GlobalDataCodeInj.MainIncludeFilesTable,\n GlobalDataCodeInj.MainFunctionsTable, GlobalDataCodeInj.MainFunctionsTaintedTable,\n GlobalDataCodeInj.MainTaintedTable, GlobalDataCodeInj.mus, GlobalDataCodeInj.MainLinesToCorrect,\n GlobalDataCodeInj.MainClassesTable, GlobalDataCodeInj.MainInstancesTable, fileList); \n\n GlobalDataCodeInj.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataCodeInj.MainSymbolTable.get(s));\n GlobalDataCodeInj.MainSymbolTable.remove(s);\n }\n }\n\n SymbolTable st_aux = GlobalDataCodeInj.MainIncludeFilesTable.get(s);\n if (st_aux.getIncludeFiles().isEmpty() == false){\n st_aux.mvIncludeFiles(fileList);\n }\n }\n\n if(GlobalDataApp.args_flags[7] == 1){\n if (GlobalDataXSS.MainSymbolTable.containsKey(s) == true){\n GlobalDataXSS.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataXSS.MainSymbolTable.get(s));\n GlobalDataXSS.MainSymbolTable.remove(s);\n }\n else{\n if (GlobalDataXSS.MainIncludeFilesTable.containsKey(s) == false){\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(s, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n\n // build walker tree to SQLI\n buildWalkerTree_XSS xss = new buildWalkerTree_XSS(nodes, s, GlobalDataXSS.MainSymbolTable, GlobalDataXSS.MainIncludeFilesTable,\n GlobalDataXSS.MainFunctionsTable, GlobalDataXSS.MainFunctionsTaintedTable,\n GlobalDataXSS.MainTaintedTable, GlobalDataXSS.mus, GlobalDataXSS.MainLinesToCorrect,\n GlobalDataXSS.MainClassesTable, GlobalDataXSS.MainInstancesTable, fileList);\n\n GlobalDataXSS.MainIncludeFilesTable.put(s, (SymbolTable)GlobalDataXSS.MainSymbolTable.get(s));\n GlobalDataXSS.MainSymbolTable.remove(s);\n }\n }\n\n SymbolTable st_aux = GlobalDataXSS.MainIncludeFilesTable.get(s);\n if (st_aux.getIncludeFiles().isEmpty() == false){\n st_aux.mvIncludeFiles(fileList);\n }\n }\n } \n }\n\n \n \n /*\n * Move include file symbolTable from mst to mift\n */\n public void mvIncludeFiles(List fileList, String file) throws IOException{\n if(GlobalDataApp.args_flags[3] == 1){\n if (GlobalDataSqli.MainIncludeFilesTable.containsKey(file) == false){\n if (GlobalDataSqli.MainSymbolTable.containsKey(file) == true){ \n GlobalDataSqli.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataSqli.MainSymbolTable.get(file));\n GlobalDataSqli.MainSymbolTable.remove(file);\n }\n else{\n try {\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(file, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n \n // build walker tree to SQLI\n buildWalkerTree_sqli sqli = new buildWalkerTree_sqli(nodes, file, GlobalDataSqli.MainSymbolTable, GlobalDataSqli.MainIncludeFilesTable,\n GlobalDataSqli.MainFunctionsTable, GlobalDataSqli.MainFunctionsTaintedTable,\n GlobalDataSqli.MainTaintedTable, GlobalDataSqli.mus, GlobalDataSqli.MainLinesToCorrect,\n GlobalDataSqli.MainClassesTable, GlobalDataSqli.MainInstancesTable, fileList);\n \n GlobalDataSqli.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataSqli.MainSymbolTable.get(file));\n GlobalDataSqli.MainSymbolTable.remove(file);\n } catch (RecognitionException ex) {\n Logger.getLogger(SymbolTable.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n } \n }\n \n if(GlobalDataApp.args_flags[6] == 1){\n if (GlobalDataCodeInj.MainIncludeFilesTable.containsKey(file) == false){\n if (GlobalDataCodeInj.MainSymbolTable.containsKey(file) == true){\n GlobalDataCodeInj.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataCodeInj.MainSymbolTable.get(file));\n GlobalDataCodeInj.MainSymbolTable.remove(file);\n }\n else{\n try{\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(file, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n\n // build walker tree to Code Injection\n buildWalkerTree_CodeInj ci = new buildWalkerTree_CodeInj(nodes, file, GlobalDataCodeInj.MainSymbolTable, GlobalDataCodeInj.MainIncludeFilesTable,\n GlobalDataCodeInj.MainFunctionsTable, GlobalDataCodeInj.MainFunctionsTaintedTable,\n GlobalDataCodeInj.MainTaintedTable, GlobalDataCodeInj.mus, GlobalDataCodeInj.MainLinesToCorrect,\n GlobalDataCodeInj.MainClassesTable, GlobalDataCodeInj.MainInstancesTable, fileList); \n\n GlobalDataCodeInj.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataCodeInj.MainSymbolTable.get(file));\n GlobalDataCodeInj.MainSymbolTable.remove(file);\n } catch (Exception ex) {\n Logger.getLogger(SymbolTable.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n } \n } \n \n if(GlobalDataApp.args_flags[7] == 1){\n if (GlobalDataXSS.MainIncludeFilesTable.containsKey(file) == false){\n if (GlobalDataXSS.MainSymbolTable.containsKey(file) == true){\n GlobalDataXSS.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataXSS.MainSymbolTable.get(file));\n GlobalDataXSS.MainSymbolTable.remove(file);\n }\n else{\n try{\n // file include do not exists in mst and mift\n // Create AST\n buildAST ast = new buildAST(file, 0);\n CommonTreeNodeStream nodes = ast.getNodes();\n\n // build walker tree to XSS\n buildWalkerTree_XSS xss = new buildWalkerTree_XSS(nodes, file, GlobalDataXSS.MainSymbolTable, GlobalDataXSS.MainIncludeFilesTable,\n GlobalDataXSS.MainFunctionsTable, GlobalDataXSS.MainFunctionsTaintedTable,\n GlobalDataXSS.MainTaintedTable, GlobalDataXSS.mus, GlobalDataXSS.MainLinesToCorrect,\n GlobalDataXSS.MainClassesTable, GlobalDataXSS.MainInstancesTable, fileList); \n\n GlobalDataXSS.MainIncludeFilesTable.put(file, (SymbolTable)GlobalDataXSS.MainSymbolTable.get(file));\n GlobalDataXSS.MainSymbolTable.remove(file);\n } catch (Exception ex) {\n Logger.getLogger(SymbolTable.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n } \n } \n} \n \n\n /*\n * Print the elements of the main Map scope.\n */\n public void print(Scope scp){\n Symbol aux1;\n Scope s;\n if (!scp.getMembers().isEmpty()){\n System.out.println(\"\\nScope: \"+scp.getScopeName()+\"\\tsize=\"+scp.getMembers().size());\n Iterator <Symbol> it = scp.getMembers().iterator();\n for(; it.hasNext();){\n aux1 = it.next();\n if ( aux1.getRootScope() != null ) { // is a root of a new scope?\n s = aux1.getRootScope();\n s.print(s);\n }\n }\n }\n else{\n aux1 = scp.getScopeSymbol();\n System.out.println(\"Name: \"+aux1.getName()+\"\\t\\tline: \"+aux1.getCodeLine()+\"\\t\\ttainted: \"\n +aux1.getTainted()+\"\\t\\tScope: \"+aux1.getScope().getScopeName()+\"\\n\");\n }\n }\n\n\n @Override\n public String toString() {\n \treturn getScopeName()+\":\"+symbols;\n }\n\n public void resolveSymbolIncludeSQLI(Scope scp, TaintedTable mts, UntaintedTable mus, Map mift, String filename, Map mft, Map mst, Map varsDB, Map mftt, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public String resolveVarInclude(Scope scp, SymbolTable st) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolFunctionSQLI(MethodSymbol mt, Scope rootScope, TaintedTable mts, UntaintedTable mus, Map mift, String filename, Map mft, Map mst, Map varsDB, Map mftt, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public Boolean verifyNumberVarList(int num_var){\n throw new UnsupportedOperationException(\"Not supported yet.\"); \n }\n \n public void populateList(Scope scp_left, Scope scp_right, int num_var, TaintedTable mts, UntaintedTable mus, String filename){\n throw new UnsupportedOperationException(\"Not supported yet.\"); \n }\n\n public String buildCorrectSQL(String connDB, String nameDB, int lineMysqliBindParam, List UserInput, TaintedTable mts_princ, SymbolTable st, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public Boolean buildCorrectCodeInj(String fileInc, List UserInput, TaintedTable mts_princ, SymbolTable st, Map MainLinesToCorrect){\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolClass(TaintedTable mts, UntaintedTable mus, String filename) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void printtt(String string, Scope cp){\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolParam(TaintedTable mts, UntaintedTable mus, String filename) {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n public void resolveParam(Symbol symb, TaintedTable mts, UntaintedTable mus) {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n}", "public class MethodTable implements Scope{\n String name;\n List<MethodSymbol> methods;\n \n\n // *** CONSTRUCTORS\n public MethodTable(String name) {\n this.name = name;\n //symbols = new LinkedHashMap<String, Symbol>();\n methods = new ArrayList<MethodSymbol>();\n }\n\n\n // *** METHODS\n\n // Satisfy Scope interface\n public String getScopeName() {\n return name;\n }\n\n // am I nested in another?\n public Scope getEnclosingScope() {\n \treturn null;\n }\n\n /*\n * Give the List that contain the methods (functions defined by user) of the file\n */\n public List getMembers() { \n return methods;\n }\n \n public List getMembersList() {\n return null;\n }\n\n /*\n * Give the root Symbol of the scope. In another words, give the symbol\n * that create a new scope.\n * Here, in main table of symbols, don't exist root symbol.\n */\n public Symbol getScopeSymbol() {\n \treturn null;\n }\n\n /*\n * Insert a root symbol (new scope) in main Map.\n */\n public void define(MethodSymbol meth) {\n methods.add(meth);\n }\n \n /*\n * Insert a root symbol (new scope) in main Map.\n */\n //public void define(Symbol sym, Scope scp, Boolean IsVariableSymbol) {\n public void define(MethodSymbol meth, Scope scp, Boolean IsVariableSymbol) { \n methods.add(meth);\n meth.setRootScope(scp);\n meth.setScope(this);\n meth.setIsVariableSymbol(IsVariableSymbol);\n }\n\n\n /*\n * Not relevant here!\n */\n //public Boolean resolve(String name, TaintedTable mts, UntaintedTable mus) {\n public void resolveSymbol(Scope scp, Symbol sy, TaintedTable mts, UntaintedTable mus, String file){\n \t//return symbols.get(name);\n // return true;\n }\n\n\n public Boolean resolve(Symbol symb, TaintedTable mts, UntaintedTable mus) {\n \t//return symbols.get(name);\n return true;\n }\n\n\n\n /*\n * Print the elements of the main Map scope.\n */\n public void print(Scope scp){\n Symbol aux1 = null;\n Scope s;\n if (!scp.getMembers().isEmpty()){\n System.out.println(\"\\nScope: \"+scp.getScopeName()+\"\\tsize=\"+scp.getMembers().size());\n Iterator <Symbol> it = scp.getMembers().iterator();\n for(; it.hasNext();){\n aux1 = it.next();\n //System.out.println(\"Name: \"+aux1.getName()+\"\\t\\tline: \"+aux1.getCodeLine()+\"\\t\\ttainted: \"\n // +aux1.getTainted()+\"\\t\\tScope: \"+aux1.getScope().getScopeName()+\"\\n\");\n if ( aux1.getRootScope() != null ) { // is a root of a new scope?\n s = aux1.getRootScope();\n s.print(s);\n }\n }\n }\n else{\n aux1 = scp.getScopeSymbol();\n System.out.println(\"Name: \"+aux1.getName()+\"\\t\\tline: \"+aux1.getCodeLine()+\"\\t\\ttainted: \"\n +aux1.getTainted()+\"\\t\\tScope: \"+aux1.getScope().getScopeName()+\"\\n\");\n }\n }\n\n @Override\n public String toString() {\n \treturn getScopeName()+\":\"+methods;\n }\n\n public void resolveSymbolIncludeSQLI(Scope scp, TaintedTable mts, UntaintedTable mus, Map mift, String filename, Map mft, Map mst, Map varsDB, Map mftt, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public String resolveVarInclude(Scope scp, SymbolTable st) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void define(Symbol sym, Scope scp, Boolean IsVariableSymbol) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolFunctionSQLI(MethodSymbol mt, Scope rootScope, TaintedTable mts, UntaintedTable mus, Map mift, String filename, Map mft, Map mst, Map varsDB, Map mftt, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public Boolean verifyNumberVarList(int num_var){\n throw new UnsupportedOperationException(\"Not supported yet.\"); \n }\n \n public void populateList(Scope scp_left, Scope scp_right, int num_var, TaintedTable mts, UntaintedTable mus, String filename){\n throw new UnsupportedOperationException(\"Not supported yet.\"); \n } \n \n public String buildCorrectSQL(String connDB, String nameDB, int lineMysqliBindParam, List UserInput, TaintedTable mts_princ, SymbolTable st, Map MainLinesToCorrect) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public Boolean buildCorrectCodeInj(String fileInc, List UserInput, TaintedTable mts_princ, SymbolTable st, Map MainLinesToCorrect){\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolClass(TaintedTable mts, UntaintedTable mus, String filename) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void printtt(String string, Scope cp){\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void resolveSymbolParam(TaintedTable mts, UntaintedTable mus, String filename) {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n public void resolveParam(Symbol symb, TaintedTable mts, UntaintedTable mus) {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n}", "public class MethodSymbol extends ScopedSymbol implements Cloneable{\n Boolean haveSubFunctions;\n String Progenitorfunction = \"\";\n Map <String, ArgFunctionSymbol> argsFunction;\n Map<String, Symbol> globalVars;\n List<Symbol> symbols;\n \n \n // ****** CONSTRUCTORS ***********\n public MethodSymbol(String function_name, int line, int tainted, Scope parent, String filename) {\n //this.functionName = fname;\n super (function_name, line, tainted, parent, filename);\n\thaveSubFunctions = false;\n argsFunction = new HashMap <String, ArgFunctionSymbol>();\n globalVars = new HashMap<String, Symbol>();\n //staticVars = new HashMap<String, Object>();\n symbols = new ArrayList<Symbol>(); //instructions of the function, except global instruction\n }\n \n \n // *** METHODS ********\n public String getFunctionName() {\n return this.getName();\n }\n\n public Boolean getHaveSubFunctions() {\n return haveSubFunctions;\n }\n \n public String getProgenitorFunction() {\n return this.Progenitorfunction;\n }\n \n public Map getArgsFunction() {\n return argsFunction;\n }\n \n \n public Map getGlobalVarsOfFunction() {\n return globalVars;\n }\n \n \n public void setFunctionName(String name) {\n this.setName(name);\n } \n \n public void setHaveSubFunctions() {\n this.haveSubFunctions = true;\n }\n \n public void setProgenitorFunction(String p) {\n this.Progenitorfunction = p;\n }\n \n public void setArgFunction(String argName, ArgFunctionSymbol arg) {\n argsFunction.put(argName, arg);\n }\n \n public void setGlobalVarFunction(String varName, Symbol gvar) {\n globalVars.put(varName, gvar);\n\n }\n\n public MethodSymbol copyMethodSymbol(MethodSymbol meth_sym, String function_name, int line, Scope parent, String filename) {\n MethodSymbol mt = new MethodSymbol(function_name, line, 0, parent, filename);\n Symbol sym;\n\n //copia o map de argumentos da funcao\n ArgFunctionSymbol arg;\n for(Iterator <ArgFunctionSymbol> it = meth_sym.getArgsFunction().values().iterator(); it.hasNext();){\n arg = it.next();\n try {\n mt.argsFunction.put(arg.getParamName(), (ArgFunctionSymbol) arg.clone());\n } catch (CloneNotSupportedException ex) {\n Logger.getLogger(MethodSymbol.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n \n //copia o map das vars globais da funcao\n for(Iterator <Symbol> it = meth_sym.getGlobalVarsOfFunction().values().iterator(); it.hasNext();){\n sym = it.next();\n try {\n mt.getGlobalVarsOfFunction().put(sym.getName(), (Symbol) sym.clone());\n } catch (CloneNotSupportedException ex) {\n Logger.getLogger(MethodSymbol.class.getName()).log(Level.SEVERE, null, ex);\n }\n\t }\n \n \n //copia a lista de instrucoes da funcao\n Scope scp, scpRoot=null;\n CallSymbol curScope;\n Symbol sy;\n for(Iterator <Symbol> it = meth_sym.getMembers().iterator(); it.hasNext();){\n sy = it.next();\n if (sy.getIsVariableSymbol() == false){\n scp = (Scope) sy; \n sym = scp.getScopeSymbol();\n curScope = new CallSymbol (sym.getName(), sym.getCodeLine(), null, sym.getTainted(), sym.getFileSymbol());\n curScope.setRootScope(curScope);\n curScope.setScope(curScope);\n curScope.setIsVariableSymbol(false);\n curScope.getScopeSymbol().setIsInstance(sym.getIsInstance());\n curScope.getScopeSymbol().setIsClone(sym.getIsClone());\n curScope.getScopeSymbol().setIsStaticMember(sym.getIsStaticMember());\n curScope.getScopeSymbol().setIsClassInstruction(sym.getIsClassInstruction());\n \n curScope.getScopeSymbol().setIsFunction(sym.getIsFunction());\n curScope.getScopeSymbol().setIsSecureFunction(sym.getIsSecureFunction());\n curScope.getScopeSymbol().setIsTaintedFunction(sym.getIsTaintedFunction());\n curScope.getScopeSymbol().setAlfanumeric(sym.getAlfanumeric());\n curScope.getScopeSymbol().setIsUserFunction(sym.getIsUserFunction());\n curScope.getScopeSymbol().setIsClassMethod(sym.getIsClassMethod()); \n \n copyScope(scp, curScope);\n mt.getMembers().add(curScope);\n }\n }\n \n return mt;\n }\n\n public void copyScope(Scope cs, Scope csClone){\n Symbol aux1, aux2;\n Scope s, s1 = null;\n CallSymbol curScope1;\n if (!cs.getMembers().isEmpty()){\n for(Iterator <Symbol> it = cs.getMembers().iterator(); it.hasNext();){\n aux1 = it.next();\n if ( aux1.getRootScope() != null ) { // is a root of a new scope?\n s = aux1.getRootScope();\n //aux2 = s.getScopeSymbol();\n try {\n s1 = (Scope) cs.getScopeSymbol().clone();\n } catch (CloneNotSupportedException ex) {\n Logger.getLogger(MethodSymbol.class.getName()).log(Level.SEVERE, null, ex);\n } \n curScope1 = new CallSymbol (aux1.getName(), aux1.getCodeLine(), s1, aux1.getTainted(), aux1.getFileSymbol());\n curScope1.getScopeSymbol().setIsFunction(aux1.getIsFunction());\n curScope1.getScopeSymbol().setIsSecureFunction(aux1.getIsSecureFunction());\n curScope1.getScopeSymbol().setIsTaintedFunction(aux1.getIsTaintedFunction());\n curScope1.getScopeSymbol().setAlfanumeric(aux1.getAlfanumeric());\n curScope1.getScopeSymbol().setIsUserFunction(aux1.getIsUserFunction());\n curScope1.getScopeSymbol().setIsInstance(aux1.getIsInstance());\n curScope1.getScopeSymbol().setIsClone(aux1.getIsClone());\n curScope1.getScopeSymbol().setIsStaticMember(aux1.getIsStaticMember());\n curScope1.getScopeSymbol().setIsClassInstruction(aux1.getIsClassInstruction());\n curScope1.getScopeSymbol().setIsClassMethod(aux1.getIsClassMethod());\n\n csClone.define(curScope1, curScope1, false);\n copyScope(s, curScope1);\n }\n else{\n VariableSymbol vs = new VariableSymbol(aux1.getName(), aux1.getTainted(), aux1.getCodeLine(), aux1.getAlfanumeric(), aux1.getFileSymbol());\n csClone.define(vs, null, true);\n\n }\n \n }\n } \n }\n\n\n public void cleanAll(){\n haveSubFunctions = false;\n Progenitorfunction = \"\";\n\n Collection <ArgFunctionSymbol> c = argsFunction.values();\n c.removeAll(c);\n argsFunction.clear();\n\n Collection <Symbol> c1 = globalVars.values();\n c1.removeAll(c1);\n globalVars.clear();\n\n Collection <Symbol> c2 = symbols;\n c2.removeAll(c2);\n symbols.clear();\n }\n \n // give the members (instructions) of the function\n public List<Symbol> getMembers() {\n return symbols;\n }\n\n public void printMethodSymbol() {\n System.out.println(\"FUNCTION: \"+this.getFunctionName()+\"\\tTAINTED: \"+this.getTainted());\n System.out.println(\"\\tHave SubFunctions: \"+ this.getHaveSubFunctions());\n System.out.println(\"\\tFunction Progenitor: \"+ this.getProgenitorFunction());\n \n System.out.println(\"\\tPARAMETERS\");\n Iterator <ArgFunctionSymbol> it;\n ArgFunctionSymbol afs;\n for(it = this.getArgsFunction().values().iterator(); it.hasNext();){\n afs = it.next();\n System.out.println(\"\\t\\tName: \"+afs.getParamName()+\"\\tType: \"+afs.getType()+\"\\tPosition: \"+afs.getPositionParam()+\n \"\\tTainted: \"+afs.getTaintedValueCallFunctionArg()+\"\\tArgCallFunction: \"+afs.getCallFunctionArg());\n }\n \n System.out.println(\"\\tGLOBALS\");\n Iterator <Symbol> it1;\n Symbol sym;\n for(it1 = this.getGlobalVarsOfFunction().values().iterator(); it1.hasNext();){\n sym = it1.next();\n System.out.println(\"\\t\\tName: \"+sym.getName()+\"\\tTainted: \"+sym.getTainted());\n }\n \n System.out.println(\"\\tINSTRUCTIONS\");\n Scope sc;\n for(it1 = this.getMembers().iterator(); it1.hasNext();){\n sc = (Scope) it1.next();\n System.out.println(\"ScopeName: \"+sc.getScopeName()+\"\\tTainted: \"+sc.getScopeSymbol().getTainted()\n +\"\\tRootScope: \"+sc.getScopeSymbol().getRootScope().getScopeName()\n +\"\\tTaintedRootScope: \"+sc.getScopeSymbol().getRootScope().getScopeSymbol().getTainted());\n sc.print(sc);\n } \n } \n \n public void print(Scope scp) {\n\n }\n\n}" ]
import org.homeunix.wap.utils.LinesToCorrect; import org.homeunix.wap.utils.GlobalDataApp; import org.homeunix.wap.utils.ManageFiles; import org.homeunix.wap.table.tainted.ListVulners; import org.homeunix.wap.table.symbol.SymbolTable; import org.homeunix.wap.table.symbol.MethodTable; import org.homeunix.wap.table.symbol.MethodSymbol; import java.util.*; import java.io.*;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.homeunix.wap.XSS; /** * * @author iberiam */ public class OutputAnalysisXSS { //public static void outputAnalysisWithCorrection (String type_analyse, String filename) throws IOException{ public static void outputAnalysisWithCorrection (String type_analyse, String filename, LinesToCorrect ltc, int num_file) throws IOException{ FileWriter out_FileOfPaths; File dir = null; BufferedWriter bufferWritter = null; Date date = new Date(System.currentTimeMillis()); int i = GlobalDataXSS.MainLinesToCorrect.size(); if (type_analyse.equals("project") == true){ dir = new File(System.getProperty("base.dir") + File.separator + "NewFiles"); // Se ja houve analises anteriores apaga dir if (GlobalDataApp.numAnalysis == 0 && dir.exists() == true && num_file == i){
ManageFiles r = new ManageFiles(dir.toString());
2
LetsCoders/MassiveTanks
src/main/java/pl/letscode/tanks/engine/Game.java
[ "public class GameModel {\n\n\tprivate final List<Player> players;\n\tprivate final List<TankObject> tanks;\n\tprivate final List<BulletObject> bullets;\n\tprivate final MapMatrix map;\n\t\n\t/* Constructors */\n\t\n\tGameModel(List<Player> players, List<TankObject> tanks,\n\t\t\tList<BulletObject> bullets, MapMatrix map) {\n\t\tthis.players = players;\n\t\tthis.tanks = tanks;\n\t\tthis.bullets = bullets;\n\t\tthis.map = map;\n\t}\n\t\n\t/* Read model */\n\t\n\tpublic Collection<Player> getPlayers() {\n\t\treturn ImmutableList.copyOf(this.players);\n\t}\n\t\n\tpublic Collection<TankObject> getTanks() {\n\t\treturn ImmutableList.copyOf(this.tanks);\n\t}\n\t\n\tpublic Collection<BulletObject> getBullets() {\n\t\treturn ImmutableList.copyOf(this.bullets);\n\t}\n\t\n\tpublic MapMatrix getBoard() {\n\t\treturn this.map;\n\t}\n\t\n\t/* Commands */\n\t\n\tpublic void addPlayer(Player player) {\n\t\tthis.players.add(player);\n\t}\n\t\n\tpublic void removePlayer(Player player) {\n\t\tthis.players.remove(player);\n\t}\n\t\n\tpublic void addTank(TankObject tank) {\n\t\tthis.tanks.add(tank);\n\t}\n\t\n\tpublic void removeTank(TankObject tank) {\n\t\tthis.tanks.remove(tank);\n\t}\n\t\n\tpublic void addBullet(BulletObject bullet) {\n\t\tthis.bullets.add(bullet);\n\t}\n\t\n\tpublic void removeBullet(BulletObject bullet) {\n\t\tthis.bullets.remove(bullet);\n\t}\n\n\tpublic void addTerrainBlock(TerrainObject object, int x, int y) {\n\t\tthis.map.setTerrainObject(x, y, object);\n\t}\n\t\n\tpublic void removeTerrainBlock(TerrainObject object) {\n\t\tthis.map.remove(object.getId());\n\t}\n\t\n}", "public interface PhysicsObject {\n\n\tlong getId();\n\n\tBody getBody();\n\n\tvoid setPosition(Position position);\n\n\tPosition getPosition();\n\n}", "public interface Shootable extends PhysicsObject {\n\n\tboolean isDead();\n\n\tvoid shootMe();\n\n\tint getHP();\n\n}", "public class BulletObject extends BaseGameObject {\n\n\tprivate TankObject sourceTank;\n\tprivate Axis2D direction;\n\tprivate int damage;\n\tprivate double movementSpeed;\n\n\tpublic BulletObject(Body body, long id, TankObject sourceTank,\n\t\t\tAxis2D direction, int damage, double movementSpeed) {\n\t\tsuper(body, id);\n\t\tthis.sourceTank = sourceTank;\n\t\tthis.direction = direction;\n\t\tthis.damage = damage;\n\t\tthis.movementSpeed = movementSpeed;\n\t}\n\n\tpublic int getDamage() {\n\t\treturn damage;\n\t}\n\n\tpublic Axis2D getDirection() {\n\t\treturn direction;\n\t}\n\n\tpublic TankObject getSourceTank() {\n\t\treturn sourceTank;\n\t}\n\n\tpublic double getMovementSpeed() {\n\t\treturn this.movementSpeed;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(this.getId());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null || !(obj instanceof BulletObject))\n\t\t\treturn false;\n\t\tBulletObject that = (BulletObject) obj;\n\t\tif (this.id == that.id)\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Objects.toStringHelper(this).addValue(this.id)\n\t\t\t\t.addValue(this.getPosition()).addValue(this.sourceTank)\n\t\t\t\t.addValue(this.direction).addValue(this.damage)\n\t\t\t\t.addValue(this.movementSpeed).toString();\n\t}\n\n}", "public class TankObject extends BaseGameObject implements Shootable {\n\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(TankObject.class);\n\n\tprivate final Player player;\n\tprivate Axis2D facingDirection;\n\tprivate Axis2D movementDirection;\n\tprivate int hp;\n\tprivate double movementSpeed;\n\n\tpublic TankObject(Body body, long id, Player player, int initialHp,\n\t\t\tdouble movementSpeed, Axis2D facingDirection,\n\t\t\tAxis2D movementDirection) {\n\t\tsuper(body, id);\n\t\tthis.hp = initialHp;\n\t\tthis.movementSpeed = movementSpeed;\n\t\tthis.facingDirection = facingDirection;\n\t\tthis.movementDirection = movementDirection;\n\t\tthis.player = player;\n\t}\n\n\tpublic Axis2D getFacingDirection() {\n\t\treturn facingDirection;\n\t}\n\n\t@Override\n\tpublic boolean isDead() {\n\t\treturn this.hp < 1;\n\t}\n\n\t@Override\n\tpublic void shootMe() {\n\t\tthis.hp--;\n\t}\n\n\t@Override\n\tpublic int getHP() {\n\t\treturn this.hp;\n\t}\n\n\tpublic Axis2D getMovementDirection() {\n\t\treturn this.movementDirection;\n\t}\n\n\tpublic Position getVelocity() {\n\t\treturn new Position(this.getBody().getLinearVelocity().x, this\n\t\t\t\t.getBody().getLinearVelocity().y);\n\t}\n\t\n\tpublic Player getPlayer() {\n\t\treturn this.player;\n\t}\n\n\tpublic boolean changeTankDirection(Axis2D newDirection) {\n\t\tif (this.movementDirection.equals(newDirection)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tthis.movementDirection = newDirection;\n\t\t\tif (!newDirection.equals(Axis2D.NONE)) {\n\t\t\t\tthis.facingDirection = newDirection;\n\t\t\t}\n\t\t\tLOGGER.info(\"Direction {}\", newDirection);\n\t\t\tLOGGER.info(\"New speed x, y {}, {}\", newDirection.getX()\n\t\t\t\t\t* movementSpeed, newDirection.getY() * movementSpeed);\n\t\t\t// set speed\n\t\t\tthis.getBody().setLinearVelocity(\n\t\t\t\t\tnewDirection.getX() * movementSpeed,\n\t\t\t\t\tnewDirection.getY() * movementSpeed);\n\t\t\tthis.getBody().setAsleep(false);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(this.getId());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null || !(obj instanceof TankObject))\n\t\t\treturn false;\n\t\tTankObject that = (TankObject) obj;\n\t\tif (this.id == that.id)\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn Objects.toStringHelper(this).addValue(this.id).addValue(this.hp)\n\t\t\t\t.addValue(this.movementSpeed).addValue(this.movementDirection)\n\t\t\t\t.addValue(this.facingDirection).toString();\n\t}\n\n}", "public class PlayerStateDTO {\n\n\tprivate Player player;\n\tprivate TankObject tank;\n\t\n\tpublic PlayerStateDTO(Player player, TankObject tank) {\n\t\tsuper();\n\t\tthis.player = player;\n\t\tthis.tank = tank;\n\t}\n\tpublic Player getPlayer() {\n\t\treturn player;\n\t}\n\tpublic TankObject getTank() {\n\t\treturn tank;\n\t}\n\t\n}", "public class MapMatrix {\n\n\tprivate int height;\n\n\tprivate int width;\n\n\tprivate TerrainObject[][] matrix;\n\n\t/* Constructors */\n\t\n\tMapMatrix(int height, int width) {\n\t\tthis.height = height;\n\t\tthis.width = width;\n\t\t// +2 for Borders\n\t\tthis.matrix = new TerrainObject[height + 2][width + 2];\n\t}\n\n\t/* Read */\n\t\n\tpublic int getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\t\n\tpublic Collection<TerrainObject> getBlocks() {\n\t\tList<TerrainObject> result = new ArrayList<TerrainObject>();\n\t\tfor (int i = 0; i < matrix.length; i++) {\n\t\t\tfor (int j = 0; j < matrix[i].length; j++) {\n\t\t\t\tTerrainObject terrainObject = matrix[i][j];\n\t\t\t\tif (terrainObject != null) {\n\t\t\t\t\tresult.add(terrainObject);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ImmutableList.copyOf(result);\n\t}\n\n\tpublic TerrainObject[][] getMatrix() {\n\t\treturn matrix;\n\t}\n\n\tpublic TerrainObject getTerrainObject(final Coord coord) {\n\t\treturn this.matrix[coord.getX()][coord.getY()];\n\t}\n\t\n\tpublic TerrainObject getTerrainObject(int x, int y) {\n\t\treturn this.matrix[x][y];\n\t}\n\t\n\tpublic boolean exists(int x, int y) {\n\t\treturn this.matrix[x][y] != null;\n\t}\n\t\n\tpublic int getBrickAmount() {\n\t\tint counter = 0;\n\t\tfor (int i = 0; i < matrix.length; i++) {\n\t\t\tfor (int j = 0; j < matrix[i].length; j++) {\n\t\t\t\tTerrainObject terrainObject = matrix[i][j];\n\t\t\t\tif (terrainObject != null\n\t\t\t\t\t\t&& terrainObject.getType() == TerrainType.BRICK) {\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn counter;\n\t}\n\t\n\t/* Commands */\n\n\tpublic void setTerrainObject(final Coord coord,\n\t\t\tfinal TerrainObject terrainObject) {\n\t\tthis.matrix[coord.getX()][coord.getY()] = terrainObject;\n\t}\n\t\n\tpublic void setTerrainObject(int x, int y,\n\t\t\tfinal TerrainObject terrainObject) {\n\t\tthis.matrix[x][y] = terrainObject;\n\t}\n\n\tpublic void remove(final long id) {\n\t\tfor (int i = 0; i < matrix.length; i++) {\n\t\t\tfor (int j = 0; j < matrix[i].length; j++) {\n\t\t\t\tTerrainObject terrainObject = matrix[i][j];\n\t\t\t\tif (terrainObject != null && terrainObject.getId() == id) {\n\t\t\t\t\tmatrix[i][j] = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}", "public class TerrainObject extends BaseGameObject {\n\n\tpublic static final int DEFAULT_TERRAIN_SIZE = 32;\n\n\tprotected TerrainType type;\n\n\tpublic TerrainObject(Body body, long id) {\n\t\tsuper(body, id);\n\t}\n\n\tpublic TerrainType getType() {\n\t\treturn type;\n\t}\n\n}", "public class Player {\n\n\tprivate String name;\n\tprivate int score;\n\n\t/* Constructors */\n\t\n\tpublic Player(String name, int score) {\n\t\tthis.name = name;\n\t\tthis.score = score;\n\t}\n\n\t/* Read */\n\t\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\t\n\tpublic int getScore() {\n\t\treturn this.score;\n\t}\n\t\n\t/* Commands */\n\t\n\tpublic void addFrag() {\n\t\tthis.score++;\n\t}\n\n\t/* Utilities */\n\t\n\t@Override\n\tpublic boolean equals(Object object) {\n\t\tif (object == null)\n\t\t\treturn false;\n\t\tif (this == object)\n\t\t\treturn true;\n\t\tif (object instanceof Player) {\n\t\t\tPlayer player = (Player) object;\n\t\t\tif (player.getName().equals(this.name))\n\t\t\t\treturn true;\n\t\t\telse\n\t\t\t\treturn false;\n\t\t} else\n\t\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(this.name);\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.dyn4j.Listener; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.dynamics.World; import com.google.common.base.Objects; import pl.letscode.tanks.engine.model.GameModel; import pl.letscode.tanks.engine.objects.PhysicsObject; import pl.letscode.tanks.engine.objects.Shootable; import pl.letscode.tanks.engine.objects.bullet.BulletObject; import pl.letscode.tanks.engine.objects.tank.TankObject; import pl.letscode.tanks.events.server.json.PlayerStateDTO; import pl.letscode.tanks.map.MapMatrix; import pl.letscode.tanks.map.terrain.TerrainObject; import pl.letscode.tanks.player.Player;
package pl.letscode.tanks.engine; /** * Aggregate root, contains whole state. World object also has to be here as it * contains references to Body objects. * * Need to somehow keep them in sync. * * @author edhendil * */ public class Game { private final long id; private final GameModel model; private final World world; /* Constructors */ Game(long id, GameModel model, World world) { this.id = id; this.model = model; this.world = world; } /* Read model */ public long getId() { return this.id; }
public Collection<Player> getPlayers() {
8
bupt1987/JgFramework
src/main/java/com/zhaidaosi/game/jgframework/Router.java
[ "@SuppressWarnings(\"resource\")\npublic class BaseFile {\n\n private static final Logger log = LoggerFactory.getLogger(BaseFile.class);\n\n\n public static Set<Class<?>> getClasses(String pack, boolean recursive) {\n return getClasses(pack, \"\", recursive);\n }\n\n /**\n * 从包package中获取所有的Class\n *\n * @param pack String\n * @param suffix String\n * @param recursive 是迭代\n * @return String\n */\n public static Set<Class<?>> getClasses(String pack, String suffix, boolean recursive) {\n // 第一个class类的集合\n Set<Class<?>> classes = new LinkedHashSet<Class<?>>();\n // 获取包的名字 并进行替换\n String packageName = pack;\n String packageDirName = packageName.replace('.', '/');\n // 定义一个枚举的集合 并进行循环来处理这个目录下的things\n Enumeration<URL> dirs;\n try {\n dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);\n // 循环迭代下去\n while (dirs.hasMoreElements()) {\n // 获取下一个元素\n URL url = dirs.nextElement();\n // 得到协议的名称\n String protocol = url.getProtocol();\n // 如果是以文件的形式保存在服务器上\n if (\"file\".equals(protocol)) {\n // 获取包的物理路径\n String filePath = URLDecoder.decode(url.getFile(), \"UTF-8\");\n // 以文件的方式扫描整个包下的文件 并添加到集合中\n findAndAddClassesInPackageByFile(packageName, filePath, suffix, recursive, classes);\n } else if (\"jar\".equals(protocol)) {\n // 如果是jar包文件\n // 定义一个JarFile\n JarFile jar;\n try {\n String jarPath = url.getPath();\n if (jarPath.indexOf(\"file:\") == 0) {\n jarPath = jarPath.substring(5);\n }\n int index = jarPath.lastIndexOf(\".jar\");\n jarPath = jarPath.substring(0, index) + \".jar\";\n // 获取jar\n jar = new JarFile(jarPath);\n // 从此jar包 得到一个枚举类\n Enumeration<JarEntry> entries = jar.entries();\n // 同样的进行循环迭代\n while (entries.hasMoreElements()) {\n // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件\n JarEntry entry = entries.nextElement();\n String name = entry.getName();\n // 如果是以/开头的\n if (name.charAt(0) == '/') {\n // 获取后面的字符串\n name = name.substring(1);\n }\n // 如果前半部分和定义的包名相同\n if (name.startsWith(packageDirName)) {\n int idx = name.lastIndexOf('/');\n // 如果以\"/\"结尾 是一个包\n if (idx != -1) {\n // 获取包名 把\"/\"替换成\".\"\n packageName = name.substring(0, idx).replace('/', '.');\n }\n // 如果可以迭代下去 并且是一个包\n if ((idx != -1) || recursive) {\n // 如果是一个.class文件 而且不是目录\n if (name.endsWith(\".class\") && !entry.isDirectory()) {\n // 去掉后面的\".class\" 获取真正的类名\n String className = name.substring(packageName.length() + 1, name.length() - 6);\n try {\n // 添加到classes\n classes.add(Class.forName(packageName + '.' + className));\n } catch (ClassNotFoundException e) {\n log.error(\"添加用户自定义视图类错误 找不到此类的.class文件\", e);\n }\n }\n }\n }\n }\n } catch (IOException e) {\n log.error(\"在扫描用户定义视图时从jar包获取文件出错\", e);\n }\n }\n }\n } catch (IOException e) {\n }\n\n return classes;\n }\n\n /**\n * 以文件的形式来获取包下的所有Class\n *\n * @param packageName\n * @param packagePath\n * @param recursive\n * @param classes\n */\n private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final String suffix, final boolean recursive, Set<Class<?>> classes) {\n // 获取此包的目录 建立一个File\n File dir = new File(packagePath);\n // 如果不存在或者 也不是目录就直接返回\n if (!dir.exists() || !dir.isDirectory()) {\n // log.warn(\"用户定义包名 \" + packageName + \" 下没有任何文件\");\n return;\n }\n // 如果存在 就获取包下的所有文件 包括目录\n File[] dirfiles = dir.listFiles(new FileFilter() {\n // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)\n public boolean accept(File file) {\n return (recursive && file.isDirectory()) || (file.getName().endsWith(suffix + \".class\"));\n }\n });\n // 循环所有文件\n for (File file : dirfiles) {\n // 如果是目录 则继续扫描\n if (file.isDirectory()) {\n findAndAddClassesInPackageByFile(packageName + \".\" + file.getName(), file.getAbsolutePath(), suffix, recursive, classes);\n } else {\n // 如果是java类文件 去掉后面的.class 只留下类名\n String className = file.getName().substring(0, file.getName().length() - 6);\n try {\n // 添加到集合中去\n // classes.add(Class.forName(packageName + '.' +\n // className));\n // 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净\n classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));\n } catch (ClassNotFoundException e) {\n log.error(\"添加用户自定义视图类错误 找不到此类的.class文件\", e);\n }\n }\n }\n }\n\n public static List<String> fileList(String path) {\n return fileList(path, false);\n }\n\n public static List<String> fileList(String path, boolean needDir) {\n List<String> list = new ArrayList<String>();\n File file = new File(path);\n if (file.isDirectory()) {\n String[] filelist = file.list();\n for (int i = 0; i < filelist.length; i++) {\n file = new File(path + \"/\" + filelist[i]);\n if (!file.isDirectory()) {\n list.add(file.getName());\n } else {\n if (needDir) {\n list = fileList(list, path, file.getName());\n }\n }\n }\n }\n return list;\n }\n\n private static List<String> fileList(List<String> list, String path, String dir) {\n File file = new File(path + \"/\" + dir);\n if (file.isDirectory()) {\n String[] filelist = file.list();\n for (int i = 0; i < filelist.length; i++) {\n file = new File(path + \"/\" + dir + \"/\" + filelist[i]);\n if (!file.isDirectory()) {\n list.add(dir + \"/\" + file.getName());\n } else {\n list = fileList(list, path, dir + \"/\" + file.getName());\n }\n }\n }\n return list;\n }\n\n public static String readResourceByLines(String resourcePath) {\n // 返回读取指定资源的输入流\n InputStream is = BaseFile.class.getClassLoader().getResourceAsStream(resourcePath);\n BufferedReader reader = new BufferedReader(new InputStreamReader(is));\n StringBuffer buffer = new StringBuffer(\"\");\n try {\n String tempString = null;\n while ((tempString = reader.readLine()) != null) {\n buffer.append(tempString);\n buffer.append(\"\\n\");\n }\n } catch (IOException e) {\n log.error(\"读取文件失败\", e);\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e1) {\n }\n }\n }\n return buffer.toString();\n }\n\n /**\n * 以行为单位读取文件,常用于读面向行的格式化文件\n */\n public static String readFileByLines(String fileName) {\n File file = new File(fileName);\n return readFileByLines(file);\n }\n\n /**\n * 以行为单位读取文件,常用于读面向行的格式化文件\n */\n public static String readFileByLines(File file) {\n BufferedReader reader = null;\n StringBuffer buffer = new StringBuffer(\"\");\n try {\n reader = new BufferedReader(new FileReader(file));\n String tempString = null;\n // 一次读入一行,直到读入null为文件结束\n while ((tempString = reader.readLine()) != null) {\n buffer.append(tempString);\n buffer.append(\"\\n\");\n }\n reader.close();\n } catch (IOException e) {\n log.error(\"读取文件失败\", e);\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e1) {\n }\n }\n }\n return buffer.toString();\n }\n\n public static String readFileLastByLine(String filePath, int lastStart, int limit) {\n File file = new File(filePath);\n String buffer = \"\";\n if (!file.exists()) {\n return buffer;\n }\n RandomAccessFile raf;\n try {\n raf = new RandomAccessFile(file, \"r\");\n long len = raf.length();\n int line = 0;\n if (len != 0L) {\n long pos = len - 1;\n while (pos > 0) {\n raf.seek(pos);\n if (raf.readByte() == '\\n') {\n if (lastStart <= line && line < lastStart + limit) {\n String temp = \"\";\n // Windows下有乱码问题\n String tempLine = raf.readLine();\n if (tempLine == null) {\n pos--;\n continue;\n }\n temp += tempLine;\n temp += \"\\n\";\n buffer += temp;\n pos--;\n }\n line++;\n } else {\n pos--;\n }\n if (line >= lastStart + limit) {\n break;\n }\n }\n }\n raf.close();\n } catch (IOException e) {\n log.error(\"读取文件失败\", e);\n }\n return buffer;\n }\n\n /**\n * 判断文件的编码格式\n *\n * @param fileName\n * :file\n * @return 文件编码格式\n * @throws Exception\n */\n public static String codeString(String fileName) throws Exception {\n BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));\n int p = (bin.read() << 8) + bin.read();\n String code = null;\n // 其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数\n switch (p) {\n case 0xefbb:\n code = \"UTF-8\";\n break;\n case 0xfffe:\n code = \"Unicode\";\n break;\n case 0xfeff:\n code = \"UTF-16BE\";\n break;\n case 0x5c75:\n code = \"ANSI|ASCII\";\n break;\n default:\n code = \"GBK\";\n }\n\n return code;\n }\n\n}", "public class BaseString {\n\n public static boolean isEmpty(String str) {\n if (str == null) {\n return true;\n }\n str = str.trim();\n return str.equals(\"\");\n }\n\n}", "public abstract class BaseHandler implements IBaseHandler {\n\n protected String handlerName;\n\n @Override\n public abstract IBaseMessage run(InMessage im, Channel ch) throws Exception;\n\n @Override\n public String getHandlerName() {\n return handlerName;\n }\n\n @Override\n public void setHandlerName(String handlerName) {\n this.handlerName = handlerName;\n }\n\n public static IBaseMessage doHeart() {\n return OutMessage.showSucc(\"\");\n }\n\n}", "public interface IBaseHandler {\n\n IBaseMessage run(InMessage im, Channel ch) throws Exception;\n\n String getHandlerName();\n\n void setHandlerName(String handlerName);\n\n}", "public interface IBaseMessage {\n\n String toString();\n\n String getH();\n\n void setH(String h);\n\n}", "public class InMessage implements IBaseMessage {\n /**\n * 控制器handler路径\n */\n private String h;\n /**\n * 参数\n */\n private HashMap<String, Object> p = new HashMap<>();\n\n public InMessage() {\n }\n\n public InMessage(String h) {\n this.h = h;\n }\n\n public InMessage(String h, HashMap<String, Object> p) {\n this.h = h;\n this.p = p;\n }\n\n public static InMessage getMessage(String msg) throws MessageException {\n if (msg.startsWith(\"{\") && msg.endsWith(\"}\")) {\n return BaseJson.JsonToObject(msg, InMessage.class);\n } else {\n throw new MessageException(\"msg格式错误\");\n }\n }\n\n public String toString() {\n return BaseJson.ObjectToJson(this);\n }\n\n public String getH() {\n return h;\n }\n\n public HashMap<String, Object> getP() {\n return p;\n }\n\n public void setH(String h) {\n this.h = h;\n }\n\n\n public void setP(HashMap<String, Object> p) {\n this.p = p;\n }\n\n public void putMember(String key, Object value) {\n this.p.put(key, value);\n }\n\n public Object getMember(String key) {\n return p.get(key);\n }\n\n}" ]
import com.zhaidaosi.game.jgframework.common.BaseFile; import com.zhaidaosi.game.jgframework.common.BaseRunTimer; import com.zhaidaosi.game.jgframework.common.BaseString; import com.zhaidaosi.game.jgframework.handler.BaseHandler; import com.zhaidaosi.game.jgframework.handler.IBaseHandler; import com.zhaidaosi.game.jgframework.message.IBaseMessage; import com.zhaidaosi.game.jgframework.message.InMessage; import com.zhaidaosi.game.jgframework.message.OutMessage; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Set;
package com.zhaidaosi.game.jgframework; public class Router { private static final Logger log = LoggerFactory.getLogger(Router.class); private static HashMap<String, IBaseHandler> handlers = new HashMap<>(); private static final String classSuffix = "Handler"; public static final String ERROR_HANDLERNAME = "_error_"; public static final String HEART_HANDLERNAME = "_heart_"; public static final String WAIT_HANDLERNAME = "_wait_"; /** * 初始化handler */ public static void init() { Set<Class<?>> classes = BaseFile.getClasses(Boot.SERVER_HANDLER_PACKAGE_PATH, classSuffix, true); for (Class<?> c : classes) { String className = c.getName(); IBaseHandler handler; try { handler = (IBaseHandler) c.newInstance(); // 只取Handler前面部分 String handlerName = className.replace(Boot.SERVER_HANDLER_PACKAGE_PATH + ".", "").replace(classSuffix, "").toLowerCase(); handler.setHandlerName(handlerName); handlers.put(handlerName, handler); log.info("handler类 : " + className + " 加载完成"); } catch (InstantiationException | IllegalAccessException e) { log.error("handler类 : " + className + " 加载失败", e); } } } /** * 运行handler * @param im * @param ch * @return * @throws Exception */
public static IBaseMessage run(InMessage im, Channel ch) throws Exception {
4
enguerrand/xdat
src/main/java/org/xdat/gui/panels/ScatterChart2DPanel.java
[ "public class Main extends JFrame {\n\tpublic static final long serialVersionUID = 10L;\n\tprivate MainMenuBar mainMenuBar;\n\tprivate Session currentSession;\n\tprivate List<ChartFrame> chartFrames = new LinkedList<>();\n\tprivate final BuildProperties buildProperties;\n\tprivate final ClusterFactory clusterFactory = new ClusterFactory();\n\tprivate final DatasheetListener datasheetListener;\n\tprivate final List<DatasheetListener> subListeners = new CopyOnWriteArrayList<>();\n\tprivate DataSheetTablePanel dataSheetTablePanel;\n\tprivate final List<ParallelChartFrameComboModel> comboModels = new LinkedList<>();\n\tprivate final SettingsGroup generalSettingsGroup;\n\tprivate final SettingsGroup parallelCoordinatesAxisSettingsGroup;\n\n\tprivate static final List<String> LOOK_AND_FEEL_ORDER_OF_PREF = Arrays.asList(\n\t\t\t\"com.sun.java.swing.plaf.gtk.GTKLookAndFeel\",\n\t\t\t\"com.sun.java.swing.plaf.windows.WindowsLookAndFeel\",\n\t\t\t\"javax.swing.plaf.nimbus.NimbusLookAndFeel\"\n\t);\n\n\tpublic Main() {\n\t\tsuper(\"xdat - Untitled\");\n\t\tgeneralSettingsGroup = SettingsGroupFactory.buildGeneralParallelCoordinatesChartSettingsGroup();\n\t\tfor (Setting<?> value : generalSettingsGroup.getSettings().values()) {\n\t\t\tvalue.addListener((source, transaction) -> source.setCurrentToDefault());\n\t\t}\n\t\tparallelCoordinatesAxisSettingsGroup = SettingsGroupFactory.buildParallelCoordinatesChartAxisSettingsGroup();\n\t\tfor (Setting<?> value : parallelCoordinatesAxisSettingsGroup.getSettings().values()) {\n\t\t\tvalue.addListener((source, transaction) -> source.setCurrentToDefault());\n\t\t}\n\n\t\tthis.buildProperties = new BuildProperties();\n\t\tthis.datasheetListener = new DatasheetListener() {\n\t\t\t@Override\n\t\t\tpublic void onClustersChanged() {\n\t\t\t\trepaintAllChartFrames();\n\t\t\t\tfireSubListeners(DatasheetListener::onClustersChanged);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onDataPanelUpdateRequired() {\n\t\t\t\tupdateDataPanel();\n\t\t\t\tfireSubListeners(DatasheetListener::onDataPanelUpdateRequired);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onDataChanged(boolean[] autoFitRequired, boolean[] filterResetRequired, boolean[] applyFiltersRequired) {\n\t\t\t\tfinal ProgressMonitor progressMonitor = new ProgressMonitor(Main.this, \"\", \"Rebuilding charts\", 0, getDataSheet().getParameterCount() - 1);\n\t\t\t\tprogressMonitor.setMillisToPopup(0);\n\n\t\t\t\tfor (int i = 0; i < getDataSheet().getParameterCount(); i++) {\n\t\t\t\t\tfinal int progress = i;\n\t\t\t\t\tif (progressMonitor.isCanceled()) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tSwingUtilities.invokeLater(() ->\n\t\t\t\t\t\t\tprogressMonitor.setProgress(progress));\n\t\t\t\t\tif (autoFitRequired[i]) {\n\t\t\t\t\t\tautofitAxisAllChartFrames(i);\n\t\t\t\t\t}\n\t\t\t\t\tif (filterResetRequired[i]) {\n\t\t\t\t\t\tresetFiltersOnAxisAllChartFrames(i);\n\t\t\t\t\t}\n\t\t\t\t\tif (applyFiltersRequired[i]) {\n\t\t\t\t\t\trefilterAllChartFrames(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tprogressMonitor.close();\n\n\t\t\t\trepaintAllChartFrames();\n\n\t\t\t\tfireSubListeners(l -> l.onDataChanged(autoFitRequired, filterResetRequired, applyFiltersRequired));\n\t\t\t}\n\t\t};\n\t\tthis.currentSession = new Session();\n\t\tthis.addWindowListener(new WindowClosingAdapter(true));\n\t\tthis.mainMenuBar = new MainMenuBar(this);\n\t\tthis.setJMenuBar(this.mainMenuBar);\n\t\tImageIcon img = new ImageIcon(Main.class.getClassLoader().getResource(\"org/xdat/images/icon.png\"));\n\t\tthis.setIconImage(img.getImage());\n\n\t\tGraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n\t\tDimension screenSize;\n\t\ttry {\n\t\t\tscreenSize = new Dimension(ge.getScreenDevices()[0].getDisplayMode().getWidth(), ge.getScreenDevices()[0].getDisplayMode().getHeight());\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tscreenSize = getToolkit().getScreenSize();\n\t\t\t} catch (HeadlessException e1) {\n\t\t\t\tscreenSize = new Dimension(1200, 800);\n\t\t\t}\n\t\t}\n\t\tsetLocation((int) (0.25 * screenSize.width), (int) (0.25 * screenSize.height));\n\t\tsetSize((int) (0.5 * screenSize.width), (int) (0.5 * screenSize.height));\n\t\tsetVisible(true);\n\t}\n\n\tpublic void initialiseDataPanel() {\n\t\tSwingUtilities.invokeLater(new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tif (dataSheetTablePanel == null) {\n\t\t\t\t\tdataSheetTablePanel = new DataSheetTablePanel(Main.this);\n\t\t\t\t\tsetContentPane(dataSheetTablePanel);\n\t\t\t\t\t// this.repaint();\n\t\t\t\t\tdataSheetTablePanel.revalidate();\n\t\t\t\t} else if (currentSession.getCurrentDataSheet() != null) {\n\t\t\t\t\tdataSheetTablePanel.initialiseDataSheetTableModel();\n\t\t\t\t\tdataSheetTablePanel.revalidate();\n\t\t\t\t} else {\n\t\t\t\t\tsetContentPane(new JPanel());\n\t\t\t\t\trepaint();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void updateDataPanel() {\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tif (dataSheetTablePanel == null) {\n\t\t\t\tdataSheetTablePanel = new DataSheetTablePanel(Main.this);\n\t\t\t\tsetContentPane(dataSheetTablePanel);\n\t\t\t\tdataSheetTablePanel.revalidate();\n\t\t\t} else if (currentSession.getCurrentDataSheet() != null) {\n\t\t\t\tdataSheetTablePanel.updateRunsTableModel();\n\t\t\t\tdataSheetTablePanel.revalidate();\n\t\t\t} else {\n\t\t\t\tsetContentPane(new JPanel());\n\t\t\t\trepaint();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * The main method.\n\t *\n\t * @param args\n\t * the command line arguments (not used)\n\t */\n\tpublic static void main(String[] args) {\n\t\tsetLookAndFeel();\n\t\tnew Main();\n\t}\n\n\tprivate static void setLookAndFeel() {\n\t\tfor (String lnf : LOOK_AND_FEEL_ORDER_OF_PREF) {\n\t\t\ttry {\n\t\t\t\tUIManager.setLookAndFeel(lnf);\n\t\t\t\tbreak;\n\t\t\t} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ignored) {\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic DataSheet getDataSheet() {\n\t\treturn this.currentSession.getCurrentDataSheet();\n\t}\n\n\tpublic void setDataSheet(DataSheet dataSheet) {\n\t\tDataSheet currentDataSheet = this.currentSession.getCurrentDataSheet();\n\t\tif(currentDataSheet != null) {\n\t\t\tcurrentDataSheet.removeListener(this.datasheetListener);\n\t\t}\n\t\tthis.currentSession.setCurrentDataSheet(dataSheet);\n\t\tif (dataSheet == null) {\n\t\t\tthis.remove(this.dataSheetTablePanel);\n\t\t} else {\n\t\t\tdataSheet.addListener(this.datasheetListener);\n\t\t}\n\t\tthis.initialiseDataPanel();\n\t\tthis.repaint();\n\t\tthis.rebuildAllChartFrames();\n\t}\n\n\tpublic ClusterSet getCurrentClusterSet() {\n return this.currentSession.getCurrentClusterSet();\n }\n\n public void setCurrentClusterSet(ClusterSet clusterSet) {\n this.currentSession.setCurrentClusterSet(clusterSet);\n }\n\n\tpublic Session getCurrentSession() {\n\t\treturn currentSession;\n\t}\n\n\tpublic void setCurrentSession(Session currentSession) {\n\t\tthis.currentSession = currentSession;\n\t}\n\n\tpublic void addChartFrame(ChartFrame chartFrame) {\n\t\tthis.chartFrames.add(chartFrame);\n\t\tthis.addChartToComboboxes(chartFrame);\n\t}\n\n\tpublic void removeChartFrame(ChartFrame chartFrame) {\n\t\tthis.chartFrames.remove(chartFrame);\n\t\tthis.currentSession.removeChart(chartFrame.getChart());\n\t\tthis.removeChartFromComboboxes(chartFrame);\n\t}\n\n\tpublic void removeParameter(String paramName) {\n\t\tgetCurrentSession().removeParameter(paramName);\n\t}\n\n\tpublic ChartFrame getChartFrame(int index) {\n\t\treturn this.chartFrames.get(index);\n\t}\n\n\tpublic ChartFrame getChartFrame(String title) {\n\t\tfor (int i = 0; i < this.getChartFrameCount(); i++) {\n\t\t\tif (title.equals(this.getChartFrame(i).getTitle()))\n\t\t\t\treturn this.getChartFrame(i);\n\t\t}\n\t\tthrow new RuntimeException(\"No chart found with title \" + title);\n\t}\n\n\tpublic int getChartFrameCount() {\n\t\treturn this.chartFrames.size();\n\t}\n\n\tpublic int getUniqueChartId(Class chartClass) {\n\t\tint id = 0;\n\t\tfor (int i = 0; i < this.getChartFrameCount(); i++) {\n\n\t\t\tif (chartClass.equals(this.chartFrames.get(i).getChart().getClass())) {\n\t\t\t\tid = this.chartFrames.get(i).getChart().getID();\n\t\t\t}\n\t\t}\n\t\treturn ++id;\n\t}\n\n\tpublic void disposeAllChartFrames() {\n\t\tfor (int i = this.chartFrames.size() - 1; i >= 0; i--) {\n\t\t\tthis.removeChartFromComboboxes(this.chartFrames.get(i));\n\t\t\tthis.chartFrames.get(i).dispose();\n\t\t}\n\t\tthis.chartFrames.clear();\n\t\tthis.currentSession.clearAllCharts();\n\t}\n\n\tprivate void rebuildAllChartFrames() {\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tList<Chart> chartsSnapshot = new ArrayList<>(currentSession.getCharts());\n\t\t\tdisposeAllChartFrames();\n\t\t\tfor (Chart chart : chartsSnapshot) {\n\t\t\t\ttry {\n\t\t\t\t\tChartFrame newFrame = new ChartFrame(Main.this, chart);\n\t\t\t\t\tchartFrames.add(newFrame);\n\t\t\t\t\tcurrentSession.addChart(chart);\n\t\t\t\t} catch (NoParametersDefinedException e) {\n\t\t\t\t\tJOptionPane.showMessageDialog(Main.this, \"Cannot create chart when no parameters are defined.\", \"No parameters defined!\", JOptionPane.ERROR_MESSAGE);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void repaintAllChartFrames() {\n\t\trepaintAllChartFrames(new ArrayList<>());\n\t}\n\n\tprivate void repaintAllChartFrames(final List<ChartFrame> exclusionList) {\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tfor (ChartFrame cf : chartFrames) {\n\t\t\t\tif (!exclusionList.contains(cf)) {\n\t\t\t\t\tcf.repaint();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void refilterAllChartFrames(int columnIndex) {\n\t\tfor (int i = 0; i < this.chartFrames.size(); i++) {\n\t\t\tChart c = this.chartFrames.get(i).getChart();\n\t\t\tif (c.getClass().equals(ParallelCoordinatesChart.class)) {\n\t\t\t\t((ParallelCoordinatesChart) c).getAxis(columnIndex).applyFilters(getDataSheet());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void autofitAxisAllChartFrames(int axisIndex) {\n\t\tfor (int i = 0; i < this.chartFrames.size(); i++) {\n\t\t\tChart c = this.chartFrames.get(i).getChart();\n\t\t\tif (c.getClass().equals(ParallelCoordinatesChart.class)) {\n\t\t\t\t((ParallelCoordinatesChart) c).getAxis(axisIndex).autofit(getDataSheet());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void resetFiltersOnAxisAllChartFrames(int axisIndex) {\n\t\tfor (int i = 0; i < this.chartFrames.size(); i++) {\n\t\t\tChart c = this.chartFrames.get(i).getChart();\n\t\t\tif (c.getClass().equals(ParallelCoordinatesChart.class)) {\n\t\t\t\t((ParallelCoordinatesChart) c).getAxis(axisIndex).resetFilters(getDataSheet());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void loadSession(String pathToFile) {\n\t\ttry {\n\t\t\tthis.disposeAllChartFrames();\n\t\t\tthis.currentSession = Session.readFromFile(pathToFile);\n\n\t\t\tthis.setTitle(\"xdat - \" + pathToFile);\n\n\t\t\tfor (Chart chart : getCurrentSession().getCharts()) {\n\t\t\t\ttry {\n\t\t\t\t\tnew ChartFrame(this, chart);\n\t\t\t\t} catch (NoParametersDefinedException e) {\n\t\t\t\t\tJOptionPane.showMessageDialog(this, \"Cannot create chart when no parameters are defined.\", \"No parameters defined!\", JOptionPane.ERROR_MESSAGE);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.currentSession.getCurrentDataSheet() != null) {\n\t\t\t\tthis.getMainMenuBar().setItemsRequiringDataSheetEnabled(true);\n\t\t\t} else {\n\t\t\t\tthis.initialiseDataPanel();\n\t\t\t\tthis.getMainMenuBar().setItemsRequiringDataSheetEnabled(false);\n\t\t\t}\n\n\t\t} catch (InvalidClassException | ClassNotFoundException e) {\n\t\t\tJOptionPane.showMessageDialog(this, \"The file \" + pathToFile + \" is not a proper xdat version \" + buildProperties.getVersion() + \" Session file\", \"Load Session\", JOptionPane.OK_OPTION);\n\t\t} catch (IOException e) {\n\t\t\tJOptionPane.showMessageDialog(this, \"Error on loading session: \" + e.getMessage(), \"Load Session\", JOptionPane.ERROR_MESSAGE);\n\t\t}\n\n\t}\n\n\tpublic void saveSessionAs(String pathToFile) {\n\t\ttry {\n\t\t\tthis.currentSession.saveToFile(pathToFile);\n\t\t} catch (IOException e) {\n\t\t\tJOptionPane.showMessageDialog(this, \"IOException on saving session: \" + e.getMessage(), \"Save Session\", JOptionPane.ERROR_MESSAGE);\n\t\t}\n\t}\n\n\tpublic MainMenuBar getMainMenuBar() {\n\t\treturn mainMenuBar;\n\t}\n\n\tpublic DataSheetTablePanel getDataSheetTablePanel() {\n\t\treturn dataSheetTablePanel;\n\t}\n\n\tpublic void addChartToComboboxes(ChartFrame chartFrame) {\n\t\tfor (int i = 0; i < this.comboModels.size(); i++) {\n\t\t\tif (chartFrame.getChart().getClass().equals(ParallelCoordinatesChart.class)) {\n\t\t\t\tcomboModels.get(i).addElement(chartFrame.getChart().getTitle());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void removeChartFromComboboxes(ChartFrame chartFrame) {\n\t\tfor (int i = 0; i < this.comboModels.size(); i++) {\n\t\t\tif (chartFrame.getChart().getClass().equals(ParallelCoordinatesChart.class)) {\n\t\t\t\tcomboModels.get(i).removeElement(chartFrame.getChart().getTitle());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void registerComboModel(ParallelChartFrameComboModel comboModel) {\n\t\tthis.comboModels.add(comboModel);\n\t}\n\n\tpublic void unRegisterComboModel(ParallelChartFrameComboModel comboModel) {\n\t\tthis.comboModels.remove(comboModel);\n\t}\n\n\tpublic ClusterFactory getClusterFactory() {\n\t\treturn clusterFactory;\n\t}\n\n\tpublic SettingsGroup getGeneralSettingsGroup() {\n\t\treturn generalSettingsGroup;\n\t}\n\n\tpublic SettingsGroup getParallelCoordinatesAxisSettingsGroup() {\n\t\treturn parallelCoordinatesAxisSettingsGroup;\n\t}\n\n\tpublic void addDataSheetSubListener(DatasheetListener listener) {\n\t\tthis.subListeners.add(listener);\n\t}\n\n\tpublic void removeDataSheetSubListener(DatasheetListener listener) {\n\t\tthis.subListeners.remove(listener);\n\t}\n\n\tprivate void fireSubListeners(Consumer<DatasheetListener> action) {\n\t\tfor (DatasheetListener l : this.subListeners) {\n\t\t\taction.accept(l);\n\t\t}\n\t}\n\n\tpublic void fireClustersChanged() {\n\t\tthis.datasheetListener.onClustersChanged();\n\t}\n\n\tpublic void fireDataPanelUpdateRequired() {\n\t\tthis.datasheetListener.onDataPanelUpdateRequired();\n\t}\n\n\tpublic void fireOnDataChanged(boolean[] axisAutofitRequired, boolean[] axisResetFilterRequired, boolean[] axisApplyFiltersRequired) {\n\t\tthis.datasheetListener.onDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired);\n\t}\n}", "public class ParallelCoordinatesChart extends Chart implements Serializable {\n\n\tstatic final long serialVersionUID = 4;\n\tprivate static final int BOTTOM_PADDING = 60;\n\tprivate int topMargin = 10;\n\tprivate List<Axis> axes = new LinkedList<>();\n\tprivate SettingsGroup chartSettings;\n\tpublic ParallelCoordinatesChart(DataSheet dataSheet, ProgressMonitor progressMonitor, int id) {\n\t\tsuper(dataSheet, id);\n\t\tthis.chartSettings = SettingsGroupFactory.buildGeneralParallelCoordinatesChartSettingsGroup();\n\t\tthis.setLocation(new Point(100, 100));\n\t\tthis.setFrameSize(new Dimension(1280, 800));\n\t\tprogressMonitor.setMaximum(dataSheet.getParameterCount() - 1);\n\t\tprogressMonitor.setNote(\"Building Chart...\");\n\t\tfor (int i = 0; i < dataSheet.getParameterCount() && !progressMonitor.isCanceled(); i++) {\n\t\t\tAxis newAxis = new Axis(dataSheet, this, dataSheet.getParameter(i));\n\t\t\tthis.addAxis(newAxis);\n\t\t\tprogressMonitor.setProgress(i);\n\t\t}\n\n\t\tif (!progressMonitor.isCanceled()) {\n\t\t\tprogressMonitor.setNote(\"Building Filters...\");\n\t\t\tprogressMonitor.setProgress(0);\n\t\t\tfor (int i = 0; i < dataSheet.getParameterCount() && !progressMonitor.isCanceled(); i++) {\n\t\t\t\tthis.axes.get(i).addFilters(dataSheet);\n\t\t\t\tprogressMonitor.setProgress(i);\n\t\t\t}\n\t\t}\n\t\tStream.concat(\n\t\t\t\tthis.chartSettings.getSettings().values().stream(),\n\t\t\t\taxes.stream()\n\t\t\t\t\t\t.map(Axis::getSettings)\n\t\t\t\t\t\t.flatMap(g -> g.getSettings().values().stream())\n\t\t).forEach(s ->\n\t\t\t\ts.addListener((source, transaction) ->\n\t\t\t\t\t\thandleSettingChange(this::fireChanged, transaction))\n\t\t);\n\t}\n\n\tprivate void handleSettingChange(Runnable changeHandler, @Nullable SettingsTransaction transaction) {\n\t\tif (transaction == null) {\n\t\t\tchangeHandler.run();\n\t\t} else {\n\t\t\ttransaction.handleOnce(changeHandler);\n\t\t}\n\t}\n\n\tpublic String getTitle() {\n\t\treturn \"Parallel Coordinates Chart \" + this.getID();\n\t}\n\n\tpublic int getWidth() {\n\t\tint width = 0;\n\t\tif (this.getAxis(0).isActive()) {\n\t\t\twidth = width + (int) (0.5 * this.getAxis(0).getWidth());\n\t\t}\n\t\tfor (int i = 1; i < this.getAxisCount(); i++) {\n\t\t\tif (this.getAxis(i).isActive()) {\n\t\t\t\twidth = width + this.getAxis(i).getWidth();\n\t\t\t}\n\t\t}\n\t\treturn width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn getAxisTopPos() + getAxisHeight();\n\t}\n\n\tpublic int getAxisMaxWidth() {\n\t\tint width = 0;\n\t\tfor (int i = 0; i < this.getAxisCount(); i++) {\n\t\t\tif (this.getAxis(i).isActive()) {\n\t\t\t\tif (width < this.getAxis(i).getWidth()) {\n\t\t\t\t\twidth = this.getAxis(i).getWidth();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn width;\n\t}\n\n\tpublic void incrementAxisWidth(int deltaWidth) {\n\t\tfor (Axis axis : axes) {\n\t\t\taxis.setWidth(Math.max(0, axis.getWidth() + deltaWidth));\n\t\t}\n\t}\n\n\tpublic int getAxisTopPos() {\n\t\tboolean verticallyOffsetAxisLabels = this.chartSettings.getBoolean(Key.PARALLEL_COORDINATES_VERTICALLY_OFFSET_AXIS_LABELS);\n\t\tint topPos;\n\t\tif (verticallyOffsetAxisLabels) {\n\t\t\ttopPos = 2 * getMaxAxisLabelFontSize() + this.getAxisLabelVerticalDistance() + this.getTopMargin() * 2 + this.getFilterHeight();\n\t\t} else {\n\t\t\ttopPos = getMaxAxisLabelFontSize() + this.getTopMargin() * 2 + this.getFilterHeight();\n\t\t}\n\t\treturn topPos;\n\t}\n\n\tpublic Axis getAxis(int index) {\n\t\treturn axes.get(index);\n\t}\n\n\tpublic Axis getAxis(String parameterName) {\n\t\tfor (Axis axis : this.axes) {\n\t\t\tif (parameterName.equals(axis.getParameter().getName())) {\n\t\t\t\treturn axis;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Axis \" + parameterName + \" not found\");\n\t}\n\n\tpublic int getMaxAxisLabelFontSize() {\n\t\tint maxAxisLabelFontSize = 0;\n\t\tfor (Axis axis : axes) {\n\t\t\tif (maxAxisLabelFontSize < axis.getAxisLabelFontSize()) {\n\t\t\t\tmaxAxisLabelFontSize = axis.getAxisLabelFontSize();\n\t\t\t}\n\t\t}\n\t\treturn maxAxisLabelFontSize;\n\t}\n\n\tpublic int getAxisCount() {\n\t\treturn axes.size();\n\t}\n\n\tpublic int getAxisLabelVerticalDistance() {\n\t\treturn chartSettings.getInteger(Key.PARALLEL_COORDINATES_LABELS_VERTICAL_DISTANCE);\n\t}\n\n\tpublic boolean isVerticallyOffsetAxisLabels() {\n\t\treturn chartSettings.getBoolean(Key.PARALLEL_COORDINATES_VERTICALLY_OFFSET_AXIS_LABELS);\n\t}\n\n\tpublic void addAxis(Axis axis) {\n\t\tthis.axes.add(axis);\n\t}\n\n\tpublic void removeAxis(String parameterName) {\n\t\tfor (int i = 0; i < this.axes.size(); i++) {\n\t\t\tif (parameterName.equals(this.axes.get(i).getParameter().getName())) {\n\t\t\t\tthis.axes.remove(i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Axis \" + parameterName + \" not found\");\n\t}\n\n\tpublic void moveAxis(int oldIndex, int newIndex) {\n\t\tAxis axis = this.axes.remove(oldIndex);\n\t\tthis.axes.add(newIndex, axis);\n\t}\n\n\tpublic int getAxisHeight() {\n\t\treturn this.getFrameSize().height - this.getAxisTopPos() - BOTTOM_PADDING;\n\t}\n\n\tpublic int getDesignLabelFontSize() {\n\t\treturn chartSettings.getInteger(Key.DESIGN_LABEL_FONT_SIZE);\n\t}\n\n\tpublic int getLineThickness() {\n\t\treturn chartSettings.getInteger(Key.LINE_THICKNESS);\n\t}\n\n\tpublic void setActiveDesignColor(Color newColor) {\n\t\tchartSettings.getColorSetting(Key.ACTIVE_DESIGN_DEFAULT_COLOR).set(newColor);\n\t}\n\n\tpublic Color getActiveDesignColor() {\n\t\treturn chartSettings.getColor(Key.ACTIVE_DESIGN_DEFAULT_COLOR);\n\t}\n\n\tpublic Color getActiveDesignColorNoAlpha() {\n\t\treturn new Color(getActiveDesignColor().getRGB());\n\t}\n\n\tpublic Color getFilteredDesignColor() {\n\t\treturn chartSettings.getColor(Key.IN_ACTIVE_DESIGN_DEFAULT_COLOR);\n\t}\n\n\tpublic Color getFilteredDesignColorNoAlpha() {\n\t\treturn new Color(getFilteredDesignColor().getRGB());\n\t}\n\n\tpublic Color getDesignColor(Design design, boolean designActive, boolean useAlpha, Color activeDesignColor, Color activeDesignColorNoAlpha, Color filteredDesignColor, Color filteredDesignColorNoAlpha) // design active is function argument to improve performance\n\t{\n\t\tif (designActive && design.hasGradientColor()) {\n\t\t\treturn design.getGradientColor();\n\t\t} else if (designActive && design.getCluster() != null) {\n\t\t\treturn design.getCluster().getActiveDesignColor(useAlpha);\n\t\t} else if (designActive) {\n\t\t\treturn useAlpha ? activeDesignColor : activeDesignColorNoAlpha;\n\t\t}\n\t\telse {\n\t\t\treturn useAlpha ? filteredDesignColor : filteredDesignColorNoAlpha;\n\t\t}\n\t}\n\n\tpublic int getSelectedDesignsLineThickness() {\n\t\treturn chartSettings.getInteger(Key.SELECTED_DESIGN_LINE_THICKNESS);\n\t}\n\n\tpublic Color getDefaultDesignColor(boolean designActive, boolean useAlpha) {\n\t\tif (designActive)\n\t\t\treturn useAlpha ? getActiveDesignColor() : getActiveDesignColorNoAlpha();\n\t\telse\n\t\t\treturn useAlpha ? getFilteredDesignColor() : getFilteredDesignColorNoAlpha();\n\t}\n\n\tpublic Color getSelectedDesignColor() {\n\t\treturn chartSettings.getColor(Key.SELECTED_DESIGN_DEFAULT_COLOR);\n\t}\n\n\tpublic boolean isShowDesignIDs() {\n\t\treturn chartSettings.getBoolean(Key.SHOW_DESIGN_IDS);\n\t}\n\n\tpublic boolean isShowFilteredDesigns() {\n\t\treturn chartSettings.getBoolean(Key.SHOW_FILTERED_DESIGNS);\n\t}\n\n\tpublic boolean isShowOnlySelectedDesigns() {\n\t\treturn chartSettings.getBoolean(Key.PARALLEL_COORDINATES_SHOW_ONLY_SELECTED_DESIGNS);\n\t}\n\n\tpublic Color getFilterColor() {\n\t\treturn chartSettings.getColor(Key.PARALLEL_COORDINATES_FILTER_COLOR);\n\t}\n\n\tpublic int getTopMargin() {\n\t\treturn topMargin;\n\t}\n\n\tpublic void resetDisplaySettingsToDefault(DataSheet dataSheet) {\n\t\tthis.chartSettings.resetToDefault();\n\t\tfor (Axis axis : axes) {\n\t\t\taxis.resetSettingsToDefault(dataSheet);\n\t\t}\n\t}\n\n\tpublic Color getBackGroundColor() {\n\t\treturn chartSettings.getColor(Key.PARALLEL_CHART_BACKGROUND_COLOR);\n\t}\n\n\t@Override\n\tpublic void setBackGroundColor(Color backGroundColor) {\n\t\tthis.chartSettings.getColorSetting(Key.PARALLEL_CHART_BACKGROUND_COLOR).set(backGroundColor);\n\t}\n\n\tpublic int getFilterHeight() {\n\t\treturn chartSettings.getInteger(Key.PARALLEL_COORDINATES_FILTER_HEIGHT);\n\t}\n\n\tpublic int getFilterWidth() {\n\t\treturn chartSettings.getInteger(Key.PARALLEL_COORDINATES_FILTER_WIDTH);\n\t}\n\n\t@Override\n\tpublic void initTransientDataImpl() {\n\t\tthis.chartSettings.initTransientData();\n\t\tthis.axes.forEach(Axis::initTransientData);\n\t}\n\n\tpublic SettingsGroup getChartSettingsGroup() {\n\t\treturn this.chartSettings;\n\t}\n\n\tpublic List<Axis> getAxes() {\n\t\treturn Collections.unmodifiableList(this.axes);\n\t}\n}", "public class ScatterChart2D extends Chart {\n\n\tstatic final long serialVersionUID = 1;\n\tprivate ScatterPlot2D scatterPlot2D;\n\n\tpublic ScatterChart2D(DataSheet dataSheet, boolean showDecorations, Dimension frameSize, int id) {\n\t\tsuper(dataSheet, id);\n\t\tthis.scatterPlot2D = new ScatterPlot2D(dataSheet, showDecorations);\n\t\tthis.setFrameSize(frameSize);\n\n\t}\n\n\tpublic void setCurrentSettingsAsDefault() {\n\t\tUserPreferences userPreferences = UserPreferences.getInstance();\n\t\tuserPreferences.setScatterChart2DDisplayMode(this.scatterPlot2D.getDisplayedDesignSelectionMode());\n\t\tuserPreferences.setScatterChart2DAutofitX(this.scatterPlot2D.isAutofit(AxisType.X));\n\t\tuserPreferences.setScatterChart2DAutofitY(this.scatterPlot2D.isAutofit(AxisType.Y));\n\t\tuserPreferences.setScatterChart2DAxisTitleFontsizeX(this.scatterPlot2D.getAxisLabelFontSize(AxisType.X));\n\t\tuserPreferences.setScatterChart2DAxisTitleFontsizeY(this.scatterPlot2D.getAxisLabelFontSize(AxisType.Y));\n\t\tuserPreferences.setScatterChart2DTicCountX(this.scatterPlot2D.getTicCount(AxisType.X));\n\t\tuserPreferences.setScatterChart2DTicCountY(this.scatterPlot2D.getTicCount(AxisType.Y));\n\t\tuserPreferences.setScatterChart2DTicLabelFontsizeX(this.scatterPlot2D.getTicLabelFontSize(AxisType.X));\n\t\tuserPreferences.setScatterChart2DTicLabelFontsizeY(this.scatterPlot2D.getTicLabelFontSize(AxisType.Y));\n\t\tuserPreferences.setScatterChart2DDataPointSize(this.scatterPlot2D.getDotRadius());\n\t\tuserPreferences.setScatterChart2DForegroundColor(this.scatterPlot2D.getDecorationsColor());\n\t\tuserPreferences.setScatterChart2DBackgroundColor(this.scatterPlot2D.getBackGroundColor());\n\t\tuserPreferences.setScatterChart2DActiveDesignColor(this.scatterPlot2D.getActiveDesignColor());\n\t\tuserPreferences.setScatterChart2DSelectedDesignColor(this.scatterPlot2D.getSelectedDesignColor());\n\n\t}\n\n\tpublic int getWidth() {\n\t\treturn this.getFrameSize().width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn this.getFrameSize().height;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn \"2D Scatter Chart \" + this.getID();\n\t}\n\n\tpublic ScatterPlot2D getScatterPlot2D() {\n\t\treturn this.scatterPlot2D;\n\t}\n\n\tpublic Color getBackGroundColor() {\n\t\treturn this.scatterPlot2D.getBackGroundColor();\n\t}\n\n\tpublic void setBackGroundColor(Color backGroundColor) {\n\t\tthis.scatterPlot2D.setBackGroundColor(backGroundColor);\n\t}\n\n\tpublic void resetDisplaySettingsToDefault(DataSheet dataSheet) {\n\t\tthis.scatterPlot2D.resetDisplaySettingsToDefault();\n\t}\n\n\t@Override\n\tpublic void initTransientDataImpl() {\n\n\t}\n\n}", "public class ScatterPlot2D extends Plot {\n\tstatic final long serialVersionUID = 4;\n\tpublic static final int SHOW_ALL_DESIGNS = 0;\n\tpublic static final int SHOW_SELECTED_DESIGNS = 1;\n\tpublic static final int SHOW_DESIGNS_ACTIVE_IN_PARALLEL_CHART = 2;\n\tpublic static final int AXIS_LABEL_PADDING = 10;\n\tpublic static final int TIC_LABEL_PADDING = 5;\n\tpublic static final String TIC_LABEL_FORMAT = \"%4.3f\";\n\tprivate int displayedDesignSelectionMode = SHOW_ALL_DESIGNS;\n\t@Nullable\n\tprivate ParallelCoordinatesChart parallelCoordinatesChartForFiltering;\n\tprivate int dotRadius = 4;\n\tprivate Color activeDesignColor = new Color(0, 150, 0);\n\tprivate Color selectedDesignColor = Color.BLUE;\n\tprivate Parameter parameterForXAxis;\n\tprivate Parameter parameterForYAxis;\n\tprivate boolean showDecorations;\n\tprivate Color decorationsColor = Color.BLACK;\n\tprivate boolean autofitX = true;\n\tprivate boolean autofitY = true;\n\tprivate int ticCountX = 2;\n\tprivate int ticCountY = 2;\n\tprivate int ticSize = 5;\n\tprivate final Map<String, Double> minValues = new HashMap<>();\n\tprivate final Map<String, Double> maxValues = new HashMap<>();\n\tprivate int axisLabelFontSizeX = 20;\n\tprivate int axisLabelFontSizeY = 20;\n\tprivate int ticLabelFontSizeX = 12;\n\tprivate int ticLabelFontSizeY = 12;\n\n\tScatterPlot2D(DataSheet dataSheet, boolean showDecorations) {\n\t\tsuper();\n\t\tthis.showDecorations = showDecorations;\n\t\tif (dataSheet.getParameterCount() > 1) {\n\t\t\tthis.parameterForXAxis = dataSheet.getParameter(0);\n\t\t\tthis.parameterForYAxis = dataSheet.getParameter(1);\n\t\t} else if (dataSheet.getParameterCount() > 0) {\n\t\t\tthis.parameterForXAxis = dataSheet.getParameter(0);\n\t\t\tthis.parameterForYAxis = dataSheet.getParameter(0);\n\t\t}\n\t\tfor (int i = 0; i < dataSheet.getParameterCount(); i++) {\n\t\t\tautofitParam(dataSheet, dataSheet.getParameter(i));\n\t\t}\n\n\t\tresetDisplaySettingsToDefault();\n\t}\n\n\tpublic Color getDesignColor(Design design) {\n\t\tif (design.getCluster() != null) {\n\t\t\treturn design.getCluster().getActiveDesignColor(false);\n\t\t} else {\n\t\t\treturn activeDesignColor;\n\t\t}\n\t}\n\n\tpublic Color getActiveDesignColor() {\n\t\treturn activeDesignColor;\n\t}\n\n\tpublic void setActiveDesignColor(Color activeDesignColor) {\n\t\tthis.activeDesignColor = activeDesignColor;\n\t}\n\n\tpublic int getDisplayedDesignSelectionMode() {\n\t\treturn displayedDesignSelectionMode;\n\t}\n\n\tpublic void setDisplayedDesignSelectionMode(int displayedDesignSelectionMode) {\n\t\tthis.displayedDesignSelectionMode = displayedDesignSelectionMode;\n\t}\n\n\t@Nullable\n\tpublic ParallelCoordinatesChart getParallelCoordinatesChartForFiltering() {\n\t\treturn parallelCoordinatesChartForFiltering;\n\t}\n\n\tpublic void setParallelCoordinatesChartForFiltering(@Nullable ParallelCoordinatesChart parallelCoordinatesChartForFiltering) {\n\t\tthis.parallelCoordinatesChartForFiltering = parallelCoordinatesChartForFiltering;\n\t}\n\n\tpublic int getDotRadius() {\n\t\treturn dotRadius;\n\t}\n\n\tpublic void setDotRadius(int dotRadius) {\n\t\tthis.dotRadius = dotRadius;\n\t}\n\n\tpublic Color getSelectedDesignColor() {\n\t\treturn selectedDesignColor;\n\t}\n\n\tpublic void setSelectedDesignColor(Color selectedDesignColor) {\n\t\tthis.selectedDesignColor = selectedDesignColor;\n\t}\n\n public Parameter getParameterForAxis(AxisType axisType) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\treturn parameterForXAxis;\n\t\t\tcase Y:\n\t\t\t\treturn parameterForYAxis;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic void setParameterForAxis(AxisType axisType, Parameter parameter) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\tthis.parameterForXAxis = parameter;\n\t\t\t\tbreak;\n\t\t\tcase Y:\n this.parameterForYAxis = parameter;\n break;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic Color getDecorationsColor() {\n\t\treturn decorationsColor;\n\t}\n\n\tpublic void setDecorationsColor(Color decorationsColor) {\n\t\tthis.decorationsColor = decorationsColor;\n\t}\n\n\tpublic boolean isAutofit(AxisType axisType) {\n\t\tswitch (axisType) {\n\t\t\tcase X: return autofitX;\n\t\t\tcase Y: return autofitY;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic void setAutofit(AxisType axisType, boolean autofit) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\tthis.autofitX = autofit;\n\t\t\t\tbreak;\n\t\t\tcase Y:\n\t\t\t\tthis.autofitY = autofit;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic void autofit(DataSheet dataSheet, AxisType axisType) {\n\t\tParameter parameter = getParameterForAxis(axisType);\n\t\tautofitParam(dataSheet, parameter);\n\t}\n\n\tprivate void autofitParam(DataSheet dataSheet, Parameter parameter) {\n\t\tsetMin(parameter, dataSheet.getMinValueOf(parameter));\n\t\tsetMax(parameter, dataSheet.getMinValueOf(parameter));\n\t}\n\n\tpublic void setMin(AxisType axisType, double value) {\n Parameter parameter = getParameterForAxis(axisType);\n\t\tsetMin(parameter, value);\n\t}\n\n\tprivate void setMin(Parameter parameter, double value) {\n\t\tthis.minValues.put(parameter.getName(), value);\n\t}\n\n\tpublic double getMin(AxisType axisType) {\n Parameter parameter = getParameterForAxis(axisType);\n return this.minValues.get(parameter.getName());\n\t}\n\n\tpublic void setMax(AxisType axisType, double value) {\n Parameter parameter = getParameterForAxis(axisType);\n\t\tsetMax(parameter, value);\n\t}\n\n\tprivate void setMax(Parameter parameter, double value) {\n\t\tthis.maxValues.put(parameter.getName(), value);\n\t}\n\n\tpublic double getMax(AxisType axisType) {\n Parameter parameter = getParameterForAxis(axisType);\n\t\treturn this.maxValues.get(parameter.getName());\n\t}\n\n\tpublic int getTicSize() {\n\t\treturn ticSize;\n\t}\n\n\n\tpublic void setTicCount(AxisType axisType, int value) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\tthis.ticCountX = value;\n\t\t\t\tbreak;\n\t\t\tcase Y:\n\t\t\t\tthis.ticCountY = value;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic int getTicCount(AxisType axisType) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\treturn ticCountX;\n\t\t\tcase Y:\n\t\t\t\treturn ticCountY;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic void setAxisLabelFontSize(AxisType axisType, int value) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\tthis.axisLabelFontSizeX = value;\n\t\t\t\tbreak;\n\t\t\tcase Y:\n\t\t\t\tthis.axisLabelFontSizeY = value;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic int getAxisLabelFontSize(AxisType axisType) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\treturn axisLabelFontSizeX;\n\t\t\tcase Y:\n\t\t\t\treturn axisLabelFontSizeY;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic void setTicLabelFontSize(AxisType axisType, int value) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\tthis.ticLabelFontSizeX = value;\n\t\t\t\tbreak;\n\t\t\tcase Y:\n\t\t\t\tthis.ticLabelFontSizeY = value;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic int getTicLabelFontSize(AxisType axisType) {\n\t\tswitch (axisType) {\n\t\t\tcase X:\n\t\t\t\treturn ticLabelFontSizeX;\n\t\t\tcase Y:\n\t\t\t\treturn ticLabelFontSizeY;\n\t\t\tdefault: throw new IllegalArgumentException(\"Unknown axis type \"+axisType);\n\t\t}\n\t}\n\n\tpublic int getPlotAreaDistanceToLeft(int ticLabelOffset) {\n\t\tint distance = this.getMargin();\n\t\tif (this.showDecorations) {\n\t\t\tdistance = distance + this.axisLabelFontSizeY + 2 * AXIS_LABEL_PADDING + 2 * TIC_LABEL_PADDING + ticLabelOffset;\n\t\t}\n\t\treturn distance;\n\t}\n\n\tpublic int getPlotAreaDistanceToRight() {\n\t\tint distance = this.getMargin();\n\t\tif (this.showDecorations) {\n\t\t\tdistance = distance + 2 * AXIS_LABEL_PADDING;\n\t\t}\n\t\treturn distance;\n\t}\n\n\tpublic int getPlotAreaDistanceToTop() {\n\t\tint distance = this.getMargin();\n\t\tif (this.showDecorations) {\n\t\t\tdistance = distance + 2 * AXIS_LABEL_PADDING;\n\t\t}\n\t\treturn distance;\n\t}\n\n\tpublic int getPlotAreaDistanceToBottom() {\n\t\tint distance = this.getMargin();\n\t\tif (this.showDecorations) {\n\t\t\tdistance = distance + this.axisLabelFontSizeX + 2 * AXIS_LABEL_PADDING + this.ticLabelFontSizeX + 2 * TIC_LABEL_PADDING;\n\t\t}\n\t\treturn distance;\n\t}\n\n\tpublic boolean isShowDecorations() {\n\t\treturn showDecorations;\n\t}\n\n\tpublic void resetDisplaySettingsToDefault() {\n\t\tUserPreferences userPreferences = UserPreferences.getInstance();\n\t\tthis.setDisplayedDesignSelectionMode(userPreferences.getScatterChart2DDisplayMode());\n\t\tthis.autofitX = userPreferences.isScatterChart2DAutofitX();\n\t\tthis.autofitY = userPreferences.isScatterChart2DAutofitY();\n\t\tthis.axisLabelFontSizeX = userPreferences.getScatterChart2DAxisTitleFontsizeX();\n\t\tthis.axisLabelFontSizeY = userPreferences.getScatterChart2DAxisTitleFontsizeY();\n\t\tthis.ticCountX = userPreferences.getScatterChart2DTicCountX();\n\t\tthis.ticCountY = userPreferences.getScatterChart2DTicCountY();\n\t\tthis.ticLabelFontSizeX = userPreferences.getScatterChart2DTicLabelFontsizeX();\n\t\tthis.ticLabelFontSizeY = userPreferences.getScatterChart2DTicLabelFontsizeY();\n\t\tthis.setDotRadius(userPreferences.getScatterChart2DDataPointSize());\n\t\tthis.setDecorationsColor(userPreferences.getScatterChart2DForegroundColor());\n\t\tthis.setBackGroundColor(userPreferences.getScatterChart2DBackgroundColor());\n\t\tthis.setActiveDesignColor(userPreferences.getScatterChart2DActiveDesignColor());\n\t\tthis.setSelectedDesignColor(userPreferences.getScatterChart2DSelectedDesignColor());\n\t}\n}", "public enum AxisType {\n X(\"X-Axis\"),\n Y(\"Y-Axis\");\n\n private String label;\n\n AxisType(String label) {\n this.label = label;\n }\n\n public String getLabel() {\n return label;\n }\n}", "public class DataSheet implements Serializable, ListModel {\n\n\tstatic final long serialVersionUID = 8;\n\tprivate List<Design> data = new ArrayList<>();\n\tprivate Map<Integer, Design> designIdsMap = new HashMap<>();\n\tprivate List<Parameter> parameters = new LinkedList<>();\n\tprivate transient List<ListDataListener> listDataListener;\n\tprivate transient List<DatasheetListener> listeners;\n\tprivate String delimiter;\n\n\tpublic void initTransientData() {\n\t\tthis.listDataListener = new ArrayList<>();\n\t\tthis.listeners = new ArrayList<>();\n\t}\n\n\tpublic DataSheet(String pathToInputFile, boolean dataHasHeaders, Main mainWindow, ProgressMonitor progressMonitor) throws IOException {\n\t\tinitTransientData();\n\t\tUserPreferences userPreferences = UserPreferences.getInstance();\n\t\tthis.delimiter = userPreferences.getDelimiter();\n\t\tif (userPreferences.isTreatConsecutiveAsOne())\n\t\t\tthis.delimiter = this.delimiter + \"+\";\n\t\timportData(pathToInputFile, dataHasHeaders, progressMonitor);\n\t\tboolean continueChecking = true;\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (parameter.isMixed(this) && continueChecking) {\n\t\t\t\tint userAction = JOptionPane.showConfirmDialog(mainWindow, \"Parameter \" + parameter.getName() + \" has numeric values in some designs\\n\" + \"and non-numerical values in others. \\nThis will result in the parameter being treated as a \\n\" + \"non-numeric parameter. \\n\" + \"If this is incorrect it is recommended to find the design(s)\\n\" + \"with non-numeric values and correct or remove them.\\n\\n\" + \"Press Ok to continue checking parameters or Cancel to\\n\" + \"suppress further warnings.\", \"Mixed Parameter Warning\", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);\n\t\t\t\tcontinueChecking = (userAction == JOptionPane.OK_OPTION);\n\t\t\t}\n\t\t\tparameter.setTicLabelDigitCount(userPreferences.getParallelCoordinatesAxisTicLabelDigitCount());\n\t\t}\n\t}\n\n\tprivate void importData(String pathToInputFile, boolean dataHasHeaders, ProgressMonitor progressMonitor) throws IOException {\n\t\tList<Design> buffer = new ArrayList<>();\n\t\tif (this.data != null) {\n\t\t\tbuffer = new ArrayList<>(this.data);\n\t\t}\n\t\tint lineCount = getLineCount(pathToInputFile);\n\t\tprogressMonitor.setMaximum(lineCount);\n\n\t\tBufferedReader f;\n\t\tString line;\n\t\tint idCounter = 1;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\t\tline = (f.readLine()).trim();\n\n\t\tString[] lineElements = line.split(this.delimiter);\n\t\tif (dataHasHeaders) {\n\t\t\t// if data has headers read the parameter names from the first line\n\t\t\tfor (String lineElement : lineElements) {\n\t\t\t\tthis.parameters.add(new Parameter(this.getUniqueParameterName(lineElement), this));\n\t\t\t}\n\t\t} else {\n\t\t\t// if data does not have headers read the first Design from the first line and create default Parameter names\n\t\t\tDesign newDesign = new Design(idCounter++);\n\t\t\tfor (int i = 0; i < lineElements.length; i++) {\n\t\t\t\tthis.parameters.add(new Parameter(\"Parameter \" + (i + 1), this));\n\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\n\t\t\t}\n\t\t\tthis.data.add(newDesign);\n\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t\tprogressMonitor.setProgress(idCounter - 1);\n\t\t}\n\t\ttry {\n\t\t\treadDesignsFromFile(progressMonitor, f, idCounter);\n\t\t} catch (IOException e) {\n\n\t\t\tthis.data = buffer;\n\t\t\tthrow e;\n\t\t}\n\t\tf.close();\n\t\tif (progressMonitor.isCanceled()) {\n\t\t\tthis.data = buffer;\n\t\t}\n\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\t}\n\n\tpublic void updateData(String pathToInputFile, boolean dataHasHeaders, ProgressMonitor progressMonitor, ClusterSet clusterSet) throws IOException, InconsistentDataException {\n\t\tint lineCount = getLineCount(pathToInputFile);\n\t\tprogressMonitor.setMaximum(lineCount);\n\n\t\tBufferedReader f;\n\t\tString line;\n\t\tint idCounter = 1;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\n\t\t// check datasheet to be read for consistency\n\t\tline = (f.readLine()).trim();\n\t\tString[] lineElements = line.split(this.delimiter);\n\t\tif (lineElements.length != this.getParameterCount()) {\n\t\t\tf.close();\n\t\t\tthrow new InconsistentDataException(pathToInputFile);\n\t\t}\n\n\t\tList<Design> buffer = new ArrayList<>(this.data);\n\t\tMap<Integer, Design> idbuffer = new HashMap<>(this.designIdsMap);\n\t\t// clusterId -> designHashes\n\t\tMap<Integer, Set<Integer>> clustersToDesignHashes = computeClusterDesignHashes(this.data);\n\t\tthis.data.clear();\n\t\tthis.designIdsMap.clear();\n\n\t\t// if data has headers read the parameter names from the first line\n\t\tif (dataHasHeaders){\n\t\t\tfor (Parameter parameter : this.parameters) {\n\t\t\t\tparameter.setName(null);\n\t\t\t}\n\t\t\tfor (int i = 0; i < lineElements.length; i++) {\n\t\t\t\tthis.parameters.get(i).setName(this.getUniqueParameterName(lineElements[i]));\n\t\t\t}\n\t\t\t// if data does not have headers read the first Design from the first line and create default Parameter names\n\t\t} else {\n\t\t\tDesign newDesign = new Design(idCounter++);\n\t\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\t\tif (lineElements.length <= i) {\n\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), \"-\", this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.parameters.get(i).setName(\"Parameter \" + (i + 1));\n\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tthis.data.add(newDesign);\n\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t}\n\n\t\ttry {\n\t\t\treadDesignsFromFile(progressMonitor, f, idCounter);\n\t\t} catch (IOException e) {\n\t\t\tthis.data = buffer;\n\t\t\tthis.designIdsMap = idbuffer;\n\t\t\tthrow e;\n\t\t}\n\t\tf.close();\n\t\tif (progressMonitor.isCanceled()) {\n\t\t\tthis.data = buffer;\n\t\t\tthis.designIdsMap = idbuffer;\n\t\t}\n\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tparameter.updateNumeric(this);\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\n\t\trestoreClustersFromHashes(clustersToDesignHashes, this.data, clusterSet);\n\n\t\tfireOnDataChanged(initialiseBooleanArray(true), initialiseBooleanArray(true), initialiseBooleanArray(true));\n\t\tfireDataPanelUpdateRequired();\n\n\t}\n\n\tprivate void restoreClustersFromHashes(Map<Integer, Set<Integer>> clustersToDesignHashes, List<Design> designs, ClusterSet clusterSet) {\n\t\tfor (Map.Entry<Integer, Set<Integer>> entry : clustersToDesignHashes.entrySet()) {\n\t\t\tInteger clusterId = entry.getKey();\n\t\t\tSet<Integer> designHashes = entry.getValue();\n\t\t\tclusterSet.findClusterById(clusterId).ifPresent(cluster -> {\n\t\t\t\tfor (Design design : designs) {\n\t\t\t\t\tif (designHashes.contains(design.computeValuesHash(parameters))) {\n\t\t\t\t\t\tdesign.setCluster(cluster);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate Map<Integer, Set<Integer>> computeClusterDesignHashes(List<Design> designs) {\n\t\tMap<Integer, Set<Integer>> clustersToDesignHashes = new HashMap<>();\n\t\tfor (Design design : designs) {\n\t\t\tCluster cluster = design.getCluster();\n\t\t\tif(cluster != null) {\n\t\t\t\tclustersToDesignHashes\n\t\t\t\t\t\t.computeIfAbsent(cluster.getUniqueId(), k -> new HashSet<>())\n\t\t\t\t\t\t.add(design.computeValuesHash(parameters));\n\t\t\t}\n\t\t}\n\t\treturn clustersToDesignHashes;\n\t}\n\n\tprivate void readDesignsFromFile(ProgressMonitor progressMonitor, BufferedReader f, int idCounter) throws IOException {\n\t\tString line;\n\t\tString[] lineElements;\n\t\twhile ((line = f.readLine()) != null && !progressMonitor.isCanceled()) // read all subsequent lines into Designs\n\t\t{\n\t\t\tprogressMonitor.setProgress(idCounter - 1);\n\t\t\tDesign newDesign;\n\t\t\tlineElements = line.split(this.delimiter);\n\t\t\tif (lineElements.length > 0) {\n\t\t\t\tnewDesign = new Design(idCounter++);\n\t\t\t\tboolean newDesignContainsValues = false;\n\t\t\t\tfor (String lineElement : lineElements) {\n\t\t\t\t\tif (lineElement.length() > 0 && (!lineElement.equals(\"\\\\s\"))) {\n\t\t\t\t\t\tnewDesignContainsValues = true; // found non-empty empty\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (newDesignContainsValues) {\n\t\t\t\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\t\t\t\tif (lineElements.length <= i || lineElements[i].length() <= 0 || lineElements[i].equals(\"\\\\s\")) {\n\t\t\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), \"-\", this);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnewDesign.setValue(this.parameters.get(i), lineElements[i], this);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.data.add(newDesign);\n\t\t\t\t\tthis.designIdsMap.put(newDesign.getId(), newDesign);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setValueAt(Object newValue, int rowIndex, int columnIndex) {\n\t\tParameter parameter = this.parameters.get(columnIndex - 1);\n\t\tboolean previousNumeric = parameter.isNumeric();\n\t\tboolean[] axisAutofitRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisResetFilterRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisApplyFiltersRequired = initialiseBooleanArray(false);\n\t\tthis.data.get(rowIndex).setValue(parameters.get(columnIndex - 1), newValue.toString(), this);\n\n\t\tif (!previousNumeric) {\n\t\t\tparameter.updateDiscreteLevels(this);\n\t\t}\n\n\t\tOptional<Float> parsed = NumberParser.parseNumber(newValue.toString());\n\t\tboolean parsable = parsed.isPresent();\n\n\t\tif(previousNumeric && !parsable) {\n\t\t\tparameter.setNumeric(false, this);\n\t\t} else if (!previousNumeric && parsable) {\n\t\t\tparameter.updateNumeric(this);\n\t\t}\n\t\tif (previousNumeric != parameter.isNumeric()) {\n\t\t\taxisAutofitRequired[columnIndex - 1] = true;\n\t\t\taxisResetFilterRequired[columnIndex - 1] = true;\n\t\t}\n\n\t\taxisApplyFiltersRequired[columnIndex - 1] = true;\n\t\tfireOnDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired);\n\t}\n\n\tprivate int getLineCount(String pathToInputFile) throws IOException {\n\t\tBufferedReader f;\n\t\tf = new BufferedReader(new FileReader(pathToInputFile));\n\t\tint lineCount = 0;\n\t\twhile ((f.readLine()) != null)\n\t\t\tlineCount++;\n\t\tf.close();\n\t\treturn lineCount;\n\t}\n\n\tpublic Design getDesign(int i) {\n\t\treturn this.data.get(i);\n\t}\n\n\tpublic Design getDesignByID(int id) {\n\t\treturn this.designIdsMap.get(id);\n\t}\n\n\tpublic void removeDesigns(int[] designsToRemove) {\n\t\tboolean[] axisAutofitRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisResetFilterRequired = initialiseBooleanArray(false);\n\t\tboolean[] axisApplyFiltersRequired = initialiseBooleanArray(false);\n\n\t\tboolean[] discrete = new boolean[this.parameters.size()]; // check which parameters are discrete\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\tdiscrete[i] = !this.parameters.get(i).isNumeric();\n\t\t}\n\n\t\tfor (int i = designsToRemove.length - 1; i >= 0; i--) {\n\t\t\tDesign removedDesign = data.remove(designsToRemove[i]);\n\t\t\tthis.designIdsMap.remove(removedDesign.getId());\n\t\t\t// check if that makes any non-numeric parameter numeric\n\t\t\tfor (Parameter parameter : this.parameters) {\n\t\t\t\tif (!parameter.isNumeric()) {\n\t\t\t\t\tString string = removedDesign.getStringValue(parameter);\n\t\t\t\t\tif (!NumberParser.parseNumber(string).isPresent()) {\n\t\t\t\t\t\tparameter.updateNumeric(this);\n\t\t\t\t\t\tparameter.updateDiscreteLevels(this);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\taxisAutofitRequired[i] = discrete[i] && this.parameters.get(i).isNumeric();\n\t\t\taxisApplyFiltersRequired[i] = true;\n\t\t}\n\n\t\tfireOnDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired);\n\t\tfireDataPanelUpdateRequired();\n\t}\n\n\tpublic int getParameterCount() {\n\t\treturn this.parameters.size();\n\t}\n\n\tpublic String getParameterName(int index) {\n\t\tif (index >= this.parameters.size() || index < 0)\n\t\t\tthrow new IllegalArgumentException(\"Invalid Index \" + index);\n\t\treturn this.parameters.get(index).getName();\n\t}\n\n\tpublic Parameter getParameter(int index) {\n\t\tif (index >= this.parameters.size() || index < 0)\n\t\t\tthrow new IllegalArgumentException(\"Invalid Index \" + index);\n\t\treturn this.parameters.get(index);\n\t}\n\n\tpublic Parameter getParameter(String parameterName) {\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (parameterName.equals(parameter.getName())) {\n\t\t\t\treturn parameter;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Parameter \" + parameterName + \" not found\");\n\t}\n\n\tpublic int getParameterIndex(String parameterName) {\n\t\tfor (int i = 0; i < this.parameters.size(); i++) {\n\t\t\tif (parameterName.equals(this.parameters.get(i).getName())) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Parameter \" + parameterName + \" not found\");\n\t}\n\n public boolean parameterExists(Parameter param) {\n\t\treturn this.parameters.contains(param);\n\t}\n\n\tpublic double getMaxValueOf(Parameter param) {\n\t\tif (param.isNumeric()) {\n\t\t\tdouble max = Double.NEGATIVE_INFINITY;\n\t\t\tfor (Design datum : this.data) {\n\t\t\t\tif (max < datum.getDoubleValue(param)) {\n\t\t\t\t\tmax = datum.getDoubleValue(param);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn max;\n\t\t} else {\n\t\t\treturn param.getDiscreteLevelCount() - 1;\n\t\t}\n\t}\n\n\tpublic double getMinValueOf(Parameter param) {\n\t\tif (param.isNumeric()) {\n\t\t\tdouble min = Double.POSITIVE_INFINITY;\n\t\t\tfor (Design datum : this.data) {\n\t\t\t\tif (min > datum.getDoubleValue(param)) {\n\t\t\t\t\tmin = datum.getDoubleValue(param);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn min;\n\t\t} else {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\tpublic int getDesignCount() {\n\t\treturn this.data.size();\n\t}\n\n\tprivate String getUniqueParameterName(String nameSuggestion) {\n\t\tString name = nameSuggestion;\n\t\tint id = 2;\n\t\twhile (!isNameUnique(name)) {\n\t\t\tname = nameSuggestion + \" (\" + (id++) + \")\";\n\t\t}\n\t\treturn name;\n\t}\n\n\tprivate boolean isNameUnique(String name) {\n\t\tboolean unique = true;\n\t\tfor (Parameter parameter : this.parameters) {\n\t\t\tif (name.equals(parameter.getName())) {\n\t\t\t\tunique = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn unique;\n\t}\n\n\tpublic void evaluateBoundsForAllDesigns(ParallelCoordinatesChart chart) {\n\t\tfor (int i = 0; i < this.getDesignCount(); i++) {\n\t\t\tthis.data.get(i).evaluateBounds(chart, this);\n\t\t}\n\t}\n\n\tpublic void moveParameter(int oldIndex, int newIndex) {\n\t\tParameter param = this.parameters.remove(oldIndex);\n\t\tthis.parameters.add(newIndex, param);\n\t}\n\n\tprivate boolean[] initialiseBooleanArray(boolean value) {\n\t\tboolean[] array = new boolean[this.getParameterCount()];\n\t\tfor (int i = 0; i < this.getParameterCount(); i++) {\n\t\t\tarray[i] = value;\n\t\t}\n\t\treturn array;\n\t}\n\n\t@Override\n\tpublic void addListDataListener(ListDataListener l) {\n\t\tlistDataListener.add(l);\n\t}\n\n\t@Override\n\tpublic Object getElementAt(int index) {\n\t\treturn this.parameters.get(index).getName();\n\t}\n\n\t@Override\n\tpublic int getSize() {\n\t\treturn this.parameters.size();\n\t}\n\n\t@Override\n\tpublic void removeListDataListener(ListDataListener l) {\n\t\tlistDataListener.remove(l);\n\t}\n\n\tpublic void addListener(DatasheetListener l) {\n\t\tthis.listeners.add(l);\n\t}\n\n\tpublic void removeListener(DatasheetListener l) {\n\t\tthis.listeners.remove(l);\n\t}\n\n\tprivate void fireListeners(Consumer<DatasheetListener> action) {\n\t\tfor (DatasheetListener listener : this.listeners) {\n\t\t\taction.accept(listener);\n\t\t}\n\t}\n\n\tvoid onClustersUpdated(List<Cluster> changed, List<Cluster> added, List<Cluster> removed) {\n\t\tfor (Cluster removedCluster : removed) {\n\t\t\tfor (int j = 0; j < getDesignCount(); j++) {\n\t\t\t\tif (removedCluster.equals(getDesign(j).getCluster())) {\n\t\t\t\t\tgetDesign(j).setCluster(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (changed.isEmpty() && added.isEmpty() && removed.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\tfireClustersChanged();\n\t}\n\n\tpublic Collection<Design> getDesigns() {\n\t\treturn Collections.unmodifiableList(this.data);\n\t}\n\n\tpublic List<Parameter> getParameters() {\n\t\treturn Collections.unmodifiableList(this.parameters);\n\t}\n\n\tpublic void fireClustersChanged() {\n\t\tfireListeners(DatasheetListener::onClustersChanged);\n\t}\n\n\tpublic void fireDataPanelUpdateRequired() {\n\t\tfireListeners(DatasheetListener::onDataPanelUpdateRequired);\n\t}\n\n\tpublic void fireOnDataChanged(boolean axisAutofitRequired, boolean axisResetFilterRequired, boolean axisApplyFiltersRequired) {\n\t\tboolean[] autofit = new boolean[parameters.size()];\n\t\tboolean[] resetFilter = new boolean[parameters.size()];\n\t\tboolean[] applyFilters = new boolean[parameters.size()];\n\t\tArrays.fill(autofit, axisAutofitRequired);\n\t\tArrays.fill(resetFilter, axisResetFilterRequired);\n\t\tArrays.fill(applyFilters, axisApplyFiltersRequired);\n\t\tfireOnDataChanged(autofit, resetFilter, applyFilters);\n\t}\n\n\tpublic void fireOnDataChanged(boolean[] axisAutofitRequired, boolean[] axisResetFilterRequired, boolean[] axisApplyFiltersRequired) {\n\t\tfireListeners(l -> l.onDataChanged(axisAutofitRequired, axisResetFilterRequired, axisApplyFiltersRequired));\n\t}\n}", "public class Design implements Serializable {\n\n\tstatic final long serialVersionUID = 4L;\n\tprivate Map<Parameter, String> stringParameterValues = new HashMap<>(0, 1);\n\tprivate Map<Parameter, Float> numericalParameterValues = new HashMap<>(0, 1);\n\tprivate int id;\n\tprivate Cluster cluster;\n\tprivate Map<Filter, Boolean> activationMap = new HashMap<>();\n\tprivate boolean insideBounds;\n\tprivate boolean selected = false;\n\tprivate Color gradientColor = null;\n\tpublic Design(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setValue(Parameter param, String parameterValue, DataSheet dataSheet) {\n\t\tOptional<Float> parsed = NumberParser.parseNumber(parameterValue);\n\t\tif (parsed.isPresent()) {\n\t\t\tthis.numericalParameterValues.put(param, parsed.get());\n\t\t\tthis.stringParameterValues.remove(param);\n\t\t} else {\n\t\t\tparam.setNumeric(false, dataSheet);\n\t\t\tthis.stringParameterValues.put(param, parameterValue);\n\t\t\tthis.numericalParameterValues.remove(param);\n\t\t}\n\t}\n\n\tpublic double getDoubleValue(Parameter param) {\n\t\tif (stringParameterValues.containsKey(param)) {\n\t\t\treturn param.getDoubleValueOf(stringParameterValues.get(param));\n\t\t} else if (numericalParameterValues.containsKey(param) && param.isNumeric()) {\n\t\t\treturn (numericalParameterValues.get(param));\n\t\t} else if (numericalParameterValues.containsKey(param)) {\n\t\t\treturn param.getDoubleValueOf(Float.toString(numericalParameterValues.get(param)));\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unknown parameter \" + param.getName());\n\t\t}\n\t}\n\n\tpublic String getStringValue(Parameter param) {\n\t\tif (stringParameterValues.containsKey(param)) {\n\t\t\treturn (stringParameterValues.get(param));\n\t\t} else if (numericalParameterValues.containsKey(param)) {\n\t\t\treturn Float.toString(numericalParameterValues.get(param));\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unknown parameter \" + param.getName());\n\t\t}\n\t}\n\n\tpublic boolean isActive(ParallelCoordinatesChart chart) {\n\t\tfor (int i = 0; i < chart.getAxisCount(); i++) {\n\t\t\tFilter uf = chart.getAxis(i).getUpperFilter();\n\t\t\tFilter lf = chart.getAxis(i).getLowerFilter();\n\t\t\tif (!this.activationMap.containsKey(uf)) {\n\t\t\t\tthis.activationMap.put(uf, true);\n\t\t\t}\n\t\t\tif (!this.activationMap.containsKey(lf)) {\n\t\t\t\tthis.activationMap.put(lf, true);\n\t\t\t}\n\t\t\tif (chart.getAxis(i).isFilterInverted()) {\n\t\t\t\tif (!(this.activationMap.get(uf) || this.activationMap.get(lf)))\n\t\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tif (!this.activationMap.get(uf))\n\t\t\t\t\treturn false;\n\t\t\t\tif (!this.activationMap.get(lf))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic void setActive(Filter filter, boolean active) {\n\t\tthis.activationMap.put(filter, active);\n\t}\n\n\tpublic void evaluateBounds(ParallelCoordinatesChart chart, DataSheet dataSheet) {\n\t\tthis.insideBounds = true;\n\t\tfor (int i = 0; i < chart.getAxisCount(); i++) {\n\t\t\tif (!isInsideBounds(chart.getAxis(i), dataSheet)) {\n\t\t\t\tthis.insideBounds = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean isInsideBounds(Axis axis, DataSheet dataSheet) {\n\t\tdouble value = this.getDoubleValue(axis.getParameter());\n\t\tdouble max = axis.getMax();\n\t\tdouble min = axis.getMin();\n\t\treturn min <= value && value <= max;\n\t}\n\n\tpublic boolean isInsideBounds(ParallelCoordinatesChart chart) {\n\t\treturn this.insideBounds;\n\t}\n\n\tpublic boolean isSelected() {\n\t\treturn this.selected;\n\t}\n\n\tpublic void setSelected(boolean selected) {\n\t\tthis.selected = selected;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic Cluster getCluster() {\n\t\treturn cluster;\n\t}\n\n\tpublic void setCluster(Cluster cluster) {\n\t\tthis.cluster = cluster;\n\t}\n\n\tpublic Color getGradientColor() {\n\t\treturn gradientColor;\n\t}\n\n\tpublic void setAxisGradientColor(Color gradientColor) {\n\t\tthis.gradientColor = gradientColor;\n\t}\n\t\n\tpublic void removeAxisGradientColor() {\n\t\tthis.gradientColor = null;\n\t}\n\n\tpublic boolean hasGradientColor() {\n\t\treturn (this.gradientColor != null);\n\t}\n\n\tpublic int computeValuesHash(List<Parameter> parameters) {\n\t\treturn Objects.hash(parameters.stream()\n\t\t\t\t.map(p -> new ParameterValue(p, getStringValue(p)))\n\t\t\t\t.toArray());\n\t}\n\n\tprivate static class ParameterValue {\n\t\tprivate final Parameter parameter;\n\t\tprivate final String value;\n\n\t\tprivate ParameterValue(Parameter parameter, String value) {\n\t\t\tthis.parameter = parameter;\n\t\t\tthis.value = value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object o) {\n\t\t\tif (this == o) return true;\n\t\t\tif (o == null || getClass() != o.getClass()) return false;\n\t\t\tParameterValue that = (ParameterValue) o;\n\t\t\treturn Objects.equals(parameter, that.parameter) &&\n\t\t\t\t\tObjects.equals(value, that.value);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Objects.hash(parameter, value);\n\t\t}\n\t}\n}", "public class Parameter implements Serializable {\n\tstatic final long serialVersionUID = 4L;\n\tprivate String name;\n\tprivate boolean numeric = true;\n\tprivate TreeSet<String> discreteLevels = new TreeSet<>(new ReverseStringComparator());\n private int ticLabelDigitCount = 3;\n\tpublic Parameter(String name, DataSheet dataSheet) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Checks whether the parameter is mixed. A parameter is mixed if at least\n\t * one design has a numeric value and at least one design has a non-numeric\n\t * value.\n\t * \n\t * @return true, if the parameter is mixed\n\t * @param dataSheet\n\t */\n\tboolean isMixed(DataSheet dataSheet) {\n\t\treturn getType(dataSheet) == ParameterType.MIXED;\n\t}\n\n\tprivate ParameterType getType(DataSheet dataSheet){\n\t\tboolean foundNumericValue = false;\n\t\tboolean foundStringValue = false;\n for (Design design : dataSheet.getDesigns()) {\n String string = design.getStringValue(this);\n if(NumberParser.parseNumber(string).isPresent()){\n foundNumericValue = true;\n } else {\n foundStringValue = true;\n }\n if(foundNumericValue && foundStringValue) {\n return ParameterType.MIXED;\n }\n }\n if (foundStringValue) {\n return ParameterType.NON_NUMERIC;\n } else if (foundNumericValue) {\n return ParameterType.NUMERIC;\n }\n // This can only happen if we have no designs. Consider the parameter numeric in this case\n return ParameterType.NUMERIC;\n\t}\n\n\tpublic boolean isNumeric() {\n\t\treturn numeric;\n\t}\n\n\tvoid setNumeric(boolean numeric, DataSheet dataSheet) {\n\t\tif (numeric == this.numeric) {\n\t\t\treturn;\n\t\t}\n\t\tthis.numeric = numeric;\n\t\tupdateDiscreteLevels(dataSheet);\n\t}\n\n\t/**\n\t * Gets a numeric representation of a string value for this parameter.\n\t * <p>\n\t * If the parameter is numeric, an attempt is made to parse the string as a\n\t * Double. If this attempt fails, the parameter is not considered numeric anymore,\n\t * but is transformed into a discrete parameter.\n\t * <p>\n\t * If the parameter is not numeric, the string is looked up in the TreeSet\n\t * discreteLevels that should contain all discrete values (that is Strings)\n\t * that were found in the data sheet for this parameter. If the value is not\n\t * found it is added as a new discrete level for this parameter. The treeSet\n\t * is then searched again in order to get the correct index of the new\n\t * discrete level.\n\t * <p>\n\t * If this second search does not yield the result, something unexpected has\n\t * gone wrong and a CorruptDataException is thrown.\n\t * \n\t * @param string\n\t * the string\n\t * @return the numeric representation of the given string\n\t */\n\tdouble getDoubleValueOf(String string) {\n\t\tif (this.numeric) {\n\t\t\tOptional<Float> parsed = NumberParser.parseNumber(string);\n\t\t\tif(parsed.isPresent()) {\n\t\t\t\treturn parsed.get();\n\t\t\t}\n\t\t}\n\n\t\tint index = 0;\n\t\tIterator<String> it = discreteLevels.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tif (string.equalsIgnoreCase(it.next())) {\n\t\t\t\treturn index;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\n\t\t// String not found, add it to discrete levels\n\t\tthis.discreteLevels.add(string);\n\t\tindex = 0;\n\t\tit = discreteLevels.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tString next = it.next();\n\t\t\tif (string.equalsIgnoreCase(next)) {\n\t\t\t\treturn index;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\tthrow new CorruptDataException(this);\n\t}\n\n\t/**\n\t * Gets the string representation of a given double value for this\n\t * parameter.\n\t * <p>\n\t * If the parameter is numeric, the provided value is simply converted to a\n\t * String and returned.\n\t * <p>\n\t * If it is discrete, the double value is casted to an Integer value and\n\t * this value is used as an index to look up the corresponding discrete\n\t * value string in the TreeSet discreteLevels.\n\t * <p>\n\t * If no value is found for the given index the data is assumed to be\n\t * corrupt and a CorruptDataException is thrown.\n\t * \n\t * @param value\n\t * the numeric value\n\t * @return the string representation of the given double value for this\n\t * parameter.\n\t */\n\tpublic String getStringValueOf(double value) {\n\t\tif (this.numeric) {\n\t\t\treturn Double.toString(value);\n\t\t} else {\n\t\t\tint index = (int) value;\n\t\t\tint currentIndex = 0;\n\t\t\tIterator<String> it = discreteLevels.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tString next = it.next();\n\t\t\t\tif (currentIndex == index) {\n\t\t\t\t\treturn next;\n\t\t\t\t}\n\t\t\t\tcurrentIndex++;\n\t\t\t}\n\t\t\tthrow new CorruptDataException(this);\n\t\t}\n\t}\n\n\tpublic int getDiscreteLevelCount() {\n\t\tif (this.isNumeric()) {\n\t\t\tthrow new RuntimeException(\"Parameter \" + this.name + \" is numeric!\");\n\t\t} else {\n\t\t\t// log(\"getDiscreteLevelCount returning size \"+this.discreteLevels.size());\n\t\t\treturn this.discreteLevels.size();\n\t\t}\n\t}\n\n\tvoid updateNumeric(DataSheet dataSheet) {\n\t\tthis.setNumeric(getType(dataSheet) == ParameterType.NUMERIC, dataSheet);\n\n\t}\n\n\tvoid updateDiscreteLevels(DataSheet dataSheet){\n\t this.discreteLevels.clear();\n\t if (isNumeric()) {\n\t return;\n }\n\t this.discreteLevels.addAll(dataSheet.getDesigns()\n .stream()\n .map(d -> d.getStringValue(this))\n .collect(Collectors.toSet()));\n }\n\n\n public void setTicLabelDigitCount(int value) {\n this.ticLabelDigitCount = value;\n }\n\n public int getTicLabelDigitCount(){\n return this.ticLabelDigitCount;\n }\n\n public String getTicLabelFormat() {\n int digitCount = getTicLabelDigitCount();\n return \"%\"+(digitCount+1)+\".\"+digitCount+\"f\";\n }\n\n\tpublic int getLongestTicLabelStringLength(FontMetrics fm, String numberFormat, DataSheet dataSheet) {\n\t\tif (this.isNumeric()) {\n\t\t\tdouble minValue = Double.POSITIVE_INFINITY;\n\t\t\tdouble maxValue = Double.NEGATIVE_INFINITY;\n\n\t\t\tfor (int i = 0; i < dataSheet.getDesignCount(); i++) {\n\t\t\t\tif (dataSheet.getDesign(i).getDoubleValue(this) > maxValue)\n\t\t\t\t\tmaxValue = dataSheet.getDesign(i).getDoubleValue(this);\n\t\t\t\tif (dataSheet.getDesign(i).getDoubleValue(this) < minValue)\n\t\t\t\t\tminValue = dataSheet.getDesign(i).getDoubleValue(this);\n\t\t\t}\n\t\t\tint minLength = fm.stringWidth(String.format(numberFormat, minValue));\n\t\t\tint maxLength = fm.stringWidth(String.format(numberFormat, maxValue));\n\t\t\treturn Math.max(minLength, maxLength);\n\t\t} else {\n\t\t\tint length = 0;\n\t\t\tfor (int i = 0; i < this.getDiscreteLevelCount(); i++) {\n\t\t\t\tint tempLength = fm.stringWidth(this.getStringValueOf(i));\n\t\t\t\tif (tempLength > length)\n\t\t\t\t\tlength = tempLength;\n\t\t\t}\n\t\t\treturn length;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n\tprivate static class ReverseStringComparator implements Comparator<String>, Serializable {\n\t\tstatic final long serialVersionUID = 0L;\n\t\tpublic int compare(String s1, String s2) {\n\t\t\treturn (s2.compareToIgnoreCase(s1));\n\t\t}\n\t}\n}" ]
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import org.jetbrains.annotations.Nullable; import org.xdat.Main; import org.xdat.chart.ParallelCoordinatesChart; import org.xdat.chart.ScatterChart2D; import org.xdat.chart.ScatterPlot2D; import org.xdat.data.AxisType; import org.xdat.data.DataSheet; import org.xdat.data.Design; import org.xdat.data.Parameter;
/* * Copyright 2014, Enguerrand de Rochefort * * This file is part of xdat. * * xdat is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * xdat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xdat. If not, see <http://www.gnu.org/licenses/>. * */ package org.xdat.gui.panels; public class ScatterChart2DPanel extends ChartPanel { static final long serialVersionUID = 1L; private Main mainWindow; private int yAxisOffset = 0; public ScatterChart2DPanel(Main mainWindow, ScatterChart2D chart) { super(chart); this.mainWindow = mainWindow; } public void paintComponent(Graphics g) { super.paintComponent(g); ScatterChart2D chart = (ScatterChart2D) this.getChart();
ScatterPlot2D plot = chart.getScatterPlot2D();
3
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/HomeCommand.java
[ "public class HomeCommandElement extends SelectorCommandElement {\n\n /**\n * HomeCommandElement constructor\n *\n * @param key Text\n */\n public HomeCommandElement(@Nullable Text key) {\n super(key);\n }\n\n @Override\n protected Iterable<String> getChoices(CommandSource source) {\n\n if (!(source instanceof Player)) {\n return null;\n }\n\n Player player = (Player) source;\n List<String> list = new CopyOnWriteArrayList<>();\n PlayerCache.instance.get(player).getHomes().forEach(home -> list.add(home.getName()));\n\n return list;\n }\n\n @Override\n protected Object getValue(String choice) throws IllegalArgumentException {\n return choice;\n }\n\n @Override\n protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {\n final StringBuilder stringBuilder = new StringBuilder(args.next());\n while (args.hasNext()) {\n stringBuilder.append(' ').append(args.next());\n }\n return stringBuilder.toString();\n }\n\n}", "@Entity\n@DynamicUpdate\n@Table(name = \"homes\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"home_id\")\n})\npublic class HomeEntity implements Serializable {\n\n private static final long serialVersionUID = -3949473855412057897L;\n\n @Id\n @Column(name = \"home_id\", unique = true, nullable = false)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n\n @Column(name = \"name\", nullable = false)\n private String name;\n\n @OneToOne(cascade = CascadeType.ALL)\n @JoinColumn(name = \"location_id\", nullable = false)\n private LocationEntity location;\n\n /**\n * HomeEntity default constructor\n */\n public HomeEntity() {\n }\n\n /**\n * HomeEntity constructor\n *\n * @param name String\n * @param location LocationEntity\n */\n public HomeEntity(String name, LocationEntity location) {\n Preconditions.checkNotNull(name);\n Preconditions.checkNotNull(location);\n\n this.name = name;\n this.location = location;\n }\n\n /**\n * @return long\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id long\n */\n public void setId(long id) {\n Preconditions.checkNotNull(id);\n\n this.id = id;\n }\n\n /**\n * @return String\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name String\n */\n public void setName(String name) {\n Preconditions.checkNotNull(name);\n\n this.name = name;\n }\n\n /**\n * @return LocationEntity\n */\n public LocationEntity getLocation() {\n return location;\n }\n\n /**\n * @param location LocationEntity\n */\n public void setLocation(LocationEntity location) {\n Preconditions.checkNotNull(location);\n\n this.location = location;\n }\n}", "@Entity\n@DynamicUpdate\n@Table(name = \"players\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"player_id\")\n})\n@NamedQueries({\n @NamedQuery(name = \"getPlayer\", query = \"from PlayerEntity p where p.identifier = :identifier\")\n})\npublic class PlayerEntity implements Serializable {\n\n private static final long serialVersionUID = -6211408372176281682L;\n\n @Id\n @Column(name = \"player_id\", unique = true, nullable = false)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n\n @Column(name = \"identifier\", unique = true, nullable = false)\n private String identifier;\n\n @Column(name = \"name\", unique = true, nullable = false)\n private String name;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<BackEntity> backs = new HashSet<>();\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<BedEntity> beds = new HashSet<>();\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n private Set<HomeEntity> homes = new HashSet<>();\n\n /**\n * PlayerEntity default constructor\n */\n public PlayerEntity() {\n }\n\n /**\n * PlayerEntity constructor\n *\n * @param player Player\n */\n public PlayerEntity(Player player) {\n Preconditions.checkNotNull(player);\n\n this.identifier = player.getIdentifier();\n this.name = player.getName();\n }\n\n /**\n * @return long\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id long\n */\n public void setId(long id) {\n Preconditions.checkNotNull(id);\n\n this.id = id;\n }\n\n /**\n * @return String\n */\n public String getIdentifier() {\n return identifier;\n }\n\n /**\n * @param identifier String\n */\n public void setIdentifier(String identifier) {\n Preconditions.checkNotNull(identifier);\n\n this.identifier = identifier;\n }\n\n /**\n * @return String\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name String\n */\n public void setName(String name) {\n Preconditions.checkNotNull(name);\n\n this.name = name;\n }\n\n /**\n * @return Set<BackEntity>\n */\n public Set<BackEntity> getBacks() {\n return backs;\n }\n\n /**\n * @param backs Set<BackEntity>\n */\n public void setBacks(Set<BackEntity> backs) {\n Preconditions.checkNotNull(backs);\n\n this.backs = backs;\n }\n\n /**\n * @return Set<BedEntity>\n */\n public Set<BedEntity> getBeds() {\n return beds;\n }\n\n /**\n * @param beds Set<BedEntity>\n */\n public void setBeds(Set<BedEntity> beds) {\n Preconditions.checkNotNull(beds);\n\n this.beds = beds;\n }\n\n /**\n * @return Set<HomeEntity>\n */\n public Set<HomeEntity> getHomes() {\n return homes;\n }\n\n /**\n * @param homes Set<HomeEntity>\n */\n public void setHomes(Set<HomeEntity> homes) {\n Preconditions.checkNotNull(homes);\n\n this.homes = homes;\n }\n}", "public class PlayerTeleportHomeEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Home {\n\n /**\n * PlayerTeleportHomeEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportHomeEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n}", "public class PlayerTeleportPreEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Pre {\n\n /**\n * PlayerTeleportPreEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportPreEvent(Player player, Location<World> location, Vector3d rotation) {\n super(player, location, rotation);\n }\n\n}", "public class PlayerCache {\n\n public static final PlayerCache instance = new PlayerCache();\n\n private final Map<Player, PlayerEntity> cache = new ConcurrentHashMap<>();\n private final Map<Player, ResourceBundle> resourceCache = new ConcurrentHashMap<>();\n\n /**\n * Get the PlayerEntity for this Player from the cache\n *\n * @param player Player\n * @return PlayerEntity\n */\n public PlayerEntity get(Player player) {\n if (!cache.containsKey(player)) {\n PlayerEntity playerEntity = PlayerUtil.getPlayerEntity(player);\n cache.put(player, playerEntity);\n }\n return cache.get(player);\n }\n\n /**\n * Set the PlayerEntity for this Player in the cache\n *\n * @param player Player\n * @param playerEntity PlayerEntity\n */\n public void set(Player player, PlayerEntity playerEntity) {\n cache.put(player, playerEntity);\n }\n\n /**\n * Get the ResourceBundle for this player from the cache\n *\n * @param player Player\n * @return ResourceBundle\n */\n public ResourceBundle getResourceCache(Player player) {\n if (!resourceCache.containsKey(player)) {\n ResourceBundle resourceBundle = ResourceBundle.getBundle(\"lang/messages\", player.getLocale());\n resourceCache.put(player, resourceBundle);\n }\n return resourceCache.get(player);\n }\n\n}", "public class BlockUtil {\n\n /**\n * Is this a solid block?\n *\n * @param blockLoc Block\n * @return Whether or not this block is solid\n */\n public static boolean isSolid(Location blockLoc) {\n if (blockLoc.getProperty(SolidCubeProperty.class).isPresent()) {\n SolidCubeProperty property = (SolidCubeProperty) blockLoc.getProperty(SolidCubeProperty.class).get();\n return property.getValue();\n }\n return false;\n }\n\n /**\n * Is this block a bed?\n *\n * @param blockLoc Block\n * @return Whether or not this block is a bed\n */\n public static boolean isBed(Location<World> blockLoc) {\n return blockLoc.getBlock().getType().equals(BlockTypes.BED);\n }\n\n /**\n * Is this an occupied bed?\n *\n * @param blockLoc Block\n * @return Whether or not this block is an occupied bed\n */\n public static boolean isBedOccupied(Location<World> blockLoc) {\n return isBed(blockLoc) ? blockLoc.getBlock().getTraitValue(BooleanTraits.BED_OCCUPIED).orElse(false) : false;\n }\n\n /**\n * Get the distance between two locations\n *\n * @param a Location\n * @param b Location\n * @return double\n */\n public static double distance(Location a, Location b) {\n double x = Math.pow((a.getX() - b.getX()), 2);\n double y = Math.pow((a.getY() - b.getY()), 2);\n double z = Math.pow((a.getZ() - b.getZ()), 2);\n return Math.sqrt(x + y + z);\n }\n\n}", "public class MessagesUtil {\n\n /**\n * Get the message associated with this key, for this player's locale\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text get(Player player, String key, Object... args) {\n ResourceBundle messages = PlayerCache.instance.getResourceCache(player);\n return messages.containsKey(key) ? Text.of(String.format(messages.getString(key), args)) : Text.EMPTY;\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a success (green).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text success(Player player, String key, Object... args) {\n return Text.of(TextColors.GREEN, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as a warning (gold).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text warning(Player player, String key, Object... args) {\n return Text.of(TextColors.GOLD, get(player, key, args));\n }\n\n /**\n * Get the message associated with this key, for this player's locale.\n * Message colored as an error (red).\n *\n * @param player Player\n * @param key String\n * @param args String.format args\n * @return Text formatting of message\n */\n public static Text error(Player player, String key, Object... args) {\n return Text.of(TextColors.RED, get(player, key, args));\n }\n\n}", "public class PlayerUtil {\n\n /**\n * Get the PlayerEntity in storage for this player\n *\n * @param player Player\n * @return PlayerEntity\n */\n public static PlayerEntity getPlayerEntity(Player player) {\n Optional<PlayerEntity> optional = PlayerRepository.instance.get(player);\n return optional.orElseGet(() -> PlayerRepository.instance.save(new PlayerEntity(player)));\n }\n\n /**\n * Get the last used bed for this player in the current world\n * If the last used bed has been deleted, or is currently occupied, get the next last bed (and so on)\n *\n * @param playerEntity PlayerEntity\n * @param player Player\n * @return BedEntity|null\n */\n public static BedEntity getBed(PlayerEntity playerEntity, Player player) {\n List<BedEntity> beds = new CopyOnWriteArrayList<>(playerEntity.getBeds());\n beds.sort(new BedComparator());\n\n Destinations.getInstance().getLogger().info(\"Beds: \" + beds.size());\n\n for (BedEntity bed : beds) {\n if (bed.getLocation().getWorld().getIdentifier().equals(player.getWorld().getUniqueId().toString())) {\n Location<World> block = player.getWorld().getLocation(bed.getLocation().getLocation().getBlockPosition());\n if (BlockUtil.isBed(block)) {\n if (!BlockUtil.isBedOccupied(block)) {\n return bed;\n }\n } else {\n playerEntity.getBeds().remove(bed);\n playerEntity = PlayerRepository.instance.save(playerEntity);\n PlayerCache.instance.set(player, playerEntity);\n }\n }\n }\n return null;\n }\n\n /**\n * Get a list of Player's homes from the world that player is currently in\n *\n * @param playerEntity PlayerEntity\n * @param location Location\n * @return Set<HomeEntity>\n */\n public static Set<HomeEntity> getFilteredHomes(PlayerEntity playerEntity, Location location) {\n Set<HomeEntity> filtered = new HashSet<>();\n playerEntity.getHomes().forEach(home -> {\n if (home.getLocation().getWorld().getIdentifier().equals(location.getExtent().getUniqueId().toString())) {\n filtered.add(home);\n }\n });\n return filtered;\n }\n\n /**\n * Get a player's home by name\n *\n * @param playerEntity PlayerEntity\n * @param name String\n * @return HomeEntity\n */\n public static HomeEntity getPlayerHomeByName(PlayerEntity playerEntity, String name) {\n for (HomeEntity home : playerEntity.getHomes()) {\n if (home.getName().equalsIgnoreCase(name)) {\n return home;\n }\n }\n return null;\n }\n\n /**\n * Get the next available name for a player's home\n *\n * @param playerEntity PlayerEntity\n * @return String\n */\n public static String getPlayerHomeAvailableName(PlayerEntity playerEntity) {\n int max = 0, temp = 0;\n for (HomeEntity home : playerEntity.getHomes()) {\n if (home.getName().startsWith(\"home\") && home.getName().matches(\".*\\\\d.*\")) {\n temp = Integer.parseInt(home.getName().replaceAll(\"[\\\\D]\", \"\"));\n }\n if (temp > max) {\n max = temp;\n }\n }\n if (playerEntity.getHomes().size() > max) {\n max = playerEntity.getHomes().size();\n }\n return (playerEntity.getHomes().size() == 0) ? \"home\" : \"home\" + Integer.toString(max + 1);\n }\n\n /**\n * Get a list of warps that this player can use\n *\n * @param playerEntity PlayerEntity\n * @return Set<WarpEntity>\n */\n public static Set<WarpEntity> getPlayerWarps(PlayerEntity playerEntity) {\n Set<WarpEntity> results = new HashSet<>();\n WarpCache.instance.get().forEach(warp -> {\n if (!warp.isPrivate()) {\n results.add(warp);\n } else if (warp.getOwner().getIdentifier().equals(playerEntity.getIdentifier())) {\n results.add(warp);\n } else {\n warp.getAccess().forEach(access -> {\n if (access.getPlayer().getIdentifier().equals(playerEntity.getIdentifier())) {\n results.add(warp);\n }\n });\n }\n });\n return results;\n }\n\n}" ]
import com.github.mmonkey.destinations.commands.elements.HomeCommandElement; import com.github.mmonkey.destinations.entities.HomeEntity; import com.github.mmonkey.destinations.entities.PlayerEntity; import com.github.mmonkey.destinations.events.PlayerTeleportHomeEvent; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.persistence.cache.PlayerCache; import com.github.mmonkey.destinations.utilities.BlockUtil; import com.github.mmonkey.destinations.utilities.MessagesUtil; import com.github.mmonkey.destinations.utilities.PlayerUtil; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.world.Location; import java.util.Set;
package com.github.mmonkey.destinations.commands; public class HomeCommand implements CommandExecutor { public static final String[] ALIASES = {"home", "h"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.home.use") .description(Text.of("/home [name]")) .extendedDescription(Text.of("Teleport to the nearest home or to the named home.")) .executor(new HomeCommand()) .arguments(GenericArguments.optional(new HomeCommandElement(Text.of("name")))) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } String name = (String) args.getOne("name").orElse(""); Player player = (Player) src; PlayerEntity playerEntity = PlayerCache.instance.get(player);
Set<HomeEntity> homes = playerEntity.getHomes();
1
Bernardo-MG/repository-pattern-java
src/test/java/com/wandrell/pattern/test/integration/repository/access/h2/eclipselink/ITModifyH2EclipselinkJpaRepository.java
[ "public class PersistenceContextPaths {\n\n /**\n * Eclipselink JPA persistence.\n */\n public static final String ECLIPSELINK = \"classpath:context/persistence/jpa-eclipselink.xml\";\n\n /**\n * Hibernate JPA persistence.\n */\n public static final String HIBERNATE = \"classpath:context/persistence/jpa-hibernate.xml\";\n\n /**\n * Spring JDBC persistence.\n */\n public static final String SPRING_JDBC = \"classpath:context/persistence/spring-jdbc.xml\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private PersistenceContextPaths() {\n super();\n }\n\n}", "public class RepositoryContextPaths {\n\n /**\n * JPA repository.\n */\n public static final String JPA = \"classpath:context/repository/jpa-repository.xml\";\n\n /**\n * Spring JDBC repository.\n */\n public static final String SPRING_JDBC = \"classpath:context/repository/spring-jdbc-repository.xml\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private RepositoryContextPaths() {\n super();\n }\n\n}", "public class DatabaseScriptsPropertiesPaths {\n\n /**\n * MSSQL database scripts.\n */\n public static final String MSSQL = \"classpath:config/db/script/test-script-mssql.properties\";\n\n /**\n * MySQL database scripts.\n */\n public static final String MYSQL = \"classpath:config/db/script/test-script-mysql.properties\";\n\n /**\n * Plain SQL database scripts.\n */\n public static final String PLAIN = \"classpath:config/db/script/test-script-plain.properties\";\n\n /**\n * PostgreSQL database scripts.\n */\n public static final String POSTGRESQL = \"classpath:config/db/script/test-script-postgresql.properties\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private DatabaseScriptsPropertiesPaths() {\n super();\n }\n\n}", "public class JdbcPropertiesPaths {\n\n /**\n * H2 JDBC configuration.\n */\n public static final String H2 = \"classpath:config/persistence/jdbc/test-jdbc-h2.properties\";\n\n /**\n * HSQLDB JDBC configuration.\n */\n public static final String HSQLDB = \"classpath:config/persistence/jdbc/test-jdbc-hsqldb.properties\";\n\n /**\n * MySQL JDBC configuration.\n */\n public static final String MYSQL = \"classpath:config/persistence/jdbc/test-jdbc-mysql.properties\";\n\n /**\n * PostgreSQL JDBC configuration.\n */\n public static final String POSTGRESQL = \"classpath:config/persistence/jdbc/test-jdbc-postgresql.properties\";\n\n /**\n * SQLite JDBC configuration.\n */\n public static final String SQLITE = \"classpath:config/persistence/jdbc/test-jdbc-sqlite.properties\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private JdbcPropertiesPaths() {\n super();\n }\n\n}", "public class JpaPropertiesPaths {\n\n /**\n * H2 JPA configuration.\n */\n public static final String H2 = \"classpath:config/persistence/jpa/test-jpa-h2.properties\";\n\n /**\n * HSQLDB JPA configuration.\n */\n public static final String HSQLDB = \"classpath:config/persistence/jpa/test-jpa-hsqldb.properties\";\n\n /**\n * MySQL JPA configuration.\n */\n public static final String MYSQL = \"classpath:config/persistence/jpa/test-jpa-mysql.properties\";\n\n /**\n * PostgreSQL JPA configuration.\n */\n public static final String POSTGRESQL = \"classpath:config/persistence/jpa/test-jpa-postgresql.properties\";\n\n /**\n * SQLite JPA configuration.\n */\n public static final String SQLITE = \"classpath:config/persistence/jpa/test-jpa-sqlite.properties\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private JpaPropertiesPaths() {\n super();\n }\n\n}", "public class PersistenceProviderPropertiesPaths {\n\n /**\n * Eclipselink JPA persistence provider.\n */\n public static final String ECLIPSELINK = \"classpath:config/persistence/provider/test-provider-jpa-eclipselink.properties\";\n\n /**\n * Hibernate JPA persistence provider.\n */\n public static final String HIBERNATE = \"classpath:config/persistence/provider/test-provider-jpa-hibernate.properties\";\n\n /**\n * Spring JDBC persistence provider.\n */\n public static final String SPRING_JDBC = \"classpath:config/persistence/provider/test-provider-spring-jdbc.properties\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private PersistenceProviderPropertiesPaths() {\n super();\n }\n\n}", "public class TestPropertiesPaths {\n\n /**\n * Test entity bean.\n */\n public static final String ENTITY = \"classpath:config/entity/test-entity.properties\";\n\n /**\n * Test JPA entity.\n */\n public static final String ENTITY_JPA = \"classpath:config/entity/test-entity-jpa.properties\";\n\n /**\n * Private constructor to avoid initialization.\n */\n private TestPropertiesPaths() {\n super();\n }\n\n}", "public abstract class AbstractITModify\n extends AbstractTransactionalTestNGSpringContextTests {\n\n /**\n * The entity manager for the test context.\n */\n @Autowired(required = false)\n private EntityManager emanager;\n\n /**\n * Initial number of entities in the repository.\n */\n @Value(\"${entities.total}\")\n private Integer entitiesCount;\n\n /**\n * Entity for the addition test.\n */\n @Autowired\n @Qualifier(\"newEntity\")\n private TestEntity newEntity;\n\n /**\n * The repository being tested.\n */\n @Autowired\n private FilteredRepository<TestEntity, NamedParameterQueryData> repository;\n\n /**\n * Query for acquiring an entity by it's id.\n */\n @Value(\"${query.byId}\")\n private String selectByIdQuery;\n\n /**\n * Default constructor.\n */\n public AbstractITModify() {\n super();\n }\n\n /**\n * Tests that adding an entity changes the contents of the repository.\n */\n @Test\n @Transactional\n public final void testAdd() {\n // Checks that the id has not been assigned\n Assert.assertNull(newEntity.getId());\n\n // Adds the entity\n getRepository().add(newEntity);\n\n if (emanager != null) {\n // Flushed to force updating ids\n emanager.flush();\n }\n\n // Checks the entity has been added\n Assert.assertEquals(getRepository().getAll().size(), entitiesCount + 1);\n\n // Checks that the id has been assigned\n Assert.assertNotNull(newEntity.getId());\n Assert.assertTrue(newEntity.getId() >= 0);\n }\n\n /**\n * Tests that removing an entity changes the contents of the repository.\n */\n @Test\n @Transactional\n public final void testRemove() {\n final TestEntity entity; // Entity being tested\n final Map<String, Object> parameters; // Params for the query\n final NamedParameterQueryData query; // Query for retrieving the entity\n\n // Acquires the entity\n parameters = new LinkedHashMap<>();\n parameters.put(\"id\", 1);\n query = new DefaultNamedParameterQueryData(selectByIdQuery, parameters);\n entity = getRepository().getEntity(query);\n\n // Removes the entity\n getRepository().remove(entity);\n\n // Checks that the number of entities has decreased\n Assert.assertEquals(getRepository().getAll().size(), entitiesCount - 1);\n\n // Tries to retrieve the removed entity\n // The entity is now null\n Assert.assertNull(getRepository().getEntity(query));\n }\n\n /**\n * Tests that updating an entity changes it.\n */\n @Test\n public final void testUpdate() {\n final Map<String, Object> parameters; // Params for the query\n final NamedParameterQueryData query; // Query for retrieving the entity\n final String nameChange; // Name set on the entity\n TestEntity entity; // The entity being tested\n\n // Acquires the entity\n parameters = new LinkedHashMap<>();\n parameters.put(\"id\", 1);\n query = new DefaultNamedParameterQueryData(selectByIdQuery, parameters);\n entity = getRepository().getEntity(query);\n\n // Changes the entity name\n nameChange = \"The new name\";\n entity.setName(nameChange);\n getRepository().update(entity);\n\n // Retrieves the entity again\n entity = getRepository().getEntity(query);\n\n // Checks the entity's name\n Assert.assertEquals(entity.getName(), nameChange);\n }\n\n /**\n * Returns the repository being tested.\n *\n * @return the repository being tested.\n */\n protected final FilteredRepository<TestEntity, NamedParameterQueryData> getRepository() {\n return repository;\n }\n\n}" ]
import com.wandrell.pattern.test.util.config.properties.DatabaseScriptsPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.JdbcPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.JpaPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.PersistenceProviderPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.QueryPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.RepositoryPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.TestPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.UserPropertiesPaths; import com.wandrell.pattern.test.util.test.integration.repository.access.AbstractITModify; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import com.wandrell.pattern.test.util.config.context.PersistenceContextPaths; import com.wandrell.pattern.test.util.config.context.RepositoryContextPaths; import com.wandrell.pattern.test.util.config.context.TestContextPaths;
/** * The MIT License (MIT) * <p> * Copyright (c) 2015 the original author or authors. * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wandrell.pattern.test.integration.repository.access.h2.eclipselink; /** * Integration tests for * {@link com.wandrell.pattern.repository.jpa.JpaRepository JPARepository} * implementing {@code AbstractITModify}, using an H2 in-memory database and * Eclipselink-based JPA. * * @author Bernardo Martínez Garrido * @see com.wandrell.pattern.repository.jpa.JpaRepository JPARepository */ @ContextConfiguration(locations = { TestContextPaths.DEFAULT, TestContextPaths.ENTITY_MODIFIABLE, PersistenceContextPaths.ECLIPSELINK,
RepositoryContextPaths.JPA })
1
evolvingstuff/RecurrentJava
src/loss/LossSoftmax.java
[ "public class Graph {\n\tboolean applyBackprop;\n\t\n\tList<Runnable> backprop = new ArrayList<>();\n\t\n\tpublic Graph() {\n\t\tthis.applyBackprop = true;\n\t}\n\t\n\tpublic Graph(boolean applyBackprop) {\n\t\tthis.applyBackprop = applyBackprop;\n\t}\n\t\n\tpublic void backward() {\n\t\tfor (int i = backprop.size()-1; i >= 0; i--) {\n\t\t\tbackprop.get(i).run();\n\t\t}\n\t}\n\t\n\tpublic Matrix concatVectors(final Matrix m1, final Matrix m2) throws Exception {\n\t\tif (m1.cols > 1 || m2.cols > 1) {\n\t\t\tthrow new Exception(\"Expected column vectors\");\n\t\t}\n\t\tfinal Matrix out = new Matrix(m1.rows + m2.rows);\n\t\tint loc = 0;\n\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\tout.w[loc] = m1.w[i];\n\t\t\tout.dw[loc] = m1.dw[i];\n\t\t\tout.stepCache[loc] = m1.stepCache[i];\n\t\t\tloc++;\n\t\t}\n\t\tfor (int i = 0; i < m2.w.length; i++) {\n\t\t\tout.w[loc] = m2.w[i];\n\t\t\tout.dw[loc] = m2.dw[i];\n\t\t\tout.stepCache[loc] = m2.stepCache[i];\n\t\t\tloc++;\n\t\t}\n\t\tif (this.applyBackprop) {\n\t\t\tRunnable bp = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tint loc = 0;\n\t\t\t\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\t\t\t\tm1.w[i] = out.w[loc];\n\t\t\t\t\t\tm1.dw[i] = out.dw[loc];\n\t\t\t\t\t\tm1.stepCache[i] = out.stepCache[loc];\n\t\t\t\t\t\tloc++;\n\t\t\t\t\t}\n\t\t\t\t\tfor (int i = 0; i < m2.w.length; i++) {\n\t\t\t\t\t\tm2.w[i] = out.w[loc];\n\t\t\t\t\t\tm2.dw[i] = out.dw[loc];\n\t\t\t\t\t\tm2.stepCache[i] = out.stepCache[loc];\n\t\t\t\t\t\tloc++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tbackprop.add(bp);\n\t\t}\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix nonlin(final Nonlinearity neuron, final Matrix m) throws Exception {\n\t\tfinal Matrix out = new Matrix(m.rows, m.cols);\n\t\tfinal int n = m.w.length;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tout.w[i] = neuron.forward(m.w[i]);\n\t\t}\n\t\tif (this.applyBackprop) {\n\t\t\tRunnable bp = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\t\tm.dw[i] += neuron.backward(m.w[i]) * out.dw[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tbackprop.add(bp);\n\t\t}\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix mul(final Matrix m1, final Matrix m2) throws Exception {\n\t\tif (m1.cols != m2.rows) {\n\t\t\tthrow new Exception(\"matrix dimension mismatch\");\n\t\t}\n\t\t\n\t\tfinal int m1rows = m1.rows;\n\t\tfinal int m1cols = m1.cols;\n\t\tfinal int m2cols = m2.cols;\n\t\tfinal Matrix out = new Matrix(m1rows, m2cols);\n\t\tfinal int outcols = m2cols;\n\t\tfor (int i = 0; i < m1rows; i++) {\n\t\t\tint m1col = m1cols*i;\n\t\t\tfor (int j = 0; j < m2cols; j++) {\n\t\t\t\tdouble dot = 0;\n\t\t\t\tfor (int k = 0; k < m1cols; k++) {\n\t\t\t\t\tdot += m1.w[m1col + k] * m2.w[m2cols*k + j];\n\t\t\t\t}\n\t\t\t\tout.w[outcols*i + j] = dot;\n\t\t\t}\n\t\t}\n\t\tif (this.applyBackprop) {\n\t\t\tRunnable bp = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (int i = 0; i < m1.rows; i++) {\n\t\t\t\t\t\tint outcol = outcols*i;\n\t\t\t\t\t\tfor (int j = 0; j < m2.cols; j++) {\n\t\t\t\t\t\t\tdouble b = out.dw[outcol + j];\n\t\t\t\t\t\t\tfor (int k = 0; k < m1.cols; k++) {\n\t\t\t\t\t\t\t\tm1.dw[m1cols*i + k] += m2.w[m2cols*k + j] * b;\n\t\t\t\t\t\t\t\tm2.dw[m2cols*k + j] += m1.w[m1cols*i + k] * b;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tbackprop.add(bp);\n\t\t}\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix add(final Matrix m1, final Matrix m2) throws Exception {\n\t\tif (m1.rows != m2.rows || m1.cols != m2.cols) {\n\t\t\tthrow new Exception(\"matrix dimension mismatch\");\n\t\t}\n\t\tfinal Matrix out = new Matrix(m1.rows, m1.cols);\n\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\tout.w[i] = m1.w[i] + m2.w[i];\n\t\t}\n\t\tif (this.applyBackprop) {\n\t\t\tRunnable bp = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\t\t\t\tm1.dw[i] += out.dw[i];\n\t\t\t\t\t\tm2.dw[i] += out.dw[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tbackprop.add(bp);\n\t\t}\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix oneMinus(final Matrix m) throws Exception {\n\t\tMatrix ones = Matrix.ones(m.rows, m.cols);\n\t\tMatrix out = sub(ones, m);\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix sub(final Matrix m1, final Matrix m2) throws Exception {\n\t\tMatrix out = add(m1, neg(m2));\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix smul(final Matrix m, final double s) throws Exception {\n\t\tMatrix m2 = Matrix.uniform(m.rows, m.cols, s);\n\t\tMatrix out = elmul(m, m2);\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix smul(final double s, final Matrix m) throws Exception {\n\t\tMatrix out = smul(m, s);\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix neg(final Matrix m) throws Exception {\n\t\tMatrix negones = Matrix.negones(m.rows, m.cols);\n\t\tMatrix out = elmul(negones, m);\n\t\treturn out;\n\t}\n\t\n\tpublic Matrix elmul(final Matrix m1, final Matrix m2) throws Exception {\n\t\tif (m1.rows != m2.rows || m1.cols != m2.cols) {\n\t\t\tthrow new Exception(\"matrix dimension mismatch\");\n\t\t}\n\t\tfinal Matrix out = new Matrix(m1.rows, m1.cols);\n\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\tout.w[i] = m1.w[i] * m2.w[i];\n\t\t}\n\t\tif (this.applyBackprop) {\n\t\t\tRunnable bp = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (int i = 0; i < m1.w.length; i++) {\n\t\t\t\t\t\tm1.dw[i] += m2.w[i] * out.dw[i];\n\t\t\t\t\t\tm2.dw[i] += m1.w[i] * out.dw[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tbackprop.add(bp);\n\t\t}\n\t\treturn out;\n\t}\n}", "public class Matrix implements Serializable {\n\t\n\tprivate static final long serialVersionUID = 1L;\n\tpublic int rows;\n\tpublic int cols;\n\tpublic double[] w;\n\tpublic double[] dw;\n\tpublic double[] stepCache;\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString result = \"\";\n\t\tfor (int r = 0; r < rows; r++) {\n\t\t\tfor (int c = 0; c < cols; c++) {\n\t\t\t\tresult += String.format(\"%.4f\",getW(r, c)) + \"\\t\";\n\t\t\t}\n\t\t\tresult += \"\\n\";\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic Matrix clone() {\n\t\tMatrix result = new Matrix(rows, cols);\n\t\tfor (int i = 0; i < w.length; i++) {\n\t\t\tresult.w[i] = w[i];\n\t\t\tresult.dw[i] = dw[i];\n\t\t\tresult.stepCache[i] = stepCache[i];\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic void resetDw() {\n\t\tfor (int i = 0; i < dw.length; i++) {\n\t\t\tdw[i] = 0;\n\t\t}\n\t}\n\t\n\tpublic void resetStepCache() {\n\t\tfor (int i = 0; i < stepCache.length; i++) {\n\t\t\tstepCache[i] = 0;\n\t\t}\n\t}\n\t\n\tpublic static Matrix transpose(Matrix m) {\n\t\tMatrix result = new Matrix(m.cols, m.rows);\n\t\tfor (int r = 0; r < m.rows; r++) {\n\t\t\tfor (int c = 0; c < m.cols; c++) {\n\t\t\t\tresult.setW(c, r, m.getW(r, c));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) {\n\t\tMatrix result = new Matrix(rows, cols);\n\t\tfor (int i = 0; i < result.w.length; i++) {\n\t\t\tresult.w[i] = rng.nextGaussian() * initParamsStdDev;\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic static Matrix ident(int dim) {\n\t\tMatrix result = new Matrix(dim, dim);\n\t\tfor (int i = 0; i < dim; i++) {\n\t\t\tresult.setW(i, i, 1.0);\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic static Matrix uniform(int rows, int cols, double s) {\n\t\tMatrix result = new Matrix(rows, cols);\n\t\tfor (int i = 0; i < result.w.length; i++) {\n\t\t\tresult.w[i] = s;\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic static Matrix ones(int rows, int cols) {\n\t\treturn uniform(rows, cols, 1.0);\n\t}\n\t\n\tpublic static Matrix negones(int rows, int cols) {\n\t\treturn uniform(rows, cols, -1.0);\n\t}\n\t\n\tpublic Matrix(int dim) {\n\t\tthis.rows = dim;\n\t\tthis.cols = 1;\n\t\tthis.w = new double[rows * cols];\n\t\tthis.dw = new double[rows * cols];\n\t\tthis.stepCache = new double[rows * cols];\n\t}\n\t\n\tpublic Matrix(int rows, int cols) {\n\t\tthis.rows = rows;\n\t\tthis.cols = cols;\n\t\tthis.w = new double[rows * cols];\n\t\tthis.dw = new double[rows * cols];\n\t\tthis.stepCache = new double[rows * cols];\n\t}\n\t\n\tpublic Matrix(double[] vector) {\n\t\tthis.rows = vector.length;\n\t\tthis.cols = 1;\n\t\tthis.w = vector;\n\t\tthis.dw = new double[vector.length];\n\t\tthis.stepCache = new double[vector.length];\n\t}\n\t\n\tprivate int index(int row, int col) {\n\t\tint ix = cols * row + col;\n\t\treturn ix;\n\t}\n\t\n\tprivate double getW(int row, int col) {\n\t\treturn w[index(row, col)];\n\t}\n\t\n\tprivate void setW(int row, int col, double val) {\n\t\tw[index(row, col)] = val;\n\t}\n}", "public interface Model extends Serializable {\n\tMatrix forward(Matrix input, Graph g) throws Exception;\n\tvoid resetState();\n\tList<Matrix> getParameters();\n}", "public class DataSequence implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\tpublic List<DataStep> steps = new ArrayList<>();\n\t\n\tpublic DataSequence() {\n\t\t\n\t}\n\t\n\tpublic DataSequence(List<DataStep> steps) {\n\t\tthis.steps = steps;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString result = \"\";\n\t\tresult += \"========================================================\\n\";\n\t\tfor (DataStep step : steps) {\n\t\t\tresult += step.toString() + \"\\n\";\n\t\t}\n\t\tresult += \"========================================================\\n\";\n\t\treturn result;\n\t}\n}", "public class DataStep implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\tpublic Matrix input = null;\n\tpublic Matrix targetOutput = null;\n\t\n\tpublic DataStep() {\n\t\t\n\t}\n\t\n\tpublic DataStep(double[] input, double[] targetOutput) {\n\t\tthis.input = new Matrix(input);\n\t\tif (targetOutput != null) {\n\t\t\tthis.targetOutput = new Matrix(targetOutput);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString result = \"\";\n\t\tfor (int i = 0; i < input.w.length; i++) {\n\t\t\tresult += String.format(\"%.5f\", input.w[i]) + \"\\t\";\n\t\t}\n\t\tresult += \"\\t->\\t\";\n\t\tif (targetOutput != null) {\n\t\t\tfor (int i = 0; i < targetOutput.w.length; i++) {\n\t\t\t\tresult += String.format(\"%.5f\", targetOutput.w[i]) + \"\\t\";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tresult += \"___\\t\";\n\t\t}\n\t\treturn result;\n\t}\n}", "public class Util {\n\t\n\tpublic static int pickIndexFromRandomVector(Matrix probs, Random r) throws Exception {\n\t\tdouble mass = 1.0;\n\t\tfor (int i = 0; i < probs.w.length; i++) {\n\t\t\tdouble prob = probs.w[i] / mass;\n\t\t\tif (r.nextDouble() < prob) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tmass -= probs.w[i];\n\t\t}\n\t\tthrow new Exception(\"no target index selected\");\n\t}\n\t\n\tpublic static double median(List<Double> vals) {\n\t\tCollections.sort(vals);\n\t\tint mid = vals.size()/2;\n\t\tif (vals.size() % 2 == 1) {\n\t\t\treturn vals.get(mid);\n\t\t}\n\t\telse {\n\t\t\treturn (vals.get(mid-1) + vals.get(mid)) / 2;\n\t\t}\n\t}\n\n\tpublic static String timeString(double milliseconds) {\n\t\tString result = \"\";\n\t\t\n\t\tint m = (int) milliseconds;\n\t\t\n\t\tint hours = 0;\n\t\twhile (m >= 1000*60*60) {\n\t\t\tm -= 1000*60*60;\n\t\t\thours++;\n\t\t}\n\t\tint minutes = 0;\n\t\twhile (m >= 1000*60) {\n\t\t\tm -= 1000*60;\n\t\t\tminutes++;\n\t\t}\n\t\tif (hours > 0) {\n\t\t\tresult += hours + \" hours, \";\n\t\t}\n\t\tint seconds = 0;\n\t\twhile (m >= 1000) {\n\t\t\tm -= 1000;\n\t\t\tseconds ++;\n\t\t}\n\t\tresult += minutes + \" minutes and \";\n\t\tresult += seconds + \" seconds.\";\n\t\treturn result;\n\t}\n}" ]
import java.util.ArrayList; import java.util.List; import autodiff.Graph; import matrix.Matrix; import model.Model; import datastructs.DataSequence; import datastructs.DataStep; import util.Util;
package loss; public class LossSoftmax implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override public void backward(Matrix logprobs, Matrix targetOutput) throws Exception { int targetIndex = getTargetIndex(targetOutput); Matrix probs = getSoftmaxProbs(logprobs, 1.0); for (int i = 0; i < probs.w.length; i++) { logprobs.dw[i] = probs.w[i]; } logprobs.dw[targetIndex] -= 1; } @Override public double measure(Matrix logprobs, Matrix targetOutput) throws Exception { int targetIndex = getTargetIndex(targetOutput); Matrix probs = getSoftmaxProbs(logprobs, 1.0); double cost = -Math.log(probs.w[targetIndex]); return cost; }
public static double calculateMedianPerplexity(Model model, List<DataSequence> sequences) throws Exception {
2
k0shk0sh/FastAccess
app/src/main/java/com/fastaccess/ui/modules/apps/folders/create/CreateFolderView.java
[ "public class FolderModel extends SugarRecord implements Parcelable {\n\n @Unique private String folderName;\n private long createdDate;\n private int orderIndex;\n private int color;\n private int appsCount;\n @Ignore private List<AppsModel> folderApps;\n\n public String getFolderName() {\n return folderName;\n }\n\n public void setFolderName(String folderName) {\n this.folderName = folderName;\n }\n\n public long getCreatedDate() {\n return createdDate;\n }\n\n public void setCreatedDate(long createdDate) {\n this.createdDate = createdDate;\n }\n\n public int getOrderIndex() {\n return orderIndex;\n }\n\n public void setOrderIndex(int orderIndex) {\n this.orderIndex = orderIndex;\n }\n\n public int getColor() {\n return color;\n }\n\n public void setColor(int color) {\n this.color = color;\n }\n\n public int getAppsCount() {\n appsCount = (int) AppsModel.countApps(getId());\n return appsCount;\n }\n\n @Nullable public static FolderModel getFolder(@NonNull String folderName) {\n return Select.from(FolderModel.class).where(NamingHelper.toSQLNameDefault(\"folderName\") + \" = ? COLLATE NOCASE\", new String[]{folderName})\n .first();\n }\n\n public static List<FolderModel> getFolders() {\n return Select.from(FolderModel.class)\n .orderBy(NamingHelper.toSQLNameDefault(\"createdDate\") + \" DESC\")\n .list();\n }\n\n public static void deleteFolder(@NonNull FolderModel model) {\n model.delete();\n AppsModel.deleteAll(AppsModel.class, NamingHelper.toSQLNameDefault(\"folderId\") + \" = ?\", String.valueOf(model.getId()));\n }\n\n public FolderModel() {}\n\n @Override public int describeContents() { return 0; }\n\n @Override public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.folderName);\n dest.writeLong(this.createdDate);\n dest.writeInt(this.orderIndex);\n dest.writeInt(this.color);\n dest.writeInt(this.appsCount);\n dest.writeValue(this.getId());\n }\n\n protected FolderModel(Parcel in) {\n this.folderName = in.readString();\n this.createdDate = in.readLong();\n this.orderIndex = in.readInt();\n this.color = in.readInt();\n this.appsCount = in.readInt();\n this.setId((Long) in.readValue(Long.class.getClassLoader()));\n }\n\n public static final Creator<FolderModel> CREATOR = new Creator<FolderModel>() {\n @Override public FolderModel createFromParcel(Parcel source) {return new FolderModel(source);}\n\n @Override public FolderModel[] newArray(int size) {return new FolderModel[size];}\n };\n\n public List<AppsModel> getFolderApps() {\n return AppsModel.getApps(getId());\n }\n\n public void setFolderApps(List<AppsModel> folderApps) {\n this.folderApps = folderApps;\n if (folderApps != null && !folderApps.isEmpty()) {\n for (AppsModel app : folderApps) {\n if (app.getFolderId() == 0) {\n app.setFolderId(getId());\n }\n if (app.getFolderId() != 0) app.save();\n }\n }\n }\n}", "public class Bundler {\n\n private Bundle bundle;\n\n private Bundler() {\n bundle = new Bundle();\n }\n\n public static Bundler start() {\n return new Bundler();\n }\n\n public Bundler put(@NonNull String key, boolean value) {\n bundle.putBoolean(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, boolean[] value) {\n bundle.putBooleanArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, IBinder value) {\n // Uncommment this line if your minimum sdk version is API level 18\n //start.putBinder(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, int value) {\n bundle.putInt(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, int[] value) {\n bundle.putIntArray(key, value);\n return this;\n }\n\n public Bundler putIntegerArrayList(@NonNull String key, ArrayList<Integer> value) {\n bundle.putIntegerArrayList(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, Bundle value) {\n bundle.putBundle(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, byte value) {\n bundle.putByte(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, byte[] value) {\n bundle.putByteArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, String value) {\n bundle.putString(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, String[] value) {\n bundle.putStringArray(key, value);\n return this;\n }\n\n public Bundler putStringArrayList(@NonNull String key, ArrayList<String> value) {\n bundle.putStringArrayList(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, long value) {\n bundle.putLong(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, long[] value) {\n bundle.putLongArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, float value) {\n bundle.putFloat(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, float[] value) {\n bundle.putFloatArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, char value) {\n bundle.putChar(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, char[] value) {\n bundle.putCharArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, CharSequence value) {\n bundle.putCharSequence(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, CharSequence[] value) {\n bundle.putCharSequenceArray(key, value);\n return this;\n }\n\n public Bundler putCharSequenceArrayList(@NonNull String key, ArrayList<CharSequence> value) {\n bundle.putCharSequenceArrayList(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, double value) {\n bundle.putDouble(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, double[] value) {\n bundle.putDoubleArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, Parcelable value) {\n bundle.putParcelable(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, Parcelable[] value) {\n bundle.putParcelableArray(key, value);\n return this;\n }\n\n public Bundler putParcelableArrayList(@NonNull String key, ArrayList<? extends Parcelable> value) {\n bundle.putParcelableArrayList(key, value);\n return this;\n }\n\n public Bundler putSparseParcelableArray(@NonNull String key, SparseArray<? extends Parcelable> value) {\n bundle.putSparseParcelableArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, short value) {\n bundle.putShort(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, short[] value) {\n bundle.putShortArray(key, value);\n return this;\n }\n\n public Bundler put(@NonNull String key, Serializable value) {\n bundle.putSerializable(key, value);\n return this;\n }\n\n public Bundler putAll(Bundle map) {\n bundle.putAll(map);\n return this;\n }\n\n /**\n * Get the underlying start.\n */\n public Bundle get() {\n return bundle;\n }\n\n public Bundle end() {\n return get();\n }\n\n}", "public class InputHelper {\n\n\n private static boolean isWhiteSpaces(String s) {\n return s != null && s.matches(\"\\\\s+\");\n }\n\n public static boolean isEmpty(String text) {\n return text == null || TextUtils.isEmpty(text) || isWhiteSpaces(text);\n }\n\n public static boolean isEmpty(Object text) {\n return text == null || TextUtils.isEmpty(text.toString()) || isWhiteSpaces(text.toString());\n }\n\n public static boolean isEmpty(EditText text) {\n return text == null || isEmpty(text.getText().toString());\n }\n\n public static boolean isEmpty(TextView text) {\n return text == null || isEmpty(text.getText().toString());\n }\n\n public static boolean isEmpty(TextInputLayout txt) {\n return txt == null || isEmpty(txt.getEditText());\n }\n\n public static String toString(EditText editText) {\n return editText.getText().toString();\n }\n\n public static String toString(TextView editText) {\n return editText.getText().toString();\n }\n\n public static String toString(TextInputLayout textInputLayout) {\n return toString(textInputLayout.getEditText());\n }\n\n @NonNull public static String toString(@NonNull Object object) {\n return !isEmpty(object) ? object.toString() : \"\";\n }\n\n @NonNull public static String getTwoLetters(@NonNull String value) {\n return value.length() > 1 ? (String.valueOf(value.charAt(0)) + String.valueOf(value.charAt(1))) : String.valueOf(value.charAt(0));\n }\n}", "public class ViewHelper {\n\n public interface OnTooltipDismissListener {\n void onDismissed(@StringRes int resId);\n }\n\n public static int getPrimaryColor(Context context) {\n TypedValue typedValue = new TypedValue();\n TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimary});\n int color = a.getColor(0, 0);\n a.recycle();\n return color;\n }\n\n public static int getPrimaryDarkColor(Context context) {\n TypedValue typedValue = new TypedValue();\n TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimaryDark});\n int color = a.getColor(0, 0);\n a.recycle();\n return color;\n }\n\n public static int toPx(Context context, int dp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, dp, context.getResources().getDisplayMetrics());\n }\n\n public static Drawable getDrawableSelector(int normalColor, int pressedColor) {\n if (AppHelper.isLollipopOrHigher()) {\n return new RippleDrawable(ColorStateList.valueOf(pressedColor), getRippleMask(normalColor), getRippleMask(normalColor));\n } else {\n return getStateListDrawable(normalColor, pressedColor);\n }\n }\n\n private static Drawable getRippleMask(int color) {\n float[] outerRadii = new float[8];\n Arrays.fill(outerRadii, 3);\n RoundRectShape r = new RoundRectShape(outerRadii, null, null);\n ShapeDrawable shapeDrawable = new ShapeDrawable(r);\n shapeDrawable.getPaint().setColor(color);\n return shapeDrawable;\n }\n\n private static StateListDrawable getStateListDrawable(int normalColor, int pressedColor) {\n StateListDrawable states = new StateListDrawable();\n states.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(pressedColor));\n states.addState(new int[]{android.R.attr.state_focused}, new ColorDrawable(pressedColor));\n states.addState(new int[]{android.R.attr.state_activated}, new ColorDrawable(pressedColor));\n states.addState(new int[]{android.R.attr.state_selected}, new ColorDrawable(pressedColor));\n states.addState(new int[]{}, new ColorDrawable(normalColor));\n return states;\n }\n\n public static ColorStateList textSelector(int normalColor, int pressedColor) {\n return new ColorStateList(\n new int[][]{\n new int[]{android.R.attr.state_pressed},\n new int[]{android.R.attr.state_focused},\n new int[]{android.R.attr.state_activated},\n new int[]{android.R.attr.state_selected},\n new int[]{}\n },\n new int[]{\n pressedColor,\n pressedColor,\n pressedColor,\n pressedColor,\n normalColor\n }\n );\n }\n\n private static boolean isTablet(Resources resources) {\n return (resources.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;\n }\n\n public static boolean isTablet(Context context) {\n return isTablet(context.getResources());\n }\n\n private static void setTextViewMenuCounter(@NonNull NavigationView navigationView, @IdRes int itemId, int count) {\n TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView();\n view.setText(String.format(\"%s\", count));\n }\n\n public static boolean isLandscape(Resources resources) {\n return resources.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;\n }\n\n @SuppressWarnings(\"ConstantConditions,PrivateResource\")\n public static void showTooltip(@NonNull final View view, @StringRes final int titleResId,\n int gravity, @Nullable final OnTooltipDismissListener dismissListener) {\n if (view != null && view.getContext() != null) {\n if (!PrefHelper.getBoolean(String.valueOf(titleResId))) {\n new Tooltip.Builder(view)\n .setText(titleResId)\n .setTypeface(TypeFaceHelper.getTypeface())\n .setTextColor(Color.WHITE)\n .setGravity(gravity)\n .setPadding(R.dimen.spacing_xs_large)\n .setBackgroundColor(ContextCompat.getColor(view.getContext(), R.color.primary))\n .setDismissOnClick(true)\n .setCancelable(true)\n .setTextStyle(android.support.v7.appcompat.R.style.TextAppearance_AppCompat_Title_Inverse)\n .setOnDismissListener(new OnDismissListener() {\n @Override public void onDismiss() {\n PrefHelper.set(String.valueOf(titleResId), true);\n if (dismissListener != null) dismissListener.onDismissed(titleResId);\n }\n })\n .show();\n }\n }\n }\n\n public static void showTooltip(@NonNull final View view, @StringRes int titleResId) {\n showTooltip(view, titleResId, Gravity.BOTTOM, null);\n }\n\n public static void showTooltip(@NonNull final View view, @StringRes int titleResId,\n @NonNull OnTooltipDismissListener dismissListener) {\n showTooltip(view, titleResId, Gravity.BOTTOM, dismissListener);\n }\n\n public static void showTooltip(@NonNull Context context, @NonNull final MenuItem view, @StringRes final int titleResId,\n int gravity, @Nullable final OnTooltipDismissListener dismissListener) {\n if (!PrefHelper.getBoolean(String.valueOf(titleResId))) {\n new Tooltip.Builder(context, view)\n .setText(titleResId)\n .setTypeface(TypeFaceHelper.getTypeface())\n .setTextColor(Color.WHITE)\n .setGravity(gravity)\n .setPadding(R.dimen.spacing_xs_large)\n .setBackgroundColor(ContextCompat.getColor(context, R.color.primary))\n .setDismissOnClick(true)\n .setCancelable(true)\n .setTextStyle(android.support.v7.appcompat.R.style.TextAppearance_AppCompat_Title_Inverse)\n .setOnDismissListener(new OnDismissListener() {\n @Override public void onDismiss() {\n PrefHelper.set(String.valueOf(titleResId), true);\n if (dismissListener != null) dismissListener.onDismissed(titleResId);\n }\n })\n .show();\n }\n }\n\n public static void showTooltip(@NonNull Context context, @NonNull final MenuItem view, @StringRes int titleResId) {\n showTooltip(context, view, titleResId, Gravity.BOTTOM, null);\n }\n\n public static void showTooltip(@NonNull Context context, @NonNull final MenuItem view, @StringRes int titleResId,\n @NonNull OnTooltipDismissListener dismissListener) {\n showTooltip(context, view, titleResId, Gravity.BOTTOM, dismissListener);\n }\n\n public static Rect getLayoutPosition(@NonNull View view) {\n Rect myViewRect = new Rect();\n view.getGlobalVisibleRect(myViewRect);\n return myViewRect;\n }\n\n public static int getWidthFromRecyclerView(@NonNull RecyclerView recyclerView, @NonNull WindowManager windowManager) {\n int iconSize = PrefConstant.getFinalSize(recyclerView.getContext());\n int padding = PrefConstant.getGapSize(recyclerView.getResources());\n int count = recyclerView.getAdapter().getItemCount();\n int width = (count * (iconSize + padding)) + iconSize;\n DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return width <= metrics.widthPixels ? width : metrics.widthPixels;\n }\n\n}", "public abstract class BaseBottomSheetDialog extends BottomSheetDialogFragment {\n\n protected BottomSheetBehavior<View> bottomSheetBehavior;\n private BottomSheetBehavior.BottomSheetCallback bottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {\n @Override public void onStateChanged(@NonNull View bottomSheet, int newState) {\n if (newState == BottomSheetBehavior.STATE_HIDDEN) {\n isAlreadyHidden = true;\n onHidden();\n }\n }\n\n @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) {\n if (slideOffset == -1.0) {\n isAlreadyHidden = true;\n onDismissedByScrolling();\n }\n }\n };\n protected boolean isAlreadyHidden;\n @Nullable private Unbinder unbinder;\n\n @LayoutRes protected abstract int layoutRes();\n\n protected abstract void onViewCreated(@NonNull View view);\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icepick.saveInstanceState(this, outState);\n }\n\n @Override public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null && !savedInstanceState.isEmpty()) {\n Icepick.restoreInstanceState(this, savedInstanceState);\n }\n }\n\n @Override public void setupDialog(Dialog dialog, int style) {\n super.setupDialog(dialog, style);\n View contentView = View.inflate(getContext(), layoutRes(), null);\n dialog.setContentView(contentView);\n View parent = ((View) contentView.getParent());\n bottomSheetBehavior = BottomSheetBehavior.from(parent);\n if (bottomSheetBehavior != null) {\n bottomSheetBehavior.setBottomSheetCallback(bottomSheetCallback);\n bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);\n }\n unbinder = ButterKnife.bind(this, contentView);\n onViewCreated(contentView);\n }\n\n @Override public void onDestroyView() {\n super.onDestroyView();\n if (unbinder != null) unbinder.unbind();\n }\n\n @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {\n final Dialog dialog = super.onCreateDialog(savedInstanceState);\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override public void onShow(DialogInterface dialogINterface) {\n if (ViewHelper.isTablet(getContext())) {\n if (dialog.getWindow() != null) {\n dialog.getWindow().setLayout(\n ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.MATCH_PARENT);\n }\n }\n onDialogIsVisible();\n }\n });\n dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {\n @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n isAlreadyHidden = true;\n onDismissedByScrolling();\n }\n return false;\n }\n });\n\n return dialog;\n }\n\n @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n Logger.e();\n }\n\n @Override public void onDetach() {\n if (!isAlreadyHidden) {\n onDismissedByScrolling();\n }\n super.onDetach();\n }\n\n protected void onHidden() {\n dismiss();\n }//helper method to notify dialogs\n\n protected void onDismissedByScrolling() {}//helper method to notify dialogs\n\n protected void onDialogIsVisible() {}//helper method to notify dialogs\n\n}", "interface OnNotifyFoldersAdapter {\n void onNotifyChanges();\n}", "public class FontButton extends AppCompatButton {\n\n public FontButton(Context context) {\n super(context);\n init();\n }\n\n public FontButton(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n\n public FontButton(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init();\n }\n\n private void init() {\n if (isInEditMode()) return;\n TypeFaceHelper.applyTypeface(this);\n }\n\n public void setBackground(@ColorRes int normalColor, @ColorRes int pressedColor) {\n int nColor = ContextCompat.getColor(getContext(), normalColor);\n int pColor = ContextCompat.getColor(getContext(), pressedColor);\n setBackgroundDrawable(ViewHelper.getDrawableSelector(nColor, pColor));\n }\n\n public void setTextColor(@ColorRes int normalColor, @ColorRes int pressedColor) {\n int nColor = ContextCompat.getColor(getContext(), normalColor);\n int pColor = ContextCompat.getColor(getContext(), pressedColor);\n setTextColor(ViewHelper.textSelector(nColor, pColor));\n }\n\n}", "public class ColorPickerDialog extends DialogFragment implements OnColorSelectedListener {\n\n public static final int SIZE_LARGE = 1;\n public static final int SIZE_SMALL = 2;\n\n protected AlertDialog mAlertDialog;\n\n protected static final String KEY_TITLE_ID = \"title_id\";\n protected static final String KEY_COLORS = \"colors\";\n protected static final String KEY_COLOR_CONTENT_DESCRIPTIONS = \"color_content_descriptions\";\n protected static final String KEY_SELECTED_COLOR = \"selected_color\";\n protected static final String KEY_COLUMNS = \"columns\";\n protected static final String KEY_SIZE = \"size\";\n\n protected int mTitleResId = R.string.color_picker_default_title;\n protected int[] mColors = null;\n protected String[] mColorContentDescriptions = null;\n protected int mSelectedColor;\n protected int mColumns;\n protected int mSize;\n protected String key;\n private ColorPickerPalette mPalette;\n private ProgressBar mProgress;\n\n protected OnColorSelectedListener mListener;\n\n public static ColorPickerDialog newInstance(int titleResId, int[] colors, int selectedColor,\n int columns, int size) {\n ColorPickerDialog ret = new ColorPickerDialog();\n ret.initialize(titleResId, colors, selectedColor, columns, size);\n return ret;\n }\n\n @Override public void onAttach(Context context) {\n super.onAttach(context);\n Log.e(\"ColorPickerPalette\", context + \" \" + getParentFragment());\n if (getParentFragment() != null && (getParentFragment() instanceof OnColorSelectedListener)) {\n mListener = (OnColorSelectedListener) getParentFragment();\n } else if (context instanceof OnColorSelectedListener) {\n mListener = (OnColorSelectedListener) context;\n }\n }\n\n @Override public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putIntArray(KEY_COLORS, mColors);\n outState.putInt(KEY_SELECTED_COLOR, mSelectedColor);\n outState.putStringArray(KEY_COLOR_CONTENT_DESCRIPTIONS, mColorContentDescriptions);\n outState.putString(\"key\", key);\n }\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mTitleResId = getArguments().getInt(KEY_TITLE_ID);\n mColumns = getArguments().getInt(KEY_COLUMNS);\n mSize = getArguments().getInt(KEY_SIZE);\n key = getArguments().getString(\"key\");\n }\n if (savedInstanceState != null) {\n mColors = savedInstanceState.getIntArray(KEY_COLORS);\n mSelectedColor = savedInstanceState.getInt(KEY_SELECTED_COLOR);\n mColorContentDescriptions = savedInstanceState.getStringArray(\n KEY_COLOR_CONTENT_DESCRIPTIONS);\n key = savedInstanceState.getString(\"key\");\n }\n }\n\n @SuppressLint(\"InflateParams\") @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {\n View view = LayoutInflater.from(getActivity()).inflate(R.layout.color_picker_dialog, null, false);\n final Activity activity = getActivity();\n mProgress = (ProgressBar) view.findViewById(android.R.id.progress);\n mPalette = (ColorPickerPalette) view.findViewById(R.id.color_picker);\n mPalette.init(mSize, mColumns, this);\n\n if (mColors != null) {\n showPaletteView();\n }\n\n mAlertDialog = new AlertDialog.Builder(activity)\n .setTitle(mTitleResId)\n .setView(view)\n .create();\n mAlertDialog.setCanceledOnTouchOutside(true);\n return mAlertDialog;\n }\n\n @Override public void onColorSelected(int color) {\n if (mListener != null) {\n mListener.onColorSelected(color);\n }\n PreferenceManager.getDefaultSharedPreferences(getContext())\n .edit().putInt(key, color).apply();\n if (getTargetFragment() instanceof OnColorSelectedListener) {\n final OnColorSelectedListener listener = (OnColorSelectedListener) getTargetFragment();\n listener.onColorSelected(color);\n }\n if (color != mSelectedColor) {\n mSelectedColor = color;\n mPalette.drawPalette(mColors, mSelectedColor);\n }\n dismiss();\n }\n\n public void initialize(int titleResId, int[] colors, int selectedColor, int columns, int size) {\n setArguments(titleResId, columns, size);\n setColors(colors, selectedColor);\n }\n\n public void setArguments(int titleResId, int columns, int size) {\n Bundle bundle = new Bundle();\n bundle.putInt(KEY_TITLE_ID, titleResId);\n bundle.putInt(KEY_COLUMNS, columns);\n bundle.putInt(KEY_SIZE, size);\n setArguments(bundle);\n }\n\n public void setOnColorSelectedListener(OnColorSelectedListener listener) {\n mListener = listener;\n }\n\n public void showPaletteView() {\n if (mProgress != null && mPalette != null) {\n mProgress.setVisibility(View.GONE);\n refreshPalette();\n mPalette.setVisibility(View.VISIBLE);\n }\n }\n\n public void showProgressBarView() {\n if (mProgress != null && mPalette != null) {\n mProgress.setVisibility(View.VISIBLE);\n mPalette.setVisibility(View.GONE);\n }\n }\n\n public void setColors(int[] colors, int selectedColor) {\n if (mColors != colors || mSelectedColor != selectedColor) {\n mColors = colors;\n mSelectedColor = selectedColor;\n refreshPalette();\n }\n }\n\n public void setColors(int[] colors) {\n if (mColors != colors) {\n mColors = colors;\n refreshPalette();\n }\n }\n\n public void setSelectedColor(int color) {\n if (mSelectedColor != color) {\n mSelectedColor = color;\n refreshPalette();\n }\n }\n\n public void setColorContentDescriptions(String[] colorContentDescriptions) {\n if (mColorContentDescriptions != colorContentDescriptions) {\n mColorContentDescriptions = colorContentDescriptions;\n refreshPalette();\n }\n }\n\n private void refreshPalette() {\n if (mPalette != null && mColors != null) {\n mPalette.drawPalette(mColors, mSelectedColor, mColorContentDescriptions);\n }\n }\n\n public int[] getColors() {\n return mColors;\n }\n\n public int getSelectedColor() {\n return mSelectedColor;\n }\n\n public static ColorPickerDialog newInstance(int titleResId, int[] colors, int selectedColor,\n int columns, int size, String key) {\n ColorPickerDialog ret = new ColorPickerDialog();\n ret.initialize(titleResId, colors, selectedColor, columns, size, key);\n return ret;\n }\n\n private void initialize(int titleResId, int[] colors, int selectedColor, int columns, int size, String key) {\n setArguments(titleResId, columns, size, key);\n setColors(colors, selectedColor);\n }\n\n private void setArguments(int titleResId, int columns, int size, String key) {\n Bundle bundle = new Bundle();\n bundle.putInt(KEY_TITLE_ID, titleResId);\n bundle.putInt(KEY_COLUMNS, columns);\n bundle.putInt(KEY_SIZE, size);\n bundle.putString(\"key\", key);\n setArguments(bundle);\n }\n}" ]
import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.amulyakhare.textdrawable.TextDrawable; import com.fastaccess.R; import com.fastaccess.data.dao.FolderModel; import com.fastaccess.helper.Bundler; import com.fastaccess.helper.InputHelper; import com.fastaccess.helper.ViewHelper; import com.fastaccess.ui.base.BaseBottomSheetDialog; import com.fastaccess.ui.modules.apps.folders.create.CreateFolderMvp.OnNotifyFoldersAdapter; import com.fastaccess.ui.widgets.FontButton; import org.xdty.preference.colorpicker.ColorPickerDialog; import java.util.Date; import butterknife.BindView; import butterknife.OnClick; import butterknife.OnTextChanged; import icepick.State;
package com.fastaccess.ui.modules.apps.folders.create; /** * Created by Kosh on 11 Oct 2016, 8:27 PM */ public class CreateFolderView extends BaseBottomSheetDialog implements CreateFolderMvp.View { private long folderId; @State int selectedColor = Color.parseColor("#FF2A456B"); @State String fName; @BindView(R.id.folderImage) ImageView folderImage; @BindView(R.id.folderName) TextInputLayout folderName;
@BindView(R.id.cancel) FontButton cancel;
6
iminto/baicai
src/main/java/com/baicai/controller/index/InvestController.java
[ "public abstract class BaseController implements HandlerInterceptor{\r\n\tprotected Logger logger = LoggerFactory.getLogger(this.getClass());\r\n\t\r\n\t/**\r\n\t * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用\r\n\t * @param request\r\n\t * @param response\r\n\t * @param handler\r\n\t * @return\r\n\t * @throws Exception\r\n\t */\r\n\t@Override\r\n\tpublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)\r\n\t\t\tthrows Exception {\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。\r\n\t * postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之后,也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行.\r\n\t * 也就是说在这个方法中你可以对ModelAndView进行操做\r\n\t * @param request\r\n\t * @param response\r\n\t * @param handler\r\n\t * @param modelAndView\r\n\t * @throws Exception\r\n\t */\r\n\t@Override\r\n\tpublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,\r\n\t\t\tModelAndView modelAndView) throws Exception {\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后,\r\n\t * 也就是DispatcherServlet渲染了视图执行,这个方法的主要作用是用于清理资源的\r\n\t * @param request\r\n\t * @param response\r\n\t * @param handler\r\n\t * @param ex\r\n\t * @throws Exception\r\n\t */\r\n\t@Override\r\n\tpublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)\r\n\t\t\tthrows Exception {\r\n\t}\r\n\t\r\n\t/**\r\n\t * 重定向至地址 url\r\n\t * @param url 请求地址\r\n\t * @return\r\n\t */\r\n\tprotected String redirectTo(String url) {\r\n\t\tStringBuilder rto = new StringBuilder(\"redirect:\");\r\n\t\trto.append(url);\r\n\t\treturn rto.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * 返回 JSON 格式对象\r\n\t * @param object 转换对象\r\n\t * @return\r\n\t */\r\n\tprotected String toJson(Object object) {\r\n\t\treturn JSON.toJSONString(object, SerializerFeature.BrowserCompatible);\r\n\t}\r\n\r\n\t/**\r\n\t * 返回 JSON 格式对象\r\n\t * @param object 转换对象\r\n\t * @param format 序列化格式\r\n\t * @return\r\n\t */\r\n\tprotected String toJson(Object object, String format) {\r\n\t\tif (format == null) {\r\n\t\t\treturn toJson(object);\r\n\t\t}\r\n\t\treturn JSON.toJSONStringWithDateFormat(object, format, SerializerFeature.WriteDateUseDateFormat);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 添加Model消息\r\n\t * @param message\r\n\t */\r\n\tprotected void addMessage(Model model, String... messages) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tfor (String message : messages) {\r\n\t\t\tsb.append(message).append(messages.length > 1 ? \"<br/>\" : \"\");\r\n\t\t}\r\n\t\tmodel.addAttribute(\"message\", sb.toString());\r\n\t}\r\n\t\r\n\t/**\r\n\t * 添加Flash消息\r\n\t * \r\n\t * @param message\r\n\t */\r\n\tprotected void addMessage(RedirectAttributes redirectAttributes, String... messages) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tfor (String message : messages) {\r\n\t\t\tsb.append(message).append(messages.length > 1 ? \"<br/>\" : \"\");\r\n\t\t}\r\n\t\tredirectAttributes.addFlashAttribute(\"message\", sb.toString());\r\n\t}\r\n\t\r\n\t/**\r\n\t * 客户端返回JSON字符串\r\n\t * \r\n\t * @param response\r\n\t * @param object\r\n\t * @return\r\n\t */\r\n\tprotected String renderString(HttpServletResponse response, Object object) {\r\n\t\treturn renderString(response, JSON.toJSONString(object, SerializerFeature.BrowserCompatible), \"application/json\");\r\n\t}\r\n\r\n\t/**\r\n\t * 客户端返回字符串\r\n\t * \r\n\t * @param response\r\n\t * @param string\r\n\t * @return\r\n\t */\r\n\tprotected String renderString(HttpServletResponse response, String string, String type) {\r\n\t\ttry {\r\n\t\t\tresponse.reset();\r\n\t\t\tresponse.setContentType(type);\r\n\t\t\tresponse.setCharacterEncoding(\"utf-8\");\r\n\t\t\tresponse.getWriter().print(string);\r\n\t\t\treturn null;\r\n\t\t} catch (IOException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprotected boolean isAjax(HttpServletRequest request){\r\n\t\tboolean isAjax = \"XMLHttpRequest\".equals(request.getHeader(\"X-Requested-With\"));\r\n\t\treturn isAjax;\r\n\t}\r\n\t\r\n\t@InitBinder\r\n\tprotected void initBinder(WebDataBinder binder) {\r\n\t\t// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击\r\n\t\tbinder.registerCustomEditor(String.class, new PropertyEditorSupport() {\r\n\t\t\t@Override\r\n\t\t\tpublic void setAsText(String text) {\r\n\t\t\t\tsetValue(text == null ? null : HtmlUtils.htmlEscape(text,Constant.CHARSET));\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic String getAsText() {\r\n\t\t\t\tObject value = getValue();\r\n\t\t\t\treturn value != null ? value.toString() : \"\";\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n}\r", "public class Project extends Model {\r\n\t@Key\r\n\tprivate Integer id;//\r\n\t@Key\r\n\tprivate Long proid;// 逻辑主键\r\n\tprivate Long uid;// 借款人ID\r\n\tprivate String proname;// 借款标题\r\n\tprivate Integer proaccount;// 借款金额,单位分\r\n\tprivate Integer proaccountyes;// 已投标金额,单位分\r\n\tprivate Integer protimelimit;// 借款期限\r\n\tprivate Integer protimeuint;// 借款期限类型,1为天,2为月\r\n\tprivate Integer provalidtime;// 借款有效时间\r\n\tprivate Double proapr;// 借款利率\r\n\tprivate Integer prostyle;// 还款方式\r\n\tprivate Integer prostatus;// 标的状态 0初始1初审成功,投标中2初审失败3复审成功4复审失败5流标6撤销7正常结束\r\n\tprivate Integer proverifyuser;// 审标人\r\n\tprivate Integer proverifytime;// 初审时间\r\n\tprivate String proverifyremark;// 初审备注\r\n\tprivate Integer profullverifyuser;// 满标审核人\r\n\tprivate Integer profullverifytime;// 满标审核时间\r\n\tprivate String profullverifyremark;// 满标审核备注\r\n\tprivate Integer protype;// 1信用标2担保标3抵押标4秒标5定向标\r\n\tprivate String prodxb;// 定向标密码\r\n\tprivate String prodesc;// 标的详细描述\r\n\tprivate Integer proawardtype;// 奖励类型 1百分比2固定金额\r\n\tprivate Double proaward;// 奖励的具体数值\r\n\tprivate Integer prolowaccount;// 最低要求投资金额\r\n\tprivate Integer promostaccount;// 标的最高允许投标金额\r\n\tprivate Integer successtime;// 满标时间\r\n\tprivate Integer endtime;// 根据有效期算出的截止时间\r\n\tprivate Integer ordernum;// 投标次数\r\n\tprivate Integer autoratio;// 允许的自动投标比例,百分比\r\n\tprivate Integer repayment;// 还款金额\r\n\tprivate Integer repaymentyes;// 已还金额\r\n\tprivate String expansion;// 扩充字段\r\n\tprivate Integer addtime;//\r\n\tprivate String addip;//\r\n\r\n\tpublic Integer getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(Integer id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic Long getProid() {\r\n\t\treturn proid;\r\n\t}\r\n\r\n\tpublic void setProid(Long proid) {\r\n\t\tthis.proid = proid;\r\n\t}\r\n\r\n\tpublic Long getUid() {\r\n\t\treturn uid;\r\n\t}\r\n\r\n\tpublic void setUid(Long uid) {\r\n\t\tthis.uid = uid;\r\n\t}\r\n\r\n\tpublic String getProname() {\r\n\t\treturn proname;\r\n\t}\r\n\r\n\tpublic void setProname(String proname) {\r\n\t\tthis.proname = proname;\r\n\t}\r\n\r\n\tpublic Integer getProaccount() {\r\n\t\treturn proaccount;\r\n\t}\r\n\r\n\tpublic void setProaccount(Integer proaccount) {\r\n\t\tthis.proaccount = proaccount;\r\n\t}\r\n\r\n\tpublic Integer getProaccountyes() {\r\n\t\treturn proaccountyes;\r\n\t}\r\n\r\n\tpublic void setProaccountyes(Integer proaccountyes) {\r\n\t\tthis.proaccountyes = proaccountyes;\r\n\t}\r\n\r\n\tpublic Integer getProtimelimit() {\r\n\t\treturn protimelimit;\r\n\t}\r\n\r\n\tpublic void setProtimelimit(Integer protimelimit) {\r\n\t\tthis.protimelimit = protimelimit;\r\n\t}\r\n\r\n\tpublic Integer getProtimeuint() {\r\n\t\treturn protimeuint;\r\n\t}\r\n\r\n\tpublic void setProtimeuint(Integer protimeuint) {\r\n\t\tthis.protimeuint = protimeuint;\r\n\t}\r\n\r\n\tpublic Integer getProvalidtime() {\r\n\t\treturn provalidtime;\r\n\t}\r\n\r\n\tpublic void setProvalidtime(Integer provalidtime) {\r\n\t\tthis.provalidtime = provalidtime;\r\n\t}\r\n\r\n\tpublic Double getProapr() {\r\n\t\treturn proapr;\r\n\t}\r\n\r\n\tpublic void setProapr(Double proapr) {\r\n\t\tthis.proapr = proapr;\r\n\t}\r\n\r\n\tpublic Integer getProstyle() {\r\n\t\treturn prostyle;\r\n\t}\r\n\r\n\tpublic void setProstyle(Integer prostyle) {\r\n\t\tthis.prostyle = prostyle;\r\n\t}\r\n\r\n\tpublic Integer getProstatus() {\r\n\t\treturn prostatus;\r\n\t}\r\n\r\n\tpublic void setProstatus(Integer prostatus) {\r\n\t\tthis.prostatus = prostatus;\r\n\t}\r\n\r\n\tpublic Integer getProverifyuser() {\r\n\t\treturn proverifyuser;\r\n\t}\r\n\r\n\tpublic void setProverifyuser(Integer proverifyuser) {\r\n\t\tthis.proverifyuser = proverifyuser;\r\n\t}\r\n\r\n\tpublic Integer getProverifytime() {\r\n\t\treturn proverifytime;\r\n\t}\r\n\r\n\tpublic void setProverifytime(Integer proverifytime) {\r\n\t\tthis.proverifytime = proverifytime;\r\n\t}\r\n\r\n\tpublic String getProverifyremark() {\r\n\t\treturn proverifyremark;\r\n\t}\r\n\r\n\tpublic void setProverifyremark(String proverifyremark) {\r\n\t\tthis.proverifyremark = proverifyremark;\r\n\t}\r\n\r\n\tpublic Integer getProfullverifyuser() {\r\n\t\treturn profullverifyuser;\r\n\t}\r\n\r\n\tpublic void setProfullverifyuser(Integer profullverifyuser) {\r\n\t\tthis.profullverifyuser = profullverifyuser;\r\n\t}\r\n\r\n\tpublic Integer getProfullverifytime() {\r\n\t\treturn profullverifytime;\r\n\t}\r\n\r\n\tpublic void setProfullverifytime(Integer profullverifytime) {\r\n\t\tthis.profullverifytime = profullverifytime;\r\n\t}\r\n\r\n\tpublic String getProfullverifyremark() {\r\n\t\treturn profullverifyremark;\r\n\t}\r\n\r\n\tpublic void setProfullverifyremark(String profullverifyremark) {\r\n\t\tthis.profullverifyremark = profullverifyremark;\r\n\t}\r\n\r\n\tpublic Integer getProtype() {\r\n\t\treturn protype;\r\n\t}\r\n\r\n\tpublic void setProtype(Integer protype) {\r\n\t\tthis.protype = protype;\r\n\t}\r\n\r\n\tpublic String getProdxb() {\r\n\t\treturn prodxb;\r\n\t}\r\n\r\n\tpublic void setProdxb(String prodxb) {\r\n\t\tthis.prodxb = prodxb;\r\n\t}\r\n\r\n\tpublic String getProdesc() {\r\n\t\treturn prodesc;\r\n\t}\r\n\r\n\tpublic void setProdesc(String prodesc) {\r\n\t\tthis.prodesc = prodesc;\r\n\t}\r\n\r\n\tpublic Integer getProawardtype() {\r\n\t\treturn proawardtype;\r\n\t}\r\n\r\n\tpublic void setProawardtype(Integer proawardtype) {\r\n\t\tthis.proawardtype = proawardtype;\r\n\t}\r\n\r\n\tpublic Double getProaward() {\r\n\t\treturn proaward;\r\n\t}\r\n\r\n\tpublic void setProaward(Double proaward) {\r\n\t\tthis.proaward = proaward;\r\n\t}\r\n\r\n\tpublic Integer getProlowaccount() {\r\n\t\treturn prolowaccount;\r\n\t}\r\n\r\n\tpublic void setProlowaccount(Integer prolowaccount) {\r\n\t\tthis.prolowaccount = prolowaccount;\r\n\t}\r\n\r\n\tpublic Integer getPromostaccount() {\r\n\t\treturn promostaccount;\r\n\t}\r\n\r\n\tpublic void setPromostaccount(Integer promostaccount) {\r\n\t\tthis.promostaccount = promostaccount;\r\n\t}\r\n\r\n\tpublic Integer getSuccesstime() {\r\n\t\treturn successtime;\r\n\t}\r\n\r\n\tpublic void setSuccesstime(Integer successtime) {\r\n\t\tthis.successtime = successtime;\r\n\t}\r\n\r\n\tpublic Integer getEndtime() {\r\n\t\treturn endtime;\r\n\t}\r\n\r\n\tpublic void setEndtime(Integer endtime) {\r\n\t\tthis.endtime = endtime;\r\n\t}\r\n\r\n\tpublic Integer getOrdernum() {\r\n\t\treturn ordernum;\r\n\t}\r\n\r\n\tpublic void setOrdernum(Integer ordernum) {\r\n\t\tthis.ordernum = ordernum;\r\n\t}\r\n\r\n\tpublic Integer getAutoratio() {\r\n\t\treturn autoratio;\r\n\t}\r\n\r\n\tpublic void setAutoratio(Integer autoratio) {\r\n\t\tthis.autoratio = autoratio;\r\n\t}\r\n\r\n\tpublic Integer getRepayment() {\r\n\t\treturn repayment;\r\n\t}\r\n\r\n\tpublic void setRepayment(Integer repayment) {\r\n\t\tthis.repayment = repayment;\r\n\t}\r\n\r\n\tpublic Integer getRepaymentyes() {\r\n\t\treturn repaymentyes;\r\n\t}\r\n\r\n\tpublic void setRepaymentyes(Integer repaymentyes) {\r\n\t\tthis.repaymentyes = repaymentyes;\r\n\t}\r\n\r\n\tpublic String getExpansion() {\r\n\t\treturn expansion;\r\n\t}\r\n\r\n\tpublic void setExpansion(String expansion) {\r\n\t\tthis.expansion = expansion;\r\n\t}\r\n\r\n\tpublic Integer getAddtime() {\r\n\t\treturn addtime;\r\n\t}\r\n\r\n\tpublic void setAddtime(Integer addtime) {\r\n\t\tthis.addtime = addtime;\r\n\t}\r\n\r\n\tpublic String getAddip() {\r\n\t\treturn addip;\r\n\t}\r\n\r\n\tpublic void setAddip(String addip) {\r\n\t\tthis.addip = addip;\r\n\t}\r\n\r\n}", "public class ErrorMsg {\r\n\tprivate Integer errCode;//错误代码,非必须\r\n\tprivate String errMsg;//错误信息\r\n\tprivate String url;//跳转网址\r\n\t\r\n\tpublic ErrorMsg() {\r\n\t}\t\r\n\t\r\n\tpublic ErrorMsg(String url) {\r\n\t\tsuper();\r\n\t\tthis.url = url;\r\n\t}\r\n\r\n\tpublic ErrorMsg(String errMsg, String url) {\r\n\t\tsuper();\r\n\t\tthis.errMsg = errMsg;\r\n\t\tthis.url = url;\r\n\t}\r\n\tpublic Integer getErrCode() {\r\n\t\treturn errCode;\r\n\t}\r\n\tpublic void setErrCode(Integer errCode) {\r\n\t\tthis.errCode = errCode;\r\n\t}\r\n\tpublic String getErrMsg() {\r\n\t\treturn errMsg;\r\n\t}\r\n\tpublic void setErrMsg(String errMsg) {\r\n\t\tthis.errMsg = errMsg;\r\n\t}\r\n\tpublic String getUrl() {\r\n\t\treturn url;\r\n\t}\r\n\tpublic void setUrl(String url) {\r\n\t\tthis.url = url;\r\n\t}\r\n}\r", "public class Pagination {\r\n\tpublic Integer total=0;// 总条数\r\n\tpublic Integer pageSize = 10;// 每页条数\r\n\tpublic Integer page = 1;// 当前页数\r\n\tprivate Map pageParaMap;// 页面参数\r\n\tpublic Integer pageTotal=0;// 总页数\r\n\tpublic Integer offset;\r\n\t\r\n\tprivate List list;//容器\r\n\r\n\tpublic Pagination() {\r\n\t}\r\n\r\n\tpublic Pagination(int total) {\r\n\t\tthis.total = total;\r\n\t}\r\n\r\n\tpublic Integer getTotal() {\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void setTotal(Integer total) {\r\n\t\tthis.total = total;\r\n\t}\r\n\r\n\tpublic Integer getPageSize() {\r\n\t\treturn pageSize;\r\n\t}\r\n\r\n\tpublic void setPageSize(Integer pageSize) {\r\n\t\tthis.pageSize = pageSize;\r\n\t}\r\n\r\n\tpublic Integer getPage() {\r\n\t\treturn page>0?page:1;\r\n\t}\r\n\r\n\tpublic void setPage(Integer page) {\r\n\t\tif(page==null) page=1;\r\n\t\tthis.page = page;\r\n\t}\r\n\r\n\tpublic Map getPageParaMap() {\r\n\t\treturn pageParaMap;\r\n\t}\r\n\r\n\tpublic void setPageParaMap(Map pageParaMap) {\r\n\t\tthis.pageParaMap = pageParaMap;\r\n\t}\r\n\r\n\tpublic Integer getPageTotal() {\r\n\t\tif(total==0) return 1;\r\n\t\tInteger totalPage = (total % pageSize == 0) ? (total / pageSize ): (total\r\n\t\t\t\t/ pageSize + 1);\r\n\t\treturn (totalPage==null || totalPage == 0) ? 1 : totalPage;\r\n\t}\r\n\r\n\tpublic void setPageTotal(Integer pageTotal) {\r\n\t\tthis.pageTotal = pageTotal;\r\n\t}\r\n\r\n\tpublic static Integer pageInteger(String page) {\r\n\t\tInteger p = 1;\r\n\t\tif (page != null && !page.equals(\"\")) {\r\n\t\t\tp = Integer.valueOf(page);\r\n\t\t}\r\n\t\treturn p;\r\n\t}\r\n\r\n\tpublic List getList() {\r\n\t\treturn list;\r\n\t}\r\n\r\n\tpublic void setList(List list) {\r\n\t\tthis.list = list;\r\n\t}\r\n\r\n\tpublic Integer getOffset() {\r\n\t\treturn (this.getPage()-1)*this.getPageSize();\r\n\t}\r\n\t\r\n\t/**\r\n\t * TODO:生成连接字符串,可用于GET方式的分页,待补充\r\n\t * @return\r\n\t */\r\n\tpublic String generateLink(){\r\n\t\treturn \"\";\r\n\t}\r\n\r\n}\r", "@Service\r\npublic class ProjectService{\r\n\t@Autowired\r\n\tprotected BaseDAO dao;\r\n\t@Autowired\r\n\tprivate ProjectDAO projectDAO;\r\n\t\r\n\t@TargetDataSource(DS.DATA_SOURCE_1)\r\n\tpublic List<Project> findProjectsOnIndex(Integer cnt){\r\n\t\treturn projectDAO.findProjectsOnIndex(cnt);\r\n\t}\r\n\t\r\n\tpublic Project findProjectByproId(Long proId){\r\n\t\treturn projectDAO.findProjectByproId(proId);\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic Pagination getProjectList(Integer page){\r\n\t\tPagination pager=new Pagination();\r\n\t\tString sql_where = \" 1 \";\r\n\t\tString countSQL=\"SELECT count(*) FROM {project} WHERE \"+sql_where;\r\n\t\tint count=dao.queryForInt(countSQL);\r\n\t\tpager.setTotal(count);\r\n\t\tpager.setPage(page);\r\n\t\tString sql=\"SELECT * FROM {project} WHERE \"+sql_where+\" order by prostatus ASC LIMIT ?,?\";\r\n\t\tList<Project> list=dao.queryForList(Project.class, sql,new Object[]{pager.getOffset(),pager.getPageSize()});\r\n\t\tpager.setList(list);\t\r\n\t\treturn pager;\r\n\t}\r\n}\r", "public class NumberHelper {\n\n\t/**\n\t * 支持的最小进制\n\t */\n\tpublic static int MIN_RADIX = 2;\n\t/**\n\t * 支持的最大进制\n\t */\n\tpublic static int MAX_RADIX = 62;\n\n\t/**\n\t * 锁定创建\n\t */\n\tprivate NumberHelper() {\n\t}\n\n\t/**\n\t * 0-9a-zA-Z表示62进制内的 0到61。\n\t */\n\tprivate static final String num62 = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n\t/**\n\t * 返回一字符串,包含 number 以 toRadix 进制的表示。<br />\n\t * number 本身的进制由 fromRadix 指定。fromRadix 和 toRadix 都只能在 2 和 62 之间(包括 2 和 62)。\n\t * <br />\n\t * 高于十进制的数字用字母 a-zA-Z 表示,例如 a 表示 10,b 表示 11 以及 Z 表示 62。<br />\n\t * \n\t * @param number 需要转换的数字\n\t * @param fromRadix 输入进制\n\t * @param toRadix 输出进制\n\t * @return 指定输出进制的数字\n\t */\n\tpublic static String baseConver(String number, int fromRadix, int toRadix) {\n\t\tlong dec = any2Dec(number, fromRadix);\n\t\treturn dec2Any(dec, toRadix);\n\t}\n\n\t/**\n\t * 返回一字符串,包含 十进制 number 以 radix 进制的表示。\n\t * \n\t * @param dec 需要转换的数字\n\t * @param toRadix 输出进制。当不在转换范围内时,此参数会被设定为 2,以便及时发现。\n\t * @return 指定输出进制的数字\n\t */\n\tpublic static String dec2Any(long dec, int toRadix) {\n\t\tif (toRadix < MIN_RADIX || toRadix > MAX_RADIX) {\n\t\t\ttoRadix = 2;\n\t\t}\n\t\tif (toRadix == 10) {\n\t\t\treturn String.valueOf(dec);\n\t\t}\n\t\t// -Long.MIN_VALUE 转换为 2 进制时长度为65\n\t\tchar[] buf = new char[65]; //\n\t\tint charPos = 64;\n\t\tboolean isNegative = (dec < 0);\n\t\tif (!isNegative) {\n\t\t\tdec = -dec;\n\t\t}\n\t\twhile (dec <= -toRadix) {\n\t\t\tbuf[charPos--] = num62.charAt((int) (-(dec % toRadix)));\n\t\t\tdec = dec / toRadix;\n\t\t}\n\t\tbuf[charPos] = num62.charAt((int) (-dec));\n\t\tif (isNegative) {\n\t\t\tbuf[--charPos] = '-';\n\t\t}\n\t\treturn new String(buf, charPos, (65 - charPos));\n\t}\n\n\t/**\n\t * 返回一字符串,包含 number 以 10 进制的表示。<br />\n\t * fromBase 只能在 2 和 62 之间(包括 2 和 62)。\n\t * \n\t * @param number 输入数字\n\t * @param fromRadix 输入进制\n\t * @return 十进制数字\n\t */\n\tpublic static long any2Dec(String number, int fromRadix) {\n\t\tlong dec = 0;\n\t\tlong digitValue = 0;\n\t\tint len = number.length() - 1;\n\t\tfor (int t = 0; t <= len; t++) {\n\t\t\tdigitValue = num62.indexOf(number.charAt(t));\n\t\t\tdec = dec * fromRadix + digitValue;\n\t\t}\n\t\treturn dec;\n\t}\n\n\t/**\n\t * 当前级别为n,增加到 n+1 级需要的活跃天数\n\t * \n\t * @param n 当前级别\n\t * @return 需要的活跃天数\n\t */\n\tpublic static int scoreRate(int n) {\n\t\tint s1 = (int) Math.pow(n, 2);\n\t\tint len = Integer.valueOf(n).toString().length();\n\t\tint ret = (int) (s1 + Math.pow(10, len));\n\t\treturn ret;\n\t}\n\n\t/*\n\t * 到N级所需要的累积分数\n\t */\n\tpublic static int scoreLevel(int n) {\n\t\tint ret = 0;\n\t\tif (n <= 0) {\n\t\t\tret = 10;\n\t\t} else {\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tret += scoreRate(i);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\tpublic static Integer str2int(String str) {\n\t\tInteger i = 0;\n\t\tif (str == null) {\n\t\t\treturn i;\n\t\t} else if (str.equals(\"\")) {\n\t\t\treturn i;\n\t\t} else if (str.length() > 9) {\n\t\t\treturn Integer.MAX_VALUE;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn Integer.valueOf(str);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static long str2long(String str) {\n\t\tlong i = 0;\n\t\tif (str == null) {\n\t\t\treturn i;\n\t\t} else if (str.equals(\"\")) {\n\t\t\treturn i;\n\t\t}else {\n\t\t\ttry {\n\t\t\t\treturn Long.valueOf(str);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n}" ]
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.baicai.controller.common.BaseController; import com.baicai.domain.project.Project; import com.baicai.domain.system.ErrorMsg; import com.baicai.domain.system.Pagination; import com.baicai.service.project.ProjectService; import com.baicai.corewith.util.NumberHelper;
package com.baicai.controller.index; @Controller @RequestMapping
public class InvestController extends BaseController{
0
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/ui/reminders/ReminderFragment.java
[ "public class RemindersAdapter extends BaseRecyclerViewAdapter<RemindersAdapter.ViewHolder> {\n\n private List<Reminder> mReminderList;\n private int lastPosition = -1;\n private RemindersAdapterOnClickHandler onRecyclerClickListener;\n\n public class ViewHolder extends BaseViewHolder implements CompoundButton.OnCheckedChangeListener {\n\n public TextView tvTitle;\n public TextView tvDate;\n public SwitchCompat scState;\n\n public ViewHolder(View v, RemindersAdapterOnClickHandler onRecyclerClickListener) {\n super(v, onRecyclerClickListener);\n tvTitle = (TextView)v.findViewById(R.id.tv_name);\n tvDate = (TextView)v.findViewById(R.id.tv_date);\n scState = (SwitchCompat)v.findViewById(R.id.sc_reminder);\n scState.setOnCheckedChangeListener(this);\n v.setOnClickListener(this);\n }\n\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if(this.itemView.getTag() != null) {\n ((RemindersAdapterOnClickHandler)onRecyclerClickListener).onChecked(isChecked, this);\n }\n }\n }\n\n public RemindersAdapter(List<Reminder> mReminderList, RemindersAdapterOnClickHandler onRecyclerClickListener) {\n this.mReminderList = mReminderList;\n this.onRecyclerClickListener = onRecyclerClickListener;\n }\n\n @Override\n public RemindersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.layout_reminder_item, parent, false);\n return new ViewHolder(v, onRecyclerClickListener);\n }\n\n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n final Reminder reminder = mReminderList.get(position);\n if (reminder.getName() != null) holder.tvTitle.setText(reminder.getName());\n holder.tvDate.setText(\"Day of the Month: \".concat(String.valueOf(reminder.getDay())).concat(\" - \").concat(\"Time: \").concat(Util.formatDateToString(reminder.getDate(), \"HH:mm\")));\n holder.scState.setChecked(reminder.isState());\n holder.itemView.setTag(reminder);\n holder.itemView.setSelected(isSelected(position));\n setAnimation(holder, position);\n }\n\n @Override\n public int getItemCount() {\n return mReminderList.size();\n }\n\n public void updateReminders(List<Reminder> mReminderList) {\n this.mReminderList = mReminderList;\n notifyDataSetChanged();\n }\n\n private void setAnimation(ViewHolder holder, int position) {\n if (position > lastPosition) {\n Animation animation = AnimationUtils.loadAnimation(ExpenseTrackerApp.getContext(), R.anim.push_left_in);\n holder.itemView.startAnimation(animation);\n lastPosition = position;\n }\n }\n\n public interface RemindersAdapterOnClickHandler extends BaseViewHolder.RecyclerClickListener {\n void onChecked(boolean checked, ViewHolder vh);\n }\n\n}", "public class DefaultRecyclerViewItemDecorator extends RecyclerView.ItemDecoration {\n\n private final float mVerticalSpaceHeight;\n\n public DefaultRecyclerViewItemDecorator(float mVerticalSpaceHeight) {\n this.mVerticalSpaceHeight = mVerticalSpaceHeight;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent,\n RecyclerView.State state) {\n outRect.bottom = (int) mVerticalSpaceHeight;\n if (parent.getChildAdapterPosition(view) == 0) {\n outRect.top = (int) mVerticalSpaceHeight;\n }\n }\n\n}", "public class Category extends RealmObject {\n\n @PrimaryKey\n private String id;\n\n private String name;\n private int type;\n private RealmList<Expense> expenses;\n\n public Category() {\n }\n\n public Category(String name, @IExpensesType int type) {\n this.name = name;\n this.type = type;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public RealmList<Expense> getExpenses() {\n return expenses;\n }\n\n public void setExpenses(RealmList<Expense> expenses) {\n this.expenses = expenses;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public static List<Category> getCategoriesIncome() {\n return getCategoriesForType(IExpensesType.MODE_INCOME);\n }\n\n public static List<Category> getCategoriesExpense() {\n return getCategoriesForType(IExpensesType.MODE_EXPENSES);\n }\n\n public static List<Category> getCategoriesForType(@IExpensesType int type){\n return RealmManager.getInstance().getRealmInstance().where(Category.class)\n .equalTo(\"type\", type)\n .findAll();\n }\n\n}", "public class Reminder extends RealmObject {\n\n @PrimaryKey\n private String id;\n\n private String name;\n private boolean state;\n private int day;\n private Date date;\n private Date createdAt;\n\n public Reminder() {}\n\n public Reminder(String name, int day, boolean state, Date date) {\n this.name = name;\n this.day = day;\n this.state = state;\n this.date = date;\n this.createdAt = new Date();\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public boolean isState() {\n return state;\n }\n\n public void setState(boolean state) {\n this.state = state;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public int getDay() {\n return day;\n }\n\n public void setDay(int day) {\n this.day = day;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public static List<Reminder> getReminders() {\n return RealmManager.getInstance().getRealmInstance().where(Reminder.class).findAll();\n }\n\n public static void saveNewReminder(String name, int daySelected, boolean state, Date timeSelected) {\n Reminder reminder = new Reminder(name, daySelected, true, timeSelected);\n RealmManager.getInstance().save(reminder, Reminder.class);\n setReminder(reminder);\n }\n\n public static void setReminder(Reminder reminder) {\n Calendar alarmCalendar = Calendar.getInstance();\n Calendar reminderDate = Calendar.getInstance();\n reminderDate.setTime(reminder.getDate());\n if (reminder.getDay() <= alarmCalendar.get(Calendar.DAY_OF_MONTH) || !DateUtils.isToday(reminder.getCreatedAt())) {\n alarmCalendar.setTime(DateUtils.getLastDateOfCurrentMonth());\n }\n alarmCalendar.set(Calendar.DATE, reminder.getDay());\n alarmCalendar.set(Calendar.HOUR_OF_DAY, reminderDate.get(Calendar.HOUR_OF_DAY));\n alarmCalendar.set(Calendar.MINUTE, reminderDate.get(Calendar.MINUTE));\n\n AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class);\n intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId());\n\n PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0);\n alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), alarmIntent);\n\n }\n\n public static void cancelReminder(Reminder reminder) {\n AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class);\n intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId());\n PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0);\n alarmMgr.cancel(alarmIntent);\n }\n\n public static void updateReminder(Reminder reminder, boolean checked) {\n Reminder reminderToUpdate = new Reminder(reminder.getName(), reminder.getDay(), checked, reminder.getDate());\n reminderToUpdate.setCreatedAt(reminder.getCreatedAt());\n reminderToUpdate.setId(reminder.getId());\n RealmManager.getInstance().update(reminderToUpdate);\n if (checked) {\n setReminder(reminder);\n } else {\n cancelReminder(reminder);\n }\n }\n\n public static void eraseReminder(Reminder reminder) {\n if (reminder.isState()) {\n cancelReminder(reminder);\n }\n RealmManager.getInstance().delete(reminder);\n }\n\n public static void eraseReminders(List<Reminder> reminderList) {\n for (Reminder reminder : reminderList) {\n if (reminder.isState()) {\n cancelReminder(reminder);\n }\n }\n RealmManager.getInstance().delete(reminderList);\n }\n}", "public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, IMainActivityListener {\n\n @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_TABS})\n @Retention(RetentionPolicy.SOURCE)\n public @interface NavigationMode {}\n\n public static final int NAVIGATION_MODE_STANDARD = 0;\n public static final int NAVIGATION_MODE_TABS = 1;\n public static final String NAVIGATION_POSITION = \"navigation_position\";\n\n private int mCurrentMode = NAVIGATION_MODE_STANDARD;\n private int idSelectedNavigationItem;\n\n private DrawerLayout mainDrawerLayout;\n private NavigationView mainNavigationView;\n private Toolbar mToolbar;\n private TabLayout mainTabLayout;\n private FloatingActionButton mFloatingActionButton;\n\n // Expenses Summary related views\n private LinearLayout llExpensesSummary;\n private TextView tvDate;\n private TextView tvDescription;\n private TextView tvTotal;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n initUI();\n setUpDrawer();\n setUpToolbar();\n if ( savedInstanceState != null) {\n int menuItemId = savedInstanceState.getInt(NAVIGATION_POSITION);\n mainNavigationView.setCheckedItem(menuItemId);\n mainNavigationView.getMenu().performIdentifierAction(menuItemId, 0);\n } else {\n mainNavigationView.getMenu().performIdentifierAction(R.id.nav_expenses, 0);\n }\n }\n\n @NavigationMode\n public int getNavigationMode() {\n return mCurrentMode;\n }\n\n private void initUI() {\n mainDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);\n mainTabLayout = (TabLayout)findViewById(R.id.tab_layout);\n mainNavigationView = (NavigationView)findViewById(R.id.nav_view);\n mFloatingActionButton = (FloatingActionButton)findViewById(R.id.fab_main);\n llExpensesSummary = (LinearLayout)findViewById(R.id.ll_expense_container);\n tvDate = (TextView)findViewById(R.id.tv_date);\n tvDescription = (TextView)findViewById(R.id.tv_description);\n tvTotal = (TextView)findViewById(R.id.tv_total);\n }\n\n private void setUpDrawer() {\n mainNavigationView.setNavigationItemSelectedListener(this);\n }\n\n private void setUpToolbar() {\n mToolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(mToolbar);\n\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);\n mToolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n mainDrawerLayout.openDrawer(GravityCompat.START);\n }\n });\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n //noinspection SimplifiableIfStatement\n if (id == R.id.action_settings) {\n startActivity(new Intent(this, SettingsActivity.class));\n return true;\n } else if (id == R.id.action_help) {\n startActivity(new Intent(this, HelpActivity.class));\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n outState.putInt(NAVIGATION_POSITION, idSelectedNavigationItem);\n super.onSaveInstanceState(outState);\n }\n\n @Override\n public boolean onNavigationItemSelected(MenuItem menuItem) {\n menuItem.setChecked(true);\n mainDrawerLayout.closeDrawers();\n switchFragment(menuItem.getItemId());\n return false;\n }\n\n @Override\n public void setTabs(List<String> tabList, final TabLayout.OnTabSelectedListener onTabSelectedListener) {\n mainTabLayout.removeAllTabs();\n mainTabLayout.setVisibility(View.VISIBLE);\n mainTabLayout.setOnTabSelectedListener(onTabSelectedListener);\n for (String tab : tabList) {\n mainTabLayout.addTab(mainTabLayout.newTab().setText(tab).setTag(tab));\n }\n }\n\n @Override\n public void setMode(@NavigationMode int mode) {\n mFloatingActionButton.setVisibility(View.GONE);\n llExpensesSummary.setVisibility(View.GONE);\n mCurrentMode = mode;\n switch (mode) {\n case NAVIGATION_MODE_STANDARD:\n setNavigationModeStandard();\n break;\n case NAVIGATION_MODE_TABS:\n setNavigationModeTabs();\n break;\n }\n }\n\n @Override\n public void setExpensesSummary(@IDateMode int dateMode) {\n float total = Expense.getTotalExpensesByDateMode(dateMode);\n tvTotal.setText(Util.getFormattedCurrency(total));\n String date;\n switch (dateMode) {\n case IDateMode.MODE_TODAY:\n date = Util.formatDateToString(DateUtils.getToday(), Util.getCurrentDateFormat());\n break;\n case IDateMode.MODE_WEEK:\n date = Util.formatDateToString(DateUtils.getFirstDateOfCurrentWeek(), Util.getCurrentDateFormat()).concat(\" - \").concat(Util.formatDateToString(DateUtils.getRealLastDateOfCurrentWeek(), Util.getCurrentDateFormat()));\n break;\n case IDateMode.MODE_MONTH:\n date = Util.formatDateToString(DateUtils.getFirstDateOfCurrentMonth(), Util.getCurrentDateFormat()).concat(\" - \").concat(Util.formatDateToString(DateUtils.getRealLastDateOfCurrentMonth(), Util.getCurrentDateFormat()));\n break;\n default:\n date = \"\";\n break;\n }\n tvDate.setText(date);\n }\n\n @Override\n public void setFAB(@DrawableRes int drawableId, View.OnClickListener onClickListener) {\n mFloatingActionButton.setImageDrawable(getResources().getDrawable(drawableId));\n mFloatingActionButton.setOnClickListener(onClickListener);\n mFloatingActionButton.show();\n }\n\n @Override\n public void setTitle(String title) {\n getSupportActionBar().setTitle(title);\n }\n\n @Override\n public void setPager(ViewPager vp, final TabLayout.ViewPagerOnTabSelectedListener viewPagerOnTabSelectedListener) {\n mainTabLayout.setupWithViewPager(vp);\n mainTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(vp) {\n @Override\n public void onTabSelected(TabLayout.Tab tab) {\n @IDateMode int dateMode;\n switch (tab.getPosition()) {\n case 0:\n dateMode = IDateMode.MODE_TODAY;\n break;\n case 1:\n dateMode = IDateMode.MODE_WEEK;\n break;\n case 2:\n dateMode = IDateMode.MODE_MONTH;\n break;\n default:\n dateMode = IDateMode.MODE_TODAY;\n }\n setExpensesSummary(dateMode);\n viewPagerOnTabSelectedListener.onTabSelected(tab);\n }\n\n @Override\n public void onTabUnselected(TabLayout.Tab tab) {\n viewPagerOnTabSelectedListener.onTabUnselected(tab);\n }\n });\n setExpensesSummary(IDateMode.MODE_TODAY);\n }\n\n public ActionMode setActionMode(final ActionMode.Callback actionModeCallback) {\n return mToolbar.startActionMode(new ActionMode.Callback() {\n @Override\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n mainDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);\n return actionModeCallback.onCreateActionMode(mode,menu);\n }\n\n @Override\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n return actionModeCallback.onPrepareActionMode(mode, menu);\n }\n\n @Override\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\n return actionModeCallback.onActionItemClicked(mode, item);\n }\n\n @Override\n public void onDestroyActionMode(ActionMode mode) {\n mainDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);\n actionModeCallback.onDestroyActionMode(mode);\n }\n });\n }\n\n private void setNavigationModeTabs() {\n mainTabLayout.setVisibility(View.VISIBLE);\n llExpensesSummary.setVisibility(View.VISIBLE);\n }\n\n private void setNavigationModeStandard() {\n CoordinatorLayout coordinator = (CoordinatorLayout) findViewById(R.id.main_coordinator);\n AppBarLayout appbar = (AppBarLayout) findViewById(R.id.app_bar_layout);\n CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appbar.getLayoutParams();\n AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();\n if (behavior != null && appbar != null) {\n int[] consumed = new int[2];\n behavior.onNestedPreScroll(coordinator, appbar, null, 0, -1000, consumed);\n }\n mainTabLayout.setVisibility(View.GONE);\n }\n\n private void switchFragment(int menuItemId) {\n Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.main_content);\n switch (menuItemId) {\n case R.id.nav_expenses:\n if (!(currentFragment instanceof ExpensesContainerFragment)) replaceFragment(ExpensesContainerFragment.newInstance(), false);\n break;\n case R.id.nav_categories:\n if (!(currentFragment instanceof CategoriesFragment)) replaceFragment(CategoriesFragment.newInstance(), false);\n break;\n case R.id.nav_statistics:\n if (!(currentFragment instanceof StatisticsFragment)) replaceFragment(StatisticsFragment.newInstance(), false);\n break;\n case R.id.nav_reminders:\n if (!(currentFragment instanceof ReminderFragment)) replaceFragment(ReminderFragment.newInstance(), false);\n break;\n case R.id.nav_history:\n if (!(currentFragment instanceof HistoryFragment)) replaceFragment(HistoryFragment.newInstance(), false);\n break;\n }\n }\n}", "public class MainFragment extends BaseFragment {\n\n protected IMainActivityListener mMainActivityListener;\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n mMainActivityListener = (IMainActivityListener)context;\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mMainActivityListener = null;\n }\n\n}", "public class DialogManager {\n\n private static DialogManager ourInstance = new DialogManager();\n\n public static DialogManager getInstance() {\n return ourInstance;\n }\n\n private DialogManager() {\n }\n\n public AlertDialog createEditTextDialog(Activity activity, String title, String confirmText, String negativeText, final DialogInterface.OnClickListener listener) {\n LayoutInflater inflater = activity.getLayoutInflater();\n View dialogLayout = inflater.inflate(R.layout.layout_dialog_edit_text, null);\n return createAlertDialog(activity, title, dialogLayout, null, confirmText, negativeText, listener);\n }\n\n public void createCustomAcceptDialog(Activity activity, String title, String message, String confirmText, String negativeText, final DialogInterface.OnClickListener listener) {\n createAlertDialog(activity, title, null, message, confirmText, negativeText, listener);\n }\n\n public void createSinglePickDialog(Activity activity, String title, @ArrayRes int arrayId, DialogInterface.OnClickListener listener) {\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder.setTitle(title)\n .setItems(arrayId, listener);\n builder.create().show();\n }\n\n public void createTimePickerDialog(Activity activity, int hour, int minute, TimePickerDialog.OnTimeSetListener listener) {\n new TimePickerDialog(activity, listener, hour, minute, DateFormat.is24HourFormat(activity)).show();\n }\n\n private AlertDialog createAlertDialog(Activity activity, String title, View dialogLayout, String message, String confirmText, String negativeText, final DialogInterface.OnClickListener listener) {\n ContextThemeWrapper ctw = new ContextThemeWrapper(activity, R.style.DialogTheme);\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ctw);\n dialogBuilder.setTitle(title);\n if (dialogLayout != null) dialogBuilder.setView(dialogLayout);\n if (message != null) dialogBuilder.setMessage(message);\n dialogBuilder.setCancelable(false);\n dialogBuilder.setPositiveButton(confirmText, listener);\n dialogBuilder.setNegativeButton(negativeText, listener);\n AlertDialog alertDialog = dialogBuilder.create();\n alertDialog.show();\n return alertDialog;\n }\n\n public void showShortSnackBar(View view, String message) {\n Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show();\n }\n\n public void showShortToast(String message) {\n Toast.makeText(ExpenseTrackerApp.getContext(), message, Toast.LENGTH_SHORT).show();\n }\n\n public void showDatePickerDialog(Context context, DatePickerDialog.OnDateSetListener dateSetListener, Calendar calendar) {\n showDatePicker(context, dateSetListener, calendar,null, null);\n }\n\n public void showDatePicker(Context context, DatePickerDialog.OnDateSetListener dateSetListener, Calendar calendar, Date minDate, Date maxDate) {\n DatePickerDialog datePickerDialog = new DatePickerDialog(context, R.style.DialogTheme, dateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));\n if (minDate != null) datePickerDialog.getDatePicker().setMinDate(minDate.getTime());\n if (maxDate != null) datePickerDialog.getDatePicker().setMaxDate(maxDate.getTime());\n datePickerDialog.show();\n }\n}", "public class RealmManager {\n\n private Realm realm;\n\n private static RealmManager ourInstance = new RealmManager();\n\n public static RealmManager getInstance() {\n return ourInstance;\n }\n\n public RealmManager(){\n realm = Realm.getInstance(ExpenseTrackerApp.getContext());\n }\n\n public Realm getRealmInstance() {\n return realm;\n }\n\n public <E extends RealmObject> void update(final E object) {\n realm.executeTransaction(new Realm.Transaction() {\n @Override\n public void execute(Realm realm) {\n realm.copyToRealmOrUpdate(object);\n }\n });\n }\n\n public <E extends RealmObject> void update(final Iterable<E> object) {\n realm.executeTransaction(new Realm.Transaction() {\n @Override\n public void execute(Realm realm) {\n realm.copyToRealmOrUpdate(object);\n }\n });\n }\n\n public <E extends RealmObject> void save(final E object, final Class<E> clazz) {\n realm.executeTransaction(new Realm.Transaction() {\n @Override\n public void execute(Realm realm) {\n checkDuplicateUUID(object, clazz);\n realm.copyToRealmOrUpdate(object);\n }\n });\n }\n\n public <E extends RealmObject> void delete(final Iterable<E> objects){\n realm.executeTransaction(new Realm.Transaction() {\n @Override\n public void execute(Realm realm) {\n if (objects == null) {\n return;\n }\n for (E object : objects) {\n if (object instanceof Category) {\n Category category = (Category) object;\n RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category);\n for (int i = expenseList.size()-1; i >= 0; i--) {\n expenseList.get(i).removeFromRealm();\n }\n }\n object.removeFromRealm();\n }\n }\n });\n }\n\n public <E extends RealmObject> void delete(final E object){\n realm.executeTransaction(new Realm.Transaction() {\n @Override\n public void execute(Realm realm) {\n if (object instanceof Category) {\n Category category = (Category) object;\n RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category);\n for (int i = expenseList.size()-1; i >= 0; i--) {\n expenseList.get(i).removeFromRealm();\n }\n }\n object.removeFromRealm();\n }\n });\n }\n\n public <E extends RealmObject> RealmObject findById(Class<E> clazz, String id) {\n return realm.where(clazz).equalTo(\"id\", id).findFirst();\n }\n\n public <E extends RealmObject> void checkDuplicateUUID(E object, Class<E> clazz) {\n boolean repeated = true;\n while (repeated) {\n String id = UUID.randomUUID().toString();\n RealmObject realmObject = findById(clazz, id);\n if ( realmObject == null ) {\n if (object instanceof Expense) {\n ((Expense)object).setId(id);\n } else if (object instanceof Category){\n ((Category)object).setId(id);\n } else {\n ((Reminder)object).setId(id);\n }\n repeated = false;\n }\n }\n }\n\n}" ]
import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.adapters.RemindersAdapter; import com.pedrocarrillo.expensetracker.custom.DefaultRecyclerViewItemDecorator; import com.pedrocarrillo.expensetracker.entities.Category; import com.pedrocarrillo.expensetracker.entities.Reminder; import com.pedrocarrillo.expensetracker.interfaces.IUserActionsMode; import com.pedrocarrillo.expensetracker.ui.MainActivity; import com.pedrocarrillo.expensetracker.ui.MainFragment; import com.pedrocarrillo.expensetracker.utils.DialogManager; import com.pedrocarrillo.expensetracker.utils.RealmManager; import java.util.ArrayList; import java.util.List;
package com.pedrocarrillo.expensetracker.ui.reminders; /** * Created by pcarrillo on 17/09/2015. */ public class ReminderFragment extends MainFragment implements RemindersAdapter.RemindersAdapterOnClickHandler { public static final int RQ_REMINDER = 1002; private RecyclerView rvReminders;
private List<Reminder> mReminderList;
3
enebo/racob
unittest/org/racob/test/vbscript/ScriptTest2.java
[ "public class ActiveXComponent extends Dispatch {\n\n\t/**\n\t * Normally used to create a new connection to a microsoft application. The\n\t * passed in parameter is the name of the program as registered in the\n\t * registry. It can also be the object name.\n\t * <p>\n\t * This constructor causes a new Windows object of the requested type to be\n\t * created. The windows CoCreate() function gets called to create the\n\t * underlying windows object.\n\t * \n\t * <pre>\n\t * new ActiveXComponent(&quot;ScriptControl&quot;);\n\t * </pre>\n\t * \n\t * @param programId\n\t */\n\tpublic ActiveXComponent(String programId) {\n\t\tsuper(programId);\n\t}\n\n\t/**\n\t * Creates an active X component that is built on top of the COM pointers\n\t * held in the passed in dispatch. This widens the Dispatch object to pick\n\t * up the ActiveXComponent API\n\t * \n\t * @param dispatchToBeWrapped\n\t */\n\tpublic ActiveXComponent(Dispatch dispatchToBeWrapped) {\n\t\tsuper(dispatchToBeWrapped);\n\t}\n\n\t/**\n\t * only used by the factories\n\t * \n\t */\n\tprivate ActiveXComponent() {\n\t\tsuper();\n\t}\n\n\t/**\n\t * Probably was a cover for something else in the past. Should be\n\t * deprecated.\n\t * \n\t * @return Now it actually returns this exact same object.\n\t */\n\tpublic Dispatch getObject() {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Most code should use the standard ActiveXComponent(String) contructor and\n\t * not this factory method. This method exists for applications that need\n\t * special behavior. <B>Experimental in release 1.9.2.</B>\n\t * <p>\n\t * Factory that returns a Dispatch object wrapped around the result of a\n\t * CoCreate() call. This differs from the standard constructor in that it\n\t * throws no exceptions and returns null on failure.\n\t * <p>\n\t * This will fail for any prog id with a \":\" in it.\n\t * \n\t * @param pRequestedProgramId\n\t * @return Dispatch pointer to the COM object or null if couldn't create\n\t */\n\tpublic static ActiveXComponent createNewInstance(String pRequestedProgramId) {\n\t\tActiveXComponent mCreatedDispatch = null;\n\t\ttry {\n\t\t\tmCreatedDispatch = new ActiveXComponent();\n\t\t\tmCreatedDispatch.coCreateInstance(pRequestedProgramId);\n\t\t} catch (Exception e) {\n\t\t\tmCreatedDispatch = null;\n\t\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\t\tIUnknown.debug(\"Unable to co-create instance of \"\n\t\t\t\t\t\t+ pRequestedProgramId);\n\t\t\t}\n\t\t}\n\t\treturn mCreatedDispatch;\n\t}\n\n\t/**\n\t * Most code should use the standard ActiveXComponent(String) constructor and\n\t * not this factory method. This method exists for applications that need\n\t * special behavior. <B>Experimental in release 1.9.2.</B>\n\t * <p>\n\t * Factory that returns a Dispatch wrapped around the result of a\n\t * getActiveObject() call. This differs from the standard constructor in\n\t * that it throws no exceptions and returns null on failure.\n\t * <p>\n\t * This will fail for any prog id with a \":\" in it\n\t * \n\t * @param pRequestedProgramId\n\t * @return Dispatch pointer to a COM object or null if wasn't already\n\t * running\n\t */\n\tpublic static ActiveXComponent connectToActiveInstance(\n\t\t\tString pRequestedProgramId) {\n\t\tActiveXComponent mCreatedDispatch = null;\n\t\ttry {\n\t\t\tmCreatedDispatch = new ActiveXComponent();\n\t\t\tmCreatedDispatch.getActiveInstance(pRequestedProgramId);\n\t\t} catch (Exception e) {\n\t\t\tmCreatedDispatch = null;\n\t\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\t\tIUnknown.debug(\"Unable to attach to running instance of \"\n\t\t\t\t\t\t+ pRequestedProgramId);\n\t\t\t}\n\t\t}\n\t\treturn mCreatedDispatch;\n\t}\n\n\t/*\n\t * ============================================================\n\t * \n\t * start of instance based calls to the COM layer\n\t * ===========================================================\n\t */\n\n\t/**\n\t * retrieves a property and returns it as a Variant\n\t * \n\t * @param propertyName\n\t * @return variant value of property\n\t */\n\tpublic Variant getProperty(String propertyName) {\n\t\treturn get(propertyName);\n\t}\n\n\t/**\n\t * retrieves a property and returns it as an ActiveX component\n\t * \n\t * @param propertyName\n\t * @return Dispatch representing the object under the property name\n\t */\n\tpublic ActiveXComponent getPropertyAsComponent(String propertyName) {\n\t\treturn new ActiveXComponent(get(propertyName).getDispatch());\n\t}\n\n\t/**\n\t * retrieves a property and returns it as a Boolean\n\t * \n\t * @param propertyName\n\t * property we are looking up\n\t * @return boolean value of property\n\t */\n\tpublic boolean getPropertyAsBoolean(String propertyName) {\n\t\treturn get(propertyName).getBoolean();\n\t}\n\n\t/**\n\t * retrieves a property and returns it as a byte\n\t * \n\t * @param propertyName\n\t * property we are looking up\n\t * @return byte value of property\n\t */\n\tpublic byte getPropertyAsByte(String propertyName) {\n\t\treturn get(propertyName).getByte();\n\t}\n\n\t/**\n\t * retrieves a property and returns it as a String\n\t * \n\t * @param propertyName\n\t * @return String value of property\n\t */\n\tpublic String getPropertyAsString(String propertyName) {\n\t\treturn get(propertyName).getString();\n\n\t}\n\n\t/**\n\t * retrieves a property and returns it as a int\n\t * \n\t * @param propertyName\n\t * @return the property value as an int\n\t */\n\tpublic int getPropertyAsInt(String propertyName) {\n\t\treturn get(propertyName).getInt();\n\t}\n\n\t/**\n\t * sets a property on this object\n\t * \n\t * @param propertyName\n\t * property name\n\t * @param arg\n\t * variant value to be set\n\t */\n\tpublic void setProperty(String propertyName, Variant arg) {\n\t\tput(propertyName, arg);\n\t}\n\n\t/**\n\t * sets a property on this object\n\t * \n\t * @param propertyName\n\t * property name\n\t * @param arg\n\t * variant value to be set\n\t */\n\tpublic void setProperty(String propertyName, Dispatch arg) {\n\t\tput(propertyName, arg);\n\t}\n\n\t/**\n\t * sets a property to be the value of the string\n\t * \n\t * @param propertyName\n\t * @param propertyValue\n\t */\n\tpublic void setProperty(String propertyName, String propertyValue) {\n\t\tthis.setProperty(propertyName, new Variant(propertyValue));\n\t}\n\n\t/**\n\t * sets a property as a boolean value\n\t * \n\t * @param propertyName\n\t * @param propValue\n\t * the boolean value we want the prop set to\n\t */\n\tpublic void setProperty(String propertyName, boolean propValue) {\n\t\tthis.setProperty(propertyName, new Variant(propValue));\n\t}\n\n\t/**\n\t * sets a property as a boolean value\n\t * \n\t * @param propertyName\n\t * @param propValue\n\t * the boolean value we want the prop set to\n\t */\n\tpublic void setProperty(String propertyName, byte propValue) {\n\t\tthis.setProperty(propertyName, new Variant(propValue));\n\t}\n\n\t/**\n\t * sets the property as an int value\n\t * \n\t * @param propertyName\n\t * @param propValue\n\t * the int value we want the prop to be set to.\n\t */\n\tpublic void setProperty(String propertyName, int propValue) {\n\t\tthis.setProperty(propertyName, new Variant(propValue));\n\t}\n\n\t/*-------------------------------------------------------\n\t * Listener logging helpers\n\t *-------------------------------------------------------\n\t */\n\n\t/**\n\t * This boolean determines if callback events should be logged\n\t */\n\tpublic static boolean shouldLogEvents = false;\n\n\t/**\n\t * used by the doc and application listeners to get intelligent logging\n\t * \n\t * @param description\n\t * event description\n\t * @param args\n\t * args passed in (variants)\n\t * \n\t */\n\tpublic void logCallbackEvent(String description, Variant[] args) {\n\t\tString argString = \"\";\n\t\tif (args != null && ActiveXComponent.shouldLogEvents) {\n\t\t\tif (args.length > 0) {\n\t\t\t\targString += \" args: \";\n\t\t\t}\n\t\t\tfor (int i = 0; i < args.length; i++) {\n\t\t\t\tshort argType = args[i].getvt();\n\t\t\t\targString += \",[\" + i + \"]\";\n\t\t\t\t// break out the byref bits if they are on this\n\t\t\t\tif ((argType & Variant.VariantByref) == Variant.VariantByref) {\n\t\t\t\t\t// show the type and the fact that its byref\n\t\t\t\t\targString += \"(\"\n\t\t\t\t\t\t\t+ (args[i].getvt() & ~Variant.VariantByref) + \"/\"\n\t\t\t\t\t\t\t+ Variant.VariantByref + \")\";\n\t\t\t\t} else {\n\t\t\t\t\t// show the type\n\t\t\t\t\targString += \"(\" + argType + \")\";\n\t\t\t\t}\n\t\t\t\targString += \"=\";\n\t\t\t\tif (argType == Variant.VariantDispatch) {\n\t\t\t\t\tDispatch foo = (args[i].getDispatch());\n\t\t\t\t\targString += foo;\n\t\t\t\t} else if ((argType & Variant.VariantBoolean) == Variant.VariantBoolean) {\n\t\t\t\t\t// do the boolean thing\n\t\t\t\t\tif ((argType & Variant.VariantByref) == Variant.VariantByref) {\n\t\t\t\t\t\t// boolean by ref\n\t\t\t\t\t\targString += args[i].getBoolean();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// boolean by value\n\t\t\t\t\t\targString += args[i].getBoolean();\n\t\t\t\t\t}\n\t\t\t\t} else if ((argType & Variant.VariantString) == Variant.VariantString) {\n\t\t\t\t\t// do the string thing\n\t\t\t\t\tif ((argType & Variant.VariantByref) == Variant.VariantByref) {\n\t\t\t\t\t\t// string by ref\n\t\t\t\t\t\targString += args[i].getString();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// string by value\n\t\t\t\t\t\targString += args[i].getString();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\targString += args[i].toString();\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.out.println(description + argString);\n\t\t}\n\t}\n\n\t/*\n\t * ==============================================================\n\t * \n\t * covers for dispatch call methods\n\t * =============================================================\n\t */\n\n\t/**\n\t * makes a dispatch call for the passed in action and no parameter\n\t * \n\t * @param callAction\n\t * @return ActiveXComponent representing the results of the call\n\t */\n\tpublic ActiveXComponent invokeGetComponent(String callAction) {\n\t\treturn new ActiveXComponent(invoke(callAction).getDispatch());\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and single parameter\n\t * \n\t * @param callAction\n\t * @param parameter\n\t * @return ActiveXComponent representing the results of the call\n\t */\n\tpublic ActiveXComponent invokeGetComponent(String callAction,\n\t\t\tVariant parameter) {\n\t\treturn new ActiveXComponent(invoke(callAction, parameter).getDispatch());\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and single parameter\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @return ActiveXComponent representing the results of the call\n\t */\n\tpublic ActiveXComponent invokeGetComponent(String callAction,\n\t\t\tVariant parameter1, Variant parameter2) {\n\t\treturn new ActiveXComponent(invoke(callAction, parameter1, parameter2).getDispatch());\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and single parameter\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @param parameter3\n\t * @return ActiveXComponent representing the results of the call\n\t */\n\tpublic ActiveXComponent invokeGetComponent(String callAction,\n\t\t\tVariant parameter1, Variant parameter2, Variant parameter3) {\n\t\treturn new ActiveXComponent(invoke(callAction, parameter1, parameter2,\n\t\t\t\tparameter3).getDispatch());\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and single parameter\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @param parameter3\n\t * @param parameter4\n\t * @return ActiveXComponent representing the results of the call\n\t */\n\tpublic ActiveXComponent invokeGetComponent(String callAction,\n\t\t\tVariant parameter1, Variant parameter2, Variant parameter3,\n\t\t\tVariant parameter4) {\n\t\treturn new ActiveXComponent(invoke(callAction, parameter1, parameter2,\n\t\t\t\tparameter3, parameter4).getDispatch());\n\t}\n\n\t/**\n\t * invokes a single parameter call on this dispatch that returns no value\n\t * \n\t * @param actionCommand\n\t * @param parameter\n\t * @return a Variant but that may be null for some calls\n\t */\n\tpublic Variant invoke(String actionCommand, String parameter) {\n\t\treturn call(actionCommand, parameter);\n\t}\n\n\t/**\n\t * makes a dispatch call to the passed in action with a single boolean\n\t * parameter\n\t * \n\t * @param actionCommand\n\t * @param parameter\n\t * @return Variant result\n\t */\n\tpublic Variant invoke(String actionCommand, boolean parameter) {\n\t\treturn call(actionCommand, new Variant(parameter));\n\t}\n\n\t/**\n\t * makes a dispatch call to the passed in action with a single int parameter\n\t * \n\t * @param actionCommand\n\t * @param parameter\n\t * @return Variant result of the invoke (Dispatch.call)\n\t */\n\tpublic Variant invoke(String actionCommand, int parameter) {\n\t\treturn call(actionCommand, new Variant(parameter));\n\t}\n\n\t/**\n\t * makes a dispatch call to the passed in action with a string and integer\n\t * parameter (this was put in for some application)\n\t * \n\t * @param actionCommand\n\t * @param parameter1\n\t * @param parameter2\n\t * @return Variant result\n\t */\n\tpublic Variant invoke(String actionCommand, String parameter1,\n\t\t\tint parameter2) {\n\t\treturn call(actionCommand, parameter1, new Variant(parameter2));\n\t}\n\n\t/**\n\t * makes a dispatch call to the passed in action with two integer parameters\n\t * (this was put in for some application)\n\t * \n\t * @param actionCommand\n\t * @param parameter1\n\t * @param parameter2\n\t * @return a Variant but that may be null for some calls\n\t */\n\tpublic Variant invoke(String actionCommand, int parameter1, int parameter2) {\n\t\treturn call(actionCommand, \n new Variant(parameter1), new Variant(parameter2));\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and single parameter\n\t * \n\t * @param callAction\n\t * @param parameter\n\t * @return a Variant but that may be null for some calls\n\t */\n\tpublic Variant invoke(String callAction, Variant parameter) {\n\t\treturn call(callAction, parameter);\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and two parameter\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @return a Variant but that may be null for some calls\n\t */\n\tpublic Variant invoke(String callAction, Variant parameter1,\n\t\t\tVariant parameter2) {\n\t\treturn call(callAction, parameter1, parameter2);\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and two parameter\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @param parameter3\n\t * @return Variant result data\n\t */\n\tpublic Variant invoke(String callAction, Variant parameter1,\n\t\t\tVariant parameter2, Variant parameter3) {\n\t\treturn call(callAction, parameter1, parameter2, parameter3);\n\t}\n\n\t/**\n\t * calls call() with 4 variant parameters\n\t * \n\t * @param callAction\n\t * @param parameter1\n\t * @param parameter2\n\t * @param parameter3\n\t * @param parameter4\n\t * @return Variant result data\n\t */\n\tpublic Variant invoke(String callAction, Variant parameter1,\n\t\t\tVariant parameter2, Variant parameter3, Variant parameter4) {\n\t\treturn call(callAction, parameter1, parameter2,\tparameter3, parameter4);\n\t}\n\n\t/**\n\t * makes a dispatch call for the passed in action and no parameter\n\t * \n\t * @param callAction\n\t * @return a Variant but that may be null for some calls\n\t */\n\tpublic Variant invoke(String callAction) {\n\t\treturn call(callAction);\n\t}\n\n\t/**\n\t * This is really a cover for call(String,Variant[]) that should be\n\t * eliminated call with a variable number of args mainly used for quit.\n\t * \n\t * @param name\n\t * @param args\n\t * @return Variant returned by the invoke (Dispatch.callN)\n\t */\n\tpublic Variant invoke(String name, Variant[] args) {\n\t\treturn callN(name, args);\n\t}\n\n}", "public abstract class ComException extends RuntimeException {\n\n\t/**\n\t * COM code initializes this filed with an appropriate return code that was\n\t * returned by the underlying com code\n\t */\n\tprotected int hr;\n\t/**\n\t * No documentation is available at this time. Someone should document this\n\t * field\n\t */\n\tprotected int m_helpContext;\n\t/**\n\t * No documentation is available at this time. Someone should document this\n\t * field\n\t */\n\tprotected String m_helpFile;\n\t/**\n\t * No documentation is available at this time. Someone should document this\n\t * field\n\t */\n\tprotected String m_source;\n\n\t/**\n\t * constructor\n\t * \n\t */\n\tpublic ComException() {\n\t\tsuper();\n\t}\n\n\t/**\n\t * constructor with error code?\n\t * \n\t * @param newHr ??\n\t */\n\tpublic ComException(int newHr) {\n\t\tsuper();\n\t\tthis.hr = newHr;\n\t}\n\n\t/**\n\t * @param newHr\n\t * @param description\n\t */\n\tpublic ComException(int newHr, String description) {\n\t\tsuper(description);\n\t\tthis.hr = newHr;\n\t}\n\n\t/**\n\t * @param newHr\n\t * @param source\n\t * @param helpFile\n\t * @param helpContext\n\t */\n\tpublic ComException(int newHr, String source, String helpFile,\n\t\t\tint helpContext) {\n\t\tsuper();\n\t\tthis.hr = newHr;\n\t\tm_source = source;\n\t\tm_helpFile = helpFile;\n\t\tm_helpContext = helpContext;\n\t}\n\n\t/**\n\t * @param newHr\n\t * @param description\n\t * @param source\n\t * @param helpFile\n\t * @param helpContext\n\t */\n\tpublic ComException(int newHr, String description, String source,\n\t\t\tString helpFile, int helpContext) {\n\t\tsuper(description);\n\t\tthis.hr = newHr;\n\t\tm_source = source;\n\t\tm_helpFile = helpFile;\n\t\tm_helpContext = helpContext;\n\t}\n\n\t/**\n\t * @param description\n\t */\n\tpublic ComException(String description) {\n\t\tsuper(description);\n\t}\n\n\t/**\n\t * @return int representation of the help context\n\t */\n\t// Methods\n\tpublic int getHelpContext() {\n\t\treturn m_helpContext;\n\t}\n\n\t/**\n\t * @return String ??? help file\n\t */\n\tpublic String getHelpFile() {\n\t\treturn m_helpFile;\n\t}\n\n\t/**\n\t * @return int hr result ??\n\t */\n\tpublic int getHResult() {\n\t\treturn hr;\n\t}\n\n\t/**\n\t * @return String source ??\n\t */\n\tpublic String getSource() {\n\t\treturn m_source;\n\t}\n}", "public abstract class ComThread {\n\tprivate static final int MTA = 0x0;\n\n\tprivate static final int STA = 0x2;\n\n\t/**\n\t * Comment for <code>haveSTA</code>\n\t */\n\tpublic static boolean haveSTA = false;\n\n\t/**\n\t * Comment for <code>mainSTA</code>\n\t */\n\tpublic static MainSTA mainSTA = null;\n\n\t/**\n\t * Initialize the current java thread to be part of the Multi-threaded COM\n\t * Apartment\n\t */\n\tpublic static synchronized void InitMTA() {\n\t\tInitMTA(false);\n\t}\n\n\t/**\n\t * Initialize the current java thread to be an STA\n\t */\n\tpublic static synchronized void InitSTA() {\n\t\tInitSTA(false);\n\t}\n\n\t/**\n\t * Initialize the current java thread to be part of the Multi-threaded COM\n\t * Apartment, if createMainSTA is true, create a separate MainSTA thread\n\t * that will house all Apartment Threaded components\n\t * \n\t * @param createMainSTA\n\t */\n\tpublic static synchronized void InitMTA(boolean createMainSTA) {\n\t\tInit(createMainSTA, MTA);\n\t}\n\n\t/**\n\t * Initialize the current java thread to be an STA COM Apartment, if\n\t * createMainSTA is true, create a separate MainSTA thread that will house\n\t * all Apartment Threaded components\n\t * \n\t * @param createMainSTA\n\t */\n\tpublic static synchronized void InitSTA(boolean createMainSTA) {\n\t\tInit(createMainSTA, STA);\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic static synchronized void startMainSTA() {\n\t\tmainSTA = new MainSTA();\n\t\thaveSTA = true;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic static synchronized void quitMainSTA() {\n\t\tif (mainSTA != null)\n\t\t\tmainSTA.quit();\n\t}\n\n\t/**\n\t * Initialize the current java thread to be part of the MTA/STA COM\n\t * Apartment\n\t * \n\t * @param createMainSTA\n\t * @param mode\n\t */\n\tpublic static synchronized void Init(boolean createMainSTA, int mode) {\n\t\tif (createMainSTA && !haveSTA) {\n\t\t\t// if the current thread is going to be in the MTA and there\n\t\t\t// is no STA thread yet, then create a main STA thread\n\t\t\t// to avoid COM creating its own\n\t\t\tstartMainSTA();\n\t\t}\n\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\tIUnknown.debug(\"ComThread: before Init: \" + mode);\n\t\t}\n\t\tdoCoInitialize(mode);\n\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\tIUnknown.debug(\"ComThread: after Init: \" + mode);\n\t\t}\n\t}\n\n\t/**\n\t * Call CoUninitialize to release this java thread from COM\n\t */\n\tpublic static synchronized void Release() {\n\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\tIUnknown.debug(\"ComThread: before clearObjects\");\n\t\t}\n\t\tROT.clearObjects();\n\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\tIUnknown.debug(\"ComThread: before UnInit\");\n\t\t}\n\t\tdoCoUninitialize();\n\t\tif (IUnknown.isDebugEnabled()) {\n\t\t\tIUnknown.debug(\"ComThread: after UnInit\");\n\t\t}\n\t}\n\n\t/**\n\t * @param threadModel\n\t */\n\tpublic static native void doCoInitialize(int threadModel);\n\n\t/**\n\t * \n\t */\n\tpublic static native void doCoUninitialize();\n\n\t/**\n\t * load the DLL. We do this in case COMThread is called before any\n\t * other reference to one of the JacboObject subclasses is made.\n\t */\n\tstatic {\n\t\tLibraryLoader.loadLibrary();\n\t}\n}", "public class Dispatch extends IUnknown {\n public static final int LOCALE_SYSTEM_DEFAULT = 2048;\n public static final int LSD = LOCALE_SYSTEM_DEFAULT;\n\n public static final int Method = 1;\n public static final int Get = 2;\n public static final int Put = 4;\n public static final int PutRef = 8;\n public static final int MGet = Method | Get; // Convenience\n \n /** program Id passed in by ActiveX components in their constructor */\n private String programId = null;\n\n private final static int[] NO_INT_ARGS = new int[0];\n public final static Variant[] NO_VARIANT_ARGS = new Variant[0];\n\n /**\n * zero argument constructor that sets the dispatch pointer to 0 This is the\n * only way to create a Dispatch without a value in the pointer field.\n */\n public Dispatch() {\n super();\n }\n\n /**\n * This constructor calls CoCreate with progid. This is the constructor\n * used by the ActiveXComponent or by programs that don't like the activeX\n * interface but wish to create new connections to windows programs.\n *\n * @param id is the name of the program you wish to cocreate to.\n * @throws IllegalArgumentException if an invalid progid is specified\n */\n public Dispatch(String id) {\n super();\n pointer.set(createInstanceNative(setProgramId(id)));\n }\n private native int createInstanceNative(String progid);\n\n /**\n * Constructor that only gets called internally from jni. Do not use!!!\n */\n public Dispatch(int pointer) {\n super(pointer);\n }\n\n /**\n * Constructor to be used by subclass that want to swap themselves in for\n * the default Dispatch class. Usually you will have a class like\n * WordDocument that is a subclass of Dispatch and it will have a\n * constructor public WordDocument(Dispatch). That constructor should just\n * call this constructor as super(Dispatch)\n *\n * @param dispatchToBeDisplaced\n */\n public Dispatch(Dispatch dispatchToBeDisplaced) {\n super(dispatchToBeDisplaced.pointer.get()); // TAKE OVER THE IDispatch POINTER\n dispatchToBeDisplaced.pointer.invalidate(); // NULL OUT THE INPUT POINTER\n }\n \n /**\n * Make dispatch get assigned to whatever GetActiveObject() returns in\n * Windows.\n *\n * @param id is the name of the program you wish to connect to.\n */\n protected void getActiveInstance(String id) {\n pointer.set(getActiveInstanceNative(setProgramId(id)));\n }\n private native int getActiveInstanceNative(String progid);\n\n /**\n * Make Dispatch by calling CoCreate on windows side.\n *\n * @param id is the name of the program you wish to cocreate to.\n */\n protected void coCreateInstance(String id) {\n pointer.set(coCreateInstanceNative(setProgramId(id)));\n }\n private native int coCreateInstanceNative(String progid);\n\n private String setProgramId(String id) {\n if (id == null || id.equals(\"\")) {\n throw new IllegalArgumentException(\"Empty/null progId\");\n }\n programId = id;\n\n return id;\n }\n\n /**\n * @return the program id if instantiated by a progid string.\n */\n public String getProgramId() {\n return programId;\n }\n\n /**\n * Run QueryInterface() on this dispatch object to query for another\n * interface it may implement.\n *\n * @param id is {xxxx-xxxx-xxxx-xxx} format id\n * @return Dispatch a new dispatch object based on new interface\n */\n public Dispatch queryInterface(String id) {\n return queryInterface(pointer.get(), id);\n }\n private native Dispatch queryInterface(int pointer, String iid);\n\n public TypeInfo getTypeInfo() {\n return getTypeInfo(pointer.get());\n }\n private native TypeInfo getTypeInfo(int pointer);\n\n private int livePointer() {\n int value = pointer.get();\n\n if (!pointer.isAlive()) {\n throw new IllegalStateException(\"IDispatch is dead pointer\");\n }\n\n return value;\n }\n\n private Variant[] vargs(Object[] args) {\n return VariantUtilities.objectsToVariants(args);\n }\n\n public void invokeSubv(String name, int dispID, int lcid, int flags,\n Variant[] args, int[] errs) {\n invokev(livePointer(), name, dispID, lcid, flags, args, errs);\n }\n\n public void invokeSubv(String name, int flags, Variant[] args, int[] errs) {\n invokev(livePointer(), name, 0, LSD, flags, args, errs);\n }\n\n public void invokeSubv(int dispID, int flags, Variant[] args, int[] errs) {\n invokev(livePointer(), null, dispID, LSD, flags, args, errs);\n }\n\n public void callSubN(String name, Object[] args) {\n invokeSubv(name, MGet, vargs(args), new int[args.length]);\n }\n\n public void callSubN(int dispID, Object[] args) {\n invokeSubv(dispID, MGet, vargs(args), new int[args.length]);\n }\n\n public int getIDOfName(String name) {\n return getIDsOfNames(LSD, new String[]{name})[0];\n }\n\n public int[] getIDsOfNames(int lcid, String[] names) {\n return getIDsOfNames(pointer.get(), lcid, names);\n }\n private static native int[] getIDsOfNames(int pointer, int lcid, String[] names);\n\n public int[] getIDsOfNames(String[] names) {\n return getIDsOfNames(LSD, names);\n }\n\n public Variant callN(String name, Object[] args) {\n return invokev(name, MGet, vargs(args), new int[args.length]);\n }\n\n public Variant callN(int dispID, Object[] args) {\n return invokev(dispID, MGet, vargs(args), new int[args.length]);\n }\n\n public Variant invoke(String name, int dispID, int lcid, int flags,\n Object[] args, int[] errs) {\n return invokev(livePointer(), name, dispID, lcid, flags, vargs(args), errs);\n }\n\n public Variant invoke(String name, int flags, Object[] args, int[] errs) {\n return invokev(name, flags, vargs(args), errs);\n }\n\n public Variant invoke(int dispID, int flags, Object[] args, int[] errs) {\n return invokev(dispID, flags, vargs(args), errs);\n }\n\n public Object callO(String name) {\n return invokev0(livePointer(), name, 0, LSD, MGet);\n }\n\n public Object callO(int dispid) {\n return invokev0(livePointer(), null, dispid, LSD, MGet);\n }\n\n public Variant call(String name, Object... args) {\n return callN(name, args);\n }\n\n public Variant call(int dispid, Object... args) {\n return callN(dispid, args);\n }\n\n public void put(String name, Object val) {\n invoke(name, Put, new Object[]{val}, new int[1]);\n }\n\n public void put(int dispid, Object val) {\n invoke(dispid, Put, new Object[]{val}, new int[1]);\n }\n\n public Variant invokev(String name, int dispID, int lcid, int flags,\n Variant[] args, int[] errs) {\n return invokev(livePointer(), name, dispID, lcid, flags, args, errs);\n }\n\n private static native Object invokev0(int pointer, String name,\n int dispID, int lcid, int flags);\n\n private static native Variant invokev(int pointer, String name,\n int dispID, int lcid, int flags, Variant[] args, int[] errs);\n\n public Variant invokev(String name, int flags, Variant[] args, int[] errs) {\n return invokev(livePointer(), name, 0, LSD, flags, args, errs);\n }\n\n public Variant invokev(int dispID, int flags, Variant[] args, int[] errs) {\n return invokev(livePointer(), null, dispID, LSD, flags, args, errs);\n }\n\n public void invokeSub(String name, int dispid, int lcid, int flags,\n Object[] args, int[] errs) {\n invokeSubv(name, dispid, lcid, flags, vargs(args), errs);\n }\n\n public void invokeSub(String name, int flags, Object[] args, int[] errs) {\n invokeSub(name, 0, LSD, flags, args, errs);\n }\n\n public void invokeSub(int dispid, int flags, Object[] args, int[] errs) {\n invokeSub(null, dispid, LSD, flags, args, errs);\n }\n\n public void callSub(String name, Object... args) {\n callSubN(name, args);\n }\n\n public void callSub(int dispid, Object... args) {\n callSubN(dispid, args);\n }\n\n public Variant get(String name) {\n return invokev(name, Get, NO_VARIANT_ARGS, NO_INT_ARGS);\n }\n\n public Variant get(int dispid) {\n return invokev(dispid, Get, NO_VARIANT_ARGS, NO_INT_ARGS);\n }\n\n public void putRef(String name, Object val) {\n invoke(name, PutRef, new Object[]{val}, new int[1]);\n }\n\n public void putRef(int dispid, Object val) {\n invoke(dispid, PutRef, new Object[]{val}, new int[1]);\n }\n}", "public class DispatchEvents extends IUnknown {\n /**\n * the wrapper for the event sink. This object is the one that will be sent\n * a message when an event occurs in the MS layer. Normally, the\n * InvocationProxy will forward the messages to a wrapped object that it\n * contains.\n */\n InvocationProxy mInvocationProxy = null;\n\n /**\n * This is the most commonly used constructor.\n * <p>\n * Creates the event callback linkage between the the MS program represented\n * by the Dispatch object and the Java object that will receive the\n * callback.\n * <p>\n * Can be used on any object that implements IProvideClassInfo.\n *\n * @param sourceOfEvent\n * Dispatch object who's MS app will generate callbacks\n * @param eventSink\n * Java object that wants to receive the events\n */\n public DispatchEvents(Dispatch sourceOfEvent, Object eventSink) {\n this(sourceOfEvent, eventSink, null);\n }\n\n /**\n * None of the samples use this constructor.\n * <p>\n * Creates the event callback linkage between the the MS program represented\n * by the Dispatch object and the Java object that will receive the\n * callback.\n * <p>\n * Used when the program doesn't implement IProvideClassInfo. It provides a\n * way to find the TypeLib in the registry based on the programId. The\n * TypeLib is looked up in the registry on the path\n * HKEY_LOCAL_MACHINE/SOFTWARE/Classes/CLSID/(CLID drived from\n * progid)/ProgID/Typelib\n *\n * @param sourceOfEvent\n * Dispatch object who's MS app will generate callbacks\n * @param eventSink\n * Java object that wants to receive the events\n * @param progId\n * program id in the registry that has a TypeLib subkey. The\n * progrId is mapped to a CLSID that is they used to look up the\n * key to the Typelib\n */\n public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,\n String progId) {\n this(sourceOfEvent, eventSink, progId, null);\n }\n\n /**\n * Creates the event callback linkage between the the MS program represented\n * by the Dispatch object and the Java object that will receive the\n * callback.\n * <p>\n * This method was added because Excel doesn't implement IProvideClassInfo\n * and the registry entry for Excel.Application doesn't include a typelib\n * key.\n *\n * <pre>\n * DispatchEvents de = new DispatchEvents(someDispatch, someEventHAndler,\n * \t\t&quot;Excel.Application&quot;,\n * \t\t&quot;C:\\\\Program Files\\\\Microsoft Office\\\\OFFICE11\\\\EXCEL.EXE&quot;);\n * </pre>\n *\n * @param sourceOfEvent\n * Dispatch object who's MS app will generate callbacks\n * @param eventSink\n * Java object that wants to receive the events\n * @param progId ,\n * mandatory if the typelib is specified\n * @param typeLib\n * The location of the typelib to use\n */\n public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,\n String progId, String typeLib) {\n if (IUnknown.isDebugEnabled()) {\n System.out.println(\"DispatchEvents: Registering \" + eventSink + \"for events \");\n }\n if (eventSink instanceof InvocationProxy) {\n mInvocationProxy = (InvocationProxy) eventSink;\n } else {\n mInvocationProxy = getInvocationProxy(eventSink);\n }\n if (mInvocationProxy == null) {\n if (IUnknown.isDebugEnabled()) {\n IUnknown.debug(\"Cannot register null event sink for events\");\n }\n throw new IllegalArgumentException(\n \"Cannot register null event sink for events\");\n }\n pointer.set(init3(sourceOfEvent.pointer.get(), mInvocationProxy, progId, typeLib));\n }\n\n /**\n * Returns an instance of the proxy configured with pTargetObject as its\n * target\n *\n * @param pTargetObject\n * @return InvocationProxy an instance of the proxy this DispatchEvents will\n * send to the COM layer\n */\n protected InvocationProxy getInvocationProxy(Object pTargetObject) {\n InvocationProxy newProxy = new InvocationProxyAllVariants();\n newProxy.setTarget(pTargetObject);\n return newProxy;\n }\n\n /**\n * hooks up a connection point proxy by progId event methods on the sink\n * object will be called by name with a signature of <name>(Variant[] args)\n *\n * You must specify the location of the typeLib.\n *\n * @param src\n * dispatch that is the source of the messages\n * @param sink\n * the object that will receive the messages\n * @param progId\n * optional program id. most folks don't need this either\n * @param typeLib\n * optional parameter for those programs that don't register\n * their type libs (like Excel)\n */\n private native int init3(int pointer, Object sink, String progId,\n String typeLib);\n\n public static native void messageLoop();\n\n /*\n * (non-Javadoc)\n *\n * @see com.jacob.com.IUnknown#safeRelease()\n */\n @Override\n public void safeRelease() {\n if (mInvocationProxy != null) {\n mInvocationProxy.setTarget(null);\n mInvocationProxy = null;\n }\n super.safeRelease();\n }\n}", "public class DispatchProxy extends IUnknown {\n\n /**\n * Marshals the passed in dispatch into the stream\n *\n * @param localDispatch\n */\n public DispatchProxy(Dispatch localDispatch) {\n super();\n pointer.set(MarshalIntoStream(localDispatch.pointer.get()));\n }\n\n /**\n *\n * @return Dispatch the dispatch retrieved from the stream\n */\n public Dispatch toDispatch() {\n Dispatch dispatch = MarshalFromStream(pointer.get());\n pointer.invalidate(); // Cannot marshal from stream more than once\n return dispatch;\n }\n\n private native int MarshalIntoStream(int pointer);\n\n private native Dispatch MarshalFromStream(int pointer);\n}", "public class STA extends Thread {\n\t/**\n\t * referenced by STA.cpp\n\t */\n\tpublic int threadID;\n\n\t/**\n\t * constructor for STA\n\t */\n\tpublic STA() {\n\t\tstart(); // start the thread\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Thread#run()\n\t */\n @Override\n\tpublic void run() {\n\t\t// init COM\n\t\tComThread.InitSTA();\n\t\tif (OnInit()) {\n\t\t\t// this call blocks in the win32 message loop\n\t\t\t// until quitMessagePump is called\n\t\t\tdoMessagePump();\n\t\t}\n\t\tOnQuit();\n\t\t// uninit COM\n\t\tComThread.Release();\n\t}\n\n\t/**\n\t * Override this method to create and initialize any COM component that you\n\t * want to run in this thread. If anything fails, return false to terminate\n\t * the thread.\n\t * \n\t * @return always returns true\n\t */\n\tpublic boolean OnInit() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Override this method to destroy any resource before the thread exits and\n\t * COM in uninitialized\n\t */\n\tpublic void OnQuit() {\n\t\t// there is nothing to see here\n\t}\n\n\t/**\n\t * calls quitMessagePump\n\t */\n\tpublic void quit() {\n\t\tquitMessagePump(threadID);\n\t}\n\n\t/**\n\t * run a message pump for the main STA\n\t */\n\tpublic native void doMessagePump();\n\n\t/**\n\t * quit message pump for the main STA\n\t */\n\tpublic native void quitMessagePump(int threadID);\n\n\t/**\n\t * STA isn't a subclass of JacobObject so a reference to it doesn't load the\n\t * DLL without this\n\t */\n\tstatic {\n\t\tLibraryLoader.loadLibrary();\n\t}\n}", "public class Variant { \n /** Use this constant for optional parameters */\n public final static Variant DEFAULT;\n /** Same than {@link #DEFAULT} */\n public final static Variant VT_MISSING;\n /** Use for true/false variant parameters */\n public final static Variant VT_TRUE = new Variant(true, false);\n /** Use for true/false variant parameters */\n public final static Variant VT_FALSE = new Variant(false, false);\n /** variant's type is empty : equivalent to VB Nothing and VT_EMPTY */\n public final static short VariantEmpty = 0;\n /** variant's type is null : equivalent to VB Null and VT_NULL */\n public final static short VariantNull = 1;\n /** variant's type is short VT_I2 */\n public final static short VariantShort = 2;\n /** variant's type is int VT_I4, a Long in VC */\n public final static short VariantInt = 3;\n /** variant's type is float VT_R4 */\n public final static short VariantFloat = 4;\n /** variant's type is double VT_R8 */\n public final static short VariantDouble = 5;\n /** variant's type is currency VT_CY */\n public final static short VariantCurrency = 6;\n /** variant's type is date VT_DATE */\n public final static short VariantDate = 7;\n /** variant's type is string also known as VT_BSTR */\n public final static short VariantString = 8;\n /** variant's type is dispatch VT_DISPATCH */\n public final static short VariantDispatch = 9;\n /** variant's type is error VT_ERROR */\n public final static short VariantError = 10;\n /** variant's type is boolean VT_BOOL */\n public final static short VariantBoolean = 11;\n /** variant's type is variant it encapsulate another variant VT_VARIANT */\n public final static short VariantVariant = 12;\n /** variant's type is object VT_UNKNOWN */\n public final static short VariantObject = 13;\n /** variant's type is object VT_DECIMAL */\n public final static short VariantDecimal = 14;\n // VT_I1 = 16\n /** variant's type is byte VT_UI1 */\n public final static short VariantByte = 17;\n // VT_UI2 = 18\n public final static short VariantUnsignedShort = 18;\n // VT_UI4 = 19;\n public final static short VariantUnsignedLong = 19;\n\n /**\n * variant's type is 64 bit long integer VT_I8 - not yet implemented in\n * Jacob because we have to decide what to do with Currency and because its\n * only supported on XP and later. No win2k, NT or 2003 server.\n */\n public final static short VariantLongInt = 20;\n // VT_UI8 = 21\n public final static short VariantUnsignedInt = 21;\n // VT_INT = 22\n // VT_UNIT = 23\n // VT_VOID = 24\n // VT_HRESULT = 25\n /**\n * This value is for reference only and is not to be used by any callers\n */\n public final static short VariantPointer = 26;\n // VT_SAFEARRAY = 27\n // VT_CARRARY = 28\n // VT_USERDEFINED = 29\n /** what is this? VT_TYPEMASK && VT_BSTR_BLOB */\n public final static short VariantTypeMask = 4095;\n /** variant's type is array VT_ARRAY */\n public final static short VariantArray = 8192;\n /** variant's type is a reference (to IDispatch?) VT_BYREF */\n public final static short VariantByref = 16384;\n\n\n public static final int DISP_E_PARAMNOTFOUND = new Integer(0x80020004);\n\n private static boolean initialized;\n\n /*\n * Do the run time definition of DEFAULT and MISSING. Have to use static\n * block because of the way the initialization is done via two calls instead\n * of just a constructor for this type.\n */\n static {\n initialize();\n Variant vtMissing = new Variant(DISP_E_PARAMNOTFOUND, VariantError, false);\n DEFAULT = vtMissing;\n VT_MISSING = vtMissing;\n }\n\n private static native void initializeNative();\n\n public static void initialize() {\n if (!initialized) {\n initialized = true;\n initializeNative();\n }\n }\n\n // Is V_VT(v) in C or manually passed if going from Java to VARIANT\n private short type;\n private Object value;\n\n public Variant(Object value, short vt) {\n this.value = value;\n this.type = vt;\n }\n\n /** Generic constructor */\n public Variant(Object value, short type, boolean byRef) {\n this(value, (short) (type | (byRef ? VariantByref : 0)));\n }\n\n /** Constructor that sets type to VariantEmpty */\n public Variant() {\n this(null, VariantEmpty, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(boolean in, boolean byRef) {\n this(new Boolean(in), VariantBoolean, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(boolean in) {\n this(new Boolean(in), VariantBoolean, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(byte in, boolean byRef) {\n this(new Byte(in), VariantByte, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(byte in) {\n this(new Byte(in), VariantByte, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(double in, boolean byRef) {\n this(new Double(in), VariantDouble, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(double in) {\n this(new Double(in), VariantDouble, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(float in, boolean byRef) {\n this(new Float(in), VariantFloat, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(float in) {\n this(new Float(in), VariantFloat, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(short in, boolean byRef) {\n this(new Short(in), VariantShort, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(short in) {\n this(new Short(in), VariantShort, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(int in, boolean byRef) {\n this(new Integer(in), VariantInt, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(int in) {\n this(new Integer(in), VariantInt, false);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(long in, boolean byRef) {\n this(new Long(in), VariantLongInt, byRef);\n }\n\n /** Constructor that accepts a primitive rather than an object */\n public Variant(long in) {\n this(new Long(in), VariantLongInt, false);\n }\n\n public Variant(BigDecimal decimal, boolean byRef) {\n this(decimal, VariantDecimal, byRef);\n }\n\n public Variant(BigDecimal decimal) {\n this(decimal, VariantDecimal, false);\n }\n\n public Variant(Currency currency, boolean byRef) {\n this(currency, VariantLongInt, byRef);\n }\n\n public Variant(Currency currency) {\n this(currency, VariantLongInt, false);\n }\n\n public Variant(Dispatch dispatch, boolean byRef) {\n this(dispatch, VariantDispatch, byRef);\n }\n\n public Variant(Dispatch dispatch) {\n this(dispatch, VariantDispatch, false);\n }\n\n public Variant(Date date, boolean byRef) {\n this(date, VariantDate, byRef);\n }\n\n public Variant(Date date) {\n this(date, VariantDate, false);\n }\n\n public Variant(SafeArray array, boolean byRef) {\n this(array, VariantArray, byRef);\n }\n\n public Variant(SafeArray array) {\n this(array, VariantArray, false);\n }\n\n public Variant(String string, boolean byRef) {\n this(string, VariantString, byRef);\n }\n\n public Variant(String string) {\n this(string, VariantString, false);\n }\n\n public Variant(Variant variant, boolean byRef) {\n this(variant, VariantVariant, byRef);\n }\n\n public Variant(Variant variant) {\n this(variant, VariantVariant, false);\n }\n\n private void illegal(String methodName, String variantName) {\n throw new IllegalStateException(methodName +\n \"() only legal on Variants of type \" + variantName + \" not \" + \n getvt());\n }\n\n public boolean isA(short testType) {\n return type == testType || type == (testType | VariantByref);\n }\n\n public boolean isArray() {\n return (type & VariantArray) != 0;\n }\n\n public boolean isByref() {\n return (type & VariantByref) != 0;\n }\n\n public short getvt() {\n return type;\n }\n\n public short getType() {\n return (short) (type & ~VariantByref);\n }\n \n public Object getValue() {\n return value;\n }\n\n public static Variant createDispatchVariant(int pointer) {\n // No point making a variant that has an invalid pointer\n if (pointer == 0) return null;\n\n return new Variant(new Dispatch(pointer));\n }\n\n public static Variant createDateVariant(double comDateValue) {\n return new Variant(DateUtilities.convertWindowsTimeToDate(comDateValue));\n }\n\n public static Variant createIntVariant(int value) {\n return new Variant(new Integer(value));\n }\n\n /**\n * Cover for native method so we can cover it.\n * <p>\n * This cannot convert an object to a byRef. It can convert from byref to\n * not byref\n *\n * @param in type to convert this variant too\n * @return Variant returns this same object so folks can change when\n * replacing calls toXXX() with changeType().getXXX()\n */\n public Variant changeType(short in) {\n this.type = in;\n // FIXME: This needs some round tripping to make sure it is valid\n return this;\n }\n\n public SafeArray getArray() {\n if (!isArray()) illegal(\"getArray\", \"VariantArray\");\n return (SafeArray) value;\n }\n\n /**\n * @return returns the value as a boolean, throws an exception if its not.\n * @throws IllegalStateException if variant is not of the requested type\n */\n public boolean getBoolean() {\n if (!isA(VariantBoolean)) illegal(\"getBoolean\", \"VariantBoolean\");\n return ((Boolean) value).booleanValue();\n }\n\n /**\n * @return returns the value as a boolean, throws an exception if its not.\n * @throws IllegalStateException if variant is not of the requested type\n */\n public byte getByte() {\n if (!isA(VariantByte)) illegal(\"getByte\", \"VariantByte\");\n return ((Byte) value).byteValue();\n }\n\n /**\n * MS Currency objects are 64 bit fixed point numbers with 15 digits to the\n * left and 4 to the right of the decimal place.\n *\n * @return returns the currency value\n * @throws IllegalStateException if variant is not of the requested type\n */\n public Currency getCurrency() {\n if (!isA(VariantCurrency)) illegal(\"getCurrency\", \"VariantCurrency\");\n return (Currency) value;\n }\n\n /**\n * @return the noughgat that JNI side wants versus full blown object.\n */\n public long getCurrencyAsLong() {\n return getCurrency().longValue();\n }\n\n /**\n * @return the date\n * @throws IllegalStateException if variant is not of the requested type\n */\n public Date getDate() {\n if (!isA(VariantDate)) illegal(\"getDate\", \"VariantDate\");\n return (Date) value;\n }\n\n /**\n * @return the noughgat that JNI side wants versus full blown object.\n */\n public double getDateAsDouble() {\n return DateUtilities.convertDateToWindowsTime(getDate());\n }\n\n /**\n * @return the BigDecimal for this Decimal\n * @throws IllegalStateException if variant is not of the requested type\n */\n public BigDecimal getDecimal() {\n if (!isA(VariantDecimal)) illegal(\"getDecimal\", \"VariantDecimal\");\n return (BigDecimal) value;\n }\n\n /**\n * @return this object as a dispatch\n * @throws IllegalStateException if wrong variant type\n */\n public Dispatch getDispatch() {\n if (!isA(VariantDispatch)) illegal(\"getDispatch\", \"VariantDispatch\");\n return (Dispatch) value;\n }\n\n public int getDispatchPointer() {\n return getDispatch().pointer.get();\n }\n\n /**\n * @return the double value\n * @throws IllegalStateException if variant is not of the requested type\n */\n public double getDouble() {\n if (!isA(VariantDouble)) illegal(\"getDouble\", \"VariantDouble\");\n return ((Double) value).doubleValue();\n }\n\n /**\n * @return the error value \n * @throws IllegalStateException if variant is not of the requested type\n */\n public int getError() {\n if (!isA(VariantError)) illegal(\"getError\", \"VariantError\");\n return ((Integer) value).intValue();\n }\n\n /**\n * @return returns the value as a float if the type is of type float\n * @throws IllegalStateException if variant is not of the requested type\n */\n public float getFloat() {\n if (!isA(VariantFloat)) illegal(\"getFloat\", \"VariantFloat\");\n return ((Float) value).floatValue();\n }\n\n /**\n * return the int value held in this variant if it is an int or a short.\n * Throws for other types.\n *\n * @return int contents of the windows memory\n * @throws IllegalStateException\n * if variant is not of the requested type\n */\n public int getInt() {\n if (isA(VariantUnsignedInt)) return ((Integer) value).intValue();\n if (isA(VariantInt)) return ((Integer) value).intValue();\n if (isA(VariantShort)) return ((Short) value).shortValue();\n illegal(\"getInt\", \"VariantInt\");\n return -1; // not reached\n }\n\n /**\n * returns the windows time contained in this Variant to a Java Date. should\n * return null if this is not a date Variant SF 959382\n *\n * @return java.util.Date returns the date if this is a VariantDate != 0,\n * null if it is a VariantDate == 0 and throws an\n * IllegalStateException if this isn't a date.\n * @throws IllegalStateException\n * if variant is not of the requested type\n */\n @Deprecated\n public Date getJavaDate() {\n // returnDate = DateUtilities.convertWindowsTimeToDate(getDate());\n return getDate();\n }\n\n /**\n * 64 bit Longs only available on x64. 64 bit long support added 1.14\n *\n * @return returns the value as a long\n * @throws IllegalStateException if variant is not of the requested type\n */\n public long getLong() {\n if (!isA(VariantLongInt) && !(isA(VariantUnsignedLong))) illegal(\"getLong\", \"VariantLongInt\");\n return ((Long) value).longValue();\n }\n\n public SafeArray getSafeArray() {\n return (SafeArray) value;\n }\n\n // FIXME: Figure out what boolean field is for.\n @Deprecated\n public SafeArray toSafeArray(boolean something) {\n return getSafeArray();\n }\n\n /**\n * @return the short value\n * @throws IllegalStateException if variant is not of the requested type\n */\n public short getShort() {\n if (!isA(VariantShort) && !isA(VariantUnsignedShort)) illegal(\"getShort\", \"VariantShort\");\n return ((Short) value).shortValue();\n }\n\n /**\n * @return string contents of the variant.\n * @throws IllegalStateException if this variant is not of type String\n */\n public String getString() {\n if (!isA(VariantString)) illegal(\"getString\", \"VariantString\");\n return (String) value;\n }\n\n /**\n * Used to get the value from a windows type of VT_VARIANT or a jacob\n * Variant type of VariantVariant. Added 1.12 pre 6 - VT_VARIANT support is\n * at an alpha level\n *\n * @return Object a java Object that represents the content of the enclosed\n * Variant\n */\n public Variant getVariant() {\n if (!isA(VariantVariant) || !isByref()) illegal(\"getVariant\", \"VariantVariant\");\n return (Variant) value;\n }\n\n /**\n * @return returns true if the variant is considered null\n */\n public boolean isNull() {\n // ENEBO: This is radically simpler than Jacob's old way and may\n // include more values.\n return value == null;\n }\n\n /**\n * Convert a Racob Variant value to a Java object.\n *\n * @return Java equivalent version of Variant value.\n */\n public Object toJavaObject() {\n return VariantUtilities.variantToObject(this);\n }\n\n public String toDebugString() {\n StringBuilder buf = new StringBuilder(\"Variant: \");\n\n switch (getType()) {\n case VariantEmpty:\n buf.append(\"Empty\"); break;\n case VariantNull:\n buf.append(\"Null\"); break;\n case VariantShort:\n buf.append(\"Short [\" + value + \"]\"); break;\n case VariantInt:\n buf.append(\"Int [\" + value + \"]\"); break;\n case VariantFloat:\n buf.append(\"Float [\" + value + \"]\"); break;\n case VariantDouble:\n buf.append(\"Double [\" + value + \"]\"); break;\n case VariantCurrency:\n buf.append(\"Currency [\" + value + \"]\"); break;\n case VariantDate:\n buf.append(\"Date [\" + value + \"]\"); break;\n case VariantString:\n buf.append(\"String [\" + value + \"]\"); break;\n case VariantDispatch:\n buf.append(\"Dispatch [\" + value + \"]\"); break;\n case VariantError:\n buf.append(\"Error [\" + value + \"]\"); break;\n case VariantBoolean:\n buf.append(\"Boolean [\" + value + \"]\"); break;\n case VariantVariant:\n buf.append(\"Variant [\" + value + \"]\"); break;\n case VariantObject:\n buf.append(\"Object [\" + value + \"]\"); break;\n case VariantDecimal:\n buf.append(\"Decimal [\" + value + \"]\"); break;\n case VariantByte:\n buf.append(\"Byte [\" + value + \"]\"); break;\n case VariantLongInt:\n buf.append(\"LongInt [\" + value + \"]\"); break;\n case VariantPointer:\n buf.append(\"Pointer [\" + value + \"]\"); break;\n case VariantTypeMask:\n buf.append(\"TypeMask [\" + value + \"]\"); break;\n case VariantArray:\n buf.append(\"Array [\" + value + \"]\"); break;\n case VariantByref:\n buf.append(\"ByRef???\"); break;\n default:\n buf.append(\"Uknown type: \").append(type);\n break;\n }\n\n if (isByref()) buf.append(\"<BYREF>\");\n\n return buf.toString();\n }\n\n /**\n * A String representation of the variant if possible. It will return\n * \"null\" if VariantEmpty, VariantError, or VariantNull.\n *\n * @return a reasonable string representation\n */\n @Override\n public String toString() {\n int vt = getvt();\n\n if (vt == VariantEmpty || vt == VariantError || vt == VariantNull) return \"null\";\n if (vt == VariantString) return getString();\n\n try {\n Object foo = toJavaObject();\n // rely on java objects to do the right thing\n if (foo == null) return \"{Java null}\";\n\n return foo.toString();\n } catch (RuntimeException e) {\n // some types do not generate a good description yet\n return \"Description not available for type: \" + getvt();\n }\n }\n}", "public class BaseTestCase extends TestCase {\n\n @Override\n\tprotected void setUp() {\n\t\t// verify we have run with the dll in the lib path\n\t\ttry {\n\t\t\tIUnknown foo = new Dispatch(0);\n\t\t\tif (foo == null) {\n\t\t\t\tfail(\"Failed basic sanity test: Can't create IUnknown (-D<java.library.path=xxx>)\");\n\t\t\t}\n\t\t} catch (UnsatisfiedLinkError ule) {\n\t\t\tfail(\"Did you remember to run with the racob.dll in the libpath ?\");\n\t\t}\n\t}\n\n\t/**\n\t * this test exists just to test the setup.\n\t */\n\tpublic void testSetup() {\n\t\tIUnknown foo = new Dispatch(0);\n\t\tassertNotNull(foo);\n\t}\n\n\t/**\n\t * \n\t * @return a simple VB script that generates the result \"3\"\n\t */\n\tpublic String getSampleVPScriptForEval() {\n\t\treturn \"1+(2*4)-3\";\n\n\t}\n\n\t/**\n\t * Converts the class name into a path and appends the resource name. Used\n\t * to derive the path to a resource in the file system where the resource is\n\t * co-located with the referenced class.\n\t * \n\t * @param resourceName\n\t * @param classInSamePackageAsResource\n\t * @return a class loader compatible fully qualified file system path to a\n\t * resource\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprivate String getJavaFilePathToPackageResource(String resourceName,\n\t\t\tClass classInSamePackageAsResource) {\n\n\t\tString classPackageName = classInSamePackageAsResource.getName();\n\t\tint i = classPackageName.lastIndexOf('.');\n\t\tif (i == -1) {\n\t\t\tclassPackageName = \"\";\n\t\t} else {\n\t\t\tclassPackageName = classPackageName.substring(0, i);\n\t\t}\n\n\t\t// change all \".\" to ^ for later conversion to \"/\" so we can append\n\t\t// resource names with \".\"\n\t\tclassPackageName = classPackageName.replace('.', '^');\n\t\tSystem.out.println(\"classPackageName: \" + classPackageName);\n\t\tString fullPathToResource;\n\t\tif (classPackageName.length() > 0) {\n\t\t\tfullPathToResource = classPackageName + \"^\" + resourceName;\n\t\t} else {\n\t\t\tfullPathToResource = resourceName;\n\t\t}\n\n\t\tfullPathToResource = fullPathToResource.replace('^', '/');\n\t\tSystem.out.println(\"fullPathToResource: \" + fullPathToResource);\n\n\t\tURL urlToLibrary = classInSamePackageAsResource.getClassLoader()\n\t\t\t\t.getResource(fullPathToResource);\n\t\tassertNotNull(\"URL to resource \" + resourceName\n\t\t\t\t+ \" should not be null.\"\n\t\t\t\t+ \" You probably need to add 'unittest' to the\"\n\t\t\t\t+ \" classpath so the tests can find resources\", urlToLibrary);\n\t\tString fullPathToResourceAsFile = urlToLibrary.getFile();\n\t\tSystem.out.println(\"url to library: \" + urlToLibrary);\n\t\tSystem.out.println(\"fullPathToResourceAsFile: \"\n\t\t\t\t+ fullPathToResourceAsFile);\n\n\t\treturn fullPathToResourceAsFile;\n\t}\n\n\t/**\n\t * Converts the class name into a path and appends the resource name. Used\n\t * to derive the path to a resource in the file system where the resource is\n\t * co-located with the referenced class.\n\t * \n\t * @param resourceName\n\t * @param classInSamePackageAsResource\n\t * @return returns the path in the file system of the requested resource in\n\t * windows c compatible format\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic String getWindowsFilePathToPackageResource(String resourceName,\n\t\t\tClass classInSamePackageAsResource) {\n\t\tString javaFilePath = getJavaFilePathToPackageResource(resourceName,\n\t\t\t\tclassInSamePackageAsResource);\n\t\tjavaFilePath = javaFilePath.replace('/', '\\\\');\n\t\treturn javaFilePath.substring(1);\n\t}\n\n\t/**\n\t * \n\t * @param resourceName\n\t * @param classInSamePackageAsResource\n\t * @return a resource located in the same package as the passed in class\n\t */\n\t@SuppressWarnings( { \"unused\", \"unchecked\" })\n\tprivate Object getPackageResource(String resourceName,\n\t\t\tClass classInSamePackageAsResource) {\n\t\tString fullPathToResource = getJavaFilePathToPackageResource(\n\t\t\t\tresourceName, classInSamePackageAsResource);\n\t\tClassLoader localClassLoader = classInSamePackageAsResource\n\t\t\t\t.getClassLoader();\n\t\tif (null == localClassLoader) {\n\t\t\treturn ClassLoader.getSystemResource(fullPathToResource);\n\t\t} else {\n\t\t\treturn localClassLoader.getResource(fullPathToResource);\n\t\t}\n\t}\n\n\t/**\n\t * load a library from same place in the file system that the class was\n\t * loaded from.\n\t * <p>\n\t * This is an attempt to let unit tests run without having to run regsvr32.\n\t * \n\t * @param libraryName\n\t * @param classInSamePackageAsResource\n\t */\n\t@SuppressWarnings( { \"unchecked\", \"unused\" })\n\tprivate void loadLibraryFromClassPackage(String libraryName,\n\t\t\tClass classInSamePackageAsResource) {\n\t\tString libraryNameWithSuffix = \"\";\n\t\tString fullLibraryNameWithPath = \"\";\n\t\tif (libraryName != null && libraryName.endsWith(\"dll\")) {\n\t\t\tlibraryNameWithSuffix = libraryName;\n\t\t} else if (libraryName != null) {\n\t\t\tlibraryNameWithSuffix = libraryName + \".dll\";\n\t\t} else {\n\t\t\tfail(\"can't create full library name \" + libraryName);\n\t\t}\n\t\t// generate the path the classloader would use to find this on the\n\t\t// classpath\n\t\tfullLibraryNameWithPath = getJavaFilePathToPackageResource(\n\t\t\t\tlibraryNameWithSuffix, classInSamePackageAsResource);\n\t\tSystem.load(fullLibraryNameWithPath);\n\t\t// requires that the dll be on the library path\n\t\t// System.loadLibrary(fullLibraryNameWithPath);\n\t}\n\n}" ]
import org.racob.activeX.ActiveXComponent; import org.racob.com.ComException; import org.racob.com.ComThread; import org.racob.com.Dispatch; import org.racob.com.DispatchEvents; import org.racob.com.DispatchProxy; import org.racob.com.STA; import org.racob.com.Variant; import org.racob.test.BaseTestCase;
package org.racob.test.vbscript; /** * This example demonstrates how to make calls between two different STA's. * First, to create an STA, you need to extend the STA class and override its * OnInit() method. This method will be called in the STA's thread so you can * use it to create your COM components that will run in that STA. If you then * try to call methods on those components from other threads (STA or MTA) - * this will fail. You cannot create a component in an STA and call its methods * from another thread. You can use the DispatchProxy to get a proxy to any * Dispatch that lives in another STA. This object has to be created in the STA * that houses the Dispatch (in this case it's created in the OnInit method). * Then, another thread can call the toDispatch() method of DispatchProxy to get * a local proxy. At most ONE (!) thread can call toDispatch(), and the call can * be made only once. This is because a IStream object is used to pass the * proxy, and it is only written once and closed when you read it. If you need * multiple threads to access a Dispatch pointer, then create that many * DispatchProxy objects. * <p> * May need to run with some command line options (including from inside * Eclipse). Look in the docs area at the Jacob usage document for command line * options. */ public class ScriptTest2 extends BaseTestCase { public void testScript2() { try {
ComThread.InitSTA();
2
badvision/jace
src/main/java/jace/hardware/massStorage/ProdosVirtualDisk.java
[ "public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulator(args);\r\n// }\r\n\r\n public static Apple2e computer;\r\n\r\n /**\r\n * Creates a new instance of Emulator\r\n * @param args\r\n */\r\n public Emulator(List<String> args) {\r\n instance = this;\r\n computer = new Apple2e();\r\n Configuration.buildTree();\r\n Configuration.loadSettings();\r\n mainThread = Thread.currentThread();\r\n applyConfiguration(args);\r\n }\r\n\r\n public void applyConfiguration(List<String> args) {\r\n Map<String, String> settings = new LinkedHashMap<>();\r\n if (args != null) {\r\n for (int i = 0; i < args.size(); i++) {\r\n if (args.get(i).startsWith(\"-\")) {\r\n String key = args.get(i).substring(1);\r\n if ((i + 1) < args.size()) {\r\n String val = args.get(i + 1);\r\n if (!val.startsWith(\"-\")) {\r\n settings.put(key, val);\r\n i++;\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n System.err.println(\"Did not understand parameter \" + args.get(i) + \", skipping.\");\r\n }\r\n }\r\n }\r\n Configuration.applySettings(settings);\r\n// EmulatorUILogic.registerDebugger();\r\n// computer.coldStart();\r\n }\r\n\r\n public static void resizeVideo() {\r\n// AbstractEmulatorFrame window = getFrame();\r\n// if (window != null) {\r\n// window.resizeVideo();\r\n// }\r\n }\r\n}", "public class EmulatorUILogic implements Reconfigurable {\r\n\r\n static Debugger debugger;\r\n\r\n static {\r\n debugger = new Debugger() {\r\n @Override\r\n public void updateStatus() {\r\n enableDebug(true);\r\n MOS65C02 cpu = (MOS65C02) Emulator.computer.getCpu();\r\n updateCPURegisters(cpu);\r\n }\r\n };\r\n }\r\n\r\n @ConfigurableField(\r\n category = \"General\",\r\n name = \"Speed Setting\"\r\n )\r\n public int speedSetting = 3;\r\n\r\n @ConfigurableField(\r\n category = \"General\",\r\n name = \"Show Drives\"\r\n )\r\n public boolean showDrives = true;\r\n\r\n public static void updateCPURegisters(MOS65C02 cpu) {\r\n// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();\r\n// debuggerPanel.valueA.setText(Integer.toHexString(cpu.A));\r\n// debuggerPanel.valueX.setText(Integer.toHexString(cpu.X));\r\n// debuggerPanel.valueY.setText(Integer.toHexString(cpu.Y));\r\n// debuggerPanel.valuePC.setText(Integer.toHexString(cpu.getProgramCounter()));\r\n// debuggerPanel.valueSP.setText(Integer.toHexString(cpu.getSTACK()));\r\n// debuggerPanel.valuePC2.setText(cpu.getFlags());\r\n// debuggerPanel.valueINST.setText(cpu.disassemble());\r\n }\r\n\r\n public static void enableDebug(boolean b) {\r\n// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();\r\n// debugger.setActive(b);\r\n// debuggerPanel.enableDebug.setSelected(b);\r\n// debuggerPanel.setBackground(\r\n// b ? Color.RED : new Color(0, 0, 0x040));\r\n }\r\n\r\n public static void enableTrace(boolean b) {\r\n Emulator.computer.getCpu().setTraceEnabled(b);\r\n }\r\n\r\n public static void stepForward() {\r\n debugger.step = true;\r\n }\r\n\r\n static void registerDebugger() {\r\n Emulator.computer.getCpu().setDebug(debugger);\r\n }\r\n\r\n public static Integer getValidAddress(String s) {\r\n try {\r\n int addr = Integer.parseInt(s.toUpperCase(), 16);\r\n if (addr >= 0 && addr < 0x10000) {\r\n return addr;\r\n }\r\n return null;\r\n } catch (NumberFormatException ex) {\r\n return null;\r\n }\r\n }\r\n public static List<RAMListener> watches = new ArrayList<>();\r\n\r\n// public static void updateWatchList(final DebuggerPanel panel) {\r\n// java.awt.EventQueue.invokeLater(() -> {\r\n// watches.stream().forEach((oldWatch) -> {\r\n// Emulator.computer.getMemory().removeListener(oldWatch);\r\n// });\r\n// if (panel == null) {\r\n// return;\r\n// }\r\n// addWatch(panel.textW1, panel.valueW1);\r\n// addWatch(panel.textW2, panel.valueW2);\r\n// addWatch(panel.textW3, panel.valueW3);\r\n// addWatch(panel.textW4, panel.valueW4);\r\n// });\r\n// }\r\n//\r\n// private static void addWatch(JTextField watch, final JLabel watchValue) {\r\n// final Integer address = getValidAddress(watch.getText());\r\n// if (address != null) {\r\n// //System.out.println(\"Adding watch for \"+Integer.toString(address, 16));\r\n// RAMListener newListener = new RAMListener(RAMEvent.TYPE.WRITE, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {\r\n// @Override\r\n// protected void doConfig() {\r\n// setScopeStart(address);\r\n// }\r\n//\r\n// @Override\r\n// protected void doEvent(RAMEvent e) {\r\n// watchValue.setText(Integer.toHexString(e.getNewValue() & 0x0FF));\r\n// }\r\n// };\r\n// Emulator.computer.getMemory().addListener(newListener);\r\n// watches.add(newListener);\r\n// // Print out the current value right away\r\n// byte b = Emulator.computer.getMemory().readRaw(address);\r\n// watchValue.setText(Integer.toString(b & 0x0ff, 16));\r\n// } else {\r\n// watchValue.setText(\"00\");\r\n// }\r\n// }\r\n// public static void updateBreakpointList(final DebuggerPanel panel) {\r\n// java.awt.EventQueue.invokeLater(() -> {\r\n// Integer address;\r\n// debugger.getBreakpoints().clear();\r\n// if (panel == null) {\r\n// return;\r\n// }\r\n// address = getValidAddress(panel.textBP1.getText());\r\n// if (address != null) {\r\n// debugger.getBreakpoints().add(address);\r\n// }\r\n// address = getValidAddress(panel.textBP2.getText());\r\n// if (address != null) {\r\n// debugger.getBreakpoints().add(address);\r\n// }\r\n// address = getValidAddress(panel.textBP3.getText());\r\n// if (address != null) {\r\n// debugger.getBreakpoints().add(address);\r\n// }\r\n// address = getValidAddress(panel.textBP4.getText());\r\n// if (address != null) {\r\n// debugger.getBreakpoints().add(address);\r\n// }\r\n// debugger.updateBreakpoints();\r\n// });\r\n// }\r\n//\r\n @InvokableAction(\r\n name = \"BRUN file\",\r\n category = \"file\",\r\n description = \"Loads a binary file in memory and executes it. File should end with #06xxxx, where xxxx is the start address in hex\",\r\n alternatives = \"Execute program;Load binary;Load program;Load rom;Play single-load game\",\r\n defaultKeyMapping = \"ctrl+shift+b\")\r\n public static void runFile() {\r\n Emulator.computer.pause();\r\n FileChooser select = new FileChooser();\r\n File binary = select.showOpenDialog(JaceApplication.getApplication().primaryStage);\r\n if (binary == null) {\r\n Emulator.computer.resume();\r\n return;\r\n }\r\n runFileNamed(binary);\r\n }\r\n\r\n public static void runFileNamed(File binary) {\r\n String fileName = binary.getName().toLowerCase();\r\n try {\r\n if (fileName.contains(\"#06\")) {\r\n String addressStr = fileName.substring(fileName.length() - 4);\r\n int address = Integer.parseInt(addressStr, 16);\r\n brun(binary, address);\r\n } else if (fileName.contains(\"#fc\")) {\r\n gripe(\"BASIC not supported yet\");\r\n }\r\n } catch (NumberFormatException | IOException ex) {\r\n }\r\n Emulator.computer.getCpu().resume();\r\n }\r\n\r\n public static void brun(File binary, int address) throws FileNotFoundException, IOException {\r\n // If it was halted already, then it was initiated outside of an opcode execution\r\n // If it was not yet halted, then it is the case that the CPU is processing another opcode\r\n // So if that is the case, the program counter will need to be decremented here to compensate\r\n // TODO: Find a better mousetrap for this one -- it's an ugly hack\r\n Emulator.computer.pause();\r\n FileInputStream in = new FileInputStream(binary);\r\n byte[] data = new byte[in.available()];\r\n in.read(data);\r\n RAM ram = Emulator.computer.getMemory();\r\n for (int i = 0; i < data.length; i++) {\r\n ram.write(address + i, data[i], false, true);\r\n }\r\n CPU cpu = Emulator.computer.getCpu();\r\n Emulator.computer.getCpu().setProgramCounter(address);\r\n Emulator.computer.resume();\r\n }\r\n\r\n @InvokableAction(\r\n name = \"Toggle Debug\",\r\n category = \"debug\",\r\n description = \"Show/hide the debug panel\",\r\n alternatives = \"Show Debug;Hide Debug;Inspect\",\r\n defaultKeyMapping = \"ctrl+shift+d\")\r\n public static void toggleDebugPanel() {\r\n// AbstractEmulatorFrame frame = Emulator.getFrame();\r\n// if (frame == null) {\r\n// return;\r\n// }\r\n// frame.setShowDebug(!frame.isShowDebug());\r\n// frame.reconfigure();\r\n// Emulator.resizeVideo();\r\n }\r\n\r\n @InvokableAction(\r\n name = \"Toggle fullscreen\",\r\n category = \"general\",\r\n description = \"Activate/deactivate fullscreen mode\",\r\n alternatives = \"fullscreen;maximize\",\r\n defaultKeyMapping = \"ctrl+shift+f\")\r\n public static void toggleFullscreen() {\r\n Platform.runLater(() -> {\r\n Stage stage = JaceApplication.getApplication().primaryStage;\r\n stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);\r\n stage.setFullScreen(!stage.isFullScreen());\r\n JaceApplication.getApplication().controller.setAspectRatioEnabled(stage.isFullScreen());\r\n });\r\n }\r\n\r\n @InvokableAction(\r\n name = \"Save Raw Screenshot\",\r\n category = \"general\",\r\n description = \"Save raw (RAM) format of visible screen\",\r\n alternatives = \"screendump;raw screenshot\",\r\n defaultKeyMapping = \"ctrl+shift+z\")\r\n public static void saveScreenshotRaw() throws FileNotFoundException, IOException {\r\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy.MM.dd.HH.mm.ss\");\r\n String timestamp = df.format(new Date());\r\n String type;\r\n int start = Emulator.computer.getVideo().getCurrentWriter().actualWriter().getYOffset(0);\r\n int len;\r\n if (start < 0x02000) {\r\n // Lo-res or double-lores\r\n len = 0x0400;\r\n type = \"gr\";\r\n } else {\r\n // Hi-res or double-hires\r\n len = 0x02000;\r\n type = \"hgr\";\r\n }\r\n boolean dres = SoftSwitches._80COL.getState() && (SoftSwitches.DHIRES.getState() || start < 0x02000);\r\n if (dres) {\r\n type = \"d\" + type;\r\n }\r\n File outFile = new File(\"screen_\" + type + \"_a\" + Integer.toHexString(start) + \"_\" + timestamp);\r\n try (FileOutputStream out = new FileOutputStream(outFile)) {\r\n RAM128k ram = (RAM128k) Emulator.computer.memory;\r\n Emulator.computer.pause();\r\n if (dres) {\r\n for (int i = 0; i < len; i++) {\r\n out.write(ram.getAuxVideoMemory().readByte(start + i));\r\n }\r\n }\r\n for (int i = 0; i < len; i++) {\r\n out.write(ram.getMainMemory().readByte(start + i));\r\n }\r\n }\r\n System.out.println(\"Wrote screenshot to \" + outFile.getAbsolutePath());\r\n }\r\n\r\n @InvokableAction(\r\n name = \"Save Screenshot\",\r\n category = \"general\",\r\n description = \"Save image of visible screen\",\r\n alternatives = \"Save image;save framebuffer;screenshot\",\r\n defaultKeyMapping = \"ctrl+shift+s\")\r\n public static void saveScreenshot() throws IOException {\r\n FileChooser select = new FileChooser();\r\n Emulator.computer.pause();\r\n Image i = Emulator.computer.getVideo().getFrameBuffer();\r\n// BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(i, null);\r\n File targetFile = select.showSaveDialog(JaceApplication.getApplication().primaryStage);\r\n if (targetFile == null) {\r\n return;\r\n }\r\n String filename = targetFile.getName();\r\n System.out.println(\"Writing screenshot to \" + filename);\r\n String extension = filename.substring(filename.lastIndexOf(\".\") + 1);\r\n// BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);\r\n//\r\n// Graphics2D graphics = bufImageRGB.createGraphics();\r\n// graphics.drawImage(bufImageARGB, 0, 0, null);\r\n//\r\n// ImageIO.write(bufImageRGB, extension, targetFile);\r\n// graphics.dispose();\r\n }\r\n\r\n public static final String CONFIGURATION_DIALOG_NAME = \"Configuration\";\r\n\r\n @InvokableAction(\r\n name = \"Configuration\",\r\n category = \"general\",\r\n description = \"Edit emulator configuraion\",\r\n alternatives = \"Reconfigure;Preferences;Settings;Config\",\r\n defaultKeyMapping = {\"f4\", \"ctrl+shift+c\"})\r\n public static void showConfig() {\r\n FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource(\"/fxml/Configuration.fxml\"));\r\n fxmlLoader.setResources(null);\r\n try {\r\n Stage configWindow = new Stage();\r\n AnchorPane node = (AnchorPane) fxmlLoader.load();\r\n ConfigurationUIController controller = fxmlLoader.getController();\r\n controller.initialize();\r\n Scene s = new Scene(node);\r\n configWindow.setScene(s);\r\n configWindow.show();\r\n } catch (IOException exception) {\r\n throw new RuntimeException(exception);\r\n }\r\n }\r\n\r\n @InvokableAction(\r\n name = \"Open IDE\",\r\n category = \"development\",\r\n description = \"Open new IDE window for Basic/Assembly/Plasma coding\",\r\n alternatives = \"IDE;dev;development;acme;assembler;editor\",\r\n defaultKeyMapping = {\"ctrl+shift+i\"})\r\n public static void showIDE() {\r\n FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource(\"/fxml/editor.fxml\"));\r\n fxmlLoader.setResources(null);\r\n try {\r\n Stage editorWindow = new Stage();\r\n AnchorPane node = (AnchorPane) fxmlLoader.load();\r\n IdeController controller = fxmlLoader.getController();\r\n controller.initialize();\r\n Scene s = new Scene(node);\r\n editorWindow.setScene(s);\r\n editorWindow.show();\r\n } catch (IOException exception) {\r\n throw new RuntimeException(exception);\r\n }\r\n }\r\n\r\n static int size = -1;\r\n\r\n @InvokableAction(\r\n name = \"Resize window\",\r\n category = \"general\",\r\n description = \"Resize the screen to 1x/1.5x/2x/3x video size\",\r\n alternatives = \"Aspect;Adjust screen;Adjust window size;Adjust aspect ratio;Fix screen;Fix window size;Fix aspect ratio;Correct aspect ratio;\",\r\n defaultKeyMapping = {\"ctrl+shift+a\"})\r\n public static void scaleIntegerRatio() {\r\n Platform.runLater(() -> {\r\n if (JaceApplication.getApplication() == null\r\n || JaceApplication.getApplication().primaryStage == null) {\r\n return;\r\n }\r\n Stage stage = JaceApplication.getApplication().primaryStage;\r\n size++;\r\n if (size > 3) {\r\n size = 0;\r\n }\r\n if (stage.isFullScreen()) {\r\n JaceApplication.getApplication().controller.toggleAspectRatio();\r\n } else {\r\n int width = 0, height = 0;\r\n switch (size) {\r\n case 0: // 1x\r\n width = 560;\r\n height = 384;\r\n break;\r\n case 1: // 1.5x\r\n width = 840;\r\n height = 576;\r\n break;\r\n case 2: // 2x\r\n width = 560 * 2;\r\n height = 384 * 2;\r\n break;\r\n case 3: // 3x (retina) 2880x1800\r\n width = 560 * 3;\r\n height = 384 * 3;\r\n break;\r\n default: // 2x\r\n width = 560 * 2;\r\n height = 384 * 2;\r\n }\r\n double vgap = stage.getScene().getY();\r\n double hgap = stage.getScene().getX();\r\n stage.setWidth(hgap * 2 + width);\r\n stage.setHeight(vgap + height);\r\n }\r\n });\r\n }\r\n\r\n @InvokableAction(\r\n name = \"About\",\r\n category = \"general\",\r\n description = \"Display about window\",\r\n alternatives = \"info;credits\",\r\n defaultKeyMapping = {\"ctrl+shift+.\"})\r\n public static void showAboutWindow() {\r\n //TODO: Implement\r\n }\r\n\r\n public static boolean confirm(String message) {\r\n// return JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(Emulator.getFrame(), message);\r\n return false;\r\n }\r\n\r\n static final Map<Object, Set<Label>> INDICATORS = new HashMap<>();\r\n\r\n static public void addIndicator(Object owner, Label icon) {\r\n addIndicator(owner, icon, 250);\r\n }\r\n\r\n static public void addIndicator(Object owner, Label icon, long TTL) {\r\n if (JaceApplication.getApplication() == null) {\r\n return;\r\n }\r\n synchronized (INDICATORS) {\r\n Set<Label> ind = INDICATORS.get(owner);\r\n if (ind == null) {\r\n ind = new HashSet<>();\r\n INDICATORS.put(owner, ind);\r\n }\r\n ind.add(icon);\r\n JaceApplication.getApplication().controller.addIndicator(icon);\r\n }\r\n }\r\n\r\n static public void removeIndicator(Object owner, Label icon) {\r\n if (JaceApplication.singleton == null) {\r\n return;\r\n }\r\n synchronized (INDICATORS) {\r\n Set<Label> ind = INDICATORS.get(owner);\r\n if (ind != null) {\r\n ind.remove(icon);\r\n }\r\n JaceApplication.singleton.controller.removeIndicator(icon);\r\n }\r\n }\r\n\r\n static public void removeIndicators(Object owner) {\r\n if (JaceApplication.singleton == null) {\r\n return;\r\n }\r\n synchronized (INDICATORS) {\r\n Set<Label> ind = INDICATORS.get(owner);\r\n if (ind == null) {\r\n return;\r\n }\r\n ind.stream().forEach((icon) -> {\r\n JaceApplication.singleton.controller.removeIndicator(icon);\r\n });\r\n INDICATORS.remove(owner);\r\n }\r\n }\r\n\r\n static public void addMouseListener(EventHandler<MouseEvent> handler) {\r\n if (JaceApplication.singleton != null) {\r\n JaceApplication.singleton.controller.addMouseListener(handler);\r\n }\r\n }\r\n\r\n static public void removeMouseListener(EventHandler<MouseEvent> handler) {\r\n if (JaceApplication.singleton != null) {\r\n JaceApplication.singleton.controller.removeMouseListener(handler);\r\n }\r\n }\r\n\r\n public static void simulateCtrlAppleReset() {\r\n Computer computer = JaceApplication.singleton.controller.computer;\r\n computer.keyboard.openApple(true);\r\n computer.warmStart();\r\n Platform.runLater(() -> {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ex) {\r\n Logger.getLogger(EmulatorUILogic.class.getName()).log(Level.SEVERE, null, ex);\r\n }\r\n computer.keyboard.openApple(false);\r\n });\r\n }\r\n\r\n public static void notify(String message) {\r\n if (JaceApplication.singleton != null) {\r\n JaceApplication.singleton.controller.displayNotification(message);\r\n }\r\n }\r\n\r\n @Override\r\n public String getName() {\r\n return \"Jace User Interface\";\r\n }\r\n\r\n @Override\r\n public String getShortName() {\r\n return \"UI\";\r\n }\r\n\r\n @Override\r\n public void reconfigure() {\r\n if (JaceApplication.getApplication() != null) {\r\n JaceApplication.getApplication().controller.setSpeed(speedSetting);\r\n }\r\n }\r\n}\r", "@Stateful\r\npublic class MOS65C02 extends CPU {\r\n private static final Logger LOG = Logger.getLogger(MOS65C02.class.getName());\r\n\r\n public boolean readAddressTriggersEvent = true;\r\n static int RESET_VECTOR = 0x00FFFC;\r\n static int INT_VECTOR = 0x00FFFE;\r\n @Stateful\r\n public int A = 0x0FF;\r\n @Stateful\r\n public int X = 0x0FF;\r\n @Stateful\r\n public int Y = 0x0FF;\r\n @Stateful\r\n public int C = 1;\r\n @Stateful\r\n public boolean interruptSignalled = false;\r\n @Stateful\r\n public boolean Z = true;\r\n @Stateful\r\n public boolean I = true;\r\n @Stateful\r\n public boolean D = true;\r\n @Stateful\r\n public boolean B = true;\r\n @Stateful\r\n public boolean V = true;\r\n @Stateful\r\n public boolean N = true;\r\n @Stateful\r\n public int STACK = 0xFF;\r\n @ConfigurableField(name = \"BRK on bad opcode\", description = \"If on, unrecognized opcodes will be treated as BRK. Otherwise, they will be NOP\")\r\n public boolean breakOnBadOpcode = false;\r\n @ConfigurableField(name = \"Ext. opcode warnings\", description = \"If on, uses of 65c02 extended opcodes (or undocumented 6502 opcodes -- which will fail) will be logged to stdout for debugging purposes\")\r\n public boolean warnAboutExtendedOpcodes = false;\r\n\r\n private RAM getMemory() {\r\n return computer.getMemory();\r\n }\r\n\r\n public MOS65C02(Computer computer) {\r\n super(computer);\r\n clearState();\r\n }\r\n\r\n @Override\r\n public void reconfigure() {\r\n }\r\n\r\n @Override\r\n public void clearState() {\r\n A = 0x0ff;\r\n X = 0x0ff;\r\n Y = 0x0ff;\r\n C = 1;\r\n interruptSignalled = false;\r\n Z = true;\r\n I = true;\r\n D = true;\r\n B = true;\r\n V = true;\r\n N = true;\r\n STACK = 0xff;\r\n setWaitCycles(0);\r\n }\r\n \r\n public enum OPCODE {\r\n ADC_IMM(0x0069, COMMAND.ADC, MODE.IMMEDIATE, 2),\r\n ADC_ZP(0x0065, COMMAND.ADC, MODE.ZEROPAGE, 3),\r\n ADC_ZP_X(0x0075, COMMAND.ADC, MODE.ZEROPAGE_X, 4),\r\n ADC_AB(0x006D, COMMAND.ADC, MODE.ABSOLUTE, 4),\r\n ADC_IND_ZP(0x0072, COMMAND.ADC, MODE.INDIRECT_ZP, 5, true),\r\n ADC_IND_ZP_X(0x0061, COMMAND.ADC, MODE.INDIRECT_ZP_X, 6),\r\n ADC_AB_X(0x007D, COMMAND.ADC, MODE.ABSOLUTE_X, 4),\r\n ADC_AB_Y(0x0079, COMMAND.ADC, MODE.ABSOLUTE_Y, 4),\r\n ADC_IND_ZP_Y(0x0071, COMMAND.ADC, MODE.INDIRECT_ZP_Y, 5),\r\n AND_IMM(0x0029, COMMAND.AND, MODE.IMMEDIATE, 2),\r\n AND_ZP(0x0025, COMMAND.AND, MODE.ZEROPAGE, 3),\r\n AND_ZP_X(0x0035, COMMAND.AND, MODE.ZEROPAGE_X, 4),\r\n AND_AB(0x002D, COMMAND.AND, MODE.ABSOLUTE, 4),\r\n AND_IND_ZP(0x0032, COMMAND.AND, MODE.INDIRECT_ZP, 5, true),\r\n AND_IND_ZP_X(0x0021, COMMAND.AND, MODE.INDIRECT_ZP_X, 6),\r\n AND_AB_X(0x003D, COMMAND.AND, MODE.ABSOLUTE_X, 4),\r\n AND_AB_Y(0x0039, COMMAND.AND, MODE.ABSOLUTE_Y, 4),\r\n AND_IND_ZP_Y(0x0031, COMMAND.AND, MODE.INDIRECT_ZP_Y, 5),\r\n ASL(0x000A, COMMAND.ASL_A, MODE.IMPLIED, 2),\r\n ASL_ZP(0x0006, COMMAND.ASL, MODE.ZEROPAGE, 5),\r\n ASL_ZP_X(0x0016, COMMAND.ASL, MODE.ZEROPAGE_X, 6),\r\n ASL_AB(0x000E, COMMAND.ASL, MODE.ABSOLUTE, 6),\r\n ASL_AB_X(0x001E, COMMAND.ASL, MODE.ABSOLUTE_X, 7),\r\n BCC_REL(0x0090, COMMAND.BCC, MODE.RELATIVE, 2),\r\n BCS_REL(0x00B0, COMMAND.BCS, MODE.RELATIVE, 2),\r\n BBR0(0x00f, COMMAND.BBR0, MODE.ZP_REL, 5, true),\r\n BBR1(0x01f, COMMAND.BBR1, MODE.ZP_REL, 5, true),\r\n BBR2(0x02f, COMMAND.BBR2, MODE.ZP_REL, 5, true),\r\n BBR3(0x03f, COMMAND.BBR3, MODE.ZP_REL, 5, true),\r\n BBR4(0x04f, COMMAND.BBR4, MODE.ZP_REL, 5, true),\r\n BBR5(0x05f, COMMAND.BBR5, MODE.ZP_REL, 5, true),\r\n BBR6(0x06f, COMMAND.BBR6, MODE.ZP_REL, 5, true),\r\n BBR7(0x07f, COMMAND.BBR7, MODE.ZP_REL, 5, true),\r\n BBS0(0x08f, COMMAND.BBS0, MODE.ZP_REL, 5, true),\r\n BBS1(0x09f, COMMAND.BBS1, MODE.ZP_REL, 5, true),\r\n BBS2(0x0af, COMMAND.BBS2, MODE.ZP_REL, 5, true),\r\n BBS3(0x0bf, COMMAND.BBS3, MODE.ZP_REL, 5, true),\r\n BBS4(0x0cf, COMMAND.BBS4, MODE.ZP_REL, 5, true),\r\n BBS5(0x0df, COMMAND.BBS5, MODE.ZP_REL, 5, true),\r\n BBS6(0x0ef, COMMAND.BBS6, MODE.ZP_REL, 5, true),\r\n BBS7(0x0ff, COMMAND.BBS7, MODE.ZP_REL, 5, true),\r\n BEQ_REL0(0x00F0, COMMAND.BEQ, MODE.RELATIVE, 2),\r\n BIT_IMM(0x0089, COMMAND.BIT, MODE.IMMEDIATE, 3, true),\r\n BIT_ZP(0x0024, COMMAND.BIT, MODE.ZEROPAGE, 3),\r\n BIT_ZP_X(0x0034, COMMAND.BIT, MODE.ZEROPAGE_X, 3, true),\r\n BIT_AB(0x002C, COMMAND.BIT, MODE.ABSOLUTE, 4),\r\n BIT_AB_X(0x003C, COMMAND.BIT, MODE.ABSOLUTE_X, 4, true),\r\n BMI_REL(0x0030, COMMAND.BMI, MODE.RELATIVE, 2),\r\n BNE_REL(0x00D0, COMMAND.BNE, MODE.RELATIVE, 2),\r\n BPL_REL(0x0010, COMMAND.BPL, MODE.RELATIVE, 2),\r\n BRA_REL(0x0080, COMMAND.BRA, MODE.RELATIVE, 2, true),\r\n // BRK(0x0000, COMMAND.BRK, MODE.IMPLIED, 7),\r\n // Do this so that BRK is treated as a two-byte instruction\r\n BRK(0x0000, COMMAND.BRK, MODE.IMMEDIATE, 7),\r\n BVC_REL(0x0050, COMMAND.BVC, MODE.RELATIVE, 2),\r\n BVS_REL(0x0070, COMMAND.BVS, MODE.RELATIVE, 2),\r\n CLC(0x0018, COMMAND.CLC, MODE.IMPLIED, 2),\r\n CLD(0x00D8, COMMAND.CLD, MODE.IMPLIED, 2),\r\n CLI(0x0058, COMMAND.CLI, MODE.IMPLIED, 2),\r\n CLV(0x00B8, COMMAND.CLV, MODE.IMPLIED, 2),\r\n CMP_IMM(0x00C9, COMMAND.CMP, MODE.IMMEDIATE, 2),\r\n CMP_ZP(0x00C5, COMMAND.CMP, MODE.ZEROPAGE, 3),\r\n CMP_ZP_X(0x00D5, COMMAND.CMP, MODE.ZEROPAGE_X, 4),\r\n CMP_AB(0x00CD, COMMAND.CMP, MODE.ABSOLUTE, 4),\r\n CMP_IND_ZP_X(0x00C1, COMMAND.CMP, MODE.INDIRECT_ZP_X, 6),\r\n CMP_AB_X(0x00DD, COMMAND.CMP, MODE.ABSOLUTE_X, 4),\r\n CMP_AB_Y(0x00D9, COMMAND.CMP, MODE.ABSOLUTE_Y, 4),\r\n CMP_IND_ZP_Y(0x00D1, COMMAND.CMP, MODE.INDIRECT_ZP_Y, 5),\r\n CMP_IND_ZP(0x00D2, COMMAND.CMP, MODE.INDIRECT_ZP, 5, true),\r\n CPX_IMM(0x00E0, COMMAND.CPX, MODE.IMMEDIATE, 2),\r\n CPX_ZP(0x00E4, COMMAND.CPX, MODE.ZEROPAGE, 3),\r\n CPX_AB(0x00EC, COMMAND.CPX, MODE.ABSOLUTE, 4),\r\n CPY_IMM(0x00C0, COMMAND.CPY, MODE.IMMEDIATE, 2),\r\n CPY_ZP(0x00C4, COMMAND.CPY, MODE.ZEROPAGE, 3),\r\n CPY_AB(0x00CC, COMMAND.CPY, MODE.ABSOLUTE, 4),\r\n DEC(0x003A, COMMAND.DEA, MODE.IMPLIED, 2, true),\r\n DEC_ZP(0x00C6, COMMAND.DEC, MODE.ZEROPAGE, 5),\r\n DEC_ZP_X(0x00D6, COMMAND.DEC, MODE.ZEROPAGE_X, 6),\r\n DEC_AB(0x00CE, COMMAND.DEC, MODE.ABSOLUTE, 6),\r\n DEC_AB_X(0x00DE, COMMAND.DEC, MODE.ABSOLUTE_X, 7),\r\n DEX(0x00CA, COMMAND.DEX, MODE.IMPLIED, 2),\r\n DEY(0x0088, COMMAND.DEY, MODE.IMPLIED, 2),\r\n EOR_IMM(0x0049, COMMAND.EOR, MODE.IMMEDIATE, 2),\r\n EOR_ZP(0x0045, COMMAND.EOR, MODE.ZEROPAGE, 3),\r\n EOR_ZP_X(0x0055, COMMAND.EOR, MODE.ZEROPAGE_X, 4),\r\n EOR_AB(0x004D, COMMAND.EOR, MODE.ABSOLUTE, 4),\r\n EOR_IND_ZP(0x0052, COMMAND.EOR, MODE.INDIRECT_ZP, 5, true),\r\n EOR_IND_ZP_X(0x0041, COMMAND.EOR, MODE.INDIRECT_ZP_X, 6),\r\n EOR_AB_X(0x005D, COMMAND.EOR, MODE.ABSOLUTE_X, 4),\r\n EOR_AB_Y(0x0059, COMMAND.EOR, MODE.ABSOLUTE_Y, 4),\r\n EOR_IND_ZP_Y(0x0051, COMMAND.EOR, MODE.INDIRECT_ZP_Y, 5),\r\n INC(0x001A, COMMAND.INA, MODE.IMPLIED, 2, true),\r\n INC_ZP(0x00E6, COMMAND.INC, MODE.ZEROPAGE, 5),\r\n INC_ZP_X(0x00F6, COMMAND.INC, MODE.ZEROPAGE_X, 6),\r\n INC_AB(0x00EE, COMMAND.INC, MODE.ABSOLUTE, 6),\r\n INC_AB_X(0x00FE, COMMAND.INC, MODE.ABSOLUTE_X, 7),\r\n INX(0x00E8, COMMAND.INX, MODE.IMPLIED, 2),\r\n INY(0x00C8, COMMAND.INY, MODE.IMPLIED, 2),\r\n JMP_AB(0x004C, COMMAND.JMP, MODE.ABSOLUTE, 3, false, false),\r\n JMP_IND(0x006C, COMMAND.JMP, MODE.INDIRECT, 5),\r\n JMP_IND_X(0x007C, COMMAND.JMP, MODE.INDIRECT_X, 6, true),\r\n JSR_AB(0x0020, COMMAND.JSR, MODE.ABSOLUTE, 6, false, false),\r\n LDA_IMM(0x00A9, COMMAND.LDA, MODE.IMMEDIATE, 2),\r\n LDA_ZP(0x00A5, COMMAND.LDA, MODE.ZEROPAGE, 3),\r\n LDA_ZP_X(0x00B5, COMMAND.LDA, MODE.ZEROPAGE_X, 4),\r\n LDA_AB(0x00AD, COMMAND.LDA, MODE.ABSOLUTE, 4),\r\n LDA_IND_ZP_X(0x00A1, COMMAND.LDA, MODE.INDIRECT_ZP_X, 6),\r\n LDA_AB_X(0x00BD, COMMAND.LDA, MODE.ABSOLUTE_X, 4),\r\n LDA_AB_Y(0x00B9, COMMAND.LDA, MODE.ABSOLUTE_Y, 4),\r\n LDA_IND_ZP_Y(0x00B1, COMMAND.LDA, MODE.INDIRECT_ZP_Y, 5),\r\n LDA_IND_ZP(0x00B2, COMMAND.LDA, MODE.INDIRECT_ZP, 5, true),\r\n LDX_IMM(0x00A2, COMMAND.LDX, MODE.IMMEDIATE, 2),\r\n LDX_ZP(0x00A6, COMMAND.LDX, MODE.ZEROPAGE, 3),\r\n LDX_ZP_Y(0x00B6, COMMAND.LDX, MODE.ZEROPAGE_Y, 4),\r\n LDX_AB(0x00AE, COMMAND.LDX, MODE.ABSOLUTE, 4),\r\n LDX_AB_Y(0x00BE, COMMAND.LDX, MODE.ABSOLUTE_Y, 4),\r\n LDY_IMM(0x00A0, COMMAND.LDY, MODE.IMMEDIATE, 2),\r\n LDY_ZP(0x00A4, COMMAND.LDY, MODE.ZEROPAGE, 3),\r\n LDY_ZP_X(0x00B4, COMMAND.LDY, MODE.ZEROPAGE_X, 4),\r\n LDY_AB(0x00AC, COMMAND.LDY, MODE.ABSOLUTE, 4),\r\n LDY_AB_X(0x00BC, COMMAND.LDY, MODE.ABSOLUTE_X, 4),\r\n LSR(0x004A, COMMAND.LSR_A, MODE.IMPLIED, 2),\r\n LSR_ZP(0x0046, COMMAND.LSR, MODE.ZEROPAGE, 5),\r\n LSR_ZP_X(0x0056, COMMAND.LSR, MODE.ZEROPAGE_X, 6),\r\n LSR_AB(0x004E, COMMAND.LSR, MODE.ABSOLUTE, 6),\r\n LSR_AB_X(0x005E, COMMAND.LSR, MODE.ABSOLUTE_X, 7),\r\n NOP(0x00EA, COMMAND.NOP, MODE.IMPLIED, 2),\r\n SPECIAL(0x00FC, COMMAND.NOP_SPECIAL, MODE.ABSOLUTE, 4),\r\n ORA_IMM(0x0009, COMMAND.ORA, MODE.IMMEDIATE, 2),\r\n ORA_ZP(0x0005, COMMAND.ORA, MODE.ZEROPAGE, 3),\r\n ORA_ZP_X(0x0015, COMMAND.ORA, MODE.ZEROPAGE_X, 4),\r\n ORA_AB(0x000D, COMMAND.ORA, MODE.ABSOLUTE, 4),\r\n ORA_IND_ZP(0x0012, COMMAND.ORA, MODE.INDIRECT_ZP, 5, true),\r\n ORA_IND_ZP_X(0x0001, COMMAND.ORA, MODE.INDIRECT_ZP_X, 6),\r\n ORA_AB_X(0x001D, COMMAND.ORA, MODE.ABSOLUTE_X, 4),\r\n ORA_AB_Y(0x0019, COMMAND.ORA, MODE.ABSOLUTE_Y, 4),\r\n ORA_IND_ZP_Y(0x0011, COMMAND.ORA, MODE.INDIRECT_ZP_Y, 5),\r\n PHA(0x0048, COMMAND.PHA, MODE.IMPLIED, 3),\r\n PHP(0x0008, COMMAND.PHP, MODE.IMPLIED, 3),\r\n PHX(0x00DA, COMMAND.PHX, MODE.IMPLIED, 3, true),\r\n PHY(0x005A, COMMAND.PHY, MODE.IMPLIED, 3, true),\r\n PLA(0x0068, COMMAND.PLA, MODE.IMPLIED, 4),\r\n PLP(0x0028, COMMAND.PLP, MODE.IMPLIED, 4),\r\n PLX(0x00FA, COMMAND.PLX, MODE.IMPLIED, 4, true),\r\n PLY(0x007A, COMMAND.PLY, MODE.IMPLIED, 4, true),\r\n RMB0(0x007, COMMAND.RMB0, MODE.ZEROPAGE, 5, true),\r\n RMB1(0x017, COMMAND.RMB1, MODE.ZEROPAGE, 5, true),\r\n RMB2(0x027, COMMAND.RMB2, MODE.ZEROPAGE, 5, true),\r\n RMB3(0x037, COMMAND.RMB3, MODE.ZEROPAGE, 5, true),\r\n RMB4(0x047, COMMAND.RMB4, MODE.ZEROPAGE, 5, true),\r\n RMB5(0x057, COMMAND.RMB5, MODE.ZEROPAGE, 5, true),\r\n RMB6(0x067, COMMAND.RMB6, MODE.ZEROPAGE, 5, true),\r\n RMB7(0x077, COMMAND.RMB7, MODE.ZEROPAGE, 5, true),\r\n ROL(0x002A, COMMAND.ROL_A, MODE.IMPLIED, 2),\r\n ROL_ZP(0x0026, COMMAND.ROL, MODE.ZEROPAGE, 5),\r\n ROL_ZP_X(0x0036, COMMAND.ROL, MODE.ZEROPAGE_X, 6),\r\n ROL_AB(0x002E, COMMAND.ROL, MODE.ABSOLUTE, 6),\r\n ROL_AB_X(0x003E, COMMAND.ROL, MODE.ABSOLUTE_X, 7),\r\n ROR(0x006A, COMMAND.ROR_A, MODE.IMPLIED, 2),\r\n ROR_ZP(0x0066, COMMAND.ROR, MODE.ZEROPAGE, 5),\r\n ROR_ZP_X(0x0076, COMMAND.ROR, MODE.ZEROPAGE_X, 6),\r\n ROR_AB(0x006E, COMMAND.ROR, MODE.ABSOLUTE, 6),\r\n ROR_AB_X(0x007E, COMMAND.ROR, MODE.ABSOLUTE_X, 7),\r\n RTI(0x0040, COMMAND.RTI, MODE.IMPLIED, 6),\r\n RTS(0x0060, COMMAND.RTS, MODE.IMPLIED, 6),\r\n SBC_IMM(0x00E9, COMMAND.SBC, MODE.IMMEDIATE, 2),\r\n SBC_ZP(0x00E5, COMMAND.SBC, MODE.ZEROPAGE, 3),\r\n SBC_ZP_X(0x00F5, COMMAND.SBC, MODE.ZEROPAGE_X, 4),\r\n SBC_AB(0x00ED, COMMAND.SBC, MODE.ABSOLUTE, 4),\r\n SBC_IND_ZP(0x00F2, COMMAND.SBC, MODE.INDIRECT_ZP, 5, true),\r\n SBC_IND_ZP_X(0x00E1, COMMAND.SBC, MODE.INDIRECT_ZP_X, 6),\r\n SBC_AB_X(0x00FD, COMMAND.SBC, MODE.ABSOLUTE_X, 4),\r\n SBC_AB_Y(0x00F9, COMMAND.SBC, MODE.ABSOLUTE_Y, 4),\r\n SBC_IND_ZP_Y(0x00F1, COMMAND.SBC, MODE.INDIRECT_ZP_Y, 5),\r\n SEC(0x0038, COMMAND.SEC, MODE.IMPLIED, 2),\r\n SED(0x00F8, COMMAND.SED, MODE.IMPLIED, 2),\r\n SEI(0x0078, COMMAND.SEI, MODE.IMPLIED, 2),\r\n SMB0(0x087, COMMAND.SMB0, MODE.ZEROPAGE, 5, true),\r\n SMB1(0x097, COMMAND.SMB1, MODE.ZEROPAGE, 5, true),\r\n SMB2(0x0a7, COMMAND.SMB2, MODE.ZEROPAGE, 5, true),\r\n SMB3(0x0b7, COMMAND.SMB3, MODE.ZEROPAGE, 5, true),\r\n SMB4(0x0c7, COMMAND.SMB4, MODE.ZEROPAGE, 5, true),\r\n SMB5(0x0d7, COMMAND.SMB5, MODE.ZEROPAGE, 5, true),\r\n SMB6(0x0e7, COMMAND.SMB6, MODE.ZEROPAGE, 5, true),\r\n SMB7(0x0f7, COMMAND.SMB7, MODE.ZEROPAGE, 5, true),\r\n STA_ZP(0x0085, COMMAND.STA, MODE.ZEROPAGE, 3),\r\n STA_ZP_X(0x0095, COMMAND.STA, MODE.ZEROPAGE_X, 4),\r\n STA_AB(0x008D, COMMAND.STA, MODE.ABSOLUTE, 4),\r\n STA_AB_X(0x009D, COMMAND.STA, MODE.ABSOLUTE_X, 5),\r\n STA_AB_Y(0x0099, COMMAND.STA, MODE.ABSOLUTE_Y, 5),\r\n STA_IND_ZP(0x0092, COMMAND.STA, MODE.INDIRECT_ZP, 5, true),\r\n STA_IND_ZP_X(0x0081, COMMAND.STA, MODE.INDIRECT_ZP_X, 6),\r\n STA_IND_ZP_Y(0x0091, COMMAND.STA, MODE.INDIRECT_ZP_Y, 6),\r\n STP(0x00DB, COMMAND.STP, MODE.IMPLIED, 3, true),\r\n STX_ZP(0x0086, COMMAND.STX, MODE.ZEROPAGE, 3),\r\n STX_ZP_Y(0x0096, COMMAND.STX, MODE.ZEROPAGE_Y, 4),\r\n STX_AB(0x008E, COMMAND.STX, MODE.ABSOLUTE, 4),\r\n STY_ZP(0x0084, COMMAND.STY, MODE.ZEROPAGE, 3),\r\n STY_ZP_X(0x0094, COMMAND.STY, MODE.ZEROPAGE_X, 4),\r\n STY_AB(0x008C, COMMAND.STY, MODE.ABSOLUTE, 4),\r\n STZ_ZP(0x0064, COMMAND.STZ, MODE.ZEROPAGE, 3, true),\r\n STZ_ZP_X(0x0074, COMMAND.STZ, MODE.ZEROPAGE_X, 4, true),\r\n STZ_AB(0x009C, COMMAND.STZ, MODE.ABSOLUTE, 4, true),\r\n STZ_AB_X(0x009E, COMMAND.STZ, MODE.ABSOLUTE_X, 5, true),\r\n TAX(0x00AA, COMMAND.TAX, MODE.IMPLIED, 2),\r\n TAY(0x00A8, COMMAND.TAY, MODE.IMPLIED, 2),\r\n TRB_ZP(0x0014, COMMAND.TRB, MODE.ZEROPAGE, 5, true),\r\n TRB_AB(0x001C, COMMAND.TRB, MODE.ABSOLUTE, 6, true),\r\n TSB_ZP(0x0004, COMMAND.TSB, MODE.ZEROPAGE, 5, true),\r\n TSB_AB(0x000C, COMMAND.TSB, MODE.ABSOLUTE, 6, true),\r\n TSX(0x00BA, COMMAND.TSX, MODE.IMPLIED, 2),\r\n TXA(0x008A, COMMAND.TXA, MODE.IMPLIED, 2),\r\n TXS(0x009A, COMMAND.TXS, MODE.IMPLIED, 2),\r\n TYA(0x0098, COMMAND.TYA, MODE.IMPLIED, 2),\r\n WAI(0x00CB, COMMAND.WAI, MODE.IMPLIED, 3, true);\r\n private int code;\r\n private boolean isExtendedOpcode;\r\n\r\n public int getCode() {\r\n return code;\r\n }\r\n private int waitCycles;\r\n\r\n public int getWaitCycles() {\r\n return waitCycles;\r\n }\r\n private COMMAND command;\r\n\r\n public COMMAND getCommand() {\r\n return command;\r\n }\r\n private MODE addressingMode;\r\n\r\n public MODE getMode() {\r\n return addressingMode;\r\n }\r\n int address = 0;\r\n int value = 0;\r\n boolean shouldFetch;\r\n\r\n private void fetch(MOS65C02 cpu) {\r\n address = getMode().calculator.calculateAddress(cpu);\r\n value = shouldFetch ? getMode().calculator.getValue(!command.isStoreOnly(), cpu) : 0;\r\n }\r\n\r\n public void execute(MOS65C02 cpu) {\r\n command.getProcessor().processCommand(address, value, addressingMode, cpu);\r\n }\r\n\r\n private OPCODE(int val, COMMAND c, MODE m, int wait) {\r\n this(val, c, m, wait, m.fetchValue, false);\r\n }\r\n\r\n private OPCODE(int val, COMMAND c, MODE m, int wait, boolean extended) {\r\n this(val, c, m, wait, m.fetchValue, extended);\r\n }\r\n\r\n private OPCODE(int val, COMMAND c, MODE m, int wait, boolean fetch, boolean extended) {\r\n code = val;\r\n waitCycles = wait - 1;\r\n command = c;\r\n addressingMode = m;\r\n isExtendedOpcode = extended;\r\n shouldFetch = fetch;\r\n }\r\n }\r\n\r\n public static interface AddressCalculator {\r\n\r\n abstract int calculateAddress(MOS65C02 cpu);\r\n\r\n default int getValue(boolean generateEvent, MOS65C02 cpu) {\r\n int address = calculateAddress(cpu);\r\n return (address > -1) ? (0x0ff & cpu.getMemory().read(address, TYPE.READ_DATA, generateEvent, false)) : 0;\r\n }\r\n }\r\n\r\n public enum MODE {\r\n\r\n IMPLIED(1, \"\", (cpu) -> -1, false),\r\n // RELATIVE(2, \"#$~1 ($R)\"),\r\n RELATIVE(2, \"$R\", (cpu) -> {\r\n int pc = cpu.getProgramCounter();\r\n int address = pc + 2 + cpu.getMemory().read(pc + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n // The wait cycles are not added unless the branch actually happens!\r\n cpu.setPageBoundaryPenalty((address & 0x00ff00) != ((pc+2) & 0x00ff00));\r\n return address;\r\n }, false),\r\n IMMEDIATE(2, \"#$~1\", (cpu) -> cpu.getProgramCounter() + 1),\r\n ZEROPAGE(2, \"$~1\", (cpu) -> cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false) & 0x00FF),\r\n ZEROPAGE_X(2, \"$~1,X\", (cpu) -> 0x0FF & (cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false) + cpu.X)),\r\n ZEROPAGE_Y(2, \"$~1,Y\", (cpu) -> 0x0FF & (cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false) + cpu.Y)),\r\n INDIRECT(3, \"$(~2~1)\", (cpu) -> {\r\n int address = cpu.getMemory().readWord(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n return cpu.getMemory().readWord(address, TYPE.READ_DATA, true, false);\r\n }),\r\n INDIRECT_X(3, \"$(~2~1,X)\", (cpu) -> {\r\n int address = cpu.getMemory().readWord(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false) + cpu.X;\r\n return cpu.getMemory().readWord(address & 0x0FFFF, TYPE.READ_DATA, true, false);\r\n }),\r\n INDIRECT_ZP(2, \"$(~1)\", (cpu) -> {\r\n int address = cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n return cpu.getMemory().readWord(address & 0x0FF, TYPE.READ_DATA, true, false);\r\n }),\r\n INDIRECT_ZP_X(2, \"$(~1,X)\", (cpu) -> {\r\n int address = cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false) + cpu.X;\r\n return cpu.getMemory().readWord(address & 0x0FF, TYPE.READ_DATA, true, false);\r\n }),\r\n INDIRECT_ZP_Y(2, \"$(~1),Y\", (cpu) -> {\r\n int address = 0x00FF & cpu.getMemory().read(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n address = cpu.getMemory().readWord(address, TYPE.READ_DATA, true, false);\r\n int address2 = address + cpu.Y;\r\n if ((address & 0x00ff00) != (address2 & 0x00ff00)) {\r\n cpu.addWaitCycles(1);\r\n }\r\n return address2;\r\n }),\r\n ABSOLUTE(3, \"$~2~1\", (cpu) -> cpu.getMemory().readWord(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false)),\r\n ABSOLUTE_X(3, \"$~2~1,X\", (cpu) -> {\r\n int address2 = cpu.getMemory().readWord(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n int address = 0x0FFFF & (address2 + cpu.X);\r\n if ((address & 0x00FF00) != (address2 & 0x00FF00)) {\r\n cpu.addWaitCycles(1);\r\n }\r\n return address;\r\n }),\r\n ABSOLUTE_Y(3, \"$~2~1,Y\", (cpu) -> {\r\n int address2 = cpu.getMemory().readWord(cpu.getProgramCounter() + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n int address = 0x0FFFF & (address2 + cpu.Y);\r\n if ((address & 0x00FF00) != (address2 & 0x00FF00)) {\r\n cpu.addWaitCycles(1);\r\n }\r\n return address;\r\n }),\r\n ZP_REL(3, \"$~1,$R\", new AddressCalculator() {\r\n @Override\r\n public int calculateAddress(MOS65C02 cpu) {\r\n // Note: This is two's compliment addition and the cpu.getMemory().read() returns a signed 8-bit value\r\n int pc = cpu.getProgramCounter();\r\n int address = pc + 3 + cpu.getMemory().read(pc + 2, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n // The wait cycles are not added unless the branch actually happens!\r\n cpu.setPageBoundaryPenalty((address & 0x00ff00) != ((pc+3) & 0x00ff00));\r\n return address;\r\n }\r\n\r\n @Override\r\n public int getValue(boolean isRead, MOS65C02 cpu) {\r\n int pc = cpu.getProgramCounter();\r\n int address = 0x0ff & cpu.getMemory().read(pc + 1, TYPE.READ_OPERAND, cpu.readAddressTriggersEvent, false);\r\n return cpu.getMemory().read(address, TYPE.READ_DATA, true, false);\r\n }\r\n });\r\n private int size;\r\n\r\n public int getSize() {\r\n return this.size;\r\n }\r\n// private String format;\r\n//\r\n// public String getFormat() {\r\n// return this.format;\r\n// }\r\n private AddressCalculator calculator;\r\n\r\n public int calcAddress(MOS65C02 cpu) {\r\n return calculator.calculateAddress(cpu);\r\n }\r\n private boolean indirect;\r\n\r\n public boolean isIndirect() {\r\n return indirect;\r\n }\r\n String f1;\r\n String f2;\r\n boolean twoByte = false;\r\n boolean relative = false;\r\n boolean implied = true;\r\n boolean fetchValue = true;\r\n\r\n private MODE(int size, String fmt, AddressCalculator calc) {\r\n this(size, fmt, calc, true);\r\n }\r\n private MODE(int size, String fmt, AddressCalculator calc, boolean fetch) {\r\n this.fetchValue = fetch;\r\n this.size = size;\r\n if (fmt.contains(\"~\")) {\r\n this.f1 = fmt.substring(0, fmt.indexOf('~'));\r\n this.f2 = fmt.substring(fmt.indexOf(\"~1\") + 2);\r\n if (fmt.contains(\"~2\")) {\r\n twoByte = true;\r\n }\r\n implied = false;\r\n } else if (fmt.contains(\"R\")) {\r\n this.f1 = fmt.substring(0, fmt.indexOf('R'));\r\n f2 = \"\";\r\n relative = true;\r\n implied = false;\r\n }\r\n// this.format = fmt;\r\n\r\n this.calculator = calc;\r\n this.indirect = toString().startsWith(\"INDIRECT\");\r\n }\r\n\r\n public MOS65C02.AddressCalculator getCalculator() {\r\n return calculator;\r\n }\r\n\r\n public String formatMode(int pc, MOS65C02 cpu) {\r\n if (implied) {\r\n return \"\";\r\n } else {\r\n int b1 = 0x00ff & cpu.getMemory().readRaw((pc + 1) & 0x0FFFF);\r\n if (relative) {\r\n String R = wordString(pc + 2 + (byte) b1);\r\n return f1 + R;\r\n } else if (twoByte) {\r\n int b2 = 0x00ff & cpu.getMemory().readRaw((pc + 2) & 0x0FFFF);\r\n return f1 + byte2(b2) + byte2(b1) + f2;\r\n } else {\r\n return f1 + byte2(b1) + f2;\r\n }\r\n }\r\n }\r\n }\r\n\r\n public static interface CommandProcessor {\r\n\r\n public void processCommand(int address, int value, MODE addressMode, MOS65C02 cpu);\r\n }\r\n\r\n private static class BBRCommand implements CommandProcessor {\r\n\r\n int bit;\r\n\r\n public BBRCommand(int bit) {\r\n this.bit = bit;\r\n }\r\n\r\n @Override\r\n public void processCommand(int address, int value, MODE addressMode, MOS65C02 cpu) {\r\n if ((value & (1 << bit)) == 0) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }\r\n }\r\n\r\n private static class BBSCommand implements CommandProcessor {\r\n\r\n int bit;\r\n\r\n public BBSCommand(int bit) {\r\n this.bit = bit;\r\n }\r\n\r\n @Override\r\n public void processCommand(int address, int value, MODE addressMode, MOS65C02 cpu) {\r\n if ((value & (1 << bit)) != 0) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }\r\n }\r\n\r\n private static class RMBCommand implements CommandProcessor {\r\n\r\n int bit;\r\n\r\n public RMBCommand(int bit) {\r\n this.bit = bit;\r\n }\r\n\r\n @Override\r\n public void processCommand(int address, int value, MODE addressMode, MOS65C02 cpu) {\r\n int mask = 0x0ff ^ (1 << bit);\r\n cpu.getMemory().write(address, (byte) (value & mask), true, false);\r\n }\r\n }\r\n\r\n private static class SMBCommand implements CommandProcessor {\r\n\r\n int bit;\r\n\r\n public SMBCommand(int bit) {\r\n this.bit = bit;\r\n }\r\n\r\n @Override\r\n public void processCommand(int address, int value, MODE addressMode, MOS65C02 cpu) {\r\n int mask = 1 << bit;\r\n cpu.getMemory().write(address, (byte) (value | mask), true, false);\r\n }\r\n }\r\n\r\n public enum COMMAND {\r\n ADC((address, value, addressMode, cpu) -> {\r\n int w;\r\n cpu.V = ((cpu.A ^ value) & 0x080) == 0;\r\n if (cpu.D) {\r\n // Decimal Mode\r\n w = (cpu.A & 0x0f) + (value & 0x0f) + cpu.C;\r\n if (w >= 10) {\r\n w = 0x010 | ((w + 6) & 0x0f);\r\n }\r\n w += (cpu.A & 0x0f0) + (value & 0x00f0);\r\n if (w >= 0x0A0) {\r\n cpu.C = 1;\r\n if (cpu.V && w >= 0x0180) {\r\n cpu.V = false;\r\n }\r\n w += 0x060;\r\n } else {\r\n cpu.C = 0;\r\n if (cpu.V && w < 0x080) {\r\n cpu.V = false;\r\n }\r\n }\r\n } else {\r\n // Binary Mode\r\n w = cpu.A + value + cpu.C;\r\n if (w >= 0x0100) {\r\n cpu.C = 1;\r\n if (cpu.V && w >= 0x0180) {\r\n cpu.V = false;\r\n }\r\n } else {\r\n cpu.C = 0;\r\n if (cpu.V && w < 0x080) {\r\n cpu.V = false;\r\n }\r\n }\r\n }\r\n cpu.A = w & 0x0ff;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n AND((address, value, addressMode, cpu) -> {\r\n cpu.A &= value;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n ASL((address, value, addressMode, cpu) -> {\r\n cpu.C = ((value & 0x080) != 0) ? 1 : 0;\r\n value = 0x0FE & (value << 1);\r\n cpu.setNZ(value);\r\n // Emulate correct behavior of fetch-store-modify\r\n // http://forum.6502.org/viewtopic.php?f=4&t=1617&view=previous\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n }),\r\n ASL_A((address, value, addressMode, cpu) -> {\r\n cpu.C = cpu.A >> 7;\r\n cpu.A = 0x0FE & (cpu.A << 1);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n BBR0(new BBRCommand(0)),\r\n BBR1(new BBRCommand(1)),\r\n BBR2(new BBRCommand(2)),\r\n BBR3(new BBRCommand(3)),\r\n BBR4(new BBRCommand(4)),\r\n BBR5(new BBRCommand(5)),\r\n BBR6(new BBRCommand(6)),\r\n BBR7(new BBRCommand(7)),\r\n BBS0(new BBSCommand(0)),\r\n BBS1(new BBSCommand(1)),\r\n BBS2(new BBSCommand(2)),\r\n BBS3(new BBSCommand(3)),\r\n BBS4(new BBSCommand(4)),\r\n BBS5(new BBSCommand(5)),\r\n BBS6(new BBSCommand(6)),\r\n BBS7(new BBSCommand(7)),\r\n BCC((address, value, addressMode, cpu) -> {\r\n if (cpu.C == 0) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BCS((address, value, addressMode, cpu) -> {\r\n if (cpu.C != 0) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BEQ((address, value, addressMode, cpu) -> {\r\n if (cpu.Z) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BIT((address, value, addressMode, cpu) -> {\r\n int result = (cpu.A & value);\r\n cpu.Z = result == 0;\r\n cpu.N = (value & 0x080) != 0;\r\n // As per http://www.6502.org/tutorials/vflag.html\r\n if (addressMode != MODE.IMMEDIATE) {\r\n cpu.V = (value & 0x040) != 0;\r\n }\r\n }),\r\n BMI((address, value, addressMode, cpu) -> {\r\n if (cpu.N) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BNE((address, value, addressMode, cpu) -> {\r\n if (!cpu.Z) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BPL((address, value, addressMode, cpu) -> {\r\n if (!cpu.N) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BRA((address, value, addressMode, cpu) -> {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 1 : 0);\r\n }),\r\n BRK((address, value, addressMode, cpu) -> {\r\n cpu.BRK();\r\n }),\r\n BVC((address, value, addressMode, cpu) -> {\r\n if (!cpu.V) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n BVS((address, value, addressMode, cpu) -> {\r\n if (cpu.V) {\r\n cpu.setProgramCounter(address);\r\n cpu.addWaitCycles(cpu.pageBoundaryPenalty ? 2 : 1);\r\n }\r\n }),\r\n CLC((address, value, addressMode, cpu) -> {\r\n cpu.C = 0;\r\n }),\r\n CLD((address, value, addressMode, cpu) -> {\r\n cpu.D = false;\r\n }),\r\n CLI((address, value, addressMode, cpu) -> {\r\n cpu.I = false;\r\n cpu.interruptSignalled = false;\r\n }),\r\n CLV((address, value, addressMode, cpu) -> {\r\n cpu.V = false;\r\n }),\r\n CMP((address, value, addressMode, cpu) -> {\r\n int val = cpu.A - value;\r\n cpu.C = (val >= 0) ? 1 : 0;\r\n cpu.setNZ(val);\r\n }),\r\n CPX((address, value, addressMode, cpu) -> {\r\n int val = cpu.X - value;\r\n cpu.C = (val >= 0) ? 1 : 0;\r\n cpu.setNZ(val);\r\n }),\r\n CPY((address, value, addressMode, cpu) -> {\r\n int val = cpu.Y - value;\r\n cpu.C = (val >= 0) ? 1 : 0;\r\n cpu.setNZ(val);\r\n }),\r\n DEC((address, value, addressMode, cpu) -> {\r\n value = 0x0FF & (value - 1);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.setNZ(value);\r\n }),\r\n DEA((address, value, addressMode, cpu) -> {\r\n cpu.A = 0x0FF & (cpu.A - 1);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n DEX((address, value, addressMode, cpu) -> {\r\n cpu.X = 0x0FF & (cpu.X - 1);\r\n cpu.setNZ(cpu.X);\r\n }),\r\n DEY((address, value, addressMode, cpu) -> {\r\n cpu.Y = 0x0FF & (cpu.Y - 1);\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n EOR((address, value, addressMode, cpu) -> {\r\n cpu.A = 0x0FF & (cpu.A ^ value);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n INC((address, value, addressMode, cpu) -> {\r\n value = 0x0ff & (value + 1);\r\n // emulator correct fetch-modify-store behavior\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.setNZ(value);\r\n }),\r\n INA((address, value, addressMode, cpu) -> {\r\n cpu.A = 0x0FF & (cpu.A + 1);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n INX((address, value, addressMode, cpu) -> {\r\n cpu.X = 0x0FF & (cpu.X + 1);\r\n cpu.setNZ(cpu.X);\r\n }),\r\n INY((address, value, addressMode, cpu) -> {\r\n cpu.Y = 0x0FF & (cpu.Y + 1);\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n JMP((address, value, addressMode, cpu) -> {\r\n cpu.setProgramCounter(address);\r\n }),\r\n JSR((address, value, addressMode, cpu) -> {\r\n cpu.JSR(address);\r\n }),\r\n LDA((address, value, addressMode, cpu) -> {\r\n cpu.A = value;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n LDX((address, value, addressMode, cpu) -> {\r\n cpu.X = value;\r\n cpu.setNZ(cpu.X);\r\n }),\r\n LDY((address, value, addressMode, cpu) -> {\r\n cpu.Y = value;\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n LSR((address, value, addressMode, cpu) -> {\r\n cpu.C = (value & 1);\r\n value = (value >> 1) & 0x07F;\r\n cpu.setNZ(value);\r\n // emulator correct fetch-modify-store behavior\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n }),\r\n LSR_A((address, value, addressMode, cpu) -> {\r\n cpu.C = cpu.A & 1;\r\n cpu.A = (cpu.A >> 1) & 0x07F;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n NOP((address, value, addressMode, cpu) -> {\r\n }),\r\n NOP_SPECIAL((address, value, addressMode, cpu) -> {\r\n byte param1 = (byte) (address & 0x0ff);\r\n byte param2 = (byte) (address >> 8);\r\n cpu.performExtendedCommand(param1, param2);\r\n }),\r\n ORA((address, value, addressMode, cpu) -> {\r\n cpu.A |= value;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n PHA((address, value, addressMode, cpu) -> {\r\n cpu.push((byte) cpu.A);\r\n }),\r\n PHP((address, value, addressMode, cpu) -> {\r\n cpu.push((cpu.getStatus()));\r\n }),\r\n PHX((address, value, addressMode, cpu) -> {\r\n cpu.push((byte) cpu.X);\r\n }),\r\n PHY((address, value, addressMode, cpu) -> {\r\n cpu.push((byte) cpu.Y);\r\n }),\r\n PLA((address, value, addressMode, cpu) -> {\r\n cpu.A = 0x0FF & cpu.pop();\r\n cpu.setNZ(cpu.A);\r\n }),\r\n PLP((address, value, addressMode, cpu) -> {\r\n cpu.setStatus(cpu.pop());\r\n }),\r\n PLX((address, value, addressMode, cpu) -> {\r\n cpu.X = 0x0FF & cpu.pop();\r\n cpu.setNZ(cpu.X);\r\n }),\r\n PLY((address, value, addressMode, cpu) -> {\r\n cpu.Y = 0x0FF & cpu.pop();\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n RMB0(new RMBCommand(0)),\r\n RMB1(new RMBCommand(1)),\r\n RMB2(new RMBCommand(2)),\r\n RMB3(new RMBCommand(3)),\r\n RMB4(new RMBCommand(4)),\r\n RMB5(new RMBCommand(5)),\r\n RMB6(new RMBCommand(6)),\r\n RMB7(new RMBCommand(7)),\r\n ROL((address, value, addressMode, cpu) -> {\r\n int oldC = cpu.C;\r\n cpu.C = value >> 7;\r\n value = 0x0ff & ((value << 1) | oldC);\r\n cpu.setNZ(value);\r\n // emulator correct fetch-modify-store behavior\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n }),\r\n ROL_A((address, value, addressMode, cpu) -> {\r\n int oldC = cpu.C;\r\n cpu.C = cpu.A >> 7;\r\n cpu.A = 0x0ff & ((cpu.A << 1) | oldC);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n ROR((address, value, addressMode, cpu) -> {\r\n int oldC = cpu.C << 7;\r\n cpu.C = value & 1;\r\n value = 0x0ff & ((value >> 1) | oldC);\r\n cpu.setNZ(value);\r\n // emulator correct fetch-modify-store behavior\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n cpu.getMemory().write(address, (byte) value, true, false);\r\n }),\r\n ROR_A((address, value, addressMode, cpu) -> {\r\n int oldC = cpu.C << 7;\r\n cpu.C = cpu.A & 1;\r\n cpu.A = 0x0ff & ((cpu.A >> 1) | oldC);\r\n cpu.setNZ(cpu.A);\r\n }),\r\n RTI((address, value, addressMode, cpu) -> {\r\n cpu.returnFromInterrupt();\r\n }),\r\n RTS((address, value, addressMode, cpu) -> {\r\n cpu.setProgramCounter(cpu.popWord() + 1);\r\n }),\r\n SBC((address, value, addressMode, cpu) -> {\r\n cpu.V = ((cpu.A ^ value) & 0x080) != 0;\r\n int w;\r\n if (cpu.D) {\r\n int temp = 0x0f + (cpu.A & 0x0f) - (value & 0x0f) + cpu.C;\r\n if (temp < 0x10) {\r\n w = 0;\r\n temp -= 6;\r\n } else {\r\n w = 0x10;\r\n temp -= 0x10;\r\n }\r\n w += 0x00f0 + (cpu.A & 0x00f0) - (value & 0x00f0);\r\n if (w < 0x100) {\r\n cpu.C = 0;\r\n if (cpu.V && w < 0x080) {\r\n cpu.V = false;\r\n }\r\n w -= 0x60;\r\n } else {\r\n cpu.C = 1;\r\n if (cpu.V && w >= 0x180) {\r\n cpu.V = false;\r\n }\r\n }\r\n w += temp;\r\n } else {\r\n w = 0x0ff + cpu.A - value + cpu.C;\r\n if (w < 0x100) {\r\n cpu.C = 0;\r\n if (cpu.V && (w < 0x080)) {\r\n cpu.V = false;\r\n }\r\n } else {\r\n cpu.C = 1;\r\n if (cpu.V && (w >= 0x180)) {\r\n cpu.V = false;\r\n }\r\n }\r\n }\r\n cpu.A = w & 0x0ff;\r\n cpu.setNZ(cpu.A);\r\n }),\r\n SEC((address, value, addressMode, cpu) -> {\r\n cpu.C = 1;\r\n }),\r\n SED((address, value, addressMode, cpu) -> {\r\n cpu.D = true;\r\n }),\r\n SEI((address, value, addressMode, cpu) -> {\r\n cpu.I = true;\r\n }),\r\n SMB0(new SMBCommand(0)),\r\n SMB1(new SMBCommand(1)),\r\n SMB2(new SMBCommand(2)),\r\n SMB3(new SMBCommand(3)),\r\n SMB4(new SMBCommand(4)),\r\n SMB5(new SMBCommand(5)),\r\n SMB6(new SMBCommand(6)),\r\n SMB7(new SMBCommand(7)),\r\n STA(true, (address, value, addressMode, cpu) -> {\r\n cpu.getMemory().write(address, (byte) cpu.A, true, false);\r\n }),\r\n STP((address, value, addressMode, cpu) -> {\r\n cpu.suspend();\r\n }),\r\n STX(true, (address, value, addressMode, cpu) -> {\r\n cpu.getMemory().write(address, (byte) cpu.X, true, false);\r\n }),\r\n STY(true, (address, value, addressMode, cpu) -> {\r\n cpu.getMemory().write(address, (byte) cpu.Y, true, false);\r\n }),\r\n STZ(true, (address, value, addressMode, cpu) -> {\r\n cpu.getMemory().write(address, (byte) 0, true, false);\r\n }),\r\n TAX((address, value, addressMode, cpu) -> {\r\n cpu.X = cpu.A;\r\n cpu.setNZ(cpu.X);\r\n }),\r\n TAY((address, value, addressMode, cpu) -> {\r\n cpu.Y = cpu.A;\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n TRB((address, value, addressMode, cpu) -> {\r\n cpu.C = (value & cpu.A) != 0 ? 1 : 0;\r\n cpu.getMemory().write(address, (byte) (value & ~cpu.A), true, false);\r\n }),\r\n TSB((address, value, addressMode, cpu) -> {\r\n cpu.C = (value & cpu.A) != 0 ? 1 : 0;\r\n cpu.getMemory().write(address, (byte) (value | cpu.A), true, false);\r\n }),\r\n TSX((address, value, addressMode, cpu) -> {\r\n cpu.X = cpu.STACK;\r\n cpu.setNZ(cpu.STACK);\r\n }),\r\n TXA((address, value, addressMode, cpu) -> {\r\n cpu.A = cpu.X;\r\n cpu.setNZ(cpu.X);\r\n }),\r\n TXS((address, value, addressMode, cpu) -> {\r\n cpu.STACK = cpu.X;\r\n }),\r\n TYA((address, value, addressMode, cpu) -> {\r\n cpu.A = cpu.Y;\r\n cpu.setNZ(cpu.Y);\r\n }),\r\n WAI((address, value, addressMode, cpu) -> {\r\n cpu.waitForInterrupt();\r\n });\r\n private CommandProcessor processor;\r\n\r\n public CommandProcessor getProcessor() {\r\n return processor;\r\n }\r\n private boolean storeOnly;\r\n\r\n public boolean isStoreOnly() {\r\n return storeOnly;\r\n }\r\n\r\n private COMMAND(CommandProcessor processor) {\r\n this(false, processor);\r\n }\r\n\r\n private COMMAND(boolean storeOnly, CommandProcessor processor) {\r\n this.storeOnly = storeOnly;\r\n this.processor = processor;\r\n }\r\n }\r\n static private OPCODE[] opcodes;\r\n\r\n static {\r\n opcodes = new OPCODE[256];\r\n for (OPCODE o : OPCODE.values()) {\r\n opcodes[o.getCode()] = o;\r\n }\r\n }\r\n\r\n @Override\r\n protected void executeOpcode() {\r\n if (interruptSignalled) {\r\n processInterrupt();\r\n }\r\n int pc = getProgramCounter();\r\n\r\n String traceEntry = null;\r\n if (isSingleTraceEnabled() || isTraceEnabled() || isLogEnabled() || warnAboutExtendedOpcodes) {\r\n traceEntry = getState().toUpperCase() + \" \" + Integer.toString(pc, 16) + \" : \" + disassemble();\r\n captureSingleTrace(traceEntry);\r\n if (isTraceEnabled()) {\r\n LOG.log(Level.INFO, traceEntry);\r\n }\r\n if (isLogEnabled()) {\r\n log(traceEntry);\r\n }\r\n }\r\n // This makes it possible to trap the memory read of an opcode, when PC == Address, you know it is executing that opcode.\r\n int op = 0x00ff & getMemory().read(pc, TYPE.EXECUTE, true, false);\r\n OPCODE opcode = opcodes[op];\r\n if (traceEntry != null && warnAboutExtendedOpcodes && opcode != null && opcode.isExtendedOpcode) {\r\n LOG.log(Level.WARNING, \">>EXTENDED OPCODE DETECTED {0}<<\", Integer.toHexString(opcode.code));\r\n LOG.log(Level.WARNING, traceEntry);\r\n if (isLogEnabled()) {\r\n log(\">>EXTENDED OPCODE DETECTED \" + Integer.toHexString(opcode.code) + \"<<\");\r\n log(traceEntry);\r\n }\r\n } \r\n if (opcode == null) {\r\n // handle bad opcode as a NOP\r\n int wait = 0;\r\n int bytes = 2;\r\n int n = op & 0x0f;\r\n switch (n) {\r\n case 2:\r\n wait = 2;\r\n break;\r\n case 3:\r\n case 7:\r\n case 0x0b:\r\n case 0x0f:\r\n wait = 1;\r\n bytes = 1;\r\n break;\r\n case 4:\r\n bytes = 2;\r\n if ((op & 0x0f0) == 0x040) {\r\n wait = 3;\r\n } else {\r\n wait = 4;\r\n } break;\r\n case 0x0c:\r\n bytes = 3;\r\n if ((op & 0x0f0) == 0x050) {\r\n wait = 8;\r\n } else {\r\n wait = 4;\r\n } break;\r\n default:\r\n }\r\n incrementProgramCounter(bytes);\r\n addWaitCycles(wait);\r\n\r\n if (isLogEnabled() || breakOnBadOpcode) {\r\n LOG.log(Level.WARNING, \"Unrecognized opcode {0} at {1}\", new Object[]{Integer.toHexString(op), Integer.toHexString(pc)});\r\n }\r\n if (breakOnBadOpcode) {\r\n OPCODE.BRK.execute(this);\r\n }\r\n } else {\r\n opcode.fetch(this);\r\n incrementProgramCounter(opcode.getMode().getSize());\r\n opcode.execute(this);\r\n addWaitCycles(opcode.getWaitCycles());\r\n }\r\n }\r\n\r\n private void setNZ(int value) {\r\n N = (value & 0x080) != 0;\r\n Z = (value & 0x0ff) == 0;\r\n }\r\n\r\n public void pushWord(int val) {\r\n push((byte) (val >> 8));\r\n push((byte) (val & 0x00ff));\r\n }\r\n\r\n public int popWord() {\r\n return (0x0FF & pop()) | (0x0ff00 & (pop() << 8));\r\n }\r\n\r\n public void push(byte val) {\r\n getMemory().write(0x0100 + STACK, val, true, false);\r\n STACK = (STACK - 1) & 0x0FF;\r\n }\r\n\r\n public byte pop() {\r\n STACK = (STACK + 1) & 0x0FF;\r\n byte val = getMemory().read(0x0100 + STACK, TYPE.READ_DATA, true, false);\r\n return val;\r\n }\r\n\r\n private byte getStatus() {\r\n return (byte) ((N ? 0x080 : 0)\r\n | (V ? 0x040 : 0)\r\n | 0x020\r\n | (B ? 0x010 : 0)\r\n | (D ? 0x08 : 0)\r\n | (I ? 0x04 : 0)\r\n | (Z ? 0x02 : 0)\r\n | ((C > 0) ? 0x01 : 0));\r\n }\r\n\r\n private void setStatus(byte b) {\r\n N = (b & 0x080) != 0;\r\n V = (b & 0x040) != 0;\r\n // B flag is unaffected in this way.\r\n D = (b & 0x08) != 0;\r\n I = (b & 0x04) != 0;\r\n Z = (b & 0x02) != 0;\r\n C = (char) (b & 0x01);\r\n }\r\n\r\n private void returnFromInterrupt() {\r\n setStatus(pop());\r\n setProgramCounter(popWord());\r\n }\r\n\r\n private void waitForInterrupt() {\r\n I = true;\r\n suspend();\r\n }\r\n\r\n @Override\r\n public void JSR(int address) {\r\n pushPC();\r\n setProgramCounter(address);\r\n }\r\n\r\n public void BRK() {\r\n if (isLogEnabled()) {\r\n LOG.log(Level.WARNING, \"BRK at ${0}\", Integer.toString(getProgramCounter(), 16));\r\n dumpTrace();\r\n }\r\n B = true;\r\n // 65c02 clears D flag on BRK\r\n D = false;\r\n interruptSignalled = true;\r\n }\r\n\r\n // Hardware IRQ generated\r\n @Override\r\n public void generateInterrupt() {\r\n B = false;\r\n interruptSignalled = true;\r\n resume();\r\n }\r\n\r\n private void processInterrupt() {\r\n if (!interruptSignalled) {\r\n return;\r\n }\r\n interruptSignalled = false;\r\n if (!I || B) {\r\n I = false;\r\n pushWord(getProgramCounter());\r\n push(getStatus());\r\n I = true;\r\n int newPC = getMemory().readWord(INT_VECTOR, TYPE.READ_DATA, true, false);\r\n// System.out.println(\"Interrupt generated, setting PC to (\" + Integer.toString(INT_VECTOR, 16) + \") = \" + Integer.toString(newPC, 16));\r\n setProgramCounter(newPC);\r\n }\r\n }\r\n\r\n public int getSTACK() {\r\n return STACK;\r\n }\r\n\r\n // Cold/Warm boot procedure\r\n @Override\r\n public void reset() {\r\n pushWord(getProgramCounter());\r\n push(getStatus());\r\n // STACK = 0x0ff;\r\n// B = false;\r\n B = true;\r\n// C = 1;\r\n D = false;\r\n// I = true;\r\n// N = true;\r\n// V = true;\r\n// Z = true;\r\n int newPC = getMemory().readWord(RESET_VECTOR, TYPE.READ_DATA, true, false);\r\n LOG.log(Level.WARNING, \"Reset called, setting PC to ({0}) = {1}\", new Object[]{Integer.toString(RESET_VECTOR, 16), Integer.toString(newPC, 16)});\r\n setProgramCounter(newPC);\r\n }\r\n\r\n @Override\r\n protected String getDeviceName() {\r\n return \"65C02 Processor\";\r\n }\r\n\r\n private static String byte2(int b) {\r\n String out = Integer.toString(b & 0x0FF, 16);\r\n if (out.length() == 1) {\r\n return \"0\" + out;\r\n }\r\n return out;\r\n }\r\n\r\n private static String wordString(int w) {\r\n String out = Integer.toHexString(w);\r\n if (out.length() == 1) {\r\n return \"000\" + out;\r\n }\r\n if (out.length() == 2) {\r\n return \"00\" + out;\r\n }\r\n if (out.length() == 3) {\r\n return \"0\" + out;\r\n }\r\n return out;\r\n }\r\n\r\n public String getState() {\r\n StringBuilder out = new StringBuilder();\r\n out.append(byte2(A)).append(\" \");\r\n out.append(byte2(X)).append(\" \");\r\n out.append(byte2(Y)).append(\" \");\r\n // out += \"PC:\"+wordString(getProgramCounter())+\" \";\r\n out.append(\"01\").append(byte2(STACK)).append(\" \");\r\n out.append(getFlags());\r\n return out.toString();\r\n }\r\n\r\n public String getFlags() {\r\n StringBuilder out = new StringBuilder();\r\n out.append(N ? \"N\" : \".\");\r\n out.append(V ? \"V\" : \".\");\r\n out.append(\"R\");\r\n out.append(B ? \"B\" : \".\");\r\n out.append(D ? \"D\" : \".\");\r\n out.append(I ? \"I\" : \".\");\r\n out.append(Z ? \"Z\" : \".\");\r\n out.append((C != 0) ? \"C\" : \".\");\r\n return out.toString();\r\n }\r\n\r\n public String disassemble() {\r\n int pc = getProgramCounter();\r\n// RAM ram = cpu.getMemory();\r\n int op = getMemory().readRaw(pc);\r\n OPCODE o = opcodes[op & 0x0ff];\r\n if (o == null) {\r\n return \"???\";\r\n }\r\n String format = o.getMode().formatMode(pc, this);\r\n// format = format.replaceAll(\"~1\", byte2(b1));\r\n// format = format.replaceAll(\"~2\", byte2(b2));\r\n// format = format.replaceAll(\"R\", R);\r\n /*\r\n String mem = wordString(pc) + \":\" + byte2(op) + \" \" +\r\n ((o.getMode().getSize() > 1) ?\r\n byte2(b1) : \" \" ) + \" \" +\r\n ((o.getMode().getSize() > 2) ?\r\n byte2(b2) : \" \" ) + \" \";\r\n */\r\n StringBuilder out = new StringBuilder(o.getCommand().toString());\r\n out.append(\" \").append(format);\r\n if (o.getMode().isIndirect()) {\r\n out.append(\" >> $\").append(Integer.toHexString(o.getMode().getCalculator().calculateAddress(this)));\r\n }\r\n return out.toString();\r\n }\r\n private boolean pageBoundaryPenalty = false;\r\n\r\n private void setPageBoundaryPenalty(boolean b) {\r\n pageBoundaryPenalty = b;\r\n }\r\n\r\n @Override\r\n public void pushPC() {\r\n pushWord(getProgramCounter() - 1);\r\n }\r\n\r\n /**\r\n * Special commands -- these are usually treated as NOP but can be reused for emulator controls\r\n * !byte $fc, $65, $00 ; Turn off tracing\r\n * !byte $fc, $65, $01 ; Turn on tracing\r\n * !byte $fc, $50, NN ; print number NN to stdout\r\n * !byte $fc, $5b, NN ; print number NN to stdout with newline\r\n * !byte $fc, $5c, NN ; print character NN to stdout\r\n * @param param1\r\n * @param param2 \r\n */\r\n public void performExtendedCommand(byte param1, byte param2) {\r\n// LOG.log(Level.INFO, \"Extended command {0},{1}\", new Object[]{Integer.toHexString(param1), Integer.toHexString(param2)});\r\n switch (param1 & 0x0ff) {\r\n case 0x50:\r\n // System out\r\n System.out.print(param2 & 0x0ff);\r\n break;\r\n case 0x5b:\r\n // System out (with line break)\r\n System.out.println(param2 & 0x0ff);\r\n break;\r\n case 0x5c:\r\n // System out (with line break)\r\n System.out.println((char) (param2 & 0x0ff)); \r\n break;\r\n case 0x65:\r\n // CPU functions\r\n switch (param2 & 0x0ff) {\r\n case 0x00:\r\n // Turn off tracing\r\n trace = false;\r\n break;\r\n case 0x01:\r\n // Turn on tracing\r\n trace = true;\r\n break;\r\n }\r\n break;\r\n case 0x64:\r\n // Memory functions\r\n getMemory().performExtendedCommand(param2 & 0x0ff);\r\n default:\r\n }\r\n }\r\n}\r", "public abstract class Computer implements Reconfigurable {\n\n public RAM memory;\n public CPU cpu;\n public Video video;\n public Keyboard keyboard;\n public StateManager stateManager;\n public Motherboard motherboard;\n public boolean romLoaded;\n @ConfigurableField(category = \"advanced\", name = \"State management\", shortName = \"rewind\", description = \"This enables rewind support, but consumes a lot of memory when active.\")\n public boolean enableStateManager;\n public final SoundMixer mixer;\n final private BooleanProperty runningProperty = new SimpleBooleanProperty(false);\n\n /**\n * Creates a new instance of Computer\n */\n public Computer() {\n keyboard = new Keyboard(this);\n mixer = new SoundMixer(this);\n romLoaded = false;\n }\n\n public RAM getMemory() {\n return memory;\n }\n\n public Motherboard getMotherboard() {\n return motherboard;\n }\n\n ChangeListener<Boolean> runningPropertyListener = (prop, oldVal, newVal) -> runningProperty.set(newVal);\n public void setMotherboard(Motherboard m) {\n if (motherboard != null && motherboard.isRunning()) {\n motherboard.suspend();\n }\n motherboard = m;\n }\n\n public BooleanProperty getRunningProperty() {\n return runningProperty;\n }\n \n public boolean isRunning() {\n return getRunningProperty().get();\n }\n \n public void notifyVBLStateChanged(boolean state) {\n for (Optional<Card> c : getMemory().cards) {\n c.ifPresent(card -> card.notifyVBLStateChanged(state));\n }\n if (state && stateManager != null) {\n stateManager.notifyVBLActive();\n }\n }\n\n public void setMemory(RAM memory) {\n if (this.memory != memory) {\n if (this.memory != null) {\n this.memory.detach();\n }\n memory.attach();\n }\n this.memory = memory;\n }\n\n public void waitForNextCycle() {\n //@TODO IMPLEMENT TIMER SLEEP CODE!\n }\n\n public Video getVideo() {\n return video;\n }\n\n public void setVideo(Video video) {\n this.video = video;\n }\n\n public CPU getCpu() {\n return cpu;\n }\n\n public void setCpu(CPU cpu) {\n this.cpu = cpu;\n }\n\n public void loadRom(String path) throws IOException {\n memory.loadRom(path);\n romLoaded = true;\n }\n\n public void deactivate() {\n if (cpu != null) {\n cpu.suspend();\n }\n if (motherboard != null) {\n motherboard.suspend();\n }\n if (video != null) {\n video.suspend(); \n }\n if (mixer != null) {\n mixer.detach();\n }\n }\n\n @InvokableAction(\n name = \"Cold boot\",\n description = \"Process startup sequence from power-up\",\n category = \"general\",\n alternatives = \"Full reset;reset emulator\",\n consumeKeyEvent = true,\n defaultKeyMapping = {\"Ctrl+Shift+Backspace\", \"Ctrl+Shift+Delete\"})\n public void invokeColdStart() {\n if (!romLoaded) {\n Thread delayedStart = new Thread(() -> {\n while (!romLoaded) {\n Thread.yield();\n }\n coldStart();\n });\n delayedStart.start();\n } else {\n coldStart();\n }\n }\n\n public abstract void coldStart();\n\n @InvokableAction(\n name = \"Warm boot\",\n description = \"Process user-initatiated reboot (ctrl+apple+reset)\",\n category = \"general\",\n alternatives = \"reboot;reset;three-finger-salute;restart\",\n defaultKeyMapping = {\"Ctrl+Ignore Alt+Ignore Meta+Backspace\", \"Ctrl+Ignore Alt+Ignore Meta+Delete\"})\n public void invokeWarmStart() {\n warmStart();\n }\n\n public abstract void warmStart();\n\n public Keyboard getKeyboard() {\n return this.keyboard;\n }\n\n protected abstract void doPause();\n\n protected abstract void doResume();\n\n @InvokableAction(name = \"Pause\", description = \"Stops the computer, allowing reconfiguration of core elements\", alternatives = \"freeze;halt\", defaultKeyMapping = {\"meta+pause\", \"alt+pause\"})\n public boolean pause() {\n boolean result = getRunningProperty().get();\n doPause();\n getRunningProperty().set(false);\n return result;\n }\n\n @InvokableAction(name = \"Resume\", description = \"Resumes the computer if it was previously paused\", alternatives = \"unpause;unfreeze;resume;play\", defaultKeyMapping = {\"meta+shift+pause\", \"alt+shift+pause\"})\n public void resume() {\n doResume();\n getRunningProperty().set(true);\n }\n\n @Override\n public void reconfigure() {\n mixer.reconfigure();\n if (enableStateManager) {\n stateManager = StateManager.getInstance(this);\n } else {\n stateManager = null;\n StateManager.getInstance(this).invalidate();\n }\n }\n}", "public abstract class RAM implements Reconfigurable {\r\n\r\n public PagedMemory activeRead;\r\n public PagedMemory activeWrite;\r\n public List<RAMListener> listeners;\r\n public List<RAMListener>[] listenerMap;\r\n public List<RAMListener>[] ioListenerMap;\r\n public Optional<Card>[] cards;\r\n // card 0 = 80 column card firmware / system rom\r\n public int activeSlot = 0;\r\n protected final Computer computer;\r\n\r\n /**\r\n * Creates a new instance of RAM\r\n *\r\n * @param computer\r\n */\r\n public RAM(Computer computer) {\r\n this.computer = computer;\r\n listeners = new ArrayList<>();\r\n cards = new Optional[8];\r\n for (int i = 0; i < 8; i++) {\r\n cards[i] = Optional.empty();\r\n }\r\n refreshListenerMap();\r\n }\r\n\r\n public void setActiveCard(int slot) {\r\n if (activeSlot != slot) {\r\n activeSlot = slot;\r\n configureActiveMemory();\r\n } else if (!SoftSwitches.CXROM.getState()) {\r\n configureActiveMemory();\r\n }\r\n }\r\n\r\n public int getActiveSlot() {\r\n return activeSlot;\r\n }\r\n\r\n public Optional<Card>[] getAllCards() {\r\n return cards;\r\n }\r\n\r\n public Optional<Card> getCard(int slot) {\r\n if (slot >= 1 && slot <= 7) {\r\n return cards[slot];\r\n }\r\n return Optional.empty();\r\n }\r\n\r\n public void addCard(Card c, int slot) {\r\n removeCard(slot);\r\n cards[slot] = Optional.of(c);\r\n c.setSlot(slot);\r\n c.attach();\r\n }\r\n\r\n public void removeCard(Card c) {\r\n c.suspend();\r\n c.detach();\r\n removeCard(c.getSlot());\r\n }\r\n\r\n public void removeCard(int slot) {\r\n cards[slot].ifPresent(Card::suspend);\r\n cards[slot].ifPresent(Card::detach);\r\n cards[slot] = Optional.empty();\r\n }\r\n\r\n abstract public void configureActiveMemory();\r\n\r\n public void write(int address, byte b, boolean generateEvent, boolean requireSynchronization) {\r\n byte[] page = activeWrite.getMemoryPage(address);\r\n if (page == null) {\r\n if (generateEvent) {\r\n callListener(RAMEvent.TYPE.WRITE, address, 0, b, requireSynchronization);\r\n }\r\n } else {\r\n int offset = address & 0x0FF;\r\n byte old = page[offset];\r\n if (generateEvent) {\r\n page[offset] = callListener(RAMEvent.TYPE.WRITE, address, old, b, requireSynchronization);\r\n } else {\r\n page[offset] = b;\r\n }\r\n }\r\n }\r\n\r\n public void writeWord(int address, int w, boolean generateEvent, boolean requireSynchronization) {\r\n write(address, (byte) (w & 0x0ff), generateEvent, requireSynchronization);\r\n write(address + 1, (byte) (w >> 8), generateEvent, requireSynchronization);\r\n }\r\n \r\n public byte readRaw(int address) {\r\n // if (address >= 65536) return 0;\r\n return activeRead.getMemoryPage(address)[address & 0x0FF];\r\n }\r\n\r\n public byte read(int address, RAMEvent.TYPE eventType, boolean triggerEvent, boolean requireSyncronization) {\r\n // if (address >= 65536) return 0;\r\n byte value = activeRead.getMemoryPage(address)[address & 0x0FF];\r\n// if (triggerEvent || ((address & 0x0FF00) == 0x0C000)) {\r\n if (triggerEvent || (address & 0x0FFF0) == 0x0c030) {\r\n value = callListener(eventType, address, value, value, requireSyncronization);\r\n }\r\n return value;\r\n }\r\n\r\n public int readWordRaw(int address) {\r\n int lsb = 0x00ff & readRaw(address);\r\n int msb = (0x00ff & readRaw(address + 1)) << 8;\r\n return msb + lsb;\r\n }\r\n\r\n public int readWord(int address, RAMEvent.TYPE eventType, boolean triggerEvent, boolean requireSynchronization) {\r\n int lsb = 0x00ff & read(address, eventType, triggerEvent, requireSynchronization);\r\n int msb = (0x00ff & read(address + 1, eventType, triggerEvent, requireSynchronization)) << 8;\r\n int value = msb + lsb;\r\n return value;\r\n }\r\n\r\n private void mapListener(RAMListener l, int address) {\r\n if ((address & 0x0FF00) == 0x0C000) {\r\n int index = address & 0x0FF;\r\n List<RAMListener> ioListeners = ioListenerMap[index];\r\n if (ioListeners == null) {\r\n ioListeners = new ArrayList<>();\r\n ioListenerMap[index] = ioListeners;\r\n }\r\n if (!ioListeners.contains(l)) {\r\n ioListeners.add(l);\r\n }\r\n } else {\r\n int index = address >> 8;\r\n List<RAMListener> otherListeners = listenerMap[index];\r\n if (otherListeners == null) {\r\n otherListeners = new ArrayList<>();\r\n listenerMap[index] = otherListeners;\r\n }\r\n if (!otherListeners.contains(l)) {\r\n otherListeners.add(l);\r\n }\r\n }\r\n }\r\n\r\n private void addListenerRange(RAMListener l) {\r\n if (l.getScope() == RAMEvent.SCOPE.ADDRESS) {\r\n mapListener(l, l.getScopeStart());\r\n } else {\r\n int start = 0;\r\n int end = 0x0ffff;\r\n if (l.getScope() == RAMEvent.SCOPE.RANGE) {\r\n start = l.getScopeStart();\r\n end = l.getScopeEnd();\r\n }\r\n for (int i = start; i <= end; i++) {\r\n mapListener(l, i);\r\n }\r\n }\r\n }\r\n\r\n private void refreshListenerMap() {\r\n listenerMap = new ArrayList[256];\r\n ioListenerMap = new ArrayList[256];\r\n listeners.stream().forEach((l) -> {\r\n addListenerRange(l);\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int address, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(address);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n handler.handleEvent(e);\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int address, boolean auxFlag, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(address);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n if (isAuxFlagCorrect(e, auxFlag)) {\r\n handler.handleEvent(e);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int addressStart, int addressEnd, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.RANGE, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(addressStart);\r\n setScopeEnd(addressEnd);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n handler.handleEvent(e);\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int addressStart, int addressEnd, boolean auxFlag, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.RANGE, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(addressStart);\r\n setScopeEnd(addressEnd);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n if (isAuxFlagCorrect(e, auxFlag)) {\r\n handler.handleEvent(e);\r\n }\r\n }\r\n });\r\n }\r\n\r\n private boolean isAuxFlagCorrect(RAMEvent e, boolean auxFlag) {\r\n if (e.getAddress() < 0x0100) {\r\n if (SoftSwitches.AUXZP.getState() != auxFlag) {\r\n return false;\r\n }\r\n } else if (SoftSwitches.RAMRD.getState() != auxFlag) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n public RAMListener addListener(final RAMListener l) {\r\n boolean restart = computer.pause();\r\n if (listeners.contains(l)) {\r\n return l;\r\n }\r\n listeners.add(l);\r\n addListenerRange(l);\r\n if (restart) {\r\n computer.resume();\r\n }\r\n return l;\r\n }\r\n\r\n public void removeListener(final RAMListener l) {\r\n boolean restart = computer.pause();\r\n listeners.remove(l);\r\n refreshListenerMap();\r\n if (restart) {\r\n computer.resume();\r\n }\r\n }\r\n\r\n public byte callListener(RAMEvent.TYPE t, int address, int oldValue, int newValue, boolean requireSyncronization) {\r\n List<RAMListener> activeListeners;\r\n if (requireSyncronization) {\r\n computer.getCpu().suspend();\r\n }\r\n if ((address & 0x0FF00) == 0x0C000) {\r\n activeListeners = ioListenerMap[address & 0x0FF];\r\n if (activeListeners == null && t.isRead()) {\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return computer.getVideo().getFloatingBus();\r\n }\r\n } else {\r\n activeListeners = listenerMap[(address >> 8) & 0x0ff];\r\n }\r\n if (activeListeners != null) {\r\n RAMEvent e = new RAMEvent(t, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY, address, oldValue, newValue);\r\n activeListeners.stream().forEach((l) -> {\r\n l.handleEvent(e);\r\n });\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return (byte) e.getNewValue();\r\n }\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return (byte) newValue;\r\n }\r\n\r\n abstract protected void loadRom(String path) throws IOException;\r\n\r\n abstract public void attach();\r\n\r\n abstract public void detach();\r\n\r\n abstract public void performExtendedCommand(int i);\r\n}\r", "public abstract class ProdosDriver {\n Computer computer;\n\n public ProdosDriver(Computer computer) {\n this.computer = computer;\n }\n \n public static int MLI_COMMAND = 0x042;\n public static int MLI_UNITNUMBER = 0x043;\n public static int MLI_BUFFER_ADDRESS = 0x044;\n public static int MLI_BLOCK_NUMBER = 0x046;\n \n public static enum MLI_RETURN {\n NO_ERROR(0), IO_ERROR(0x027), NO_DEVICE(0x028), WRITE_PROTECTED(0x02B);\n public int intValue;\n\n MLI_RETURN(int val) {\n intValue = val;\n }\n }\n\n public static enum MLI_COMMAND_TYPE {\n STATUS(0x0), READ(0x01), WRITE(0x02), FORMAT(0x03);\n public int intValue;\n\n MLI_COMMAND_TYPE(int val) {\n intValue = val;\n }\n\n public static MLI_COMMAND_TYPE fromInt(int value) {\n for (MLI_COMMAND_TYPE c : values()) {\n if (c.intValue == value) {\n return c;\n }\n }\n return null;\n }\n }\n\n abstract public boolean changeUnit(int unitNumber);\n abstract public int getSize();\n abstract public boolean isWriteProtected();\n abstract public void mliFormat() throws IOException;\n abstract public void mliRead(int block, int bufferAddress) throws IOException;\n abstract public void mliWrite(int block, int bufferAddress) throws IOException;\n abstract public Card getOwner();\n \n public void handleMLI() {\n int returnCode = prodosMLI().intValue;\n MOS65C02 cpu = (MOS65C02) computer.getCpu();\n cpu.A = returnCode;\n // Clear carry flag if no error, otherwise set carry flag\n cpu.C = (returnCode == 0x00) ? 00 : 01;\n }\n \n private MLI_RETURN prodosMLI() {\n try {\n RAM memory = computer.getMemory();\n int cmd = memory.readRaw(MLI_COMMAND);\n MLI_COMMAND_TYPE command = MLI_COMMAND_TYPE.fromInt(cmd);\n int unit = (memory.readWordRaw(MLI_UNITNUMBER) & 0x080) > 0 ? 1 : 0;\n if (changeUnit(unit) == false) {\n return MLI_RETURN.NO_DEVICE;\n }\n int block = memory.readWordRaw(MLI_BLOCK_NUMBER);\n int bufferAddress = memory.readWordRaw(MLI_BUFFER_ADDRESS);\n// System.out.println(getOwner().getName()+\" MLI Call \"+command+\", unit \"+unit+\" Block \"+block+\" --> \"+Integer.toHexString(bufferAddress));\n if (command == null) {\n System.out.println(getOwner().getName()+\" Mass storage given bogus command (\" + Integer.toHexString(cmd) + \"), returning I/O error\");\n return MLI_RETURN.IO_ERROR;\n }\n switch (command) {\n case STATUS:\n int blocks = getSize();\n MOS65C02 cpu = (MOS65C02) computer.getCpu();\n cpu.X = blocks & 0x0ff;\n cpu.Y = (blocks >> 8) & 0x0ff;\n if (isWriteProtected()) {\n return MLI_RETURN.WRITE_PROTECTED;\n }\n break;\n case FORMAT:\n mliFormat();\n case READ:\n mliRead(block, bufferAddress);\n break;\n case WRITE:\n mliWrite(block, bufferAddress);\n break;\n default:\n System.out.println(getOwner().getName()+\" MLI given bogus command (\" + Integer.toHexString(cmd) + \" = \" + command.name() + \"), returning I/O error\");\n return MLI_RETURN.IO_ERROR;\n }\n return MLI_RETURN.NO_ERROR;\n } catch (UnsupportedOperationException ex) {\n return MLI_RETURN.WRITE_PROTECTED;\n } catch (IOException ex) {\n System.out.println(getOwner().getName()+\" Encountered IO Error, returning error: \" + ex.getMessage());\n return MLI_RETURN.IO_ERROR;\n }\n }\n}", "public static enum MLI_COMMAND_TYPE {\n STATUS(0x0), READ(0x01), WRITE(0x02), FORMAT(0x03);\n public int intValue;\n\n MLI_COMMAND_TYPE(int val) {\n intValue = val;\n }\n\n public static MLI_COMMAND_TYPE fromInt(int value) {\n for (MLI_COMMAND_TYPE c : values()) {\n if (c.intValue == value) {\n return c;\n }\n }\n return null;\n }\n}" ]
import jace.Emulator; import jace.EmulatorUILogic; import jace.apple2e.MOS65C02; import jace.core.Computer; import jace.core.RAM; import static jace.hardware.ProdosDriver.*; import jace.hardware.ProdosDriver.MLI_COMMAND_TYPE; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2012 Brendan Robert (BLuRry) [email protected]. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package jace.hardware.massStorage; /** * Representation of a Prodos Volume which maps to a physical folder on the * actual hard drive. This is used by CardMassStorage in the event the disk path * is a folder and not a disk image. FreespaceBitmap and the various Node * classes are used to represent the filesystem structure. * * @author Brendan Robert (BLuRry) [email protected] */ public class ProdosVirtualDisk implements IDisk { public static final int VOLUME_START = 2; public static final int FREESPACE_BITMAP_START = 6; byte[] ioBuffer; File physicalRoot; private final DiskNode[] physicalMap; DirectoryNode rootDirectory; FreespaceBitmap freespaceBitmap; public ProdosVirtualDisk(File rootPath) throws IOException { ioBuffer = new byte[BLOCK_SIZE]; physicalMap = new DiskNode[MAX_BLOCK]; initDiskStructure(); setPhysicalPath(rootPath); } @Override
public void mliRead(int block, int bufferAddress, RAM memory) throws IOException {
4
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/component/ViewModelComponent.java
[ "@Module\npublic class ViewModelModule {\n @Provides\n StoryListViewModel providesStoryListViewModel() {\n return new StoryListViewModel();\n }\n\n @Provides\n StoryDetailViewModel providesStoryDetailViewModel() {\n return new StoryDetailViewModel();\n }\n\n @Provides\n LoginViewModel providesLoginViewModel() {\n return new LoginViewModel();\n }\n\n @Provides\n MainViewModel providesMainViewModel(@Named(\"resources\") Resources resources) {\n return new MainViewModel(resources);\n }\n\n @Provides\n AboutViewModel providesAboutViewModel(){\n return new AboutViewModel();\n }\n}", "public class AboutActivity extends BaseActivity{\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_about);\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n if(toolbar !=null){\n toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));\n toolbar.setNavigationOnClickListener(v -> finish());\n setSupportActionBar(toolbar);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n }\n if (savedInstanceState == null) {\n getSupportFragmentManager().beginTransaction()\n .add(R.id.container, AboutFragment.newInstance())\n .commit();\n }\n }\n\n public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> {\n @Inject AboutViewModel mViewModel;\n @InjectView(R.id.recycler_view) RecyclerView mRecyclerView;\n\n public static Fragment newInstance() {\n return new AboutFragment();\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_about, container, false);\n ButterKnife.inject(this, view);\n DaggerViewModelComponent.builder()\n .appComponent(HackerNewsApplication.getAppComponent())\n .build()\n .inject(this);\n\n mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));\n AboutAdapter aboutAdapter = new AboutAdapter();\n mRecyclerView.setAdapter(aboutAdapter);\n aboutAdapter.addHeader();\n for (AboutLicense license : getViewModel().getLicenses()) {\n aboutAdapter.addLicense(license);\n }\n\n return view;\n }\n\n @Override\n protected AboutViewModel getViewModel() {\n return mViewModel;\n }\n }\n}", "public class LoginActivity extends BaseViewModelActivity<LoginViewModel> {\n\n public static final String LOGIN_SUCCESS = \"login-success\";\n public static final String LOGOUT = \"logout\";\n private static final String TAG = LoginActivity.class.getSimpleName();\n @InjectView(R.id.username) EditText mUsername;\n @InjectView(R.id.password) EditText mPassword;\n @InjectView(R.id.login_button_with_progress) CircularProgressButton mLoginButton;\n\n @Inject LoginViewModel mViewModel;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_login);\n DaggerViewModelComponent.builder()\n .appComponent(HackerNewsApplication.getAppComponent())\n .build()\n .inject(this);\n ButterKnife.inject(this);\n\n // Creates Observables from the EditTexts and enables the login button if they aren't empty\n final Observable<Boolean> userNameObservable = RxTextView.textChanges(mUsername)\n .map(charSequence -> !TextUtils.isEmpty(charSequence));\n final Observable<Boolean> passwordObservable = RxTextView.textChanges(mPassword)\n .map(charSequence-> !TextUtils.isEmpty(charSequence));\n Observable.combineLatest(userNameObservable, passwordObservable,\n (usernameFilled, passwordFilled) -> usernameFilled && passwordFilled)\n .subscribe(fieldsFilled -> {\n mLoginButton.setProgress(0);\n mLoginButton.setEnabled(fieldsFilled);\n });\n\n RxView.clicks(mLoginButton)\n .subscribe(button -> {\n mLoginButton.setIndeterminateProgressMode(true);\n mLoginButton.setProgress(50);\n getViewModel().login(mUsername.getText().toString(), mPassword.getText().toString())\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<User>() {\n @Override\n public void onCompleted() {\n LocalBroadcastManager.getInstance(LoginActivity.this)\n .sendBroadcast(new Intent(LOGIN_SUCCESS));\n LoginActivity.this.finish();\n }\n\n @Override\n public void onError(Throwable e) {\n UIUtils.showToast(LoginActivity.this, \"Something went wrong!\");\n mLoginButton.setProgress(-1);\n }\n\n @Override\n public void onNext(User user) {\n if (user == null) {\n mLoginButton.setProgress(-1);\n }\n else {\n mLoginButton.setProgress(100);\n }\n }\n });\n });\n if (BuildConfig.DEBUG) {\n mUsername.setText(\"testerCookie\");\n }\n }\n\n @Override\n protected LoginViewModel getViewModel() {\n return mViewModel;\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n }\n}", "public class StoryDetailFragment extends BaseViewModelFragment<StoryDetailViewModel> implements ObservableWebView.OnScrollChangedCallback {\n public static final String HACKER_NEWS_ITEM_BASE_URL = \"https://news.ycombinator.com/item?id=\";\n public static final String HACKER_NEWS_BASE_URL = \"https://news.ycombinator.com/\";\n public static final String LINK_DRAWER_OPEN = \"LINK_DRAWER_OPEN\";\n public static final String TOP_VISIBLE_COMMENT = \"TOP_VISIBLE_COMMENT\";\n public static final String LOADING_FROM_SAVED = \"LOADING_FROM_SAVED\";\n private static final String STORY_ID = \"story_id\";\n private static final String TAG = StoryDetailFragment.class.getSimpleName();\n @InjectView(R.id.button_bar) RelativeLayout mButtonBar;\n @InjectView(R.id.action_1) Button mButtonBarAction1;\n @InjectView(R.id.action_main) Button mButtonBarMainAction;\n @InjectView(R.id.action_2) Button mButtonBarAction2;\n @InjectView(R.id.swipe_container) SwipeRefreshLayout mSwipeRefreshLayout;\n @InjectView(R.id.comments_recycler) RecyclerView mCommentsRecyclerView;\n @InjectView(R.id.story_web_view) ObservableWebView mWebView;\n @InjectView(R.id.link_layout) RelativeLayout mLinkLayout;\n @InjectView(R.id.fabbutton) FloatingActionButton mFloatingActionButton;\n @InjectView(R.id.saved_banner) TextView mSavedBanner;\n @InjectView(R.id.link_panel) SlidingUpPanelLayout mSlidingUpPanelLayout;\n @InjectView(R.id.web_progress_bar) ProgressBar mWebProgressBar;\n @Inject StoryDetailViewModel mViewModel;\n private Bundle mWebViewBundle;\n private SlidingUpPanelLayout.PanelState mOldPanelState;\n private StoryDetailRecyclerAdapter mAdapter;\n private int mCurrentFirstCompletelyVisibleItemIndex = 0;\n private LinearLayoutManager mLayoutManager;\n\n public static StoryDetailFragment newInstance(long id, boolean saved) {\n StoryDetailFragment fragment = StoryDetailFragment.newInstance(id);\n Bundle args = fragment.getArguments();\n args.putBoolean(LOADING_FROM_SAVED, saved);\n fragment.setArguments(args);\n return fragment;\n }\n\n public static StoryDetailFragment newInstance(long param1) {\n StoryDetailFragment fragment = new StoryDetailFragment();\n Bundle args = new Bundle();\n args.putLong(STORY_ID, param1);\n fragment.setArguments(args);\n return fragment;\n }\n\n private void refresh() {\n showProgress(true);\n mSubscription = getViewModel().getStoryDetailObservable()\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<StoryDetail>() {\n @Override\n public void onCompleted() {\n showProgress(false);\n mSwipeRefreshLayout.setRefreshing(false);\n }\n\n @Override\n public void onError(Throwable e) {\n Toast.makeText(getActivity(), R.string.story_details_error_toast_message, Toast.LENGTH_SHORT).show();\n if (HackerNewsApplication.isDebug()) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onNext(StoryDetail storyDetail) {\n updateHeader(storyDetail);\n updateSlidingPanel(getViewModel().startDrawerExpanded());\n updateRecyclerView(storyDetail);\n openLink(storyDetail);\n }\n });\n }\n\n private void updateRecyclerView(StoryDetail storyDetail) {\n mAdapter.clear();\n for (Comment comment : storyDetail.getCommentList()) {\n mAdapter.addComment(comment);\n }\n }\n\n private void updateHeader(StoryDetail storyDetail) {\n mAdapter.updateHeader(storyDetail);\n }\n\n private void openLink(StoryDetail storyDetail) {\n if (UserPreferenceManager.getInstance().showLinkFirst() && UserPreferenceManager.getInstance().isExternalBrowserEnabled()) {\n openLinkInExternalBrowser();\n }\n else {\n if (mWebViewBundle == null && !UserPreferenceManager.getInstance().isExternalBrowserEnabled()) {\n mWebView.loadUrl(storyDetail.getUrl());\n }\n else {\n mWebView.restoreState(mWebViewBundle);\n }\n }\n }\n\n private void openLinkInExternalBrowser() {\n Intent browserIntent = new Intent();\n browserIntent.setAction(Intent.ACTION_VIEW);\n browserIntent.setData(Uri.parse(getViewModel().getStoryDetail().getUrl()));\n startActivity(browserIntent);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n DaggerViewModelComponent.builder()\n .appComponent(HackerNewsApplication.getAppComponent())\n .build()\n .inject(this);\n\n if (getArguments() != null) {\n if (getArguments().containsKey(STORY_ID)) {\n long storyId = getArguments().getLong(STORY_ID);\n getViewModel().setStoryId(storyId);\n }\n\n if (getArguments().containsKey(LOADING_FROM_SAVED)) {\n getViewModel().setLoadFromSaved(getArguments().getBoolean(LOADING_FROM_SAVED));\n }\n }\n setHasOptionsMenu(true);\n }\n\n @SuppressLint(\"SetJavaScriptEnabled\")\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.fragment_story_comments, container, false);\n if (savedInstanceState != null) {\n mOldPanelState = (SlidingUpPanelLayout.PanelState) savedInstanceState.getSerializable(LINK_DRAWER_OPEN);\n }\n ButterKnife.inject(this, rootView);\n mContainer = rootView.findViewById(R.id.container);\n mProgressBar = (ProgressBar) rootView.findViewById(R.id.progress_bar);\n mFloatingActionButton.setOnClickListener(view -> readability());\n mSavedBanner.setVisibility(getViewModel().isSaved() ? View.VISIBLE : View.GONE);\n setupWebViewDrawer();\n\n ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();\n if (actionBar != null) {\n actionBar.show();\n actionBar.setTitle(getString(R.string.app_name));\n }\n\n\n mAdapter = new StoryDetailRecyclerAdapter(getActivity(), new StoryDetailRecyclerAdapter.StoryDetailRecyclerListener() {\n @Override\n public void onCommentClicked(int position) {\n if (mAdapter.areChildrenHidden(position)) {\n mAdapter.showChildComments(position);\n }\n else {\n mAdapter.hideChildComments(position);\n }\n }\n\n @Override\n public void onCommentActionClicked(Comment comment) {\n final CharSequence[] commentActions = getResources().getStringArray(getViewModel().getCommentActions());\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setItems(commentActions, (dialogInterface, j) -> {\n Intent sendIntent = new Intent();\n sendIntent.setAction(Intent.ACTION_SEND);\n switch (j) {\n case 0:\n sendIntent.putExtra(Intent.EXTRA_TEXT,\n String.format(\"https://news.ycombinator.com/item?id=%d\", comment.getCommentId()));\n break;\n case 1:\n sendIntent.putExtra(Intent.EXTRA_TEXT,\n String.format(\"%s: %s\", comment.getUser(), Html.fromHtml(comment.getContent())));\n break;\n case 2:\n AlertDialog.Builder replyDialog = new AlertDialog.Builder(getActivity())\n .setTitle(getString(R.string.action_reply));\n AppCompatEditText editText = new AppCompatEditText(getActivity());\n replyDialog.setView(editText)\n .setPositiveButton(getString(R.string.action_submit), (dialog, which) -> {\n ProgressDialog progressDialog = new ProgressDialog(getActivity());\n progressDialog.setMessage(getString(R.string.submitting_progress));\n progressDialog.setCancelable(false);\n progressDialog.show();\n getViewModel().reply(comment, editText.getText().toString())\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<Object>() {\n @Override\n public void onCompleted() {\n progressDialog.dismiss();\n }\n\n @Override\n public void onError(Throwable e) {\n progressDialog.dismiss();\n }\n\n @Override\n public void onNext(Object o) {\n\n }\n });\n dialog.dismiss();\n })\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n dialogInterface.dismiss();\n return;\n case 3:\n getViewModel().upvote(comment)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<Object>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Object o) {\n\n }\n });\n return;\n }\n sendIntent.setType(\"text/plain\");\n getActivity().startActivity(sendIntent);\n });\n\n builder.create().show();\n }\n });\n mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);\n mCommentsRecyclerView.setLayoutManager(mLayoutManager);\n mCommentsRecyclerView.setAdapter(mAdapter);\n mCommentsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n mCurrentFirstCompletelyVisibleItemIndex = mLayoutManager.findFirstVisibleItemPosition();\n }\n });\n\n mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_dark,\n android.R.color.holo_orange_light,\n android.R.color.holo_orange_dark,\n android.R.color.holo_orange_light);\n mSwipeRefreshLayout.setOnRefreshListener(() -> {\n mSwipeRefreshLayout.setRefreshing(true);\n refresh();\n });\n\n refresh();\n return rootView;\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n if (savedInstanceState != null) {\n mWebViewBundle = savedInstanceState;\n mWebView.restoreState(mWebViewBundle);\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n mWebView.saveState(outState);\n outState.putSerializable(LINK_DRAWER_OPEN, mSlidingUpPanelLayout.getPanelState());\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n ButterKnife.reset(this);\n }\n\n @Override\n public void onDestroy() {\n if (mSubscription != null) mSubscription.unsubscribe();\n if(mWebView != null) {\n mWebView.destroy();\n }\n super.onDestroy();\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n super.onCreateOptionsMenu(menu, inflater);\n inflater.inflate(R.menu.menu_story_detail, menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.action_share:\n final CharSequence[] shareItems = {getString(R.string.action_share_link), getString(R.string.action_share_comments)};\n new AlertDialog.Builder(getActivity())\n .setItems(shareItems, (dialogInterface, i) -> {\n Intent sendIntent = new Intent();\n sendIntent.setAction(Intent.ACTION_SEND);\n switch (i) {\n case 0:\n if(getViewModel().getStoryDetail().getUrl() != null) {\n sendIntent.setData(Uri.parse(getViewModel().getStoryDetail().getUrl()));\n }\n else {\n ToastUtils.showToast(getActivity(), R.string.open_in_browser_failure_toast);\n }\n break;\n case 1:\n sendIntent.putExtra(Intent.EXTRA_TEXT, HACKER_NEWS_ITEM_BASE_URL + getViewModel().getStoryId());\n break;\n }\n sendIntent.setType(\"text/plain\");\n startActivity(sendIntent);\n })\n .create()\n .show();\n break;\n case R.id.action_open_browser:\n final CharSequence[] openInBrowserItems = {getString(R.string.action_open_in_browser_link),\n getString(R.string.action_open_in_browser_comments)};\n new AlertDialog.Builder(getActivity())\n .setItems(openInBrowserItems, (dialogInterface, i) -> {\n Intent browserIntent = new Intent();\n browserIntent.setAction(Intent.ACTION_VIEW);\n switch (i){\n case 0:\n if(getViewModel().getStoryDetail().getUrl() != null) {\n browserIntent.setData(Uri.parse(getViewModel().getStoryDetail().getUrl()));\n }\n break;\n case 1:\n browserIntent.setData(Uri.parse(HACKER_NEWS_ITEM_BASE_URL + getViewModel().getStoryId()));\n break;\n }\n if(browserIntent.getData() != null) {\n try {\n startActivity(browserIntent);\n } catch(ActivityNotFoundException e){\n ToastUtils.showToast(getActivity(), R.string.open_in_browser_error);\n }\n }\n else {\n ToastUtils.showToast(getActivity(), R.string.open_in_browser_error);\n }\n })\n .create()\n .show();\n break;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n protected StoryDetailViewModel getViewModel() {\n return mViewModel;\n }\n\n @Override\n public void onPause() {\n super.onPause();\n mWebViewBundle = new Bundle();\n mWebView.saveState(mWebViewBundle);\n }\n\n private void updateSlidingPanel(boolean expanded) {\n if (getViewModel().useExternalBrowser()) {\n mSlidingUpPanelLayout.setTouchEnabled(false);\n }\n mButtonBarMainAction.setOnClickListener(v -> {\n if (getViewModel().useExternalBrowser()) {\n openLinkInExternalBrowser();\n }\n else {\n mSlidingUpPanelLayout.setPanelState(mSlidingUpPanelLayout.getPanelState()\n .equals(SlidingUpPanelLayout.PanelState.COLLAPSED) ? SlidingUpPanelLayout.PanelState.EXPANDED\n : SlidingUpPanelLayout.PanelState.COLLAPSED);\n }\n });\n mSlidingUpPanelLayout.post(() -> {\n\n if (expanded) {\n mButtonBarMainAction.setText(getString(R.string.show_comments));\n mButtonBarAction1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_arrow_back));\n mButtonBarAction1.setOnClickListener(view -> {\n if (mWebView.canGoBack()) {\n mWebView.goBack();\n }\n });\n mButtonBarAction2.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_arrow_forward));\n mButtonBarAction2.setOnClickListener(view -> {\n if (mWebView.canGoForward()) {\n mWebView.goForward();\n }\n });\n }\n else {\n mButtonBarMainAction.setText(getString(R.string.show_link));\n mButtonBarAction1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_keyboard_arrow_up));\n mButtonBarAction1.setOnClickListener(view -> {\n for (int i = mCurrentFirstCompletelyVisibleItemIndex - 1; i >= 0; i--) {\n final Object item = mAdapter.getItem(i);\n if (item instanceof Comment && ((Comment) item).getLevel() == 0) {\n HNLog.d(TAG, String.valueOf(i));\n mCurrentFirstCompletelyVisibleItemIndex = i;\n mLayoutManager.scrollToPositionWithOffset(i, 0);\n if(HackerNewsApplication.isDebug()) UIUtils.showToast(getActivity(), String.valueOf(i));\n return;\n }\n }\n });\n mButtonBarAction2.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_keyboard_arrow_down));\n mButtonBarAction2.setOnClickListener(view -> {\n for (int i = mCurrentFirstCompletelyVisibleItemIndex + 1; i < mAdapter.getItemCount(); i++) {\n final Object item = mAdapter.getItem(i);\n if (item instanceof Comment && ((Comment) item).getLevel() == 0) {\n HNLog.d(TAG, String.valueOf(i));\n mCurrentFirstCompletelyVisibleItemIndex = i;\n mLayoutManager.scrollToPositionWithOffset(i, 0);\n if(HackerNewsApplication.isDebug()) UIUtils.showToast(getActivity(), String.valueOf(i));\n return;\n }\n }\n });\n\n mButtonBarAction1.setVisibility(View.VISIBLE);\n mButtonBarAction2.setVisibility(View.VISIBLE);\n }\n });\n\n }\n\n @SuppressLint(\"SetJavaScriptEnabled\")\n private void setupWebViewDrawer() {\n mSlidingUpPanelLayout.setDragView(mButtonBar);\n mSlidingUpPanelLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {\n @Override\n public void onPanelSlide(View view, float v) {\n\n }\n\n @Override\n public void onPanelCollapsed(View panelView) {\n updateSlidingPanel(false);\n }\n\n @Override\n public void onPanelExpanded(View panelView) {\n updateSlidingPanel(true);\n }\n\n @Override\n public void onPanelAnchored(View view) {\n\n }\n\n @Override\n public void onPanelHidden(View view) {\n\n }\n });\n if (!UserPreferenceManager.getInstance().isExternalBrowserEnabled()) {\n if (mOldPanelState == SlidingUpPanelLayout.PanelState.EXPANDED || (UserPreferenceManager.getInstance().showLinkFirst())) {\n mButtonBarMainAction.setText(getResources().getString(R.string.show_comments));\n mSlidingUpPanelLayout.postDelayed(() -> mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED), getResources().getInteger(R.integer.fragment_animation_times));\n }\n else {\n mButtonBarMainAction.setText(getResources().getString(R.string.show_link));\n mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);\n }\n }\n\n mWebProgressBar.setVisibility(View.VISIBLE);\n mWebProgressBar.setMax(100);\n\n WebSettings webSettings = mWebView.getSettings();\n webSettings.setLoadWithOverviewMode(true);\n webSettings.setUseWideViewPort(true);\n webSettings.setSupportZoom(true);\n webSettings.setBuiltInZoomControls(true);\n webSettings.setDisplayZoomControls(false);\n webSettings.setJavaScriptEnabled(true);\n mWebView.setWebViewClient(new WebViewClient() {\n @Override\n public void onPageFinished(WebView view, String url) {\n super.onPageFinished(view, url);\n if (mWebProgressBar != null) {\n mWebProgressBar.setVisibility(View.GONE);\n }\n }\n });\n mWebView.setWebChromeClient(new WebChromeClient() {\n @Override\n public void onProgressChanged(WebView view, int newProgress) {\n super.onProgressChanged(view, newProgress);\n if (mWebProgressBar != null) {\n if (mWebProgressBar.getVisibility() == View.GONE) {\n mWebProgressBar.setVisibility(View.VISIBLE);\n }\n mWebProgressBar.setProgress(newProgress);\n }\n }\n });\n\n mWebView.setOnScrollChangedCallback(this);\n }\n\n public boolean isLinkViewVisible() {\n return mSlidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED;\n }\n\n public void hideLinkView() {\n mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);\n }\n\n private void readability() {\n getViewModel().setIsViewingReadability(!getViewModel().isViewingReadability());\n if (getViewModel().isViewingReadability()) {\n if (getViewModel().getReadabilityUrl() != null) {\n mWebView.loadUrl(getViewModel().getReadabilityUrl());\n }\n }\n else {\n mWebView.loadUrl(getViewModel().getStoryDetail().getUrl());\n }\n }\n\n @Override\n public void onScroll(int l, int t, int oldL, int oldT) {\n if(mFloatingActionButton != null) {\n if (t >= oldT) {\n mFloatingActionButton.hide();\n }\n else {\n mFloatingActionButton.show();\n }\n }\n }\n}", "public class MainActivity extends BaseViewModelActivity<MainViewModel>\n implements StoryListFragment.OnStoryListFragmentInteractionListener {\n\n public static final String STORY_ID = \"STORY_ID\";\n public static final String DETAILS_CONTAINER_VISIBLE = \"DETAILS_CONTAINER_VISIBLE\";\n\n @InjectView(R.id.toolbar) Toolbar mToolbar;\n @Optional @InjectView(R.id.details_container) View mDetailsContainer;\n\n @Inject MainViewModel mViewModel;\n\n private CharSequence mTitle;\n private boolean mIsDualPane;\n private StoryDetailFragment mStoryDetailFragment;\n private Drawer mDrawer;\n private AccountHeader mAccountHeader;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ButterKnife.inject(this);\n DaggerViewModelComponent.builder()\n .appComponent(HackerNewsApplication.getAppComponent())\n .build()\n .inject(this);\n mTitle = getTitle();\n\n // Set up the drawer.\n mAccountHeader = new AccountHeaderBuilder()\n .withActivity(this)\n .addProfiles(mViewModel.getProfileItems())\n .withSavedInstance(savedInstanceState)\n .withProfileImagesVisible(true)\n .withHeaderBackground(getResources().getDrawable(R.drawable.orange_button))\n .withOnAccountHeaderListener((view, iProfile, b) -> {\n switch (iProfile.getIdentifier()) {\n case MainViewModel.ADD_ACCOUNT_PROFILE_ITEM:\n MainActivity.this.startActivity(new Intent(MainActivity.this, LoginActivity.class));\n return true;\n case MainViewModel.LOG_OUT_PROFILE_ITEM:\n new AlertDialog.Builder(this)\n .setMessage(R.string.logout_dialog_message)\n .setPositiveButton(R.string.logout_confirm_button, (dialog, which) -> {\n mViewModel.logout()\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(o -> {\n refreshNavigationDrawer(false);\n });\n })\n .setNegativeButton(android.R.string.cancel, null)\n .create()\n .show();\n break;\n }\n\n return false;\n })\n .build();\n\n View headerView = LayoutInflater.from(this).inflate(R.layout.drawer_header, null);\n ImageView headerIcon = (ImageView) headerView.findViewById(R.id.image_view);\n TextDrawable textDrawable = TextDrawable.builder()\n .buildRound(String.valueOf(\"HN\"),\n getResources().getColor(R.color.colorPrimaryDark));\n headerIcon.setImageDrawable(textDrawable);\n mDrawer = new DrawerBuilder()\n .withActivity(this)\n .withToolbar(mToolbar)\n .withHeader(headerView)\n .withActionBarDrawerToggle(true)\n .withAnimateDrawerItems(true)\n .withSavedInstance(savedInstanceState)\n .addDrawerItems(mViewModel.getDrawerItems().toArray(new IDrawerItem[mViewModel.getDrawerItems().size()]))\n .withOnDrawerItemClickListener((adapterView, view, i, l, iDrawerItem) -> {\n Fragment storyListFragment;\n switch (iDrawerItem.getIdentifier()) {\n case MainViewModel.SECTION_TOP:\n mTitle = getString(R.string.title_section_top);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_TOP);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_BEST:\n mTitle = getString(R.string.title_section_best);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_BEST);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_NEWEST:\n mTitle = getString(R.string.title_section_newest);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_NEW);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_SHOW_HN:\n mTitle = getString(R.string.title_section_show);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_SHOW);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_SHOW_HN_NEW:\n mTitle = getString(R.string.title_section_show_new);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_SHOW_NEW);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_ASK:\n mTitle = getString(R.string.title_section_ask);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_ASK);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_SAVED:\n mTitle = getString(R.string.title_section_saved);\n storyListFragment = StoryListFragment.newInstance(StoryListViewModel.FEED_TYPE_SAVED);\n loadFeedList(storyListFragment);\n break;\n case MainViewModel.SECTION_SETTINGS:\n Intent settingsIntent = new Intent(this, SettingsActivity.class);\n startActivity(settingsIntent);\n break;\n case MainViewModel.SECTION_ABOUT:\n Intent aboutIntent = new Intent(this, AboutActivity.class);\n startActivity(aboutIntent);\n break;\n }\n return false;\n })\n .build();\n\n mDrawer.setSelectionByIdentifier(0);\n\n if (mToolbar != null) {\n mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));\n setSupportActionBar(mToolbar);\n }\n\n // The attributes you want retrieved\n mIsDualPane = mDetailsContainer != null;\n\n if (savedInstanceState != null) {\n boolean detailsContainerVisible = savedInstanceState.getBoolean(DETAILS_CONTAINER_VISIBLE, false);\n if (mDetailsContainer != null && detailsContainerVisible) {\n mDetailsContainer.setVisibility(View.VISIBLE);\n }\n }\n\n LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n refreshNavigationDrawer(true);\n }\n }, new IntentFilter(LoginActivity.LOGIN_SUCCESS));\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n if(getViewModel().shouldShowRateSnackbar()){\n Snackbar.make(findViewById(android.R.id.content), \"Like the app?\", Snackbar.LENGTH_LONG)\n .setAction(\"RATE\", view -> {\n IntentUtils.openInBrowser(MainActivity.this, \"https://play.google.com/store/apps/details?id=io.dwak.holohackernews.app\");\n })\n .show();\n\n }\n }\n\n private void refreshNavigationDrawer(boolean loggedIn) {\n if (loggedIn) {\n for (IProfile iProfile : mViewModel.getLoggedOutProfileItem()) {\n mAccountHeader.removeProfile(iProfile);\n }\n mAccountHeader.addProfiles(mViewModel.getLoggedInProfileItem());\n }\n else {\n for (IProfile iProfile : mViewModel.getLoggedInProfileItem()) {\n mAccountHeader.removeProfile(iProfile);\n }\n mAccountHeader.addProfiles(mViewModel.getLoggedOutProfileItem());\n mViewModel.clearLoggedInProfileItem();\n }\n\n mAccountHeader.toggleSelectionList(this);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (mDetailsContainer != null) {\n outState.putBoolean(DETAILS_CONTAINER_VISIBLE, mDetailsContainer.getVisibility() == View.VISIBLE);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n }\n\n\n private void loadFeedList(Fragment storyListFragment) {\n FragmentManager fragmentManager = getSupportFragmentManager();\n if (!(storyListFragment != null && fragmentManager.findFragmentByTag(StoryListFragment.class.getSimpleName() + mTitle) != null)) {\n fragmentManager.beginTransaction()\n .replace(R.id.container, storyListFragment, StoryListFragment.class.getSimpleName() + mTitle)\n .commit();\n setTitle(mTitle);\n }\n }\n\n @SuppressLint(\"NewApi\")\n @Override\n public void onStoryListFragmentInteraction(long id, boolean saved) {\n if (HackerNewsApplication.isDebug()) {\n Toast.makeText(this, String.valueOf(id), Toast.LENGTH_SHORT).show();\n }\n\n if (mIsDualPane && mDetailsContainer != null) {\n mStoryDetailFragment = StoryDetailFragment.newInstance(id, saved);\n mDetailsContainer.postDelayed(() -> {\n mDetailsContainer.setVisibility(View.VISIBLE);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.details_container, mStoryDetailFragment)\n .commit();\n }, 200);\n }\n else {\n Intent detailIntent = new Intent(this, StoryDetailActivity.class);\n detailIntent.putExtra(STORY_ID, id);\n detailIntent.putExtra(StoryDetailFragment.LOADING_FROM_SAVED, saved);\n startActivity(detailIntent);\n overridePendingTransition(R.anim.offscreen_left_to_view, R.anim.fadeout);\n }\n }\n\n @Override\n public void onBackPressed() {\n if (mIsDualPane && mStoryDetailFragment != null && mStoryDetailFragment.isLinkViewVisible()) {\n mStoryDetailFragment.hideLinkView();\n }\n else {\n super.onBackPressed();\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n return mDrawer.getActionBarDrawerToggle().onOptionsItemSelected(item) || super.onOptionsItemSelected(item);\n }\n\n @Override\n public MainViewModel getViewModel() {\n return mViewModel;\n }\n}", "public class StoryListFragment extends BaseViewModelFragment<StoryListViewModel> {\n\n public static final String FEED_TO_LOAD = \"feed_to_load\";\n private static final String TAG = StoryListFragment.class.getSimpleName();\n public static final String TOP_OF_LIST = \"TOP_OF_LIST\";\n public static final String STORY_LIST = \"STORY_LIST\";\n\n @InjectView(R.id.story_list) RecyclerView mRecyclerView;\n @InjectView(R.id.swipe_container) SwipeRefreshLayout mSwipeRefreshLayout;\n\n private OnStoryListFragmentInteractionListener mListener;\n private StoryListAdapter mRecyclerAdapter;\n private LinearLayoutManager mLayoutManager;\n\n @Inject StoryListViewModel mViewModel;\n\n public static StoryListFragment newInstance(@StoryListViewModel.FeedType int feedType) {\n StoryListFragment fragment = new StoryListFragment();\n Bundle args = new Bundle();\n args.putInt(FEED_TO_LOAD, feedType);\n fragment.setArguments(args);\n return fragment;\n }\n\n private void refresh() {\n mRecyclerAdapter.clear();\n getViewModel().setIsRestoring(false);\n getViewModel().setStoryList(null);\n react(getViewModel().getStories(), false);\n }\n\n private void react(Observable<Story> stories, boolean pageTwo) {\n stories.subscribe(new Subscriber<Story>() {\n @Override\n public void onCompleted() {\n showProgress(false);\n mSwipeRefreshLayout.setRefreshing(false);\n getViewModel().setPageTwoLoaded(pageTwo);\n }\n\n @Override\n public void onError(Throwable e) {\n if (e instanceof RetrofitError) {\n Toast.makeText(getActivity(), R.string.story_list_error_toast_message, Toast.LENGTH_SHORT).show();\n }\n else {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void onNext(Story story) {\n if (story.getStoryId() != null && mRecyclerAdapter.getPositionOfItem(story) == -1) {\n mRecyclerAdapter.addStory(story);\n }\n }\n });\n }\n\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n try {\n mListener = (OnStoryListFragmentInteractionListener) activity;\n } catch (ClassCastException e) {\n throw new ClassCastException(activity.toString()\n + \" must implement OnStoryListFragmentInteractionListener\");\n }\n\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n DaggerViewModelComponent.builder()\n .appComponent(HackerNewsApplication.getAppComponent())\n .build()\n .inject(this);\n if(savedInstanceState != null){\n getViewModel().setStoryList(savedInstanceState.getParcelableArrayList(STORY_LIST));\n getViewModel().setIsRestoring(true);\n }\n if (getArguments() != null) {\n @StoryListViewModel.FeedType final int feedType = getArguments().getInt(FEED_TO_LOAD);\n getViewModel().setFeedType(feedType);\n }\n\n setHasOptionsMenu(true);\n\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_storylist_list, container, false);\n ButterKnife.inject(this, view);\n\n getViewModel().setPageTwoLoaded(false);\n\n mContainer = view.findViewById(R.id.story_list);\n mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);\n\n final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();\n if (actionBar != null) {\n actionBar.setTitle(getViewModel().getTitle());\n }\n showProgress(true);\n\n if (savedInstanceState == null || mRecyclerAdapter == null) {\n setupRecyclerView();\n showBetaPopup();\n refresh();\n }\n else {\n showProgress(false);\n }\n\n if (getViewModel().getFeedType() == StoryListViewModel.FEED_TYPE_TOP) {\n mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {\n @Override\n public void onLoadMore(int current_page) {\n if (!getViewModel().isPageTwoLoaded()) {\n react(getViewModel().getTopStoriesPageTwo(), true);\n }\n }\n });\n }\n\n mRecyclerView.setAdapter(mRecyclerAdapter);\n\n setupSwipeToRefresh();\n\n if (savedInstanceState != null) {\n mLayoutManager.scrollToPosition(savedInstanceState.getInt(TOP_OF_LIST));\n }\n\n return view;\n }\n\n private void showBetaPopup() {\n if (!getViewModel().isReturningUser()) {\n new AlertDialog.Builder(getActivity())\n .setMessage(R.string.beta_prompt_message)\n .setPositiveButton(android.R.string.ok, (dialog, which) -> {\n Intent gPlusIntent = new Intent();\n gPlusIntent.setAction(Intent.ACTION_VIEW);\n gPlusIntent.setData(Uri.parse(\"https://plus.google.com/communities/112347719824323216860\"));\n getActivity().startActivity(gPlusIntent);\n })\n .setNegativeButton(R.string.beta_prompt_negative, (dialog, which) -> {\n\n })\n .create()\n .show();\n getViewModel().setReturningUser(true);\n }\n }\n\n private void setupRecyclerView() {\n StoryListAdapter.StoryListAdapterListener listener = new StoryListAdapter.StoryListAdapterListener() {\n @Override\n public void onStoryClick(int position) {\n getViewModel().markStoryAsRead(mRecyclerAdapter.getItem(position))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<Story>() {\n @Override\n public void onCompleted() {\n mListener.onStoryListFragmentInteraction(mRecyclerAdapter.getItemId(position),\n getViewModel().getFeedType() == StoryListViewModel.FEED_TYPE_SAVED);\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Story story) {\n mRecyclerAdapter.markStoryAsRead(position, story);\n }\n });\n }\n\n @Override\n public void onStorySave(int position, boolean save) {\n if (save) {\n //noinspection unchecked\n getViewModel().saveStory(mRecyclerAdapter.getItem(position))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe((Action1) o -> UIUtils.showToast(getActivity(), \"Saved!\"));\n }\n else {\n getViewModel().deleteStory(mRecyclerAdapter.getItem(position))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<Object>() {\n @Override\n public void onCompleted() {\n if (getViewModel().getFeedType() == StoryListViewModel.FEED_TYPE_SAVED) {\n mRecyclerAdapter.removeItem(position);\n }\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Object o) {\n\n }\n });\n }\n\n mRecyclerAdapter.notifyItemChanged(position);\n }\n };\n mRecyclerAdapter = new StoryListAdapter(getActivity(),\n new ArrayList<>(),\n listener,\n getViewModel().isNightMode());\n mLayoutManager = new LinearLayoutManager(getActivity());\n mRecyclerView.setLayoutManager(mLayoutManager);\n mRecyclerView.addItemDecoration(new SpacesItemDecoration(8));\n }\n\n private void setupSwipeToRefresh() {\n mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary),\n getResources().getColor(R.color.colorPrimaryDark));\n mSwipeRefreshLayout.setOnRefreshListener(() -> {\n mSwipeRefreshLayout.setRefreshing(true);\n if (getViewModel().getFeedType() == StoryListViewModel.FEED_TYPE_SAVED) {\n mSwipeRefreshLayout.setRefreshing(false);\n new AlertDialog.Builder(getActivity())\n .setMessage(getString(R.string.action_refresh_saved_stories))\n .setPositiveButton(android.R.string.ok, (dialog, which) -> {\n getViewModel().saveAllStories()\n .observeOn(Schedulers.io())\n .subscribeOn(AndroidSchedulers.mainThread())\n .subscribe(new Observer<Object>() {\n @Override\n public void onCompleted() {\n UIUtils.showToast(getActivity(), \"Saved!\");\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Object o) {\n\n }\n });\n })\n .setNegativeButton(android.R.string.cancel, (dialog, which) -> {\n mSwipeRefreshLayout.setRefreshing(false);\n })\n .show();\n }\n else {\n refresh();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putInt(TOP_OF_LIST, mLayoutManager.findFirstVisibleItemPosition());\n outState.putParcelableArrayList(STORY_LIST, getViewModel().getStoryList());\n }\n\n @Override\n public void onDetach() {\n mListener = null;\n super.onDetach();\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n ButterKnife.reset(this);\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n super.onCreateOptionsMenu(menu, inflater);\n if (getViewModel().getFeedType() != StoryListViewModel.FEED_TYPE_SAVED) {\n inflater.inflate(R.menu.menu_story_list_save, menu);\n }\n else {\n inflater.inflate(R.menu.menu_story_list_saved, menu);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.action_delete:\n new AlertDialog.Builder(getActivity())\n .setMessage(getString(R.string.action_share_delete_all_stories))\n .setPositiveButton(android.R.string.ok, (dialog, which) -> {\n ProgressDialog progressDialog = new ProgressDialog(getActivity());\n progressDialog.setMessage(getString(R.string.action_delete_in_progress_message));\n progressDialog.setCancelable(false);\n progressDialog.show();\n getViewModel().deleteAllSavedStories()\n .observeOn(Schedulers.io())\n .subscribeOn(AndroidSchedulers.mainThread())\n .subscribe(new Observer<Object>() {\n @Override\n public void onCompleted() {\n progressDialog.dismiss();\n mRecyclerAdapter.removeAllItems();\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Object o) {\n\n }\n });\n })\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n return true;\n case R.id.action_save:\n new AlertDialog.Builder(getActivity())\n .setMessage(getString(R.string.action_save_all_stories))\n .setPositiveButton(android.R.string.ok, (dialog, which) -> {\n getViewModel().saveAllStories()\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Observer<Object>() {\n @Override\n public void onCompleted() {\n// progressDialog.dismiss();\n UIUtils.showToast(getActivity(), \"Saved!\");\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(Object o) {\n// progressDialog.incrementProgressBy(1);\n }\n });\n })\n .setNegativeButton(android.R.string.cancel, null)\n .create()\n .show();\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public StoryListViewModel getViewModel() {\n return mViewModel;\n }\n\n public interface OnStoryListFragmentInteractionListener {\n void onStoryListFragmentInteraction(long id, boolean saved);\n }\n}" ]
import dagger.Component; import io.dwak.holohackernews.app.dagger.module.ViewModelModule; import io.dwak.holohackernews.app.ui.about.AboutActivity; import io.dwak.holohackernews.app.ui.login.LoginActivity; import io.dwak.holohackernews.app.ui.storydetail.StoryDetailFragment; import io.dwak.holohackernews.app.ui.storylist.MainActivity; import io.dwak.holohackernews.app.ui.storylist.StoryListFragment;
package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = ViewModelModule.class) public interface ViewModelComponent { void inject(MainActivity activity); void inject(StoryListFragment fragment); void inject(StoryDetailFragment fragment); void inject(LoginActivity activity);
void inject(AboutActivity.AboutFragment aboutFragment);
1
swarmcom/jSynapse
src/main/java/org/swarmcom/jsynapse/service/message/MessageServiceImpl.java
[ "public interface MessageRepository extends MongoRepository<Message, String> {\n\n List<Message> findByRoomId(String roomId);\n}", "public class Message {\n @Id\n String id;\n\n @NotNull\n @JsonProperty\n String msgtype;\n\n @Indexed\n String roomId;\n\n String body;\n\n public String getMsgtype() {\n return msgtype;\n }\n\n public void setMsgtype(String msgtype) {\n this.msgtype = msgtype;\n }\n\n public String getRoomId() {\n return roomId;\n }\n\n public void setRoomId(String roomId) {\n this.roomId = roomId;\n }\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n public static class Messages {\n List<MessageSummary> chunk = new LinkedList<>();\n\n public Messages(List<Message> messages) {\n for (Message message : messages) {\n chunk.add(new MessageSummary(message));\n }\n }\n\n public List<MessageSummary> getChunk() {\n return chunk;\n }\n }\n\n public static class MessageSummary {\n public static final String MSG_TYPE = \"msgtype\";\n public static final String BODY = \"body\";\n\n @JsonProperty\n Map<String, String> content = new LinkedHashMap<>();\n\n public MessageSummary(Message message) {\n content.put(MSG_TYPE, message.getMsgtype());\n if (StringUtils.isNotBlank(message.getBody())) {\n content.put(BODY, message.getBody());\n }\n }\n\n public Map<String, String> getContent() {\n return content;\n }\n }\n}", "public class Room {\n @Id\n String id;\n\n @JsonProperty(\"room_id\")\n @JsonView({CreateSummary.class, DirectorySummary.class})\n @Indexed\n String roomId;\n\n @NotNull\n @JsonView(NameSummary.class)\n String name;\n\n @JsonProperty\n String visibility = \"private\";\n\n @JsonProperty(\"room_alias_name\")\n @JsonView(CreateSummary.class)\n String alias;\n\n @JsonProperty\n @JsonView(TopicSummary.class)\n String topic;\n\n @JsonProperty\n List<String> invite;\n\n public Room() {\n }\n\n public void setRoomId(String roomId) {\n this.roomId = roomId;\n }\n\n public String getRoomId() {\n return roomId;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAlias() {\n return alias;\n }\n\n public void setAlias(String alias) {\n this.alias = alias;\n }\n\n public String getTopic() {\n return topic;\n }\n\n public void setTopic(String topic) {\n this.topic = topic;\n }\n\n public interface CreateSummary {}\n\n public interface DirectorySummary {}\n\n public interface TopicSummary {}\n\n public interface NameSummary {}\n}", "public interface RoomService {\n Room createRoom(Room room);\n\n Room findRoomByAlias(String alias);\n\n void deleteAlias(String roomId, String alias);\n\n Room findRoomById(String roomId);\n\n Room saveTopic(String roomId, String topic);\n\n Room saveName(String roomId, String name);\n}", "public static class Messages {\n List<MessageSummary> chunk = new LinkedList<>();\n\n public Messages(List<Message> messages) {\n for (Message message : messages) {\n chunk.add(new MessageSummary(message));\n }\n }\n\n public List<MessageSummary> getChunk() {\n return chunk;\n }\n}" ]
import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import org.swarmcom.jsynapse.dao.MessageRepository; import org.swarmcom.jsynapse.domain.Message; import org.swarmcom.jsynapse.domain.Room; import org.swarmcom.jsynapse.service.room.RoomService; import javax.inject.Inject; import static org.swarmcom.jsynapse.domain.Message.Messages;
/* * (C) Copyright 2015 eZuce Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.swarmcom.jsynapse.service.message; @Service @Validated public class MessageServiceImpl implements MessageService {
private final MessageRepository messageRepository;
0
gambitproject/gte
lib-algo/src/lse/math/games/io/ExtensiveFormXMLReader.java
[ "public class Rational \r\n{\r\n\tpublic static final Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);\r\n\tpublic static final Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE);\r\n\tpublic static final Rational NEGONE = new Rational(BigInteger.ONE.negate(), BigInteger.ONE);\r\n\tpublic BigInteger num;\r\n\tpublic BigInteger den;\r\n\t\r\n\tpublic Rational(BigInteger num, BigInteger den)\r\n\t{\r\n\t\tthis.num = num;\r\n\t\tthis.den = den;\r\n if (zero(den)) {\r\n throw new ArithmeticException(\"Divide by zero\");\r\n } else if (!one(den)) {\r\n \t\treduce();\r\n }\r\n\t}\r\n\t\r\n\tpublic Rational(Rational toCopy)\r\n\t{\r\n\t\tthis.num = toCopy.num;\r\n\t\tthis.den = toCopy.den;\r\n\t}\r\n\t\r\n /* reduces Na Da by gcd(Na,Da) */\r\n private void reduce()\r\n {\r\n \tif (!zero(num)) {\r\n if (negative(den))\r\n {\r\n den = den.negate();\r\n num = num.negate();\r\n }\r\n\t BigInteger gcd = num.gcd(den);\r\n\t if (!one(gcd)) {\r\n\t\t num = num.divide(gcd);\r\n\t\t den = den.divide(gcd);\r\n\t }\r\n \t} else {\r\n \t\tden = BigInteger.ONE;\r\n \t}\r\n }\r\n \r\n public Rational(long numerator, long denominator)\r\n\t{\r\n\t this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));\r\n\t}\r\n\r\n\tprivate void addEq(Rational toAdd)\r\n {\r\n \tif (den.equals(toAdd.den)) {\r\n \t\tnum = num.add(toAdd.num);\r\n \t} else {\r\n\t num = num.multiply(toAdd.den);\r\n\t num = num.add(toAdd.num.multiply(den));\r\n\t den = den.multiply(toAdd.den);\t \r\n \t}\r\n \treduce();\r\n }\r\n \r\n public static Rational valueOf(String s)\r\n throws NumberFormatException\r\n {\r\n \tString[] fraction = s.split(\"/\");\r\n \tif (fraction.length < 1 || fraction.length > 2) \r\n \t\tthrow new NumberFormatException(\"BigIntegerRational not formatted correctly\");\r\n\r\n \tif (fraction.length == 2) {\r\n\t \tBigInteger num = new BigInteger(fraction[0]);\r\n\t \tBigInteger den = new BigInteger(fraction[1]);\r\n\t \treturn new Rational(num, den);\r\n \t} else {\r\n \t\tBigDecimal dec = new BigDecimal(s);\r\n \t\treturn valueOf(dec);\r\n \t}\r\n }\r\n \r\n public static Rational valueOf(double dx)\r\n {\r\n BigDecimal x = BigDecimal.valueOf(dx);\r\n return valueOf(x);\r\n }\r\n \r\n public static Rational valueOf(BigDecimal x)\r\n {\r\n BigInteger num = x.unscaledValue();\r\n BigInteger den = BigInteger.ONE;\r\n \r\n int scale = x.scale();\r\n while (scale > 0) \r\n {\r\n \tden = den.multiply(BigInteger.TEN);\r\n \t--scale;\r\n } \r\n while (scale < 0)\r\n {\r\n \tnum = num.multiply(BigInteger.TEN);\r\n \t++scale;\r\n }\r\n \r\n Rational rv = new Rational(num, den);\r\n rv.reduce();\r\n return rv;\r\n } \r\n \r\n public static Rational valueOf(long value)\r\n {\r\n \tif (value == 0) return ZERO;\r\n \telse if (value == 1) return ONE;\r\n \telse return new Rational(value);\r\n }\r\n \r\n private Rational(long value)\r\n {\r\n this(value, 1);\r\n }\r\n\r\n private void mulEq(Rational other)\r\n {\r\n num = num.multiply(other.num);\r\n den = den.multiply(other.den);\r\n reduce();\r\n }\r\n\r\n //Helper Methods\r\n private void flip() /* aka. Reciprocate */\r\n {\r\n BigInteger x = num;\r\n num = den;\r\n den = x;\r\n } \r\n\r\n public Rational add(Rational b)\r\n\t{\r\n\t\tif (zero(num)) return b;\r\n\t\telse if (zero(b.num))return this; \r\n\t\tRational rv = new Rational(this);\r\n\t rv.addEq(b);\r\n\t return rv;\r\n\t}\r\n\r\n\tpublic Rational add(long b)\r\n {\r\n if (b == 0) return this;\r\n Rational rv = new Rational(b);\r\n rv.addEq(this);\r\n return rv;\r\n }\r\n\r\n public Rational subtract(Rational b)\r\n\t{\r\n\t\tif (zero(b.num))return this; \r\n\t\tRational c = b.negate();\r\n\t if (!zero(num))\r\n\t \tc.addEq(this);\r\n\t return c;\r\n\t}\r\n\r\n\tpublic Rational subtract(long b)\r\n\t{\r\n\t if (b == 0) return this;\r\n\t Rational c = new Rational(-b);\r\n\t c.addEq(this);\r\n\t return c;\r\n\t}\r\n\r\n\tpublic Rational multiply(Rational b)\r\n {\r\n if (zero(num) || zero(b.num)) return ZERO;\r\n Rational rv = new Rational(this);\r\n rv.mulEq(b);\r\n return rv;\r\n }\r\n\r\n public Rational divide(Rational b)\r\n\t{\r\n\t\tRational rv = new Rational(b);\r\n\t\trv.flip();\r\n\t\trv.mulEq(this);\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tpublic Rational negate()\r\n\t{\r\n\t if (zero(num)) return this;\r\n\t return new Rational(num.negate(), den); \r\n\t}\r\n\r\n\tpublic Rational reciprocate()\r\n\t{\r\n\t\tif (zero(num)) throw new ArithmeticException(\"Divide by zero\");\r\n\t\tRational rv = new Rational(this);\r\n\t\trv.flip();\r\n\t\tif (negative(den)) {\r\n\t\t\trv.num = rv.num.negate();\r\n\t\t\trv.den = rv.den.negate();\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tpublic int compareTo(Rational other)\r\n {\r\n if (num.equals(other.num) && den.equals(other.den))\r\n \treturn 0;\r\n \r\n //see if it is a num only compare...\r\n if (den.equals(other.den))\r\n return (greater(other.num, this.num)) ? -1 : 1;\r\n\r\n //check signs...\r\n if ((zero(num) || negative(num)) && positive(other.num)) \r\n \treturn -1;\r\n else if (positive(num) && (zero(other.num) || negative(other.num))) \r\n \treturn 1;\r\n\r\n Rational c = other.negate(); \r\n c.addEq(this);\r\n return (c.isZero() ? 0 : (negative(c.num) ? -1 : 1));\r\n }\r\n\r\n public int compareTo(long other)\r\n {\r\n \tBigInteger othernum = BigInteger.valueOf(other);\r\n if (num.equals(othernum) && one(den)) return 0;\r\n else return compareTo(new Rational(othernum, BigInteger.ONE));\r\n }\r\n\r\n\r\n public double doubleValue()\r\n\t{ \t\r\n \ttry {\r\n \t\treturn (new BigDecimal(num)).divide(new BigDecimal(den)).doubleValue();\r\n \t} catch (ArithmeticException e) {\r\n\t\t\treturn (new BigDecimal(num)).divide(new BigDecimal(den), 32, BigDecimal.ROUND_HALF_UP).doubleValue();\r\n\t\t}\r\n\t}\r\n\r\n\t//Num and Den are only used by Tableau... I'd like to get rid of them, but can't see how\r\n\tpublic boolean isZero() { return zero(num); }\r\n\r\n\tpublic boolean isOne() { return one(num) && one(den); } // should be reduced at all times\r\n\r\n\t//Basic Overrides\r\n @Override\r\n public boolean equals(Object obj)\r\n {\r\n if (obj == null || !(obj instanceof Rational))\r\n return false;\r\n\r\n Rational r = (Rational)obj;\r\n return (compareTo(r) == 0);\r\n }\r\n\r\n @Override\r\n public int hashCode()\r\n {\r\n return (num.multiply(BigInteger.valueOf(7)).intValue() ^ den.multiply(BigInteger.valueOf(17)).intValue());\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n \tStringBuilder sb = new StringBuilder();\r\n \tsb.append(num.toString());\r\n \tif (!one(den) && !zero(num))\r\n \t{\r\n \t\tsb.append(\"/\");\r\n \t\tsb.append(den);\r\n \t}\r\n \treturn sb.toString();\r\n }\r\n\r\n\tpublic static Rational sum(Iterable<Rational> list)\r\n\t{\r\n\t Rational sum = ZERO;\r\n\t for (Rational rat : list) {\r\n\t sum.addEq(rat); \r\n\t }\r\n\t return sum;\r\n\t}\r\n\r\n\t// TODO: why is this here?\r\n\tpublic static long gcd(long a, long b)\r\n\t{\r\n\t long c;\r\n\t if (a < 0L) {\r\n\t \ta = -a;\r\n\t }\r\n\t if (b < 0L) {\r\n\t \tb = -b;\r\n\t }\r\n\t if (a < b) { \r\n\t \tc = a; \r\n\t \ta = b; \r\n\t \tb = c; \r\n\t }\r\n\t while (b != 0L) {\r\n\t c = a % b;\r\n\t a = b;\r\n\t b = c;\r\n\t }\r\n\t return a;\r\n\t}\r\n\t\r\n\tpublic static Rational[] probVector(int length, Random prng)\r\n\t{\r\n\t\tif (length == 0) return new Rational[] {};\r\n\t\telse if (length == 1) return new Rational[] { Rational.ONE };\r\n\t\t\r\n\t\tdouble dProb = prng.nextDouble();\r\n\t\tRational probA = Rational.valueOf(dProb);\r\n\t\tRational probB = Rational.valueOf(1 - dProb);\r\n\t\tif (length == 2) {\r\n\t\t\treturn new Rational[] { probA, probB };\r\n\t\t} else {\r\n\t\t\tRational[] a = probVector(length / 2, prng);\r\n\t\t\tRational[] b = probVector((length + 1) / 2, prng);\r\n\t\t\tRational[] c = new Rational[a.length + b.length];\r\n\t\t\tfor (int i = 0; i < a.length; ++i) {\r\n\t\t\t\tc[i] = a[i].multiply(probA);\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < b.length; ++i) {\r\n\t\t\t\tc[a.length + i] = b[i].multiply(probB);\r\n\t\t\t}\r\n\t\t\treturn c;\r\n\t\t}\t\t\r\n\t}\r\n\t\r\n\t// TODO: put this somewhere else...\r\n\tpublic static void printRow(String name, Rational value, ColumnTextWriter colpp, boolean excludeZero)\r\n\t{\t\t\t\t\t\r\n\t\tif (!value.isZero() || !excludeZero) {\r\n\t\t\tcolpp.writeCol(name);\r\n\t\t\tcolpp.writeCol(value.toString());\r\n\t\t\t\t\t\r\n\t\t\tif (!BigIntegerUtils.one(value.den)) {\r\n\t\t\t\tcolpp.writeCol(String.format(\"%.3f\", value.doubleValue()));\t\r\n\t\t\t}\r\n\t\t\tcolpp.endRow();\r\n\t\t}\t\t\r\n\t}\r\n}\r", "public class ExtensiveForm \r\n{\r\n\tchar[] an1 = new char[] { '!', 'A', 'a' }; //Assumes 2 players in this array...\r\n char[] an2 = new char[] { '/', 'Z', 'z' }; //ditto...\r\n\r\n private Player _firstPlayer;\r\n private Player _lastPlayer;\r\n \r\n private Node _root;\r\n private int _nnodes = 0;\r\n \r\n public ExtensiveForm() {\r\n \t_root = this.createNode();\r\n }\r\n \r\n public Node createNode()\r\n {\r\n \treturn new Node(_nnodes++);\r\n }\r\n \r\n public Node root() {\r\n \treturn _root;\r\n }\r\n \r\n public Player firstPlayer() {\r\n \treturn _firstPlayer;\r\n }\r\n \r\n public Node firstLeaf() {\r\n \treturn _root.firstLeaf();\r\n }\r\n \r\n public void autoname()\r\n { \r\n for (Player pl = _firstPlayer; pl != null; pl = pl.next) /* name isets of player pl */\r\n \t{\r\n \tint idx = pl == Player.CHANCE ? 0 : pl == _firstPlayer ? 1 : 2;\r\n \t int anbase = an2[idx]-an1[idx]+1;\r\n \t \r\n \t int digits = 1; \t \r\n \t for (int max = anbase, n = nisets(pl); max < n; max *= anbase) {\r\n \t ++digits;\r\n \t }\r\n \r\n \t int count = 0;\r\n \t for (Iset h = _root.iset(); h != null; h = h.next())\r\n \t {\r\n \t \tif (h.player() == pl) {\t \t \t \t \r\n\t StringBuilder sb = new StringBuilder();\r\n\t \t for (int j = digits - 1, i = count; j >= 0; --j, i /= anbase)\r\n\t \t\t{\r\n\t char c = (char)(an1[idx] + (i % anbase));\r\n\t \t\tsb.append(c);\t \t\t\r\n\t \t\t}\r\n\t h.setName(sb.toString());\r\n \t \t}\r\n \t \t++count;\r\n \t }\r\n \t}\r\n }\r\n \r\n private int nisets(Player pl) {\r\n\t int count = 0;\r\n \tfor (Iset h = _root.iset(); h != null; h = h.next())\r\n\t {\r\n \t\tif (h.player() == pl) {\r\n \t\t\t++count;\r\n \t\t}\r\n\t }\r\n \treturn count;\r\n }\r\n \r\n private int noutcome = 0;\r\n\tpublic Outcome createOutcome(Node wrapNode) { \r\n\t\treturn new Outcome(noutcome++, wrapNode);\r\n\t}\r\n\t\r\n\tprivate Iset _secondIset;\r\n\tprivate Iset _lastIset;\r\n\tprivate int _nisets = 0;\r\n\t\r\n\tpublic Iset createIset(Player player) {\r\n\t\treturn createIset(null, player);\r\n\t}\r\n\tpublic Iset createIset(String isetId, Player player) {\r\n\t\tIset h = new Iset(_nisets++, player);\r\n\t\tif (isetId != null) {\r\n\t\t\th.setName(isetId);\r\n\t\t}\r\n\t\tif (_secondIset == null) {\r\n\t\t\t_secondIset = h;\r\n\t\t}\r\n\t\tif (_lastIset != null) {\r\n\t\t\t_lastIset.setNext(h);\r\n\t\t}\r\n\t\th.setNext(null);\r\n\t\t_lastIset = h;\r\n\t\treturn h;\r\n\t}\r\n\tpublic Player createPlayer(String playerId) \r\n\t{\r\n\t\tif (playerId == Player.CHANCE_NAME) {\r\n\t\t\treturn Player.CHANCE;\r\n\t\t}\r\n\t\t\r\n\t\tPlayer pl = new Player(playerId);\r\n\t\tif (_firstPlayer == null) {\r\n\t\t\t_firstPlayer = pl;\r\n\t\t}\r\n\t\tif (_lastPlayer != null) { \r\n\t\t\t_lastPlayer.next = pl;\r\n\t\t}\r\n\t\tpl.next = null;\r\n\t\t_lastPlayer = pl;\r\n\t\treturn pl;\r\n\t}\r\n\t\r\n\tpublic void addToIset(Node node, Iset iset) { \r\n\t\tnode.setIset(iset); \r\n\t\tiset.insertNode(node);\r\n\t\tif (node == _root) {\r\n\t\t\t// pull iset out of list & make it the front\r\n\t\t\tfor (Iset h = _secondIset; h != null; h = h.next()) {\r\n\t\t\t\tif (h.next() == iset) {\r\n\t\t\t\t\th.setNext(iset.next());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (iset != _secondIset) { //avoid the infinite loop\r\n\t\t\t\tiset.setNext(_secondIset);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate int _nmoves = 0;\r\n\tpublic Move createMove(String moveId) {\r\n\t\tMove mv = new Move(_nmoves++);\r\n\t\tif (moveId != null) {\r\n\t\t\tmv.setLabel(moveId);\r\n\t\t}\r\n\t\treturn mv;\r\n\t}\r\n\tpublic Move createMove() {\r\n\t\treturn createMove(null);\t\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString() \r\n\t{\r\n\t\tColumnTextWriter colpp = new ColumnTextWriter();\t\t\r\n\t\t\r\n\t\tcolpp.writeCol(\"node\");\r\n\t\tcolpp.writeCol(\"leaf\");\r\n\t\tcolpp.writeCol(\"iset\");\r\n\t\tcolpp.writeCol(\"player\");\r\n\t\tcolpp.writeCol(\"parent\");\r\n\t\tcolpp.writeCol(\"reachedby\");\r\n\t\tcolpp.writeCol(\"outcome\");\r\n\t\tcolpp.writeCol(\"pay1\");\r\n\t\tcolpp.writeCol(\"pay2\");\r\n\t\tcolpp.endRow();\r\n\t\t\r\n\t\trecToString(_root, colpp);\r\n\t\tcolpp.sortBy(0, 1);\r\n\r\n\t\treturn colpp.toString();\r\n\t}\r\n\t\r\n\tprivate void recToString(Node n, ColumnTextWriter colpp)\r\n\t{\t\t\r\n\t\tcolpp.writeCol(n.uid());\r\n\t\tcolpp.writeCol(n.outcome == null ? 0 : 1);\r\n\t\tcolpp.writeCol(n.iset() != null ? n.iset().name() : \"\");\r\n\t\tcolpp.writeCol(n.iset() != null ? n.iset().player().toString() : \"\");\r\n\t\tcolpp.writeCol(n.parent() != null ? n.parent().toString() : \"\");\r\n\t\tcolpp.writeCol(n.reachedby != null ? n.reachedby.toString() : \"\");\r\n\t\tcolpp.writeCol(n.outcome != null ? n.outcome.toString() : \"\");\r\n\t\tcolpp.writeCol(n.outcome != null ? n.outcome.pay(_firstPlayer).toString() : \"\");\r\n\t\tcolpp.writeCol(n.outcome != null ? n.outcome.pay(_firstPlayer.next).toString() : \"\");\r\n\t\tcolpp.endRow();\r\n\t\t\r\n\t\tfor (Node child = n.firstChild(); child != null; child = child.sibling()) {\r\n\t\t\trecToString(child, colpp);\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tprivate String parameter=null;\r\n\tpublic String getParameter(){\r\n\t\tparameter=null;\r\n\t\titerateParameter(this.root());\r\n\t\treturn parameter;\r\n\t}\r\n\t\r\n\tprivate void iterateParameter(Node n){\r\n\r\n\t\tif (n!=null) {\r\n\t\t\tif (n.outcome!=null){\r\n\t\t\t\tSet<Player> s=n.outcome.players();\r\n\t\t\t\tIterator<Player> it = s.iterator();\r\n\t\t\t\twhile (it.hasNext()) {\r\n\t\t\t\t Player p = it.next();\r\n\t\t\t\t if (n.outcome.parameter(p)!=null) {\r\n\t\t\t\t \tparameter=n.outcome.parameter(p);\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor (Node child = n.firstChild(); child != null; child = child.sibling()) {\r\n\t\t\titerateParameter(child);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n\tpublic void setTreeParameter(String param){\r\n\t\titerateTreeParameter(this.root(),param);\r\n\t}\r\n\t\r\n\tprivate void iterateTreeParameter(Node n,String param){\r\n\r\n\t\tif (n!=null) {\r\n\t\t\tif (n.outcome!=null){\r\n\t\t\t\tSet<Player> s=n.outcome.players();\r\n\t\t\t\tIterator<Player> it = s.iterator();\r\n\t\t\t\twhile (it.hasNext()) {\r\n\t\t\t\t Player p = it.next();\r\n\t\t\t\t if (n.outcome.parameter(p)!=null) {\r\n\t\t\t\t \tn.outcome.setPay(p, Rational.valueOf(param));\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor (Node child = n.firstChild(); child != null; child = child.sibling()) {\r\n\t\t\titerateTreeParameter(child,param);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n\t\r\n}\r", "public class Outcome\r\n{\r\n private Node node;\r\n private Map<Player,Rational> pay;\r\n private Map<Player,String> parameter;\r\n private int _uid;\r\n \r\n Outcome(int uid, Node wrapNode)\r\n {\r\n \t_uid = uid;\r\n this.node = wrapNode;\r\n wrapNode.terminal = true;\r\n wrapNode.outcome = this;\r\n pay = new HashMap<Player,Rational>(); \r\n parameter = new HashMap<Player,String>(); \r\n }\r\n \r\n public int uid() { return _uid; }\r\n \r\n public Node whichnode() { return node; }\r\n public int idx;\r\n \r\n public Set<Player> players() { return pay.keySet(); }\r\n\r\n \r\n public Rational pay(Player pl) {\r\n \treturn pay.get(pl);\r\n }\r\n \r\n public void setPay(Player pl, Rational value) {\r\n \tpay.put(pl, value);\r\n }\r\n \r\n \r\n public String parameter(Player pl) {\r\n \treturn parameter.get(pl);\r\n }\r\n \r\n public void setParameter(Player pl, String value) {\r\n \tparameter.put(pl, value);\r\n }\r\n \r\n @Override\r\n public String toString() {\r\n \treturn String.valueOf(_uid);\r\n }\r\n}\r", "public class Node \r\n{ \r\n\tprivate int _uid;\r\n\t\r\n\tprivate Node _firstChild;\r\n\tprivate Node _lastChild;\r\n\t\r\n private Node _parent; // node closer to root\r\n private Node _sibling; // sibling to the right\r\n\t\r\n private Iset _iset;\r\n \r\n\tNode(int uid) { \r\n\t\t_uid = uid;\r\n\t}\r\n \r\n public int uid() {\r\n \treturn _uid;\r\n }\r\n public boolean terminal;\r\n \r\n public Iset iset() { return _iset; }\r\n void setIset(Iset iset) { _iset = iset; _iset.insertNode(this);}\r\n \r\n public Node nextInIset;\r\n \r\n public Move reachedby; /* move of edge from father */\r\n public Outcome outcome;\r\n \r\n public Node firstChild() { return _firstChild; }\r\n\r\n\tpublic void addChild(Node node) {\r\n\t\tif (_firstChild == null) {\r\n\t\t\t_firstChild = node;\r\n\t\t}\r\n\t\tif (_lastChild != null) {\r\n\t\t\t_lastChild._sibling = node;\r\n\t\t}\r\n\t\tnode._parent = this;\r\n\t\tnode._sibling = null;\r\n\t\t_lastChild = node;\r\n\t}\r\n\t\r\n\tpublic Node parent() {\r\n\t\treturn _parent;\r\n\t}\r\n\t\r\n\tpublic Node sibling() {\r\n\t\treturn _sibling;\r\n\t}\r\n\t\r\n\tNode firstLeaf() {\r\n\t\tif (_firstChild == null) {\r\n\t\t\treturn this;\r\n\t\t} else {\r\n\t\t\treturn _firstChild.firstLeaf();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Node nextLeaf() {\r\n\t\tif (_sibling != null) {\r\n\t\t\treturn _sibling.firstLeaf();\r\n\t\t} else if (_parent != null) {\r\n\t\t\treturn _parent.nextLeaf();\r\n\t\t} else {\r\n\t\t\treturn null;\t\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn String.valueOf(_uid);\r\n\t}\r\n}\r", "public class Iset \r\n{\t\r\n\tprivate Iset _next;\r\n\tprivate Node _firstNode;\r\n\tprivate Node _lastNode;\r\n\tprivate int _uid;\r\n\t\r\n Iset(int uid, Player player)\r\n {\r\n \t_uid = uid;\r\n _player = player;\r\n }\r\n\r\n private Player _player;\r\n private String _name;\r\n public Move[] moves;\r\n\r\n public String name() {\r\n \tif (_name != null) return _name;\r\n \telse return String.valueOf(_uid);\r\n }\r\n \r\n public int uid() { return _uid; }\r\n \r\n public void setName(String value) {\r\n \t_name = value;\r\n }\r\n \r\n public Iset next() {\r\n \treturn _next;\r\n }\r\n \r\n public Node firstNode() {\r\n \treturn _firstNode;\r\n }\r\n \r\n void setNext(Iset h) {\r\n \t_next = h;\r\n }\r\n\r\n\tpublic void setPlayer(Player player) {\r\n\t\t_player = player;\r\n\t}\r\n\t\r\n\tpublic Player player() {\r\n\t\treturn _player;\r\n\t}\r\n\r\n\tpublic void sort() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\tthrow new RuntimeException(\"Not impl\");\r\n\t}\r\n\t\r\n\tpublic int nmoves() {\r\n \tint count = 0;\r\n \tfor (Node child = _firstNode.firstChild(); child != null; child = child.sibling()) {\r\n \t\t++count;\r\n \t}\r\n \treturn count;\r\n\t}\r\n\r\n\tvoid insertNode(Node node) {\t\t\t\t\r\n\t\tif (_firstNode == null) {\r\n\t\t\t_firstNode = node;\r\n\t\t}\r\n\t\tif (_lastNode != null) {\r\n\t\t\t_lastNode.nextInIset = node;\r\n\t\t}\r\n\t\tnode.nextInIset = null;\r\n\t\t_lastNode = node;\r\n\t}\r\n\t\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn name();\r\n\t}\r\n}\r", "public class Move {\r\n\t\r\n\tprivate int _uid;\r\n\tprivate Iset _iset; // where this move emanates from\r\n\t\r\n Move(int uid) { \r\n \t_uid = uid;\r\n } \r\n \r\n Move(int uid, Rational prob)\r\n {\r\n \tthis(uid);\r\n \tthis.prob = prob;\r\n }\r\n \r\n /* idx in the iset's move array */\r\n public int setIdx() {\r\n \tif (_iset == null) return -1;\r\n \t\r\n \tint idx = 0;\r\n \tfor (Node child = _iset.firstNode().firstChild(); child != null; child = child.sibling()) {\r\n \t\tif (child.reachedby == this) {\r\n \t\t\tbreak;\r\n \t\t}\r\n \t\t++idx;\r\n \t}\r\n \treturn idx;\r\n }\r\n\r\n public Rational prob = null; /* behavior probability */\r\n private String _label;\r\n \r\n public void setLabel(String value) { _label = value; }\r\n\r\n public int uid() { return _uid; }\r\n \r\n public Iset iset() {\r\n \treturn _iset;\r\n }\r\n \r\n public void setIset(Iset iset) {\r\n \t_iset = iset;\r\n }\r\n \r\n @Override\r\n public String toString()\r\n {\r\n \tif (_label != null) {\r\n \t\treturn _label;\r\n \t} else if (prob != null && _iset.player() == Player.CHANCE) {\r\n \t\treturn String.format(\"%s(%s)\", Player.CHANCE_NAME, prob.toString());\r\n \t}\r\n \tint setIdx = setIdx();\r\n if (setIdx < 0) return \"()\";\r\n return String.format(\"%s%d\", _iset.name(), setIdx); //index in the parent iset array\r\n } \r\n}\r" ]
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.w3c.dom.Document; import lse.math.games.Rational; import lse.math.games.tree.ExtensiveForm; import lse.math.games.tree.Outcome; import lse.math.games.tree.Node; import lse.math.games.tree.Iset; import lse.math.games.tree.Move; import lse.math.games.tree.Player;
} if (parentNode != null) { log.fine("XMLReader: processing child of " + parentNode.uid()); parentNode.addChild(node); } // process iset // if parent is an iset use that // if iset ref exists use that (make sure player is not also set) // if player exists create a new iset for that (don't add to dictionary) // else throw an error String isetId = getAttribute(elem, "iset"); if (elem.getParentNode() != null && "iset".equals(elem.getParentNode().getNodeName())) { if (isetId != null) { log.warning("Warning: @iset attribute is set for a node nested in an iset tag. Ignored."); } isetId = getAttribute(elem.getParentNode(), "id"); } String playerId = getAttribute(elem, "player"); Player player = (playerId != null) ? getPlayer(playerId) : Player.CHANCE; Iset iset = null; if (isetId == null) { iset = tree.createIset(player); singletons.add(iset); // root is already taken care of } else { //if (elem.@player != undefined) trace("Warning: @player attribute is set for a node that references an iset. Ignored."); //look it up in the map, if it doesn't exist create it and add it iset = isets.get(isetId); if (iset == null) { iset = tree.createIset(isetId, player); isets.put(isetId, iset); } else { if (player != Player.CHANCE) { if (iset.player() != Player.CHANCE && player != iset.player()) { log.warning("Warning: @player attribute conflicts with earlier iset player assignment. Ignored."); } iset.setPlayer(player); } } } tree.addToIset(node, iset); // set up the moves processMove(elem, node, parentNode); /* String moveId = getAttribute(elem, "move"); if (moveId != null) { String moveIsetId = parentNode.iset() != null ? parentNode.iset().name() : ""; Move move = moves.get(moveIsetId + "::" + moveId); if (move == null) { move = tree.createMove(moveId); moves.put(moveIsetId + "::" + moveId, move); } node.reachedby = move; } else if (parentNode != null) { // assume this comes from a chance node node.reachedby = tree.createMove(); log.fine("Node " + id + " has a parent, but no incoming probability or move is specified"); } String probStr = getAttribute(elem, "prob"); if (probStr != null && node.reachedby != null) { node.reachedby.prob = Rational.valueOf(probStr); } else if (node.reachedby != null) { log.fine("Warning: @move is missing probability. Prior belief OR chance will be random."); } */ log.fine("node: " + id + ", iset: " + isetId + ", pl: " + (getAttribute(elem, "player") == null ? getAttribute(elem.getParentNode(), "player") : getAttribute(elem, "player")) + (node.reachedby != null ? ", mv: " + node.uid() : "")); for (org.w3c.dom.Node child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if ("node".equals(child.getNodeName())) { processNode(child, node); } else if ("outcome".equals(child.getNodeName())) { processOutcome(child, node); } else { log.warning("Ignoring unknown element:\r\n" + child); } } } private void processOutcome(org.w3c.dom.Node elem, Node parent) { // Create wrapping node // get parent from dictionary... if it doesn't exist then the outcome must be the root Node wrapNode = parent != null ? tree.createNode() : tree.root(); if (parent != null) parent.addChild(wrapNode); processMove(elem, wrapNode, parent); /* String moveId = getAttribute(elem, "move"); if (moveId != null) { String moveIsetId = (parent != null && parent.iset() != null) ? parent.iset().name() : ""; Move move = moveId != null ? moves.get(moveIsetId + "::" + moveId) : null; if (move == null && moveId != null) { move = tree.createMove(moveId); moves.put(moveIsetId + "::" + moveId, move); } wrapNode.reachedby = move; } else if (parent != null) { wrapNode.reachedby = tree.createMove(); log.fine("Node " + wrapNode.uid() + " has a parent, but no incoming probability or move is specified"); } String probStr = getAttribute(elem, "prob"); if (probStr != null && wrapNode.reachedby != null) { wrapNode.reachedby.prob = Rational.valueOf(probStr); } else if (wrapNode.reachedby != null) { log.fine("Warning: @move is missing probability. Prior belief OR chance will be random."); } */ Outcome outcome = tree.createOutcome(wrapNode); for (org.w3c.dom.Node child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if ("payoff".equals(child.getNodeName())) { String playerId = getAttribute(child, "player");
Rational payoff = Rational.valueOf(getAttribute(child, "value"));
0
kkrugler/yalder
tools/src/main/java/org/krugler/yalder/tools/ModelBuilderTool.java
[ "public abstract class BaseLanguageDetector {\n\n public static final double DEFAULT_ALPHA = 0.000002;\n public static final double DEFAULT_DAMPENING = 0.001;\n\n protected static final double MIN_LANG_PROBABILITY = 0.1;\n protected static final double MIN_GOOD_LANG_PROBABILITY = 0.99;\n \n protected int _maxNGramLength;\n \n // The probability we use for an ngram when we have no data for it for a given language.\n protected double _alpha;\n \n // Used to increase an ngram's probability, to reduce rapid swings in short text\n // snippets. The probability is increased by (1 - prob) * dampening.\n protected double _dampening = DEFAULT_DAMPENING;\n\n protected Collection<? extends BaseLanguageModel> _models;\n \n protected static int getMaxNGramLengthFromModels(Collection<? extends BaseLanguageModel> models) {\n int maxNGramLength = 0;\n Iterator<? extends BaseLanguageModel> iter = models.iterator();\n while (iter.hasNext()) {\n maxNGramLength = Math.max(maxNGramLength, iter.next().getMaxNGramLength());\n }\n \n return maxNGramLength;\n }\n\n public BaseLanguageDetector(Collection<? extends BaseLanguageModel> models, int maxNGramLength) {\n _models = models;\n _maxNGramLength = maxNGramLength;\n _alpha = DEFAULT_ALPHA;\n }\n \n public BaseLanguageDetector setAlpha(double alpha) {\n _alpha = alpha;\n return this;\n }\n \n public double getAlpha() {\n return _alpha;\n }\n \n public BaseLanguageDetector setDampening(double dampening) {\n _dampening = dampening;\n return this;\n }\n \n public double getDampening() {\n return _dampening;\n }\n \n /**\n * Return true if at least one of the loaded models is for a language that\n * is weakly equal to <target>. This means that (in theory) we could get a\n * detection result that would also be weakly equal to <target>.\n * \n * @param target Language of interest\n * @return true if it's supported by the loaded set of models.\n */\n \n public boolean supportsLanguage(LanguageLocale target) {\n for (BaseLanguageModel model : _models) {\n if (model.getLanguage().weaklyEqual(target)) {\n return true;\n }\n }\n \n return false;\n }\n \n public BaseLanguageModel getModel(LanguageLocale language) {\n for (BaseLanguageModel model : _models) {\n \n if (model.getLanguage().equals(language)) {\n return model;\n }\n \n // TODO if weakly equal, and no other set to weak, save it\n }\n \n throw new IllegalArgumentException(\"Unknown language: \" + language);\n }\n\n public abstract void reset();\n \n public abstract void addText(char[] text, int offset, int length);\n \n public void addText(String text) {\n addText(text.toCharArray(), 0, text.length());\n }\n \n public abstract Collection<DetectionResult> detect();\n \n public boolean hasEnoughText() {\n return false;\n }\n \n}", "public abstract class BaseLanguageModel {\n\n // Version of model, for de-serialization\n public static final int MODEL_VERSION = 1;\n \n // The normalized counts are relative to this count, so that we\n // can combine languages built with different amounts of data.\n public static final int NORMALIZED_COUNT = 1000000;\n\n protected LanguageLocale _modelLanguage;\n \n protected int _maxNGramLength;\n \n public BaseLanguageModel() {\n }\n \n public BaseLanguageModel(LanguageLocale modelLanguage, int maxNGramLength) {\n _modelLanguage = modelLanguage;\n _maxNGramLength = maxNGramLength;\n }\n \n public LanguageLocale getLanguage() {\n return _modelLanguage;\n }\n \n public int getMaxNGramLength() {\n return _maxNGramLength;\n }\n \n @Override\n public String toString() {\n return String.format(\"'%s': %d ngrams\", _modelLanguage, size());\n }\n\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + _maxNGramLength;\n result = prime * result + ((_modelLanguage == null) ? 0 : _modelLanguage.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n BaseLanguageModel other = (BaseLanguageModel) obj;\n if (_maxNGramLength != other._maxNGramLength)\n return false;\n if (_modelLanguage == null) {\n if (other._modelLanguage != null)\n return false;\n } else if (!_modelLanguage.equals(other._modelLanguage))\n return false;\n return true;\n }\n\n public abstract int size();\n public abstract int prune(int minNormalizedCount);\n}", "public class DetectionResult implements Comparable<DetectionResult> {\n\n private LanguageLocale _language;\n private double _score;\n private double _confidence;\n private String _details;\n \n public DetectionResult(LanguageLocale language, double score) {\n _language = language;\n _score = score;\n _confidence = 0.0;\n _details = \"\";\n }\n\n public LanguageLocale getLanguage() {\n return _language;\n }\n\n public void setLanguage(LanguageLocale language) {\n _language = language;\n }\n \n public double getScore() {\n return _score;\n }\n\n public void setScore(double score) {\n _score = score;\n }\n\n public double getConfidence() {\n return _confidence;\n }\n\n public void setConfidence(double confidence) {\n _confidence = confidence;\n }\n\n public void setDetails(String details) {\n _details = details;\n }\n \n public String getDetails() {\n return _details;\n }\n \n /* Do reverse sorting.\n * (non-Javadoc)\n * @see java.lang.Comparable#compareTo(java.lang.Object)\n */\n @Override\n public int compareTo(DetectionResult o) {\n if (_score > o._score) {\n return -1;\n } else if (_score < o._score) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return String.format(\"Language '%s' with score %f and confidence %f\", _language, _score, _confidence);\n }\n \n}", "public class LanguageLocale {\n\n private static Map<String, LanguageLocale> LOCALES = new HashMap<String, LanguageLocale>();\n \n // Java Locale support uses ISO 639-2 bibliographic codes, versus the terminological codes\n // (which is what we use). So we have a table to normalize from bib to term, and we need\n // a second table to get the names for terminological codes.\n \n // From http://www.loc.gov/standards/iso639-2/php/English_list.php\n private static Map<String, String> BIB_TO_TERM_MAPPING = new HashMap<String, String>();\n \n static {\n BIB_TO_TERM_MAPPING.put(\"alb\", \"sqi\");\n BIB_TO_TERM_MAPPING.put(\"arm\", \"hye\");\n BIB_TO_TERM_MAPPING.put(\"baq\", \"eus\");\n BIB_TO_TERM_MAPPING.put(\"bur\", \"mya\");\n BIB_TO_TERM_MAPPING.put(\"chi\", \"zho\");\n BIB_TO_TERM_MAPPING.put(\"cze\", \"ces\");\n BIB_TO_TERM_MAPPING.put(\"dut\", \"nld\");\n BIB_TO_TERM_MAPPING.put(\"geo\", \"kat\");\n BIB_TO_TERM_MAPPING.put(\"ger\", \"deu\");\n BIB_TO_TERM_MAPPING.put(\"gre\", \"ell\");\n BIB_TO_TERM_MAPPING.put(\"ice\", \"isl\");\n BIB_TO_TERM_MAPPING.put(\"mac\", \"mkd\");\n BIB_TO_TERM_MAPPING.put(\"may\", \"msa\");\n BIB_TO_TERM_MAPPING.put(\"mao\", \"mri\");\n BIB_TO_TERM_MAPPING.put(\"rum\", \"ron\");\n BIB_TO_TERM_MAPPING.put(\"per\", \"fas\");\n BIB_TO_TERM_MAPPING.put(\"slo\", \"slk\");\n BIB_TO_TERM_MAPPING.put(\"tib\", \"bod\");\n BIB_TO_TERM_MAPPING.put(\"wel\", \"cym\");\n BIB_TO_TERM_MAPPING.put(\"fre\", \"fra\");\n }\n\n // Java Locale support uses \n private static Map<String, String> TERM_CODE_TO_NAME = new HashMap<String, String>();\n static {\n TERM_CODE_TO_NAME.put(\"sqi\", \"Albanian\");\n TERM_CODE_TO_NAME.put(\"hye\", \"Armenian\");\n TERM_CODE_TO_NAME.put(\"eus\", \"Basque\");\n TERM_CODE_TO_NAME.put(\"zho\", \"Chinese\");\n TERM_CODE_TO_NAME.put(\"ces\", \"Czech\");\n TERM_CODE_TO_NAME.put(\"nld\", \"Dutch\");\n TERM_CODE_TO_NAME.put(\"kat\", \"Georgian\");\n TERM_CODE_TO_NAME.put(\"deu\", \"German\");\n TERM_CODE_TO_NAME.put(\"ell\", \"Greek\");\n TERM_CODE_TO_NAME.put(\"isl\", \"Icelandic\");\n TERM_CODE_TO_NAME.put(\"mkd\", \"Macedonian\");\n TERM_CODE_TO_NAME.put(\"msa\", \"Malay\");\n TERM_CODE_TO_NAME.put(\"mri\", \"Maori\");\n TERM_CODE_TO_NAME.put(\"ron\", \"Romanian\");\n TERM_CODE_TO_NAME.put(\"fas\", \"Persian\");\n TERM_CODE_TO_NAME.put(\"slk\", \"Slovak\");\n TERM_CODE_TO_NAME.put(\"bod\", \"Tibetan\");\n TERM_CODE_TO_NAME.put(\"cym\", \"Welsh\");\n TERM_CODE_TO_NAME.put(\"fra\", \"French\");\n }\n \n private static Map<String, String> IMPLICIT_SCRIPT = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n IMPLICIT_SCRIPT.put(\"aze\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"bos\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"uzb\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"tuk\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"msa\", \"Latn\");\n \n IMPLICIT_SCRIPT.put(\"mon\", \"Cyrl\");\n IMPLICIT_SCRIPT.put(\"srp\", \"Cyrl\");\n \n IMPLICIT_SCRIPT.put(\"pan\", \"Guru\");\n }\n \n private static Map<String, String> IMPLICIT_COUNTRY_SCRIPT = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n IMPLICIT_COUNTRY_SCRIPT.put(\"zhoTW\", \"Hant\");\n IMPLICIT_COUNTRY_SCRIPT.put(\"zhoCN\", \"Hans\");\n }\n \n \n \n private static Map<String, String> SPECIFIC_TO_MACRO = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n SPECIFIC_TO_MACRO.put(\"nno\", \"nor\");\n SPECIFIC_TO_MACRO.put(\"nob\", \"nor\");\n }\n\n private String _language; // ISO 639-2/T language code (3 letters)\n private String _script; // ISO 15924 script name (4 letters) or empty\n \n public static LanguageLocale fromString(String languageName) {\n if (!LOCALES.containsKey(languageName)) {\n\n synchronized (LOCALES) {\n // Make sure nobody added it after we did our check.\n if (!LOCALES.containsKey(languageName)) {\n LOCALES.put(languageName, new LanguageLocale(languageName));\n }\n }\n }\n \n return LOCALES.get(languageName);\n }\n \n /**\n * Return a language name (suitable for passing into the fromString method) from\n * a language (2 or 3 character) and script (always four character, e.g. \"Latn\").\n * \n * @param language\n * @param script\n * @return standard format for language name\n */\n public static String makeLanguageName(String language, String script) {\n return String.format(\"%s-%s\", language, script);\n }\n \n private LanguageLocale(String languageTag) {\n Locale locale = Locale.forLanguageTag(languageTag);\n \n // First convert the language code to ISO 639-2/T\n _language = locale.getISO3Language();\n if (_language.isEmpty()) {\n throw new IllegalArgumentException(\"A valid language code must be provided\");\n }\n \n // See if we need to convert from 639-2/B to 639-2/T\n if (BIB_TO_TERM_MAPPING.containsKey(_language)) {\n _language = BIB_TO_TERM_MAPPING.get(_language);\n }\n \n // Now see if we have a script.\n _script = locale.getScript();\n // TODO - do we want to verify it's a valid script? What happens if you pass\n // in something like en-latin?\n \n // If the script is empty, and we have a country, then we might want to\n // explicitly set the script as that's how it was done previously (e.g. zh-TW\n // to set the Hant script, versus zh-CN for Hans script)\n if (_script.isEmpty()) {\n String country = locale.getCountry();\n // TODO convert UN M.39 code into two letter country \n if (!country.isEmpty()) {\n // TODO look up language + country\n String languagePlusCountry = _language + country;\n if (IMPLICIT_COUNTRY_SCRIPT.containsKey(languagePlusCountry)) {\n _script = IMPLICIT_COUNTRY_SCRIPT.get(languagePlusCountry);\n }\n }\n }\n \n // If the script isn't empty, and it's the default script for the language,\n // then remove it so we don't include it in comparisons.\n if (!_script.isEmpty() && _script.equals(IMPLICIT_SCRIPT.get(_language))) {\n _script = \"\";\n }\n }\n\n // We add a special \"weakly equal\" method that's used to\n // decide if the target locale matches us. The \"target\" in\n // this case is what we're looking for (what we want it to be)\n // versus what we got from detection\n // versus what we expect it to be. In this case,\n // target result match?\n // zho zho yes\n // zho-Hant zho-Hant yes\n // zho zho-Hant yes\n // zho-Hant zho no (want explicitly trad chinese, got unspecified)\n // zho-Hant zho-Hans no\n \n // FUTURE support country code for dialects?\n // target result match?\n // en en-GB yes\n // en-GB en-US no\n // en-GB en no\n \n public boolean weaklyEqual(LanguageLocale target) {\n if (!_language.equals(target._language)) {\n // But wait - maybe target is a macro language, and we've got\n // a more specific result...if so then they're still (maybe)\n // equal.\n if (!SPECIFIC_TO_MACRO.containsKey(_language) || !SPECIFIC_TO_MACRO.get(_language).equals(target._language)) {\n return false;\n }\n }\n \n if (target._script.isEmpty()) {\n // Target says we don't care about script, so always matches.\n return true;\n } else {\n return _script.equals(target._script);\n }\n }\n \n public String getName() {\n if (!_script.isEmpty()) {\n return String.format(\"%s-%s\", _language, _script);\n } else {\n return _language;\n }\n }\n \n public String getISO3LetterName() {\n return _language;\n }\n\n public final String toString() {\n String languageTag;\n if (!_script.isEmpty()) {\n languageTag = String.format(\"%s-%s\", _language, _script);\n } else {\n languageTag = _language;\n }\n \n String displayLanguage = Locale.forLanguageTag(languageTag).getDisplayLanguage();\n if (TERM_CODE_TO_NAME.containsKey(_language)) {\n // It's a terminological code, so we have to provide the name ourselves.\n displayLanguage = TERM_CODE_TO_NAME.get(_language);\n }\n \n return String.format(\"%s (%s)\", languageTag, displayLanguage);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((_language == null) ? 0 : _language.hashCode());\n result = prime * result + ((_script == null) ? 0 : _script.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n LanguageLocale other = (LanguageLocale) obj;\n if (_language == null) {\n if (other._language != null)\n return false;\n } else if (!_language.equals(other._language))\n return false;\n if (_script == null) {\n if (other._script != null)\n return false;\n } else if (!_script.equals(other._script))\n return false;\n return true;\n }\n\n\n \n}", "public class ModelBuilder {\n private static final Logger LOGGER = LoggerFactory.getLogger(ModelBuilder.class);\n\n public static final int DEFAULT_MAX_NGRAM_LENGTH = 4;\n \n // Minimum frequency for ngram\n public static final double DEFAULT_MIN_NGRAM_FREQUENCY = 0.00002;\n \n // Minimum number of ngrams we want to see for a language.\n // Since we get roughly <max length> * chars number of ngrams, we're really saying we\n // want at least 4000 characters.\n public static final int DEFAULT_MIN_NGRAMS_FOR_LANGUAGE = 4000 * DEFAULT_MAX_NGRAM_LENGTH;\n \n private Map<LanguageLocale, IntIntMap> _perLangHashCounts;\n private Map<LanguageLocale, Map<String, Integer>> _perLangTextCounts;\n \n private int _maxNGramLength = DEFAULT_MAX_NGRAM_LENGTH;\n private double _minNGramFrequency = DEFAULT_MIN_NGRAM_FREQUENCY;\n private int _minNGramsForLanguage = DEFAULT_MIN_NGRAMS_FOR_LANGUAGE;\n private boolean _binaryMode = true;\n \n public ModelBuilder() {\n _perLangTextCounts = new HashMap<LanguageLocale, Map<String, Integer>>();\n _perLangHashCounts = new HashMap<LanguageLocale, IntIntMap>();\n }\n \n public ModelBuilder setMaxNGramLength(int maxNGramLength) {\n _maxNGramLength = maxNGramLength;\n return this;\n }\n \n public int getMaxNGramLength() {\n return _maxNGramLength;\n }\n \n public ModelBuilder setMinNGramFrequency(double minNGramFrequency) {\n _minNGramFrequency = minNGramFrequency;\n return this;\n }\n \n public double getMinNGramFrequency() {\n return _minNGramFrequency;\n }\n \n public ModelBuilder setBinaryMode(boolean binaryMode) {\n _binaryMode = binaryMode;\n return this;\n }\n \n public void addTrainingDoc(String language, String text) {\n addTrainingDoc(LanguageLocale.fromString(language), text);\n }\n \n // TODO make sure we haven't already made the languages.\n public void addTrainingDoc(LanguageLocale language, String text) {\n if (_binaryMode) {\n addTrainingDocNGramsAsHashes(language, text);\n } else {\n addTrainingDocNGramsAsText(language, text);\n }\n }\n \n public void addTrainingDocNGramsAsText(LanguageLocale language, String text) {\n Map<String, Integer> ngramCounts = _perLangTextCounts.get(language);\n if (ngramCounts == null) {\n ngramCounts = new HashMap<String, Integer>();\n _perLangTextCounts.put(language, ngramCounts);\n }\n \n TextTokenizer tokenizer = new TextTokenizer(text, _maxNGramLength);\n while (tokenizer.hasNext()) {\n String token = tokenizer.next();\n Integer curCount = ngramCounts.get(token);\n if (curCount == null) {\n ngramCounts.put(token, 1);\n } else {\n ngramCounts.put(token, curCount + 1);\n }\n }\n }\n \n public void addTrainingDocNGramsAsHashes(LanguageLocale language, String text) {\n IntIntMap ngramCounts = _perLangHashCounts.get(language);\n if (ngramCounts == null) {\n ngramCounts = new IntIntMap();\n _perLangHashCounts.put(language, ngramCounts);\n }\n \n HashTokenizer tokenizer = new HashTokenizer(text, _maxNGramLength);\n while (tokenizer.hasNext()) {\n int token = tokenizer.next();\n ngramCounts.add(token, 1);\n }\n }\n \n // TODO make sure at least one document has been added.\n \n public Collection<BaseLanguageModel> makeModels() {\n if (_binaryMode) {\n return makeBinaryModels();\n } else {\n return makeTextModels();\n }\n }\n \n private Collection<BaseLanguageModel> makeTextModels() {\n Set<LanguageLocale> languages = new HashSet<LanguageLocale>(_perLangTextCounts.keySet());\n \n // For each language, record the total number of ngrams\n Map<LanguageLocale, Integer> perLanguageTotalNGramCount = new HashMap<LanguageLocale, Integer>();\n \n for (LanguageLocale language : languages) {\n int languageNGrams = 0;\n \n Map<String, Integer> ngramCounts = _perLangTextCounts.get(language);\n for (String ngram : ngramCounts.keySet()) {\n int count = ngramCounts.get(ngram);\n languageNGrams += count;\n }\n \n perLanguageTotalNGramCount.put(language, languageNGrams);\n }\n\n int minNormalizedCount = (int)Math.round(_minNGramFrequency) * BaseLanguageModel.NORMALIZED_COUNT;\n Set<LanguageLocale> languagesToSkip = new HashSet<LanguageLocale>();\n for (LanguageLocale language : languages) {\n int ngramsForLanguage = perLanguageTotalNGramCount.get(language);\n \n // if ngrams for language is less than a limit, skip the language\n if (ngramsForLanguage < _minNGramsForLanguage) {\n System.out.println(String.format(\"Skipping '%s' because it only has %d ngrams\", language, ngramsForLanguage));\n languagesToSkip.add(language);\n continue;\n }\n \n double datasizeNormalization = (double)BaseLanguageModel.NORMALIZED_COUNT / (double)ngramsForLanguage;\n Map<String, Integer> ngramCounts = _perLangTextCounts.get(language);\n Map<String, Integer> normalizedCounts = new HashMap<>(ngramCounts.size());\n for (String ngram : ngramCounts.keySet()) {\n int count = ngramCounts.get(ngram);\n int adjustedCount = (int)Math.round(count * datasizeNormalization);\n \n // Set to ignore if we don't have enough of these to matter.\n // TODO actually key this off alpha somehow, as if we don't have an ngram then\n // we give it a probability of x?\n if (adjustedCount >= minNormalizedCount) {\n normalizedCounts.put(ngram, adjustedCount);\n }\n }\n \n _perLangTextCounts.put(language, normalizedCounts);\n }\n\n // Remove the languages we want to skip\n languages.removeAll(languagesToSkip);\n \n List<BaseLanguageModel> models = new ArrayList<>();\n for (LanguageLocale language : languages) {\n Map<String, Integer> ngramCounts = _perLangTextCounts.get(language);\n TextLanguageModel model = new TextLanguageModel(language, _maxNGramLength, ngramCounts);\n models.add(model);\n }\n\n return models;\n }\n \n private Collection<BaseLanguageModel> makeBinaryModels() {\n Set<LanguageLocale> languages = new HashSet<LanguageLocale>(_perLangHashCounts.keySet());\n \n // For each language, record the total number of ngrams\n Map<LanguageLocale, Integer> perLanguageTotalNGramCount = new HashMap<LanguageLocale, Integer>();\n \n for (LanguageLocale language : languages) {\n IntIntMap ngramCounts = _perLangHashCounts.get(language);\n perLanguageTotalNGramCount.put(language, ngramCounts.sum());\n }\n\n int minNormalizedCount = (int)Math.round(_minNGramFrequency) * BaseLanguageModel.NORMALIZED_COUNT;\n Set<LanguageLocale> languagesToSkip = new HashSet<LanguageLocale>();\n for (LanguageLocale language : languages) {\n int ngramsForLanguage = perLanguageTotalNGramCount.get(language);\n \n // if ngrams for language is less than a limit, skip the language\n if (ngramsForLanguage < _minNGramsForLanguage) {\n System.out.println(String.format(\"Skipping '%s' because it only has %d ngrams\", language, ngramsForLanguage));\n languagesToSkip.add(language);\n continue;\n } else {\n System.out.println(String.format(\"%s has %d total ngrams\", language, ngramsForLanguage));\n }\n \n double datasizeNormalization = (double)BaseLanguageModel.NORMALIZED_COUNT / (double)ngramsForLanguage;\n IntIntMap ngramCounts = _perLangHashCounts.get(language);\n IntIntMap normalizedCounts = new IntIntMap(ngramCounts.size());\n \n for (int ngramHash : ngramCounts.keySet()) {\n int count = ngramCounts.getValue(ngramHash);\n int adjustedCount = (int)Math.round(count * datasizeNormalization);\n \n // Set to ignore if we don't have enough of these to matter.\n // FUTURE change limit based on length of the ngram (which we no longer have)?\n if (adjustedCount >= minNormalizedCount) {\n normalizedCounts.add(ngramHash, adjustedCount);\n }\n }\n \n _perLangHashCounts.put(language, normalizedCounts);\n }\n\n // Remove the languages we want to skip\n languages.removeAll(languagesToSkip);\n \n List<BaseLanguageModel> models = new ArrayList<>();\n for (LanguageLocale language : languages) {\n BaseLanguageModel model = new HashLanguageModel(language, _maxNGramLength, _perLangHashCounts.get(language));\n models.add(model);\n }\n\n return models;\n }\n\n}", "public class HashLanguageDetector extends BaseLanguageDetector {\n\n private static final int RENORMALIZE_INTERVAL = 10;\n private static final int EARLY_TERMINATION_INTERVAL = RENORMALIZE_INTERVAL * 11;\n\n // Map from language of model to index used for accessing arrays.\n private Map<LanguageLocale, Integer> _langToIndex;\n \n // Map from ngram (hash) to index.\n private IntToIndex _ngramToIndex;\n \n // For each ngram, that only occurs in a single language\n // model, store that model's index.\n private Int2IntMap _ngramToOneLanguage;\n \n // For each ngram, store the probability for each language.\n private double[][] _ngramProbabilities;\n \n // Dynamic state when processing text for a document. There is one\n // double value for every supported language (based on loaded models)\n double[] _langProbabilities;\n double[] _singleLangProbabilities;\n \n // For normalization, confidence, and early termination.\n int _numKnownNGrams;\n int _numUnknownNGrams;\n int _curBestLanguageIndex;\n\n boolean _hasEnoughText;\n \n // TODO support mixed language mode.\n // TODO support short text mode (renormalize more often)\n \n public HashLanguageDetector(Collection<BaseLanguageModel> models) {\n this(models, getMaxNGramLengthFromModels(models));\n }\n\n public HashLanguageDetector(Collection<BaseLanguageModel> models, int maxNGramLength) {\n super(models, maxNGramLength);\n\n // TODO verify that each model is a binary model\n\n int numLanguages = makeLangToIndex(models);\n \n // Build a master map from ngram to per-language probabilities\n // Each model should contain a normalized count (not probability) of the ngram\n // so we can compute probabilities for languages being mixed-in.\n \n // So the first step is to build a map from every ngram (hash) to an index.\n _ngramToIndex = new IntToIndex();\n _ngramToOneLanguage = new Int2IntOpenHashMap();\n for (BaseLanguageModel baseModel : _models) {\n int langIndex = langToIndex(baseModel.getLanguage());\n HashLanguageModel model = (HashLanguageModel)baseModel;\n IntIntMap langCounts = model.getNGramCounts();\n for (int ngramHash : langCounts.keySet()) {\n _ngramToIndex.add(ngramHash);\n if (_ngramToOneLanguage.containsKey(ngramHash)) {\n _ngramToOneLanguage.put(ngramHash, -1);\n } else {\n _ngramToOneLanguage.put(ngramHash, langIndex);\n }\n }\n }\n \n // For singletons, remove from _ngramToIndex, and add to _ngramToOneLang, with\n // the language index.\n for (int key : _ngramToOneLanguage.keySet()) {\n if (_ngramToOneLanguage.get(key) == -1) {\n _ngramToOneLanguage.remove(key);\n } else {\n _ngramToIndex.remove(key);\n }\n }\n \n // Now we can set a unique index for each ngram.\n _ngramToIndex.setIndexes();\n \n int uniqueNGrams = _ngramToIndex.size();\n int [][] ngramCounts = new int[uniqueNGrams][];\n \n _ngramProbabilities = new double[uniqueNGrams][];\n \n for (BaseLanguageModel baseModel : _models) {\n HashLanguageModel model = (HashLanguageModel)baseModel;\n LanguageLocale language = model.getLanguage();\n int langIndex = langToIndex(language);\n \n IntIntMap langCounts = model.getNGramCounts();\n for (int ngramHash : langCounts.keySet()) {\n // If it's not one of the ngrams for a single language,\n // we need to calculate probabilities across languages.\n if (!_ngramToOneLanguage.containsKey(ngramHash)) {\n int index = _ngramToIndex.getIndex(ngramHash);\n int[] counts = ngramCounts[index];\n if (counts == null) {\n counts = new int[numLanguages];\n ngramCounts[index] = counts;\n }\n\n counts[langIndex] = langCounts.getValue(ngramHash);\n }\n }\n }\n \n // Now we can calculate the probabilities\n for (int i = 0; i < uniqueNGrams; i++) {\n double totalCount = 0;\n int[] counts = ngramCounts[i];\n for (int j = 0; j < counts.length; j++) {\n totalCount += counts[j];\n }\n \n \n double[] probs = new double[numLanguages];\n for (int j = 0; j < counts.length; j++) {\n probs[j] = counts[j] / totalCount;\n }\n \n _ngramProbabilities[i] = probs;\n }\n }\n \n private int langToIndex(LanguageLocale language) {\n return _langToIndex.get(language);\n }\n \n private int makeLangToIndex(Collection<BaseLanguageModel> models) {\n // Build a master map from language to index (0...n-1), which we'll use to index into\n // arrays associated with each ngram.\n \n _langToIndex = new HashMap<>(_models.size());\n int curIndex = 0;\n for (BaseLanguageModel model : _models) {\n if (_langToIndex.put(model.getLanguage(), curIndex) != null) {\n throw new IllegalArgumentException(\"Got two models with the same language: \" + model.getLanguage());\n }\n \n curIndex += 1;\n }\n \n return curIndex;\n }\n\n @Override\n public void reset() {\n final int numLanguages = _langToIndex.size();\n _langProbabilities = new double[numLanguages];\n double startingProb = 1.0 / numLanguages;\n for (int i = 0; i < numLanguages; i++) {\n _langProbabilities[i] = startingProb;\n }\n \n _singleLangProbabilities = new double[numLanguages];\n \n _numKnownNGrams = 0;\n _numUnknownNGrams = 0;\n _curBestLanguageIndex = -1;\n _hasEnoughText = false;\n }\n \n @Override\n public void addText(char[] text, int offset, int length) {\n final int numLanguages = _langToIndex.size();\n \n HashTokenizer tokenizer = new HashTokenizer(text, offset, length, _maxNGramLength);\n while (tokenizer.hasNext()) {\n int hash = tokenizer.next();\n int index = _ngramToIndex.getIndex(hash);\n \n double[] ngramProbabilities = null;\n int singleLangIndex = -1;\n if (index == -1) {\n // Might be an ngram that's only in the model for single language\n singleLangIndex = _ngramToOneLanguage.get(hash);\n if (singleLangIndex == -1) {\n // FUTURE track how many unknown ngrams we get, and use that\n // to adjust probabilities.\n _numUnknownNGrams += 1;\n continue;\n }\n \n ngramProbabilities = _singleLangProbabilities;\n ngramProbabilities[singleLangIndex] = 1.0;\n } else {\n ngramProbabilities = _ngramProbabilities[index];\n }\n \n _numKnownNGrams += 1;\n \n for (int langIndex = 0; langIndex < numLanguages; langIndex++) {\n double prob = ngramProbabilities[langIndex];\n \n // Unknown ngrams for the language get a default probability of \"alpha\".\n if (prob == 0.0) {\n prob = _alpha;\n }\n \n // apply dampening, which increases the probability by a percentage\n // of the delta from 1.0, and thus reduces the rapid swings caused by\n // getting a few ngrams in a row with very low probability for an\n // interesting language.\n prob += (1.0 - prob) * _dampening;\n \n _langProbabilities[langIndex] *= prob;\n }\n \n if (singleLangIndex != -1) {\n _singleLangProbabilities[singleLangIndex] = 0.0;\n }\n \n // So we don't let probabilities become 0.0, we have to adjust\n if ((_numKnownNGrams % RENORMALIZE_INTERVAL) == 0) {\n normalizeLangProbabilities();\n }\n \n // See if we haven't had a change in a very probable language in N ngrams\n // We rely on probabilities being normalized, so our interval is always a\n // multiple of the renormalization interval.\n \n // TODO need to factor in confidence, which includes number of unknown ngrams.\n // TODO support \"mixed text\" mode, and skip this if it's true.\n if ((_numKnownNGrams % EARLY_TERMINATION_INTERVAL) == 0) {\n int newBestLanguageIndex = calcBestLanguageIndex();\n if ((newBestLanguageIndex != -1) && (newBestLanguageIndex == _curBestLanguageIndex)) {\n _hasEnoughText = true;\n break;\n }\n \n _curBestLanguageIndex = newBestLanguageIndex;\n }\n }\n }\n \n @Override\n public boolean hasEnoughText() {\n return _hasEnoughText;\n }\n \n @Override\n public Collection<DetectionResult> detect() {\n normalizeLangProbabilities();\n\n List<DetectionResult> result = new ArrayList<DetectionResult>();\n for (LanguageLocale language : _langToIndex.keySet()) {\n double curProb = _langProbabilities[_langToIndex.get(language)];\n \n if (curProb >= MIN_LANG_PROBABILITY) {\n DetectionResult dr = new DetectionResult(language, curProb);\n result.add(dr);\n }\n }\n\n Collections.sort(result);\n return result;\n }\n\n private int calcBestLanguageIndex() {\n for (int i = 0; i < _langProbabilities.length; i++) {\n if (_langProbabilities[i] > MIN_GOOD_LANG_PROBABILITY) {\n return i;\n }\n }\n\n return -1;\n }\n\n private void normalizeLangProbabilities() {\n double totalProb = 0.0;\n for (double prob : _langProbabilities) {\n totalProb += prob;\n }\n \n double scalar = 1.0/totalProb;\n \n for (int i = 0; i < _langProbabilities.length; i++) {\n _langProbabilities[i] *= scalar;\n }\n }\n\n}", "public class HashLanguageModel extends BaseLanguageModel {\n\n // Map from ngram hash to count\n private IntIntMap _normalizedCounts;\n \n /**\n * No-arg construct for deserialization\n */\n public HashLanguageModel() {\n super();\n }\n \n public HashLanguageModel(LanguageLocale modelLanguage, int maxNGramLength, IntIntMap normalizedCounts) {\n super(modelLanguage, maxNGramLength);\n _normalizedCounts = normalizedCounts;\n }\n \n @Override\n public int size() {\n return _normalizedCounts.size();\n }\n \n public int getNGramCount(int ngram) {\n return _normalizedCounts.getValue(ngram);\n }\n \n public IntIntMap getNGramCounts() {\n return _normalizedCounts;\n }\n \n @Override\n public int prune(int minNormalizedCount) {\n int totalPruned = 0;\n IntIntMap prunedCounts = new IntIntMap(_normalizedCounts.size());\n for (int ngramHash : _normalizedCounts.keySet()) {\n int count = _normalizedCounts.getValue(ngramHash);\n if (count >= minNormalizedCount) {\n prunedCounts.add(ngramHash, count);\n } else {\n totalPruned += 1;\n }\n }\n \n _normalizedCounts = prunedCounts;\n return totalPruned;\n }\n \n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + ((_normalizedCounts == null) ? 0 : _normalizedCounts.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (getClass() != obj.getClass())\n return false;\n HashLanguageModel other = (HashLanguageModel) obj;\n if (_normalizedCounts == null) {\n if (other._normalizedCounts != null)\n return false;\n } else if (!_normalizedCounts.equals(other._normalizedCounts))\n return false;\n return true;\n }\n\n public void readAsBinary(DataInput in) throws IOException {\n int version = in.readInt();\n if (version != MODEL_VERSION) {\n throw new IllegalArgumentException(\"Version doesn't match supported values, got \" + version);\n }\n \n _modelLanguage = LanguageLocale.fromString(in.readUTF());\n _maxNGramLength = in.readInt();\n \n int numNGrams = in.readInt();\n _normalizedCounts = new IntIntMap(numNGrams);\n for (int i = 0; i < numNGrams; i++) {\n int hash = in.readInt();\n int count = WritableUtils.readVInt(in);\n _normalizedCounts.add(hash, count);\n }\n }\n\n public void writeAsBinary(DataOutput out) throws IOException {\n out.writeInt(MODEL_VERSION);\n out.writeUTF(_modelLanguage.getName());\n out.writeInt(_maxNGramLength);\n out.writeInt(_normalizedCounts.size());;\n \n for (int ngramHash : _normalizedCounts.keySet()) {\n out.writeInt(ngramHash);\n WritableUtils.writeVInt(out, _normalizedCounts.getValue(ngramHash));\n }\n\n }\n}", "public class TextLanguageDetector extends BaseLanguageDetector {\n\n // For each ngram, store the probability for each language\n private Map<String, Map<LanguageLocale, Double>> _ngramProbabilities;\n private Map<LanguageLocale, Double> _langProbabilities;\n \n // Dynamic values during detection of one document.\n private int _numKnownNGrams;\n private int _numUnknownNGrams;\n \n public TextLanguageDetector(Collection<BaseLanguageModel> models) {\n this(models, getMaxNGramLengthFromModels(models));\n }\n\n public TextLanguageDetector(Collection<BaseLanguageModel> models, int maxNGramLength) {\n super(models, maxNGramLength);\n \n // TODO verify that each model is a text model\n \n // TODO here's the approach\n // Build a master map from ngram to per-language probabilities\n // Each model should contain a normalized count (not probability) of the ngram\n // so we can compute probabilities for languages being mixed-in.\n \n Map<String, Map<LanguageLocale, Integer>> ngramCounts = new HashMap<String, Map<LanguageLocale, Integer>>();\n _langProbabilities = new HashMap<LanguageLocale, Double>();\n \n for (BaseLanguageModel baseModel : _models) {\n TextLanguageModel model = (TextLanguageModel)baseModel;\n LanguageLocale language = model.getLanguage();\n _langProbabilities.put(language, 0.0);\n \n Map<String, Integer> langCounts = model.getNGramCounts();\n for (String ngram : langCounts.keySet()) {\n Map<LanguageLocale, Integer> curCounts = ngramCounts.get(ngram);\n if (curCounts == null) {\n curCounts = new HashMap<LanguageLocale, Integer>();\n ngramCounts.put(ngram, curCounts);\n }\n \n int newCount = langCounts.get(ngram);\n Integer curCount = curCounts.get(language);\n if (curCount == null) {\n curCounts.put(language, newCount);\n } else {\n curCounts.put(language, curCount + newCount);\n }\n }\n }\n \n // Now we can calculate the probabilities\n _ngramProbabilities = new HashMap<String, Map<LanguageLocale, Double>>();\n for (String ngram : ngramCounts.keySet()) {\n Map<LanguageLocale, Integer> counts = ngramCounts.get(ngram);\n double totalCount = 0;\n for (LanguageLocale language : counts.keySet()) {\n totalCount += counts.get(language);\n }\n \n Map<LanguageLocale, Double> probabilities = new HashMap<LanguageLocale, Double>();\n for (LanguageLocale language : counts.keySet()) {\n probabilities.put(language, counts.get(language)/totalCount);\n }\n \n _ngramProbabilities.put(ngram, probabilities);\n }\n }\n \n @Override\n public void reset() {\n double startingProb = 1.0 / _langProbabilities.size();\n for (LanguageLocale language : _langProbabilities.keySet()) {\n _langProbabilities.put(language, startingProb);\n }\n \n _numKnownNGrams = 0;\n _numUnknownNGrams = 0;\n }\n\n @Override\n public void addText(char[] text, int offset, int length) {\n addText(text, offset, length, null, null);\n }\n \n public void addText(char[] text, int offset, int length, StringBuilder details, Set<String> detailLanguages) {\n TextTokenizer tokenizer = new TextTokenizer(text, offset, length, _maxNGramLength);\n while (tokenizer.hasNext()) {\n String ngram = tokenizer.next();\n \n Map<LanguageLocale, Double> probs = _ngramProbabilities.get(ngram);\n if (probs == null) {\n // FUTURE track how many unknown ngrams we get, and use that\n // to adjust probabilities.\n _numUnknownNGrams += 1;\n// \n// if (provideDetails) {\n// details.append(String.format(\"'%s': not found\\n\", ngram));\n// }\n// \n continue;\n }\n \n _numKnownNGrams += 1;\n if (details != null) {\n details.append(String.format(\"ngram '%s' probs:\", ngram));\n details.append(detailLanguages == null ? '\\n' : ' ');\n }\n \n for (LanguageLocale language : _langProbabilities.keySet()) {\n Double probObj = probs.get(language);\n double prob = (probObj == null ? _alpha : probObj);\n if ((details != null) && (probObj != null) && ((detailLanguages == null) || (detailLanguages.contains(language)))) {\n details.append(String.format(\"\\t'%s'=%f\", language, prob));\n details.append(detailLanguages == null ? '\\n' : ' ');\n }\n \n // apply dampening, which increases the probability by a percentage\n // of the delta from 1.0, and thus reduces the rapid swings caused by\n // getting a few ngrams in a row with very low probability for an\n // interesting language.\n prob += (1.0 - prob) * _dampening;\n \n double curProb = _langProbabilities.get(language);\n curProb *= prob;\n _langProbabilities.put(language, curProb);\n }\n \n if ((details != null) && (detailLanguages != null)) {\n details.append('\\n');\n }\n\n if ((details != null) || (_numKnownNGrams % 10) == 0) {\n normalizeLangProbabilities();\n }\n \n if (details != null) {\n details.append(\"lang probabilities: \");\n details.append(getSortedProbabilities(_langProbabilities, detailLanguages));\n details.append('\\n');\n }\n }\n }\n\n @Override\n public Collection<DetectionResult> detect() {\n \n normalizeLangProbabilities();\n\n List<DetectionResult> result = new ArrayList<DetectionResult>();\n for (LanguageLocale language : _langProbabilities.keySet()) {\n double curProb = _langProbabilities.get(language);\n \n if (curProb >= MIN_LANG_PROBABILITY) {\n DetectionResult dr = new DetectionResult(language, curProb);\n result.add(dr);\n }\n }\n\n Collections.sort(result);\n return result;\n }\n\n /**\n * Given a set of languages and each one's current probability, and an optional set of\n * languages we actually care about, return a string with the details, where languages\n * are sorted by their probability (high to low), filtered to the set of ones of interest.\n * \n * This is only used during debugging.\n * \n * @param langProbabilities\n * @param detailLanguages\n * @return sorted language+probabilities\n */\n private String getSortedProbabilities(Map<LanguageLocale, Double> langProbabilities, Set<String> detailLanguages) {\n Map<LanguageLocale, Double> remainingLanguages = new HashMap<LanguageLocale, Double>(langProbabilities);\n \n StringBuilder result = new StringBuilder();\n while (!remainingLanguages.isEmpty()) {\n double maxProbability = -1.0;\n LanguageLocale maxLanguage = null;\n for (LanguageLocale language : remainingLanguages.keySet()) {\n double langProb = remainingLanguages.get(language);\n if (langProb > maxProbability) {\n maxProbability = langProb;\n maxLanguage = language;\n }\n }\n \n if ((maxProbability > 0.0000005) && ((detailLanguages == null) || detailLanguages.contains(maxLanguage))) {\n result.append(String.format(\"'%s'=%f \", maxLanguage, maxProbability));\n remainingLanguages.remove(maxLanguage);\n } else {\n break;\n }\n }\n \n return result.toString();\n }\n\n private void normalizeLangProbabilities() {\n double totalProb = 0.0;\n for (LanguageLocale language : _langProbabilities.keySet()) {\n totalProb += _langProbabilities.get(language);\n }\n\n double scalar = 1.0/totalProb;\n \n for (LanguageLocale language : _langProbabilities.keySet()) {\n double curProb = _langProbabilities.get(language);\n curProb *= scalar;\n _langProbabilities.put(language, curProb);\n }\n }\n\n\n\n}", "public class TextLanguageModel extends BaseLanguageModel {\n\n // Constants used when writing/reading the model.\n private static final String VERSION_PREFIX = \"version:\";\n private static final String LANGUAGE_PREFIX = \"language:\";\n private static final String NGRAM_SIZE_PREFIX = \"max ngram length:\";\n private static final String NGRAM_DATA_PREFIX = \"ngrams:\";\n\n // Map from ngram to count\n private Map<String, Integer> _normalizedCounts;\n \n /**\n * No-arg construct for deserialization\n */\n public TextLanguageModel() {\n super();\n }\n \n public TextLanguageModel(LanguageLocale modelLanguage, int maxNGramLength, Map<String, Integer> normalizedCounts) {\n super(modelLanguage, maxNGramLength);\n \n _normalizedCounts = normalizedCounts;\n }\n \n public int size() {\n return _normalizedCounts.size();\n }\n \n public int getNGramCount(String ngram) {\n Integer result = _normalizedCounts.get(ngram);\n return result == null ? 0 : result;\n }\n \n public Map<String, Integer> getNGramCounts() {\n return _normalizedCounts;\n }\n \n @Override\n public int prune(int minNormalizedCount) {\n Set<String> ngramsToPrune = new HashSet<>();\n for (String ngram : _normalizedCounts.keySet()) {\n if (_normalizedCounts.get(ngram) < minNormalizedCount) {\n ngramsToPrune.add(ngram);\n }\n }\n \n for (String ngram : ngramsToPrune) {\n _normalizedCounts.remove(ngram);\n }\n \n return ngramsToPrune.size();\n }\n \n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + ((_normalizedCounts == null) ? 0 : _normalizedCounts.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (getClass() != obj.getClass())\n return false;\n TextLanguageModel other = (TextLanguageModel) obj;\n if (_normalizedCounts == null) {\n if (other._normalizedCounts != null)\n return false;\n } else if (!_normalizedCounts.equals(other._normalizedCounts))\n return false;\n return true;\n }\n\n public void writeAsText(OutputStreamWriter osw) throws IOException {\n osw.write(String.format(\"%s %d\\n\", VERSION_PREFIX, MODEL_VERSION));\n osw.write(String.format(\"%s %s\\n\", LANGUAGE_PREFIX, _modelLanguage.getName()));\n osw.write(String.format(\"%s %d\\n\", NGRAM_SIZE_PREFIX, _maxNGramLength));\n osw.write(String.format(\"%s\\n\", NGRAM_DATA_PREFIX));\n \n for (String ngram : _normalizedCounts.keySet()) {\n osw.write(String.format(\"\\t%s: %d\\n\", ngram, _normalizedCounts.get(ngram)));\n }\n }\n \n public void readAsText(InputStreamReader isw) throws IOException {\n List<String> lines = IOUtils.readLines(isw);\n if (lines.size() < 5) {\n throw new IllegalArgumentException(\"Model doesn't contain enough lines of text\");\n }\n \n // First line must be the version\n String versionLine = lines.get(0);\n if (!versionLine.startsWith(VERSION_PREFIX)) {\n throw new IllegalArgumentException(\"First line of model must be the version number\");\n }\n \n versionLine = versionLine.substring(VERSION_PREFIX.length()).trim();\n int version = Integer.parseInt(versionLine);\n if (version != MODEL_VERSION) {\n throw new IllegalArgumentException(\"Version doesn't match supported values, got \" + version);\n }\n \n // Next line must be language info.\n String languageLine = lines.get(1);\n if (!languageLine.startsWith(LANGUAGE_PREFIX)) {\n throw new IllegalArgumentException(\"Second line of model must be the language info\");\n }\n \n languageLine = languageLine.substring(LANGUAGE_PREFIX.length()).trim();\n _modelLanguage = LanguageLocale.fromString(languageLine);\n \n // Next line is the ngram max length\n String ngramSizeLine = lines.get(2);\n if (!ngramSizeLine.startsWith(NGRAM_SIZE_PREFIX)) {\n throw new IllegalArgumentException(\"Third line of model must be the max ngram length\");\n }\n \n ngramSizeLine = ngramSizeLine.substring(NGRAM_SIZE_PREFIX.length()).trim();\n _maxNGramLength = Integer.parseInt(ngramSizeLine);\n\n // Next line is the ngram header\n String ngramsLine = lines.get(3);\n if (!ngramsLine.equals(NGRAM_DATA_PREFIX)) {\n throw new IllegalArgumentException(\"Fourth line of model must be the ngram data header\");\n }\n \n Pattern p = Pattern.compile(\"\\t(.+?): (.+)\");\n Matcher m = p.matcher(\"\");\n \n _normalizedCounts = new HashMap<String, Integer>(lines.size() - 4);\n for (int i = 4; i < lines.size(); i++) {\n String ngramLine = lines.get(i);\n m.reset(ngramLine);\n if (!m.matches()) {\n throw new IllegalArgumentException(String.format(\"%d ngram in model has invalid format\", i - 3));\n }\n \n String ngram = m.group(1);\n int normalizedCount = Integer.parseInt(m.group(2));\n _normalizedCounts.put(ngram, normalizedCount);\n }\n }\n\n}" ]
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.krugler.yalder.BaseLanguageDetector; import org.krugler.yalder.BaseLanguageModel; import org.krugler.yalder.DetectionResult; import org.krugler.yalder.LanguageLocale; import org.krugler.yalder.ModelBuilder; import org.krugler.yalder.hash.HashLanguageDetector; import org.krugler.yalder.hash.HashLanguageModel; import org.krugler.yalder.text.TextLanguageDetector; import org.krugler.yalder.text.TextLanguageModel;
String text = pieces[1]; boolean correct = false; detector.reset(); detector.addText(text); Collection<DetectionResult> results = detector.detect(); if (results.isEmpty()) { System.out.println(String.format("'%s' detected as '<unknown>': %s", language, text)); } else { DetectionResult result = results.iterator().next(); if (language.equals(result.getLanguage())) { correct = true; } else { System.out.println(String.format("'%s' detected as '%s': %s", language, result.getLanguage(), text)); } } Map<LanguageLocale, Integer> mapToIncrement = correct ? correctLines : incorrectLines; Integer curCount = mapToIncrement.get(language); mapToIncrement.put(language, curCount == null ? 1 : curCount + 1); } long deltaTime = System.currentTimeMillis() - startTime; System.out.println(String.format("Detecting %d lines took %dms", lines.size(), deltaTime)); int totalCorrect = 0; int totalIncorrect = 0; for (LanguageLocale language : supportedLanguages) { Integer correctCountAsObj = correctLines.get(language); int correctCount = correctCountAsObj == null ? 0 : correctCountAsObj; totalCorrect += correctCount; Integer incorrectCountAsObj = incorrectLines.get(language); int incorrectCount = incorrectCountAsObj == null ? 0 : incorrectCountAsObj; totalIncorrect += incorrectCount; int languageCount = correctCount + incorrectCount; if (languageCount > 0) { System.out.println(String.format("'%s' error rate = %.2f", language, (100.0 * incorrectCount)/languageCount)); } } System.out.println(String.format("Total error rate = %.2f", (100.0 * totalIncorrect)/(totalCorrect +totalIncorrect))); } private void changeMode() throws IOException { String curMode = _binaryMode ? "binary" : "text"; String yesNo = readInputLine(String.format("Switch from current mode of %s (y/n)?: ", curMode)); if (yesNo.equalsIgnoreCase("y")) { _binaryMode = !_binaryMode; _builder.setBinaryMode(_binaryMode); _models = null; } } private void pruneModels() { if (_models.isEmpty()) { System.err.println("Models must be built or loaded first before pruning"); return; } String minNGramCountAsStr = readInputLine("Enter minimum normalized ngram count: "); if (minNGramCountAsStr.trim().isEmpty()) { return; } int minNGramCount = Integer.parseInt(minNGramCountAsStr); int totalPruned = 0; for (BaseLanguageModel model : _models) { totalPruned += model.prune(minNGramCount); } System.out.println(String.format("Pruned %d ngrams by setting min count to 20", totalPruned)); } private void loadModels() throws IOException { String dirname = readInputLine("Enter path to directory containing models: "); if (dirname.length() == 0) { return; } File dirFile = new File(dirname); if (!dirFile.exists()) { System.out.println("Directory must exist"); return; } if (!dirFile.isDirectory()) { System.out.println(String.format("%s is not a directory", dirFile)); return; } String modelSuffix = readInputLine("Enter type of model (bin or txt): "); boolean isBinary = modelSuffix.equals("bin"); System.out.println(String.format("Loading models from files in '%s'...", dirFile.getCanonicalPath())); Set<BaseLanguageModel> newModels = new HashSet<>(); for (File file : FileUtils.listFiles(dirFile, new String[]{"txt", "bin"}, true)) { String filename = file.getName(); Pattern p = Pattern.compile(String.format("yalder_model_(.+).%s", modelSuffix)); Matcher m = p.matcher(filename); if (!m.matches()) { continue; } // Verify that language is valid LanguageLocale.fromString(m.group(1)); // Figure out if it's binary or text BaseLanguageModel model = null; if (isBinary) { DataInputStream dis = new DataInputStream(new FileInputStream(file)); HashLanguageModel binaryModel = new HashLanguageModel(); binaryModel.readAsBinary(dis); dis.close(); model = binaryModel; } else { InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
TextLanguageModel textModel = new TextLanguageModel();
8
exoplatform/task
services/src/main/java/org/exoplatform/task/dao/jpa/TaskDAOImpl.java
[ "public static String TASK_COWORKER = \"coworker\";", "public static String TASK_MANAGER = \"status.project.manager\";", "public static String TASK_MENTIONED_USERS = \"mentionedUsers\";", "public static String TASK_PARTICIPATOR = \"status.project.participator\";", "public static String TASK_PROJECT = \"status.project\";", "public interface TaskHandler extends GenericDAO<Task, Long> {\n\n ListAccess<Task> findTasksByLabel(long labelId, List<Long> projectIds, String username, OrderBy orderBy);\n \n List<Task> findByUser(String user);\n\n ListAccess<Task> findTasks(TaskQuery query);\n\n public List<Task> findAllByMembership(String user, List<String> memberships);\n\n public <T> List<T> selectTaskField(TaskQuery query, String fieldName);\n\n Task findTaskByActivityId(String activityId);\n\n void updateStatus(Status stOld, Status stNew);\n\n void updateTaskOrder(long currentTaskId, Status newStatus, long[] orders);\n\n Set<String> getCoworker(long taskid);\n\n Task getTaskWithCoworkers(long id);\n\n List<Task> getUncompletedTasks(String user, int limit);\n\n List<Task> getWatchedTasks(String user, int limit);\n\n Long countWatchedTasks(String user);\n\n List<Task> getCollaboratedTasks(String user, int limit);\n\n Long countCollaboratedTasks(String user);\n\n List<Task> getAssignedTasks(String user, int limit);\n\n Long countAssignedTasks(String user);\n\n List<Task> getByStatus(long statusid);\n\n Long countUncompletedTasks(String user);\n\n ListAccess<Task> getIncomingTasks(String user);\n\n List<Task> getOverdueTasks(String user, int limit);\n\n Long countOverdueTasks(String user);\n\n void addWatcherToTask(String username, Task task) throws Exception;\n\n void deleteWatcherOfTask(String username,Task task) throws Exception;\n\n Set<String> getWatchersOfTask(Task task);\n\n /**\n * Find tasks assigned to a user using a term to find in title or description\n * of the task\n * \n * @param user username\n * @param memberships memberships\n * @param query term to search in title or description\n * @param limit term to limit results.\n * @return {@link List} of {@link Task}\n */\n List<Task> findTasks(String user, List<String> memberships, String query, int limit);\n\n /**\n * Count tasks assigned to a user using a search term to find in title or\n * description of the task\n * \n * @param user username\n * @param query term to search in title or description\n * @return tasks count\n */\n long countTasks(String user, String query);\n\n List<Object[]> countTaskStatusByProject(long projectId);\n}", "public class TaskQuery extends Query implements Cloneable {\n //TODO: how to remove these two field\n private List<Long> projectIds = null;\n private List<String> assignee = null;\n private List<String> coworker = null;\n private List<String> watchers = null;\n\n public TaskQuery() {\n\n }\n\n TaskQuery(AggregateCondition condition, List<OrderBy> orderBies, List<Long> projectIds, List<String> assignee, List<String> coworker, List<String> watchers) {\n super(condition, orderBies);\n this.projectIds = projectIds;\n this.assignee = assignee;\n this.coworker= coworker;\n this.watchers= watchers;\n }\n\n public static TaskQuery or(TaskQuery... queries) {\n List<Condition> cond = new ArrayList<Condition>();\n for(TaskQuery q : queries) {\n if (q.getCondition() != null) {\n cond.add(q.getCondition());\n }\n }\n Condition c = Conditions.or(cond.toArray(new Condition[cond.size()]));\n TaskQuery q = new TaskQuery();\n q.add(c);\n return q;\n }\n\n public TaskQuery add(TaskQuery taskQuery) {\n this.add(taskQuery.getCondition());\n return this;\n }\n\n public void setTitle(String title) {\n this.add(like(TASK_TITLE, '%' + title + '%'));\n }\n\n public void setDescription(String description) {\n this.add(like(TASK_DES, '%' + description + '%'));\n }\n\n public List<Long> getProjectIds() {\n return projectIds;\n }\n\n public void setProjectIds(List<Long> projectIds) {\n this.projectIds = projectIds;\n this.add(in(TASK_PROJECT, projectIds));\n }\n\n public List<String> getAssignee() {\n return assignee;\n }\n\n public void setAssignee(List<String> assignee) {\n if (assignee != null) {\n this.add(in(TASK_ASSIGNEE, assignee));\n }\n this.assignee = assignee;\n }\n\n public List<String> getWatchers() {\n return watchers;\n }\n\n public void setWatchers(List<String> watchers) {\n if (watchers != null) {\n this.add(in(TASK_WATCHER, watchers));\n }\n this.watchers = watchers;\n }\n\n public void setCoworker(List<String> coworker) {\n if (coworker != null) {\n this.add(in(TASK_COWORKER, coworker));\n }\n this.coworker = coworker;\n }\n\n public void setAssigneeOrCoworker(List<String> assignee) {\n if (assignee != null && assignee.size() > 0) {\n this.add(Conditions.or(in(TASK_ASSIGNEE, assignee), in(TASK_COWORKER, assignee)));\n }\n this.assignee = assignee;\n }\n\n public void setKeyword(String keyword) {\n if (keyword == null || keyword.trim().isEmpty()) return;\n\n List<Condition> conditions = new ArrayList<Condition>();\n for(String k : keyword.split(\" \")) {\n if (!k.trim().isEmpty()) {\n k = \"%\" + k.trim().toLowerCase() + \"%\";\n conditions.add(like(TASK_TITLE, k));\n conditions.add(like(TASK_DES, k));\n conditions.add(like(TASK_ASSIGNEE, k));\n }\n }\n add(Conditions.or(conditions.toArray(new Condition[conditions.size()])));\n }\n \n public void setCompleted(Boolean completed) {\n if (completed) {\n add(isTrue(TASK_COMPLETED));\n } else {\n add(isFalse(TASK_COMPLETED));\n }\n }\n\n public void setStartDate(Date startDate) {\n add(gte(TASK_END_DATE, startDate));\n }\n\n public void setEndDate(Date endDate) {\n add(lte(TASK_START_DATE, endDate));\n }\n\n public void setMemberships(List<String> permissions) {\n add(Conditions.or(in(TASK_PARTICIPATOR, permissions), in(TASK_MANAGER, permissions)));\n }\n\n @Deprecated\n public void setAssigneeOrMembership(String username, List<String> memberships) {\n this.assignee = Arrays.asList(username);\n this.add(Conditions.or(eq(TASK_ASSIGNEE, username), in(TASK_MANAGER, memberships), in(TASK_PARTICIPATOR, memberships)));\n }\n \n public void setAccessible(Identity user) {\n this.assignee = Arrays.asList(user.getUserId());\n List<String> memberships = UserUtil.getMemberships(user);\n this.add(Conditions.or(eq(TASK_ASSIGNEE, assignee), eq(TASK_COWORKER, assignee), eq(TASK_CREATOR, assignee),\n in(TASK_MANAGER, memberships), in(TASK_PARTICIPATOR, memberships),\n in(TASK_MENTIONED_USERS, Arrays.asList(user.getUserId()))));\n }\n\n public void setAssigneeOrCoworkerOrInProject(String username, List<Long> projectIds) {\n this.assignee = Arrays.asList(username);\n this.projectIds = projectIds;\n this.add(Conditions.or(eq(TASK_ASSIGNEE, username), eq(TASK_COWORKER, username), in(TASK_PROJECT, projectIds)));\n }\n\n public void setStatus(Status status) {\n add(eq(TASK_STATUS, status));\n }\n\n public void setStatus(StatusDto status) {\n add(eq(TASK_STATUS, status));\n }\n\n public void setDueDateFrom(Date dueDateFrom) {\n if (dueDateFrom != null) {\n add(gte(TASK_DUEDATE, dueDateFrom));\n }\n }\n\n public void setDueDateTo(Date dueDateTo) {\n if (dueDateTo != null) {\n add(lte(TASK_DUEDATE, dueDateTo));\n }\n }\n\n public void setIsIncomingOf(String username) {\n add(and(Conditions.or(\n eq(TASK_ASSIGNEE, username), eq(TASK_COWORKER, username), eq(TASK_CREATOR, username),\n in(TASK_MENTIONED_USERS, Arrays.asList(username))),\n isNull(TASK_STATUS)));\n }\n\n public void setIsTodoOf(String username) {\n //setAssignee(Arrays.asList(username));\n //add(eq(TASK_ASSIGNEE, username));\n this.add(Conditions.or(eq(TASK_ASSIGNEE, username), eq(TASK_COWORKER, username), in(TASK_MENTIONED_USERS, Arrays.asList(username))));\n this.assignee = Arrays.asList(username);\n }\n\n public void setAssigneeIsTodoOf(String username) {\n this.add(Conditions.or(eq(TASK_ASSIGNEE, username), eq(TASK_COWORKER, username)));\n }\n\n public void setLabelIds(List<Long> labelIds) {\n if (labelIds != null) {\n List<Condition> cond = new LinkedList<Condition>();\n for (Long id : labelIds) {\n cond.add(eq(TASK_LABEL_ID, id));\n }\n this.add(Conditions.and(cond.toArray(new Condition[cond.size()])));\n }\n }\n \n public void setIsLabelOf(String username) {\n this.add(eq(TASK_LABEL_USERNAME, username));\n }\n\n public void setPriority(Priority priority) {\n this.add(eq(TASK_PRIORITY, priority));\n }\n\n public void setNullField(String nullField) {\n add(isNull(nullField));\n }\n\n public void setEmptyField(String emptyField) {\n add(isEmpty(emptyField));\n }\n\n public TaskQuery clone() {\n Condition condition = getCondition();\n return new TaskQuery(condition != null ? (AggregateCondition)condition.clone() : null, getOrderBy(), projectIds != null ? new ArrayList<Long>(projectIds) : null, assignee,coworker,watchers);\n }\n\n}", "@Entity(name = \"TaskTask\")\n@ExoEntity\n@Table(name = \"TASK_TASKS\")\n@NamedQueries({\n @NamedQuery(name = \"Task.findByMemberships\",\n query = \"SELECT ta FROM TaskTask ta LEFT JOIN ta.coworker coworkers \" +\n \"WHERE ta.assignee = :userName \" +\n \"OR ta.createdBy = :userName \" +\n \"OR coworkers = :userName \" +\n \"OR ta.status IN (SELECT st.id FROM TaskStatus st \" +\n \"WHERE project IN \" +\n \"(SELECT pr1.id FROM TaskProject pr1 LEFT JOIN pr1.manager managers WHERE managers IN :memberships) \" +\n \"OR project IN \" +\n \"(SELECT pr2.id FROM TaskProject pr2 LEFT JOIN pr2.participator participators \" +\n \"WHERE participators IN :memberships) \" +\n \") \"),\n @NamedQuery(name = \"Task.findTaskByProject\",\n query = \"SELECT t FROM TaskTask t WHERE t.status.project.id = :projectId\"),\n @NamedQuery(name = \"Task.findTaskByActivityId\",\n query = \"SELECT t FROM TaskTask t WHERE t.activityId = :activityId\"),\n @NamedQuery(name = \"Task.getCoworker\",\n query = \"SELECT c FROM TaskTask t inner join t.coworker c WHERE t.id = :taskid\"),\n @NamedQuery(name = \"Task.getWatcher\",\n query = \"SELECT w FROM TaskTask t inner join t.watcher w WHERE t.id = :taskid\"),\n @NamedQuery(name = \"Task.updateStatus\",\n query = \"UPDATE TaskTask t SET t.status = :status_new WHERE t.status = :status_old\"),\n @NamedQuery(name = \"Task.getTaskWithCoworkers\",\n query = \"SELECT t FROM TaskTask t LEFT JOIN FETCH t.coworker c WHERE t.id = :taskid\"),\n @NamedQuery(name = \"Task.getUncompletedTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND (ta.assignee = :userName \" +\n \"OR :userName in (select co FROM ta.coworker co) \" +\n \")\"),\n @NamedQuery(name = \"Task.countUncompletedTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND (ta.assignee = :userName \" +\n \"OR :userName in (select co FROM ta.coworker co) \" +\n \")\"),\n @NamedQuery(name = \"Task.getCollaboratedTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND :userName in (select co FROM ta.coworker co) \"),\n @NamedQuery(name = \"Task.countCollaboratedTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND :userName in (select co FROM ta.coworker co) \"),\n\n @NamedQuery(name = \"Task.getAssignedTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND ta.assignee = :userName \"),\n\n @NamedQuery(name = \"Task.countAssignedTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND ta.assignee = :userName \"),\n\n @NamedQuery(name = \"Task.getWatchedTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND :userName in (select wa FROM ta.watcher wa) \"),\n\n @NamedQuery(name = \"Task.countWatchedTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND :userName in (select wa FROM ta.watcher wa) \"),\n\n @NamedQuery(name = \"Task.getOverdueTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND ta.dueDate < CURDATE() \" +\n \"AND (ta.assignee = :userName \" +\n \"OR :userName in (select co FROM ta.coworker co) \" +\n \")\"),\n @NamedQuery(name = \"Task.countOverdueTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE ta.completed = false \" +\n \"AND ta.dueDate < CURDATE() \" +\n \"AND (ta.assignee = :userName \" +\n \"OR :userName in (select co FROM ta.coworker co) \" +\n \")\"),\n @NamedQuery(\n name = \"Task.findTasks\",\n query = \"SELECT ta FROM TaskTask ta \" +\n \"WHERE (ta.assignee = :userName OR ta.createdBy = :userName OR :userName in (select co FROM ta.coworker co) OR (SELECT participator FROM TaskProject p LEFT JOIN p.participator participator where p.id = ta.status.project.id) IN (:memberships) ) \" +\n \"AND (lower(ta.title) LIKE lower(:term) OR lower(ta.description) LIKE :term) \" +\n \"ORDER BY ta.createdTime DESC\"\n ),\n @NamedQuery(\n name = \"Task.countTasks\",\n query = \"SELECT COUNT(ta) FROM TaskTask ta \" +\n \"WHERE (ta.assignee = :userName OR ta.createdBy = :userName OR :userName in (select co FROM ta.coworker co)) \" +\n \"AND (lower(ta.title) LIKE lower(:term) OR lower(ta.description) LIKE :term) \"\n ),\n @NamedQuery(name = \"Task.countTaskStatusByProject\",\n query = \"SELECT m.status.name AS name, COUNT(m) AS total FROM TaskTask AS m where m.status.project.id = :projectId GROUP BY m.status.name ORDER BY m.status.name ASC\"),\n\n @NamedQuery(name = \"Task.getByStatus\",\n query = \"SELECT t FROM TaskTask t WHERE t.status.id = :statusid\")\n})\npublic class Task {\n\n public static final String PREFIX_CLONE = \"Copy of \";\n\n @Id\n @SequenceGenerator(name=\"SEQ_TASK_TASKS_TASK_ID\", sequenceName=\"SEQ_TASK_TASKS_TASK_ID\")\n @GeneratedValue(strategy=GenerationType.AUTO, generator=\"SEQ_TASK_TASKS_TASK_ID\")\n @Column(name = \"TASK_ID\")\n private long id;\n\n private String title;\n\n private String description;\n\n @Enumerated(EnumType.ORDINAL)\n private Priority priority;\n\n private String context;\n\n private String assignee;\n\n @ManyToOne(fetch=FetchType.LAZY)\n @JoinColumn(name = \"STATUS_ID\")\n private Status status;\n\n @Column(name = \"TASK_RANK\")\n private int rank;\n\n private boolean completed = false;\n\n @ElementCollection(fetch = FetchType.LAZY)\n @CollectionTable(name = \"TASK_TASK_COWORKERS\",\n joinColumns = @JoinColumn(name = \"TASK_ID\"))\n private Set<String> coworker = new HashSet<String>();\n\n @ElementCollection(fetch = FetchType.LAZY)\n @CollectionTable(name = \"TASK_TASK_WATCHERS\",\n joinColumns = @JoinColumn(name = \"TASK_ID\"))\n private Set<String> watcher = new HashSet<String>();\n\n @Column(name = \"CREATED_BY\")\n private String createdBy;\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"CREATED_TIME\")\n private Date createdTime;\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"START_DATE\")\n private Date startDate;\n \n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"END_DATE\")\n private Date endDate;\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"DUE_DATE\")\n private Date dueDate;\n\n //This field is only used for remove cascade\n @OneToMany(mappedBy = \"task\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\n private List<Comment> comments = new ArrayList<Comment>();\n\n //This field is only used for remove cascade\n @OneToMany(mappedBy = \"task\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\n private List<ChangeLog> logs = new ArrayList<ChangeLog>();\n\n @OneToMany(mappedBy = \"task\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\n private Set<LabelTaskMapping> lblMapping = new HashSet<LabelTaskMapping>();\n\n @Column(name = \"ACTIVITY_ID\")\n private String activityId;\n\n public Task() {\n this.priority = Priority.NORMAL;\n }\n\n\n\n public Task(String title, String description, Priority priority, String context, String assignee, Set<String> coworker, Set<String> watcher, Status status, String createdBy , Date endDate, Date startDate, Date dueDate) {\n this.title = title;\n this.assignee = assignee;\n this.coworker = coworker;\n this.watcher = watcher;\n this.context = context;\n this.createdBy = createdBy;\n this.description = description;\n this.priority = priority;\n this.startDate = startDate;\n this.endDate = endDate;\n this.dueDate = dueDate;\n this.status = status;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Priority getPriority() {\n return priority;\n }\n\n public void setPriority(Priority priority) {\n this.priority = priority;\n }\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String context) {\n this.context = context;\n }\n\n public String getAssignee() {\n return assignee;\n }\n\n public void setAssignee(String assignee) {\n this.assignee = assignee;\n }\n\n public Status getStatus() {\n return status;\n }\n\n public void setStatus(Status status) {\n this.status = status;\n }\n\n public int getRank() {\n return rank;\n }\n\n public void setRank(int rank) {\n this.rank = rank;\n }\n\n public boolean isCompleted() {\n return completed;\n }\n\n public void setCompleted(boolean completed) {\n this.completed = completed;\n }\n\n public String getCreatedBy() {\n return createdBy;\n }\n\n public void setCreatedBy(String createdBy) {\n this.createdBy = createdBy;\n }\n\n public Date getCreatedTime() {\n return createdTime;\n }\n\n public void setCreatedTime(Date createdTime) {\n this.createdTime = createdTime;\n }\n\n public Date getEndDate() {\n return endDate;\n }\n\n public void setEndDate(Date endDate) {\n this.endDate = endDate;\n }\n\n public Date getStartDate() {\n return startDate;\n }\n\n public void setStartDate(Date startDate) {\n this.startDate = startDate;\n }\n\n public Date getDueDate() {\n return dueDate;\n }\n\n public void setDueDate(Date dueDate) {\n this.dueDate = dueDate;\n }\n\n public Set<String> getCoworker() {\n return coworker;\n }\n\n public void setCoworker(Set<String> coworker) {\n this.coworker = coworker;\n }\n\n public Set<String> getWatcher() {\n return watcher;\n }\n\n public void setWatcher(Set<String> watcher) {\n this.watcher = watcher;\n }\n\n public String getActivityId() {\n return activityId;\n }\n\n public void setActivityId(String activityId) {\n this.activityId = activityId;\n }\n\n public Task clone() {\n Set<String> coworkerClone = new HashSet<String>();\n Set<String> watcherClone = new HashSet<String>();\n if (getCoworker() != null) {\n coworkerClone = new HashSet<String>(getCoworker());\n }\n if (getWatcher() != null) {\n watcherClone = new HashSet<String>(getWatcher());\n }\n Task newTask = new Task(this.getTitle(), this.getDescription(), this.getPriority(), this.getContext(), this.getAssignee(), coworkerClone, watcherClone, this.getStatus() != null ? this.getStatus().clone() : null, this.getCreatedBy() , this.getEndDate(), this.getStartDate(), this.getDueDate());\n\n newTask.setCreatedTime(getCreatedTime());\n newTask.setActivityId(getActivityId());\n newTask.setCompleted(isCompleted());\n newTask.setRank(getRank());\n newTask.setId(getId());\n\n return newTask;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Task task = (Task) o;\n\n if (completed != task.completed) return false;\n if (id != task.id) return false;\n if (assignee != null ? !assignee.equals(task.assignee) : task.assignee != null) return false;\n if (context != null ? !context.equals(task.context) : task.context != null) return false;\n if (coworker != null ? !coworker.equals(task.coworker) : task.coworker != null) return false;\n if (watcher != null ? !watcher.equals(task.watcher) : task.watcher != null) return false;\n if (createdBy != null ? !createdBy.equals(task.createdBy) : task.createdBy != null) return false;\n if (createdTime != null ? !createdTime.equals(task.createdTime) : task.createdTime != null) return false;\n if (description != null ? !description.equals(task.description) : task.description != null) return false;\n if (dueDate != null ? !dueDate.equals(task.dueDate) : task.dueDate != null) return false;\n if (priority != task.priority) return false;\n if (startDate != null ? !startDate.equals(task.startDate) : task.startDate != null) return false;\n if (endDate != null ? !endDate.equals(task.endDate) : task.endDate != null) return false;\n if (status != null ? !status.equals(task.status) : task.status != null) return false;\n if (title != null ? !title.equals(task.title) : task.title != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, title, description, priority, context, assignee, status, completed, coworker,watcher,\n createdBy, createdTime, startDate, endDate, dueDate);\n }\n}" ]
import static org.exoplatform.task.dao.condition.Conditions.TASK_COWORKER; import static org.exoplatform.task.dao.condition.Conditions.TASK_MANAGER; import static org.exoplatform.task.dao.condition.Conditions.TASK_MENTIONED_USERS; import static org.exoplatform.task.dao.condition.Conditions.TASK_PARTICIPATOR; import static org.exoplatform.task.dao.condition.Conditions.TASK_PROJECT; import java.util.*; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Order; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.task.dao.OrderBy; import org.exoplatform.task.dao.TaskHandler; import org.exoplatform.task.dao.TaskQuery; import org.exoplatform.task.dao.condition.SingleCondition; import org.exoplatform.task.domain.Status; import org.exoplatform.task.domain.Task;
} int oldRank = currentTask.getRank(); int prevRank = prevTask != null ? prevTask.getRank() : 0; int nextRank = nextTask != null ? nextTask.getRank() : 0; int newRank = prevRank + 1; if (newStatus != null && currentTask.getStatus().getId() != newStatus.getId()) { oldRank = 0; currentTask.setStatus(newStatus); } EntityManager em = getEntityManager(); StringBuilder sql = null; if (newRank == 1 || oldRank == 0) { int increment = 1; StringBuilder exclude = new StringBuilder(); if (nextRank == 0) { for (int i = currentTaskIndex - 1; i >= 0; i--) { Task task = find(orders[i]); if (task.getRank() > 0) { break; } // Load coworker to avoid they will be deleted when save task task.getCoworker(); task.setRank(newRank + currentTaskIndex - i); update(task); if (exclude.length() > 0) { exclude.append(','); } exclude.append(task.getId()); increment++; } } //Update rank of tasks have rank >= newRank with rank := rank + increment sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank + ").append(increment) .append(" WHERE ta.rank >= ").append(newRank); if (exclude.length() > 0) { sql.append(" AND ta.id NOT IN (").append(exclude.toString()).append(")"); } } else if (oldRank < newRank) { //Update all task where oldRank < rank < newRank: rank = rank - 1 sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank - 1") .append(" WHERE ta.rank > ").append(oldRank) .append(" AND ta.rank < ").append(newRank); newRank --; } else if (oldRank > newRank) { //Update all task where newRank <= rank < oldRank: rank = rank + 1 sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank + 1") .append(" WHERE ta.rank >= ").append(newRank) .append(" AND ta.rank < ").append(oldRank); newRank ++; } if (sql != null && sql.length() > 0) { // Add common condition sql.append(" AND ta.completed = FALSE AND ta.status.id = ").append(currentTask.getStatus().getId()); //TODO: This block code is temporary workaround because the update is require transaction EntityTransaction trans = em.getTransaction(); boolean active = false; if (!trans.isActive()) { trans.begin(); active = true; } em.createQuery(sql.toString()).executeUpdate(); if (active) { trans.commit(); } } currentTask.setRank(newRank); update(currentTask); } @Override public ListAccess<Task> findTasksByLabel(long labelId, List<Long> projectIds, String username, OrderBy orderBy) { TaskQuery query = new TaskQuery(); if (projectIds != null) { query.setProjectIds(projectIds); } if (orderBy != null) { query.setOrderBy(Arrays.asList(orderBy)); } if (labelId > 0) { query.setLabelIds(Arrays.asList(labelId)); } else { query.setIsLabelOf(username); } return findTasks(query); } @Override public Set<String> getCoworker(long taskid) { TypedQuery<String> query = getEntityManager().createNamedQuery("Task.getCoworker", String.class); query.setParameter("taskid", taskid); List<String> tags = query.getResultList(); return new HashSet<String>(tags); } @Override public Task getTaskWithCoworkers(long id) { TypedQuery<Task> query = getEntityManager().createNamedQuery("Task.getTaskWithCoworkers", Task.class); query.setParameter("taskid", id); try { return cloneEntity((Task)query.getSingleResult()); } catch (PersistenceException e) { log.error("Error when fetching task " + id + " with coworkers", e); return null; } } protected Path buildPath(SingleCondition condition, Root<Task> root) { String field = condition.getField(); Join join = null; Path path = null;
if (TASK_PROJECT.equals(condition.getField())) {
4
Predelnik/ChibiPaintMod
src/chibipaint/ChibiPaint.java
[ "public abstract class CPCommonController implements ICPController\n{\n\nprotected int selectionFillAlpha = 255;\npublic boolean transformPreviewHQ = true;\nprotected boolean useInteractivePreviewFloodFill = false;\nprotected boolean useInteractivePreviewMagicWand = false;\n\npublic void setSelectionAction (selectionAction selectionActionArg)\n{\n this.curSelectionAction = selectionActionArg;\n}\n\npublic selectionAction getCurSelectionAction ()\n{\n return curSelectionAction;\n}\n\npublic void setCurSelectionAction (selectionAction curSelectionAction)\n{\n this.curSelectionAction = curSelectionAction;\n}\n\npublic void setSelectionFillAlpha (int selectionFillAlphaArg)\n{\n this.selectionFillAlpha = selectionFillAlphaArg;\n}\n\npublic int getSelectionFillAlpha ()\n{\n return selectionFillAlpha;\n}\n\npublic int getColorDistanceMagicWand ()\n{\n return colorDistanceMagicWand;\n}\n\npublic int getColorDistanceFloodFill ()\n{\n return colorDistanceFloodFill;\n}\n\npublic boolean getTransformPreviewHQ ()\n{\n return transformPreviewHQ;\n}\n\npublic void setTransformPreviewHQ (boolean transformPreviewHQ)\n{\n this.transformPreviewHQ = transformPreviewHQ;\n artwork.invalidateFusion ();\n}\n\npublic void setUseInteractivePreviewFloodFill (boolean useInteractivePreviewFloodFill)\n{\n this.useInteractivePreviewFloodFill = useInteractivePreviewFloodFill;\n}\n\npublic boolean isUseInteractivePreviewFloodFill ()\n{\n return useInteractivePreviewFloodFill;\n}\n\npublic void setUseInteractivePreviewMagicWand (boolean useInteractivePreviewMagicWand)\n{\n this.useInteractivePreviewMagicWand = useInteractivePreviewMagicWand;\n}\n\npublic boolean isUseInteractivePreviewMagicWand ()\n{\n return useInteractivePreviewMagicWand;\n}\n\npublic boolean getUseInteractivePreviewFloodFill ()\n{\n return useInteractivePreviewFloodFill;\n}\n\npublic boolean getUseInteractivePreviewMagicWand ()\n{\n return useInteractivePreviewMagicWand;\n}\n\npublic enum selectionAction\n{\n FILL_AND_DESELECT,\n SELECT,\n}\n\nprivate final static String VERSION_STRING = \"0.0.5 (alpha)\";\n\nprivate final CPColor curColor = new CPColor ();\nprivate boolean oldJTabletUsed;\n// int curAlpha = 255;\n// int brushSize = 16;\n\n// some important object references\npublic CPArtwork artwork;\npublic CPCanvas canvas = null;\n\nfinal CPBrushInfo[] tools;\nprivate int curBrush = T_PENCIL;\nprivate int curMode = M_DRAW;\nprotected selectionAction curSelectionAction = selectionAction.SELECT;\n\nprivate final ArrayList<ICPColorChangeListener> colorListeners = new ArrayList<ICPColorChangeListener> ();\nprivate final ArrayList<ICPToolListener> toolListeners = new ArrayList<ICPToolListener> ();\nprivate final ArrayList<ICPModeListener> modeListeners = new ArrayList<ICPModeListener> ();\nprivate final ArrayList<ICPViewListener> viewListeners = new ArrayList<ICPViewListener> ();\nprivate final ArrayList<ICPEventListener> cpEventListeners = new ArrayList<ICPEventListener> ();\nprivate final HashMap<String, BufferedImage> imageCache = new HashMap<String, BufferedImage> ();\n\n//\n// Definition of all the standard tools available\n//\n// TODO: Make enum\npublic static final int T_INVALID = -1;\npublic static final int T_PENCIL = 0;\npublic static final int T_ERASER = 1;\npublic static final int T_PEN = 2;\npublic static final int T_SOFTERASER = 3;\npublic static final int T_AIRBRUSH = 4;\npublic static final int T_DODGE = 5;\npublic static final int T_BURN = 6;\npublic static final int T_WATER = 7;\npublic static final int T_BLUR = 8;\npublic static final int T_SMUDGE = 9;\npublic static final int T_BLENDER = 10;\nstatic final int T_MAX = 11;\n\n//\n// Definition of all the modes available\n//\n\n// TODO: Make enum\npublic static final int M_INVALID = -1;\npublic static final int M_DRAW = 0;\npublic static final int M_FLOODFILL = 1;\npublic static final int M_RECT_SELECTION = 3;\npublic static final int M_ROTATE_CANVAS = 4;\npublic static final int M_FREE_SELECTION = 5;\npublic static final int M_MAGIC_WAND = 6;\npublic static final int M_MAX = 7;\n\n// Setting for other modes than draw (probably should do different class for them)\nprotected int colorDistanceMagicWand = 0;\nprotected int colorDistanceFloodFill = 0;\nprivate boolean transformIsOn;\n\nprivate CPMainGUI mainGUI;\nprivate int activeMode;\nprivate final Cursor rotateCursor;\n\npublic boolean getTransformIsOn ()\n{\n return transformIsOn;\n}\n\npublic CPBrushInfo[] getTools ()\n{\n return tools;\n}\n\npublic Cursor getRotateCursor ()\n{\n return rotateCursor;\n}\n\npublic void performCommand (CPCommandId commandId, CPCommandSettings commandSettings)\n{\n if (commandId.isSpecificToType ())\n return;\n\n switch (commandId)\n {\n case ZoomIn:\n canvas.zoomIn ();\n break;\n case ZoomOut:\n canvas.zoomOut ();\n break;\n case Zoom100:\n canvas.zoom100 ();\n break;\n case ZoomSpecific:\n launchZoomDialog ();\n break;\n case Undo:\n artwork.undo ();\n break;\n case Redo:\n artwork.redo ();\n break;\n case ClearHistory:\n clearHistory ();\n break;\n case Pencil:\n setTool (T_PENCIL);\n break;\n case Pen:\n setTool (T_PEN);\n break;\n case Eraser:\n setTool (T_ERASER);\n break;\n case SoftEraser:\n setTool (T_SOFTERASER);\n break;\n case AirBrush:\n setTool (T_AIRBRUSH);\n break;\n case Dodge:\n setTool (T_DODGE);\n break;\n case Burn:\n setTool (T_BURN);\n break;\n case Water:\n setTool (T_WATER);\n break;\n case Blur:\n setTool (T_BLUR);\n break;\n case Smudge:\n setTool (T_SMUDGE);\n break;\n case Blender:\n setTool (T_BLENDER);\n break;\n case FloodFill:\n setMode (M_FLOODFILL);\n break;\n case FreeSelection:\n setMode (M_FREE_SELECTION);\n break;\n case MagicWand:\n setMode (M_MAGIC_WAND);\n break;\n case FreeTransform:\n canvas.initTransform ();\n callToolListeners ();\n break;\n case RectSelection:\n setMode (M_RECT_SELECTION);\n break;\n case RotateCanvas:\n setMode (M_ROTATE_CANVAS);\n break;\n case FreeHand:\n tools[getCurBrush ()].strokeMode = CPBrushInfo.SM_FREEHAND;\n callToolListeners ();\n break;\n case Line:\n tools[getCurBrush ()].strokeMode = CPBrushInfo.SM_LINE;\n callToolListeners ();\n break;\n case Bezier:\n tools[getCurBrush ()].strokeMode = CPBrushInfo.SM_BEZIER;\n callToolListeners ();\n break;\n case About:\n launchAboutDialog ();\n break;\n case Test:\n // CPTest is disabled for now\n break;\n case LayerToggleAll:\n artwork.toggleLayers ();\n artwork.finalizeUndo ();\n break;\n case LayerDuplicate:\n artwork.duplicateLayer ();\n artwork.finalizeUndo ();\n break;\n case LayerMergeDown:\n artwork.mergeDown ();\n artwork.finalizeUndo ();\n break;\n case LayerMergeAll:\n artwork.mergeAllLayers ();\n artwork.finalizeUndo ();\n break;\n case Fill:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPFillEffect (getCurColorRgb () | 0xff000000));\n artwork.finalizeUndo ();\n break;\n case Clear:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPClearEffect ());\n artwork.finalizeUndo ();\n break;\n case SelectAll:\n artwork.selectAll ();\n canvas.repaint ();\n break;\n case AlphaToSelection:\n artwork.alphaToSelection ();\n canvas.repaint ();\n break;\n case InvertSelection:\n artwork.invertSelection ();\n canvas.repaint ();\n break;\n case DeselectAll:\n artwork.deselectAll ();\n canvas.repaint ();\n break;\n case MNoise:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPGrayscaleNoiseEffect ());\n artwork.finalizeUndo ();\n break;\n case CNoise:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPColorNoiseEffect ());\n artwork.finalizeUndo ();\n break;\n case FXBoxBlur:\n showBlurDialog (BlurType.BOX_BLUR);\n break;\n case FXGaussianBlur:\n showBlurDialog (BlurType.GAUSSIAN_BLUR);\n break;\n case FXInvert:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPInverseEffect ());\n artwork.finalizeUndo ();\n break;\n case FXMakeGrayscaleByLuma:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPMakeGrayscaleEffect ());\n artwork.finalizeUndo ();\n break;\n case ApplyToAllLayers:\n canvas.setApplyToAllLayers (((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case LinearInterpolation:\n canvas.setInterpolation (((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case ShowSelection:\n canvas.setShowSelection (((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case ShowGrid:\n canvas.showGrid (((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case GridOptions:\n showGridOptionsDialog ();\n break;\n case ResetCanvasRotation:\n canvas.resetRotation ();\n break;\n case PalColor:\n mainGUI.showPalette (\"color\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalBrush:\n mainGUI.showPalette (\"tool_preferences\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalLayers:\n mainGUI.showPalette (\"layers\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalStroke:\n mainGUI.showPalette (\"stroke\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalSwatches:\n mainGUI.showPalette (\"swatches\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalTool:\n mainGUI.showPalette (\"tool\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalMisc:\n mainGUI.showPalette (\"misc\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case PalTextures:\n mainGUI.showPalette (\"textures\", ((CPCommandSettings.CheckBoxState) commandSettings).checked);\n break;\n case TogglePalettes:\n canvas.setPalettesShown (mainGUI.togglePalettes ());\n break;\n case Copy:\n canvas.copy ();\n break;\n case CopyMerged:\n canvas.copyMerged ();\n break;\n case Paste:\n canvas.paste ();\n break;\n case Cut:\n canvas.cut ();\n break;\n case ApplyTransform:\n canvas.applyTransform ();\n break;\n case CancelTransform:\n canvas.cancelTransform ();\n break;\n case MoveTransform:\n case FlipHorizontally:\n case FlipVertically:\n case Rotate90CCW:\n case Rotate90CW:\n switch (commandId)\n {\n case MoveTransform:\n artwork.doTransformAction (CPArtwork.transformType.MOVE, ((CPCommandSettings.DirectionSettings) commandSettings).direction);\n break;\n case FlipHorizontally:\n artwork.doTransformAction (CPArtwork.transformType.FLIP_H);\n break;\n case FlipVertically:\n artwork.doTransformAction (CPArtwork.transformType.FLIP_V);\n break;\n case Rotate90CCW:\n artwork.doTransformAction (CPArtwork.transformType.ROTATE_90_CCW);\n break;\n case Rotate90CW:\n artwork.doTransformAction (CPArtwork.transformType.ROTATE_90_CW);\n break;\n }\n canvas.updateTransformCursor ();\n canvas.repaint ();\n break;\n }\n}\n\n\nprivate void launchZoomDialog ()\n{\n JPanel panel = new JPanel ();\n\n panel.add (new JLabel (\"Desired Zoom Amount (in %):\"));\n SpinnerModel zoomXSM = new SpinnerNumberModel (100.0, 1.0, 1600.0, 5.0);\n JSpinner zoomX = new JSpinner (zoomXSM);\n JSpinner.NumberEditor editor = new JSpinner.NumberEditor (zoomX, \"0.00\");\n zoomX.setEditor (editor);\n CPSwingUtils.allowOnlyCorrectValues (zoomX);\n panel.add (zoomX);\n\n Object[] array = {panel};\n int choice = JOptionPane.showConfirmDialog (getDialogParent (), array, \"Zoom\", JOptionPane.OK_CANCEL_OPTION,\n JOptionPane.PLAIN_MESSAGE);\n\n if (choice == JOptionPane.OK_OPTION)\n {\n float zoom = ((Double) zoomX.getValue ()).floatValue ();\n canvas.zoomOnCenter (zoom * 0.01f);\n }\n}\n\nprivate void launchAboutDialog ()\n{\n// for copying style\n JLabel label = new JLabel ();\n Font font = label.getFont ();\n\n // create some css from the label's font\n StringBuffer style = new StringBuffer (\"font-family:\" + font.getFamily () + \";\");\n style.append (\"font-weight:\" + (font.isBold () ? \"bold\" : \"normal\") + \";\");\n style.append (\"font-size:\" + font.getSize () + \"pt;\");\n\n\n JEditorPane ep = new JEditorPane (\"text/html\", \"<html><body style=\\\"\" + style + \"\\\"><pre>ChibiPaintMod\\n\" + \"Version \"\n + VERSION_STRING + \"\\n\\n\" + \"Copyright (c) 2012-2013 Sergey Semushin.\\n\"\n + \"Copyright (c) 2006-2008 Marc Schefer. All Rights Reserved.\\n\\n\"\n + \"ChibiPaintMod is free software: you can redistribute it and/or modify\\n\"\n + \"it under the terms of the GNU General Public License as published by\\n\"\n + \"the Free Software Foundation, either version 3 of the License, or\\n\"\n + \"(at your option) any later version.\\n\\n\"\n + \"ChibiPaintMod is distributed in the hope that it will be useful,\\n\"\n + \"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\"\n + \"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\"\n + \"GNU General Public License for more details.\\n\\n\"\n\n + \"You should have received a copySelected of the GNU General Public License\\n\"\n + \"along with ChibiPaintMod. If not, see <a href=\\\"http://www.gnu.org/licenses/\\\">http://www.gnu.org/licenses/</a>.\\n\" +\n \"</pre></html>\");\n ep.setEditable (false);\n ep.setBackground (label.getBackground ());\n // handle link events\n ep.addHyperlinkListener (new HyperlinkListener ()\n {\n @Override\n public void hyperlinkUpdate (HyperlinkEvent e)\n {\n if (e.getEventType ().equals (HyperlinkEvent.EventType.ACTIVATED))\n try\n {\n BrowserLauncher.browse (e.getURL ().toURI ()); // roll your own link launcher or use Desktop if J6+\n }\n catch (URISyntaxException e1)\n {\n return;\n }\n }\n });\n JOptionPane.showMessageDialog (getDialogParent (), ep, \"About ChibiPaint...\", JOptionPane.PLAIN_MESSAGE);\n}\n\nprivate void clearHistory ()\n{\n int choice = JOptionPane\n .showConfirmDialog (\n getDialogParent (),\n \"You're about to clear the current Undo/Redo history.\\nThis operation cannot be undone, are you sure you want to do that?\",\n \"Clear History\", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);\n\n if (choice == JOptionPane.OK_OPTION)\n {\n artwork.clearHistory ();\n }\n}\n\npublic interface ICPColorChangeListener\n{\n public void colorChanged(CPColor color);\n}\n\npublic interface ICPToolListener\n{\n\n public void newTool (CPBrushInfo toolInfo);\n}\n\npublic interface ICPModeListener\n{\n\n public void modeChange (int mode);\n}\n\npublic interface ICPViewListener\n{\n\n public void viewChange (CPViewInfo viewInfo);\n}\n\npublic interface ICPEventListener\n{\n\n public void cpEvent ();\n}\n\npublic static class CPViewInfo\n{\n\n public float zoom;\n public int offsetX, offsetY;\n public int width;\n public int height;\n}\n\nCPCommonController ()\n{\n Image img = loadImage (\"cursor/rotate.png\");\n Point hotSpot = new Point (11, 11);\n CPTables.init ();\n rotateCursor = Toolkit.getDefaultToolkit ().createCustomCursor (img, hotSpot, \"Rotate\");\n tools = new CPBrushInfo[T_MAX];\n tools[T_PENCIL] = new CPBrushInfo (T_PENCIL, 16, 255, true, false, .05f, false, true,\n CPBrushInfo.B_ROUND_AA, CPBrushInfo.M_PAINT, 1f, 0f);\n tools[T_ERASER] = new CPBrushInfo (T_ERASER, 16, 255, true, false, .05f, false, false,\n CPBrushInfo.B_ROUND_AA, CPBrushInfo.M_ERASE, 1f, 0f);\n tools[T_PEN] = new CPBrushInfo (T_PEN, 2, 128, true, false, .05f, true, false, CPBrushInfo.B_ROUND_AA,\n CPBrushInfo.M_PAINT, 1f, 0f);\n tools[T_SOFTERASER] = new CPBrushInfo (T_SOFTERASER, 16, 64, false, true, .05f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_ERASE, 1f, 0f);\n tools[T_AIRBRUSH] = new CPBrushInfo (T_AIRBRUSH, 50, 32, false, true, .05f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_PAINT, 1f, 0f);\n tools[T_DODGE] = new CPBrushInfo (T_DODGE, 30, 32, false, true, .05f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_DODGE, 1f, 0f);\n tools[T_BURN] = new CPBrushInfo (T_BURN, 30, 32, false, true, .05f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_BURN, 1f, 0f);\n tools[T_WATER] = new CPBrushInfo (T_WATER, 30, 70, false, true, .02f, false, true, CPBrushInfo.B_ROUND_AA,\n CPBrushInfo.M_WATER, .3f, .6f);\n tools[T_BLUR] = new CPBrushInfo (T_BLUR, 20, 255, false, true, .05f, false, true,\n CPBrushInfo.B_ROUND_PIXEL, CPBrushInfo.M_BLUR, 1f, 0f);\n tools[T_SMUDGE] = new CPBrushInfo (T_SMUDGE, 20, 128, false, true, .01f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_SMUDGE, 0f, 1f);\n tools[T_BLENDER] = new CPBrushInfo (T_SMUDGE, 20, 60, false, true, .1f, false, true,\n CPBrushInfo.B_ROUND_AIRBRUSH, CPBrushInfo.M_OIL, 0f, .07f);\n}\n\npublic void setArtwork (CPArtwork artwork)\n{\n this.artwork = artwork;\n artwork.setForegroundColor (curColor.getRgb ());\n if (isRunningAsApplication ())\n this.artwork.getUndoManager ().setMaxUndo (50);\n}\n\npublic void setCanvas (CPCanvas canvasArg)\n{\n if (this.canvas == null)\n initTablet (canvasArg);\n this.canvas = canvasArg;\n}\n\nprivate void initTablet (final CPCanvas canvasArg)\n{\n Class<?> JTabletExtensionClass;\n try\n {\n JTabletExtensionClass = Class.forName (\"cello.jtablet.installer.JTabletExtension\");\n try\n {\n Class<?>[] params = new Class[2];\n params[0] = Component.class;\n params[1] = String.class;\n Method checkCompatibility = JTabletExtensionClass.getMethod (\"checkCompatibility\", params);\n oldJTabletUsed = !(((Boolean) checkCompatibility.invoke (JTabletExtensionClass, canvasArg, \"1.2.0\")).booleanValue ());\n }\n catch (Exception e)\n {\n System.out.format (\"Error happened during checking compatility with JTablet 1.2\\n\");\n System.exit (1);\n }\n }\n catch (ClassNotFoundException e)\n {\n oldJTabletUsed = true;\n }\n\n if (!oldJTabletUsed)\n {\n CPTablet2.connectToCanvas (canvasArg);\n\n // This stuff is to fix bug with not disappearing brush preview while moving cursor on widgets while\n // using tablet\n // It's bug of nature unknown to me, that's why I fixed it in a little confusing kind of way.\n // TODO: Maybe fix it a better way.\n canvasArg.addMouseListener (new MouseAdapter ()\n {\n @Override\n public void mouseExited (MouseEvent me)\n {\n canvasArg.setCursorIn (false);\n canvasArg.repaint ();\n }\n\n @Override\n public void mouseEntered (MouseEvent me)\n {\n canvasArg.setCursorIn (true);\n }\n });\n }\n else\n {\n canvasArg.ShowLoadingTabletListenerMessage ();\n CPTablet.getRef ();\n canvasArg.HideLoadingTabletListenerMessage ();\n canvasArg.initMouseListeners ();\n }\n}\n\npublic void setCurColor (CPColor color)\n{\n if (!curColor.isEqual (color))\n {\n artwork.setForegroundColor (color.getRgb ());\n\n curColor.copyFrom (color);\n for (Object l : colorListeners)\n {\n ((ICPColorChangeListener) l).colorChanged(color);\n }\n }\n}\n\npublic CPColor getCurColor ()\n{\n return (CPColor) curColor.clone ();\n}\n\npublic int getCurColorRgb ()\n{\n return curColor.getRgb ();\n}\n\npublic void setCurColorRgb (int color)\n{\n CPColor col = new CPColor (color);\n setCurColor (col);\n}\n\npublic void setBrushSize (int size)\n{\n tools[getCurBrush ()].size = Math.max (1, Math.min (200, size));\n callToolListeners ();\n}\n\npublic int getBrushSize ()\n{\n return tools[getCurBrush ()].size;\n}\n\npublic void setAlpha (int alpha)\n{\n tools[getCurBrush ()].alpha = alpha;\n callToolListeners ();\n}\n\npublic int getAlpha ()\n{\n return tools[getCurBrush ()].alpha;\n}\n\npublic void setTool (int tool)\n{\n setMode (M_DRAW);\n setCurBrush (tool);\n artwork.setBrush (tools[tool]);\n callToolListeners ();\n}\n\npublic CPBrushInfo getBrushInfo ()\n{\n return tools[getCurBrush ()];\n}\n\nvoid setMode (int mode)\n{\n setCurMode (mode);\n callModeListeners ();\n callToolListeners (); // For updating mode settings if they exist\n}\n\nprotected void initTransform ()\n{\n\n}\n\npublic void addColorChangeListener(ICPColorChangeListener listener)\n{\n colorListeners.add (listener);\n}\n\npublic void addToolListener (ICPToolListener listener)\n{\n toolListeners.add (listener);\n}\n\npublic void removeToolListener (ICPToolListener listener)\n{\n toolListeners.remove (listener);\n}\n\npublic void callToolListeners ()\n{\n for (ICPToolListener l : toolListeners)\n {\n l.newTool (tools[getCurBrush ()]);\n }\n}\n\npublic void addModeListener (ICPModeListener listener)\n{\n modeListeners.add (listener);\n}\n\npublic void removeModeListener (ICPModeListener listener)\n{\n modeListeners.remove (listener);\n}\n\nvoid callModeListeners ()\n{\n for (ICPModeListener l : modeListeners)\n {\n l.modeChange (getCurMode ());\n }\n}\n\npublic void addViewListener (ICPViewListener listener)\n{\n viewListeners.add (listener);\n}\n\npublic void callViewListeners (CPViewInfo info)\n{\n for (ICPViewListener l : viewListeners)\n {\n l.viewChange (info);\n }\n}\n\nvoid callCPEventListeners ()\n{\n for (ICPEventListener l : cpEventListeners)\n {\n l.cpEvent ();\n }\n}\n\nbyte[] getPngData (Image img)\n{\n int imageType = artwork.hasAlpha () ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;\n\n // FIXME: Wouldn't it be better to use a BufferedImage and avoid this anyway?\n BufferedImage bi = new BufferedImage (img.getWidth (null), img.getHeight (null), imageType);\n Graphics bg = bi.getGraphics ();\n bg.drawImage (img, 0, 0, null);\n bg.dispose ();\n\n ByteArrayOutputStream pngFileStream = new ByteArrayOutputStream (1024);\n try\n {\n ImageIO.write (bi, \"png\", pngFileStream);\n }\n catch (IOException e)\n {\n return null;\n }\n byte[] pngData = pngFileStream.toByteArray ();\n\n return pngData;\n}\n\npublic BufferedImage loadImage (String imageName)\n{\n BufferedImage img = imageCache.get (imageName);\n if (img == null)\n {\n try\n {\n ClassLoader loader = getClass ().getClassLoader ();\n Class[] classes = {Image.class};\n\n URL url = loader.getResource (\"resource/\" + imageName);\n img = ImageIO.read (url);\n }\n catch (Throwable t)\n {\n }\n imageCache.put (imageName, img);\n }\n return img;\n}\n\npublic CPArtwork getArtwork ()\n{\n return artwork;\n}\n\npublic void setMainGUI (CPMainGUI mainGUI)\n{\n this.mainGUI = mainGUI;\n}\n\npublic CPMainGUI getMainGUI ()\n{\n return mainGUI;\n}\n\n// returns the Component to be used as parent to display dialogs\nprotected abstract Component getDialogParent ();\n\n//\n// misc dialog boxes that shouldn't be here v___v\n\nenum BlurType\n{\n BOX_BLUR,\n GAUSSIAN_BLUR,\n}\n\nvoid showBlurDialog (BlurType type)\n{\n JPanel panel = new JPanel ();\n\n panel.add (new JLabel (\"Blur amount:\"));\n SpinnerModel blurXSM = new SpinnerNumberModel (3, 1, 100, 1);\n JSpinner blurX = new JSpinner (blurXSM);\n CPSwingUtils.allowOnlyCorrectValues (blurX);\n\n panel.add (blurX);\n JSpinner iter = null;\n\n if (type == BlurType.BOX_BLUR)\n {\n panel.add (new JLabel (\"Iterations:\"));\n SpinnerModel iterSM = new SpinnerNumberModel (1, 1, 8, 1);\n iter = new JSpinner (iterSM);\n CPSwingUtils.allowOnlyCorrectValues (iter);\n panel.add (iter);\n }\n\n String title = \"\";\n switch (type)\n {\n case BOX_BLUR:\n title = \"Box Blur\";\n break;\n case GAUSSIAN_BLUR:\n title = \"Gaussian Blur\";\n break;\n }\n\n Object[] array = {title + \"\\n\\n\", panel};\n int choice = JOptionPane.showConfirmDialog (getDialogParent (), array, title, JOptionPane.OK_CANCEL_OPTION,\n JOptionPane.PLAIN_MESSAGE);\n\n if (choice == JOptionPane.OK_OPTION)\n {\n\n int blur = ((Integer) blurX.getValue ()).intValue ();\n int iterations = iter != null ? ((Integer) iter.getValue ()).intValue () : 1;\n switch (type)\n {\n case BOX_BLUR:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPBoxBlurEffect (blur, iterations));\n break;\n case GAUSSIAN_BLUR:\n artwork.doEffectAction (canvas.getApplyToAllLayers (), new CPGaussianBlurEffect (blur, iterations));\n break;\n }\n\n canvas.repaint ();\n artwork.finalizeUndo ();\n }\n}\n\nvoid showGridOptionsDialog ()\n{\n JPanel panel = new JPanel ();\n\n panel.add (new JLabel (\"Grid Size:\"));\n SpinnerModel sizeSM = new SpinnerNumberModel (canvas.gridSize, 1, 1000, 1);\n JSpinner sizeSpinner = new JSpinner (sizeSM);\n panel.add (sizeSpinner);\n\n Object[] array = {\"Grid Options\\n\\n\", panel};\n int choice = JOptionPane.showConfirmDialog (getDialogParent (), array, \"Grid Options\",\n JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);\n if (choice == JOptionPane.OK_OPTION)\n {\n int size = ((Integer) sizeSpinner.getValue ()).intValue ();\n\n canvas.gridSize = size;\n canvas.repaint ();\n }\n\n}\n\npublic boolean isRunningAsApplet ()\n{\n return this instanceof CPControllerApplet;\n}\n\npublic boolean isRunningAsApplication ()\n{\n return this instanceof CPControllerApplication;\n}\n\npublic int getCurMode ()\n{\n return curMode;\n}\n\nvoid setCurMode (int curMode)\n{\n this.curMode = curMode;\n}\n\npublic void setColorDistanceFloodFill (int colorDistance)\n{\n this.colorDistanceFloodFill = colorDistance;\n}\n\npublic void setColorDistanceMagicWand (int colorDistance)\n{\n this.colorDistanceMagicWand = colorDistance;\n}\n\npublic int getCurBrush ()\n{\n return curBrush;\n}\n\nvoid setCurBrush (int curBrush)\n{\n this.curBrush = curBrush;\n}\n\nvoid setTransformStateImpl (boolean transformIsOnArg)\n{\n}\n\npublic void setTransformState (boolean transformIsOnArg)\n{\n transformIsOn = transformIsOnArg;\n setTransformStateImpl (transformIsOnArg);\n}\n\n\n}", "public class CPControllerApplet extends CPCommonController\n{\n\nprivate final ChibiPaint applet;\nprivate JFrame floatingFrame;\nprivate String postUrl, exitUrl, exitUrlTarget;\n\npublic CPControllerApplet (ChibiPaint applet)\n{\n this.applet = applet;\n getAppletParams ();\n}\n\npublic Applet getApplet ()\n{\n return applet;\n}\n\n@Override\nprotected Component getDialogParent ()\n{\n if (floatingFrame != null)\n {\n return floatingFrame;\n }\n else\n {\n return applet;\n }\n}\n\n\t/*\n * public Frame getFloatingFrame() { return frame; }\n\t */\n\npublic void setFloatingFrame (JFrame floatingFrame)\n{\n this.floatingFrame = floatingFrame;\n}\n\nvoid getAppletParams ()\n{\n postUrl = applet.getParameter (\"postUrl\");\n exitUrl = applet.getParameter (\"exitUrl\");\n exitUrlTarget = applet.getParameter (\"exitUrlTarget\");\n}\n\nboolean sendPng ()\n{\n String response = \"\";\n\n // First creates the PNG data\n byte[] pngData = getPngData (canvas.img); // FIXME: verify canvas.img is always updated\n\n // The ChibiPaintMod file data\n ByteArrayOutputStream chibiFileStream = new ByteArrayOutputStream (1024);\n CPChibiFile file = new CPChibiFile ();\n file.write (chibiFileStream, artwork);\n byte[] chibiData = chibiFileStream.toByteArray ();\n\n boolean sendLayers;\n int choice = JOptionPane\n .showConfirmDialog (\n getDialogParent (),\n \"You're about to send your oekaki to the server and end your ChibiPaintMod session.\\n\\nWould you like to send the layers file as well?\\nAdditional upload size: \"\n + chibiData.length\n / 1024\n + \" KB \\nTotal upload size:\"\n + (chibiData.length + pngData.length)\n / 1024\n + \" KB\\n\\nThe layers file allows you to edit your oekaki later with all its layers intact\\n\\n\"\n + \"Choose 'Yes' to send both files. (recommended)\\n\"\n + \"Choose 'No' to send the finished picture only.\\n\"\n + \"Choose 'Cancel' if you wish to continue editing your picture without sending it.\\n\\n\",\n \"Send Oekaki\", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);\n\n if (choice == JOptionPane.YES_OPTION)\n {\n sendLayers = true;\n }\n else if (choice == JOptionPane.NO_OPTION)\n {\n sendLayers = false;\n }\n else\n {\n return false;\n }\n\n try\n {\n URL url = new URL (applet.getDocumentBase (), postUrl);\n // new CPMessageBox(this, CPMessageBox.CP_OK_MSGBOX, url.toString()+\" / \"+url.getHost()+\" / \"+url.getFile(),\n // \"debug\");\n\n String boundary = \"---------------------------309542943615284\";\n ByteArrayOutputStream buffer = new ByteArrayOutputStream ();\n DataOutputStream bos = new DataOutputStream (buffer);\n\n bos.writeBytes (\"--\" + boundary + \"\\r\\n\");\n bos.writeBytes (\"Content-Disposition: form-data; name=\\\"picture\\\"; filename=\\\"chibipaint.png\\\"\\r\\n\");\n bos.writeBytes (\"Content-Type: image/png\\r\\n\\r\\n\");\n bos.write (pngData, 0, pngData.length);\n bos.writeBytes (\"\\r\\n\");\n\n if (sendLayers)\n {\n bos.writeBytes (\"--\" + boundary + \"\\r\\n\");\n bos.writeBytes (\"Content-Disposition: form-data; name=\\\"chibifile\\\"; filename=\\\"chibipaint.chi\\\"\\r\\n\");\n bos.writeBytes (\"Content-Type: application/octet-stream\\r\\n\\r\\n\");\n bos.write (chibiData, 0, chibiData.length);\n bos.writeBytes (\"\\r\\n\");\n }\n bos.writeBytes (\"--\" + boundary + \"--\\r\\n\");\n\n bos.flush ();\n\n byte[] data = buffer.toByteArray ();\n\n int port = url.getPort ();\n if (port < 0)\n {\n port = 80;\n }\n Socket s = new Socket (url.getHost (), port);\n DataOutputStream dos = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));\n\n dos.writeBytes (\"POST \" + url.getFile () + \" HTTP/1.0\\r\\n\");\n dos.writeBytes (\"Host: \" + url.getHost () + \"\\r\\n\");\n dos.writeBytes (\"User-Agent: ChibiPaintMod Oekaki (\" + System.getProperty (\"os.name\") + \"; \"\n + System.getProperty (\"os.version\") + \")\\r\\n\");\n dos.writeBytes (\"Cache-Control: nocache\\r\\n\");\n dos.writeBytes (\"Content-Type: multipart/form-data; boundary=\" + boundary + \"\\r\\n\");\n dos.writeBytes (\"Content-Length: \" + data.length + \"\\r\\n\");\n dos.writeBytes (\"\\r\\n\");\n\n dos.write (data, 0, data.length);\n dos.flush ();\n\n //\n // Read the answer from the server and verifies it's OK\n\n BufferedReader rd = new BufferedReader (new InputStreamReader (s.getInputStream (), \"UTF-8\"));\n String line;\n while ((line = rd.readLine ()) != null && line.length () > 0)\n {\n response += line + \"\\n\";\n }\n\n line = rd.readLine (); // should be our answer\n if (!line.startsWith (\"CHIBIOK\"))\n {\n throw new Exception (\"Error: Unexpected answer from the server\");\n }\n else\n {\n response += line + \"\\n\";\n }\n\n dos.close ();\n rd.close ();\n\n return true;\n }\n catch (Exception e)\n {\n System.out.print (\"Error while sending the oekaki...\" + e.getMessage () + \"\\n\");\n JOptionPane.showMessageDialog (getDialogParent (), \"Error while sending the oekaki...\" + e.getMessage ()\n + response, \"Error\", JOptionPane.ERROR_MESSAGE);\n // new CPMessageBox(this, CPMessageBox.CP_OK_MSGBOX, \"Error while sending the\n // oekaki...\"+e.getMessage()+response, \"Error\");\n return false;\n }\n}\n\nvoid goToExitUrl ()\n{\n if (exitUrl != null && !exitUrl.equals (\"\"))\n {\n try\n {\n applet.getAppletContext ().showDocument (new URL (applet.getDocumentBase (), exitUrl), exitUrlTarget);\n }\n catch (Exception e)\n {\n // FIXME: do something\n }\n }\n else\n {\n JOptionPane.showMessageDialog (getDialogParent (), \"The oekaki was successfully sent\", \"Send Oekaki\",\n JOptionPane.INFORMATION_MESSAGE);\n // new CPMessageBox(this, CPMessageBox.CP_OK_MSGBOX, \"The oekaki was successfully sent\", \"Send Oekaki\");\n }\n}\n\npublic void performCommand (CPCommandId commandId, CPCommandSettings commandSettings)\n{\n if (commandId.isForAppletOnly ())\n {\n switch (commandId)\n {\n case Float:\n applet.floatingMode ();\n break;\n case Send:\n if (sendPng ())\n goToExitUrl ();\n break;\n }\n }\n else\n super.performCommand (commandId, commandSettings);\n}\n}", "public class CPArtwork\n{\n\nprivate boolean showOverlay;\n\npublic void doTransformAction (transformType type)\n{\n doTransformAction (type, CPEnums.Direction.Invalid);\n}\n\nprivate boolean appletEmulation = false;\n\npublic void doTransformAction (transformType type, CPEnums.Direction direction)\n{\n CPRect updatingRect = new CPRect (transformHandler.getRectNeededForUpdating ());\n switch (type)\n {\n case FLIP_H:\n transformHandler.flipHorizontally ();\n break;\n case FLIP_V:\n transformHandler.flipVertically ();\n break;\n case ROTATE_90_CW:\n transformHandler.rotate90CW ();\n break;\n case ROTATE_90_CCW:\n transformHandler.rotate90CCW ();\n break;\n case MOVE:\n transformHandler.moveSelection (direction);\n break;\n }\n CPRect rectAfter = new CPRect (transformHandler.getRectNeededForUpdating ());\n updatingRect.union (rectAfter);\n invalidateFusion (updatingRect);\n}\n\nprivate static final int FLOODFILL_PREVIEW_COLOR = 0xFF000000;\n\npublic void updateOverlayWithFloodfillPreview (Point2D.Float pf, int distance, Point2D.Float initialPos, boolean mindSelection)\n{\n if (isPointWithin (pf.x, pf.y))\n {\n tempBuffer.clear ();\n applyFloodFillToLayer ((int) pf.x, (int) pf.y, distance, FLOODFILL_PREVIEW_COLOR, mindSelection);\n CPRect rect = new CPRect ((int) initialPos.x - 2, (int) initialPos.y - 2, (int) initialPos.x + 2, (int) initialPos.y + 2);\n tempBuffer.drawRectangle (rect, 0xffffffff, true);\n showOverlay = true;\n }\n else\n showOverlay = false;\n}\n\nvoid applyFloodFillToLayer (int x, int y, int distance, int color, boolean mindSelection)\n{\n CPColorBmp.floodFill (x, y, isSampleAllLayers () ? fusion : getActiveLayer (), distance, tempBuffer, color, mindSelection && !curSelection.isEmpty () ? curSelection : null);\n}\n\npublic void performFloodFill (float x, float y, int colorDistance)\n{\n undoManager.preserveActiveLayerData ();\n\n tempBuffer.clear ();\n\n applyFloodFillToLayer ((int) x, (int) y, colorDistance, curColor | 0xff000000, true);\n tempBuffer.drawItselfOnTarget (getActiveLayer (), 0, 0);\n\n undoManager.activeLayerDataChange (new CPRect (getWidth (), getHeight ()));\n invalidateFusion ();\n}\n\npublic void performMagicWand (float x, float y, int colorDistance, SelectionTypeOfAppliance selectionTypeOfAppliance)\n{\n tempBuffer.clear ();\n\n applyFloodFillToLayer ((int) x, (int) y, colorDistance, 0xFF000000, false);\n CPSelection tempSelection = new CPSelection (width, height);\n tempSelection.makeSelectionFromAlpha (tempBuffer.getData (), tempBuffer.getSize ());\n DoSelection (selectionTypeOfAppliance, tempSelection);\n}\n\npublic void cancelOverlayDrawing ()\n{\n showOverlay = false;\n}\n\npublic CPColorBmp getOverlayBM ()\n{\n return tempBuffer;\n}\n\npublic boolean getShowOverlay ()\n{\n return showOverlay;\n}\n\npublic void invertSelection ()\n{\n undoManager.preserveCurrentSelection ();\n curSelection.invert ();\n undoManager.currentSelectionChanged ();\n finalizeUndo ();\n}\n\npublic void alphaToSelection ()\n{\n undoManager.preserveCurrentSelection ();\n if (curSelection.isEmpty ())\n curSelection.selectAll ();\n curSelection.cutByData (activeLayer);\n undoManager.currentSelectionChanged ();\n finalizeUndo ();\n}\n\npublic boolean isAppletEmulation ()\n{\n return appletEmulation;\n}\n\npublic void setAppletEmulation (boolean appletEmulation)\n{\n this.appletEmulation = appletEmulation;\n}\n\npublic enum transformType\n{\n FLIP_H,\n FLIP_V,\n ROTATE_90_CW,\n ROTATE_90_CCW,\n MOVE,\n}\n\nprivate final int width;\nprivate final int height;\n\nprivate Vector<CPLayer> layers;\nprivate CPLayer activeLayer;\nprivate int activeLayerNumber;\n\nprivate final CPLayer fusion; // fusion is a final view of the image, like which should be saved to png (no overlays like selection or grid here)\nprivate final CPLayer tempBuffer; // for now used for floodFill, transform.\nprivate final CPRect fusionArea;\nprivate final CPRect opacityArea;\nprivate final CPTransformHandler transformHandler;\nfinal CPSelection curSelection;\n\nprivate final Random rnd = new Random ();\n\npublic CPUndoManager getUndoManager ()\n{\n return undoManager;\n}\n\npublic final CPUndoManager undoManager = new CPUndoManager (this);\n\npublic CPClip getClipboard ()\n{\n return clipboard;\n}\n\npublic boolean initializeTransform (CPCommonController controllerArg)\n{\n undoManager.preserveActiveLayerData ();\n undoManager.preserveCurrentSelection ();\n if (!transformHandler.initialize (curSelection, getActiveLayer (), controllerArg))\n {\n undoManager.restoreSelection ();\n return false;\n }\n return true;\n}\n\npublic CPTransformHandler getTransformHandler ()\n{\n return transformHandler;\n}\n\npublic void FinishTransformUndo ()\n{\n getUndoManager ().currentSelectionChanged ();\n getUndoManager ().activeLayerDataChange (getSize ());\n getUndoManager ().finalizeUndo ();\n invalidateFusion ();\n}\n\npublic void RestoreActiveLayerAndSelection ()\n{\n undoManager.restoreActiveLayerData ();\n undoManager.restoreSelection ();\n}\n\npublic void copySelected (boolean limited)\n{\n if (appletEmulation)\n limited = true;\n CPColorBmp copy = new CPColorBmp (width, height);\n copy.copyDataFrom (activeLayer);\n copy.cutBySelection (curSelection);\n CPRect rect = curSelection.getBoundingRect ();\n CPCopyPasteImage img = new CPCopyPasteImage (rect.getWidth (), rect.getHeight (), rect.getLeft (), rect.getTop ());\n img.setData (copy.copyRectToIntArray (rect));\n CPClipboardHelper.SetClipboardImage (img, limited);\n return;\n}\n\npublic void copySelectedMerged (boolean limited)\n{\n if (appletEmulation)\n limited = true;\n CPColorBmp copy = new CPColorBmp (width, height);\n copy.copyDataFrom (fusion);\n copy.cutBySelection (curSelection);\n CPRect rect = curSelection.getBoundingRect ();\n CPCopyPasteImage img = new CPCopyPasteImage (rect.getWidth (), rect.getHeight (), rect.getLeft (), rect.getTop ());\n img.setData (copy.copyRectToIntArray (rect));\n CPClipboardHelper.SetClipboardImage (img, limited);\n return;\n}\n\n\npublic void cutSelected (boolean limited)\n{\n if (appletEmulation)\n limited = true;\n undoManager.preserveActiveLayerData ();\n undoManager.preserveCurrentSelection ();\n copySelected (limited);\n activeLayer.removePartsCutBySelection (curSelection);\n CPRect rect = curSelection.getBoundingRect ();\n invalidateFusion (rect);\n curSelection.makeEmpty ();\n undoManager.currentSelectionChanged ();\n undoManager.activeLayerDataChange (rect);\n undoManager.finalizeUndo ();\n return;\n}\n\npublic void pasteFromClipboard (boolean limited)\n{\n if (appletEmulation)\n limited = true;\n CPCopyPasteImage imageInClipboard = CPClipboardHelper.GetClipboardImage (limited);\n if (imageInClipboard == null)\n return;\n addLayer ();\n getUndoManager ().preserveActiveLayerData ();\n imageInClipboard.paste (getActiveLayer ());\n CPSelection selection = new CPSelection (getWidth (), getHeight ());\n selection.makeSelectionFromAlpha (getActiveLayer ().getData (), new CPRect (imageInClipboard.getPosX (), imageInClipboard.getPosY (),\n imageInClipboard.getPosX () + imageInClipboard.getWidth (),\n imageInClipboard.getPosY () + imageInClipboard.getHeight ()));\n getUndoManager ().activeLayerDataChange (selection.getBoundingRect ());\n DoSelection (SelectionTypeOfAppliance.CREATE, selection);\n finalizeUndo ();\n\n invalidateFusion ();\n}\n\npublic void deselectAll ()\n{\n undoManager.preserveCurrentSelection ();\n curSelection.makeEmpty ();\n getUndoManager ().currentSelectionChanged ();\n undoManager.finalizeUndo ();\n}\n\npublic void selectAll ()\n{\n undoManager.preserveCurrentSelection ();\n curSelection.selectAll ();\n undoManager.currentSelectionChanged ();\n undoManager.finalizeUndo ();\n}\n\nvoid setActiveLayerNumberWithoutUpdate (int activeLayerNumberArg)\n{\n activeLayerNumber = activeLayerNumberArg;\n}\n\npublic enum SelectionTypeOfAppliance\n{\n CREATE,\n SUBTRACT,\n ADD,\n INTERSECT\n}\n\n;\n\npublic void DoSelection (SelectionTypeOfAppliance type, CPSelection selection, boolean notNeededForDrawing)\n{\n if (notNeededForDrawing)\n {\n curSelection.setNeededForDrawing (false);\n }\n\n DoSelection (type, selection);\n curSelection.setNeededForDrawing (true);\n}\n\n// All that is passed into that function shouldn't be needed for drawing\npublic void DoSelection (SelectionTypeOfAppliance type, CPSelection selection)\n{\n undoManager.preserveCurrentSelection ();\n switch (type)\n {\n case CREATE:\n curSelection.copyFromSelection (selection);\n break;\n case SUBTRACT:\n curSelection.SubtractFromSelection (selection);\n break;\n case ADD:\n curSelection.AddToSelection (selection);\n break;\n case INTERSECT:\n curSelection.IntersectWithSelection (selection);\n break;\n }\n CPRect rect = undoManager.getPreservedSelection ().getBoundingRect ();\n rect.union (curSelection.getBoundingRect ());\n undoManager.currentSelectionChanged ();\n}\n\npublic CPSelection getCurSelection ()\n{\n return curSelection;\n}\n\npublic int getWidth ()\n{\n return width;\n}\n\npublic int getHeight ()\n{\n return height;\n}\n\npublic void finalizeUndo ()\n{\n undoManager.finalizeUndo ();\n}\n\npublic interface ICPArtworkListener\n{\n\n void updateRegion (CPRect region);\n\n void layerChange (CPArtwork artwork);\n}\n\nprivate final LinkedList<ICPArtworkListener> artworkListeners = new LinkedList<ICPArtworkListener> ();\n\n// Clipboard\n\npublic static class CPClip\n{\n\n final CPColorBmp bmp;\n final int x;\n final int y;\n\n CPClip (CPColorBmp bmp, int x, int y)\n {\n this.bmp = bmp;\n this.x = x;\n this.y = y;\n }\n}\n\nprivate final CPClip clipboard = null;\n\nprivate CPBrushInfo curBrush;\n\n// FIXME: shouldn't be public\npublic final CPBrushManager brushManager = new CPBrushManager ();\n\nprivate float lastX;\nprivate float lastY;\nprivate float lastPressure;\nprivate int[] brushBuffer = null;\n\n//\n// Current Engine Parameters\n//\n\nprivate boolean sampleAllLayers = false;\nprivate boolean lockAlpha = false;\n\nprivate int curColor;\n\nprivate final CPBrushTool[] paintingModes = {new CPBrushToolSimpleBrush (), new CPBrushToolEraser (), new CPBrushToolDodge (),\n new CPBrushToolBurn (), new CPBrushToolWatercolor (), new CPBrushToolBlur (), new CPBrushToolSmudge (),\n new CPBrushToolOil (),};\n\nprivate static final int BURN_CONSTANT = 260;\nprivate static final int BLUR_MIN = 64;\nprivate static final int BLUR_MAX = 1;\n\npublic CPArtwork (int width, int height)\n{\n this.width = width;\n this.height = height;\n\n curSelection = new CPSelection (width, height);\n curSelection.setNeededForDrawing (true);\n transformHandler = new CPTransformHandler ();\n setLayers (new Vector<CPLayer> ());\n\n CPLayer defaultLayer = new CPLayer (width, height);\n defaultLayer.setName (\"Canvas\");\n defaultLayer.clear (0xffffffff);\n getLayersVector ().add (defaultLayer);\n\n activeLayer = getLayersVector ().get (0);\n fusionArea = new CPRect (0, 0, width, height);\n opacityArea = new CPRect ();\n setActiveLayerNumberWithoutUpdate (0);\n\n // we reserve a double sized buffer to be used as a 16bits per channel buffer\n tempBuffer = new CPLayer (width, height);\n\n fusion = new CPLayer (width, height);\n}\n\npublic long getDocMemoryUsed ()\n{\n return (long) getWidth () * getHeight () * 4 * (3 + getLayersVector ().size ())\n + (clipboard != null ? clipboard.bmp.getWidth () * clipboard.bmp.getHeight () * 4 : 0);\n}\n\npublic CPLayer getDisplayBM ()\n{\n fusionLayers ();\n return fusion;\n\n // for(int i=0; i<tempBuffer.data.length; i++)\n // tempBuffer.data[i] |= 0xff000000;\n // return tempBuffer;\n}\n\npublic void fusionLayers ()\n{\n if (fusionArea.isEmpty ())\n {\n return;\n }\n\n mergeOpacityBuffer (curColor);\n\n fusion.clear (fusionArea, 0x00ffffff);\n boolean fullAlpha = true, first = true;\n int i = 0;\n for (CPLayer l : getLayersVector ())\n {\n if (!first)\n {\n fullAlpha = fullAlpha && fusion.hasAlpha (fusionArea);\n }\n\n if (getActiveLayer () == l && transformHandler.isTransformActive ())\n {\n tempBuffer.clear ();\n // tempBuffer.copyDataFrom (l);\n tempBuffer.copyRectFrom (l, fusionArea);\n tempBuffer.setAlpha (l.getAlpha ());\n tempBuffer.setBlendMode (l.getBlendMode ());\n transformHandler.drawPreviewOn (tempBuffer);\n doFusionWith (tempBuffer, fullAlpha);\n }\n else\n doFusionWith (l, fullAlpha);\n }\n\n fusionArea.makeEmpty ();\n}\n\nprivate void doFusionWith (CPLayer layer, boolean fullAlpha)\n{\n if (!layer.isVisible ())\n return;\n\n if (fullAlpha)\n {\n layer.fusionWithFullAlpha (fusion, fusionArea);\n }\n else\n {\n layer.fusionWith (fusion, fusionArea);\n }\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////\n// Listeners\n// ///////////////////////////////////////////////////////////////////////////////////\n\npublic void addListener (ICPArtworkListener listener)\n{\n artworkListeners.addLast (listener);\n}\n\npublic void removeListener (ICPArtworkListener listener)\n{\n artworkListeners.remove (listener);\n}\n\nvoid callListenersUpdateRegion (CPRect region)\n{\n for (ICPArtworkListener l : artworkListeners)\n {\n l.updateRegion (region);\n }\n}\n\npublic void callListenersLayerChange ()\n{\n for (ICPArtworkListener l : artworkListeners)\n {\n l.layerChange (this);\n }\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////\n// Global Parameters\n// ///////////////////////////////////////////////////////////////////////////////////\n\npublic void setSampleAllLayers (boolean b)\n{\n sampleAllLayers = b;\n}\n\npublic void setLockAlpha (boolean b)\n{\n lockAlpha = b;\n}\n\npublic void setForegroundColor (int color)\n{\n curColor = color;\n}\n\npublic void setBrush (CPBrushInfo brush)\n{\n curBrush = brush;\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////\n// Paint engine\n// ///////////////////////////////////////////////////////////////////////////////////\n\npublic void beginStroke (float x, float y, float pressure)\n{\n if (curBrush == null)\n {\n return;\n }\n\n paintingModes[curBrush.paintMode].beginStroke (x, y, pressure);\n}\n\npublic void continueStroke (float x, float y, float pressure)\n{\n if (curBrush == null)\n {\n return;\n }\n\n paintingModes[curBrush.paintMode].continueStroke (x, y, pressure);\n}\n\npublic void endStroke ()\n{\n if (curBrush == null)\n {\n return;\n }\n\n paintingModes[curBrush.paintMode].endStroke ();\n undoManager.finalizeUndo ();\n}\n\nvoid mergeOpacityBuffer (int color)\n{\n if (!opacityArea.isEmpty ())\n {\n\n for (int j = opacityArea.top; j < opacityArea.bottom; j++)\n {\n int dstOffset = opacityArea.left + j * getWidth ();\n for (int i = opacityArea.left; i < opacityArea.right; i++, dstOffset++)\n {\n tempBuffer.getData ()[dstOffset] = curSelection.cutOpacity (tempBuffer.getData ()[dstOffset], i, j);\n }\n }\n paintingModes[curBrush.paintMode].mergeOpacityBuf (opacityArea, color);\n\n // Allow to eraser lower alpha with 'lock alpha' because it's all more logical and comfortable (look at gimp and other stuff)\n if (isLockAlpha () && curBrush.paintMode != CPBrushInfo.M_ERASE)\n {\n undoManager.restoreActiveLayerAlpha (opacityArea);\n }\n\n if (false)\n {\n tempBuffer.clear (opacityArea, 0);\n }\n\n opacityArea.makeEmpty ();\n }\n}\n\n// Extend this class to create new tools and brush types\nabstract class CPBrushTool\n{\n\n abstract public void beginStroke (float x, float y, float pressure);\n\n abstract public void continueStroke (float x, float y, float pressure);\n\n abstract public void endStroke ();\n\n abstract public void mergeOpacityBuf (CPRect dstRect, int color);\n}\n\nabstract class CPBrushToolBase extends CPBrushTool\n{\n\n private final CPRect undoArea = new CPRect ();\n\n @Override\n public void beginStroke (float x, float y, float pressure)\n {\n undoManager.preserveActiveLayerData ();\n\n tempBuffer.clear ();\n opacityArea.makeEmpty ();\n\n lastX = x;\n lastY = y;\n lastPressure = pressure;\n paintDab (x, y, pressure);\n }\n\n @Override\n public void continueStroke (float x, float y, float pressure)\n {\n float dist = (float) Math.sqrt (((lastX - x) * (lastX - x) + (lastY - y) * (lastY - y)));\n float spacing = Math.max (curBrush.minSpacing, curBrush.curSize * curBrush.spacing);\n\n if (dist > spacing)\n {\n float nx = lastX, ny = lastY, np = lastPressure;\n\n float df = (spacing - 0.001f) / dist;\n for (float f = df; f <= 1.f; f += df)\n {\n nx = f * x + (1.f - f) * lastX;\n ny = f * y + (1.f - f) * lastY;\n np = f * pressure + (1.f - f) * lastPressure;\n paintDab (nx, ny, np);\n }\n lastX = nx;\n lastY = ny;\n lastPressure = np;\n }\n }\n\n @Override\n public void endStroke ()\n {\n undoArea.clip (getSize ());\n if (!undoArea.isEmpty ())\n {\n mergeOpacityBuffer (curColor);\n undoManager.activeLayerDataChange (undoArea);\n undoArea.makeEmpty ();\n }\n brushBuffer = null;\n }\n\n void paintDab (float xArg, float yArg, float pressure)\n {\n float x = xArg, y = yArg;\n curBrush.applyPressure (pressure);\n if (curBrush.scattering > 0f)\n {\n x += rnd.nextGaussian () * curBrush.curScattering / 4f;\n y += rnd.nextGaussian () * curBrush.curScattering / 4f;\n // x += (rnd.nextFloat() - .5f) * tool.scattering;\n // y += (rnd.nextFloat() - .5f) * tool.scattering;\n }\n CPBrushDab dab = brushManager.getDab (x, y, curBrush);\n paintDab (dab);\n }\n\n void paintDab (CPBrushDab dab)\n {\n CPRect srcRect = new CPRect (dab.width, dab.height);\n CPRect dstRect = new CPRect (dab.width, dab.height);\n dstRect.translate (dab.x, dab.y);\n\n clipSourceDest (srcRect, dstRect);\n\n // drawing entirely outside the canvas\n if (dstRect.isEmpty ())\n {\n return;\n }\n\n undoArea.union (dstRect);\n opacityArea.union (dstRect);\n invalidateFusion (dstRect);\n\n paintDabImplementation (srcRect, dstRect, dab);\n }\n\n abstract void paintDabImplementation (CPRect srcRect, CPRect dstRect, CPBrushDab dab);\n}\n\nclass CPBrushToolSimpleBrush extends CPBrushToolBase\n{\n\n @Override\n void paintDabImplementation (CPRect srcRect, CPRect dstRect, CPBrushDab dab)\n {\n // FIXME: there should be no reference to a specific tool here\n // create a new brush parameter instead\n if (curBrush.isAirbrush)\n {\n paintFlow (srcRect, dstRect, dab.brush, dab.width, Math.max (1, dab.alpha / 8));\n }\n else if (curBrush.toolNb == CPCommonController.T_PEN)\n {\n paintFlow (srcRect, dstRect, dab.brush, dab.width, Math.max (1, dab.alpha / 2));\n }\n else\n {\n // paintOpacityFlow(srcRect, dstRect, brush, dab.stride, alpha, 255);\n // paintOpacityFlow(srcRect, dstRect, brush, dab.stride, 128, alpha);\n paintOpacity (srcRect, dstRect, dab.brush, dab.width, dab.alpha);\n }\n }\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int opacityAlpha = opacityData[dstOffset] / 255;\n if (opacityAlpha > 0)\n {\n int destColor = undoData[dstOffset];\n\n int destAlpha = destColor >>> 24;\n int newLayerAlpha = opacityAlpha + destAlpha * (255 - opacityAlpha) / 255;\n int realAlpha = 255 * opacityAlpha / newLayerAlpha;\n int invAlpha = 255 - realAlpha;\n\n int newColor = (((color >>> 16 & 0xff) * realAlpha + (destColor >>> 16 & 0xff) * invAlpha) / 255) << 16\n & 0xff0000\n | (((color >>> 8 & 0xff) * realAlpha + (destColor >>> 8 & 0xff) * invAlpha) / 255) << 8\n & 0xff00 | (((color & 0xff) * realAlpha + (destColor & 0xff) * invAlpha) / 255) & 0xff;\n\n newColor |= newLayerAlpha << 24 & 0xff000000;\n getActiveLayer ().getData ()[dstOffset] = newColor;\n }\n }\n }\n }\n\n void paintOpacity (CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha)\n {\n int[] opacityData = tempBuffer.getData ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int brushAlpha = (brush[srcOffset] & 0xff) * alpha;\n if (brushAlpha != 0)\n {\n int opacityAlpha = opacityData[dstOffset];\n if (brushAlpha > opacityAlpha)\n {\n opacityData[dstOffset] = brushAlpha;\n }\n }\n\n }\n }\n }\n\n void paintFlow (CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha)\n {\n int[] opacityData = tempBuffer.getData ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int brushAlpha = (brush[srcOffset] & 0xff) * alpha;\n if (brushAlpha != 0)\n {\n int opacityAlpha = Math.min (255 * 255, opacityData[dstOffset]\n + (255 - opacityData[dstOffset] / 255) * brushAlpha / 255);\n opacityData[dstOffset] = opacityAlpha;\n }\n\n }\n }\n }\n\n}\n\nclass CPBrushToolEraser extends CPBrushToolSimpleBrush\n{\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int opacityAlpha = opacityData[dstOffset] / 255;\n if (opacityAlpha > 0)\n {\n int destColor = undoData[dstOffset];\n int destAlpha = destColor >>> 24;\n\n int realAlpha = destAlpha * (255 - opacityAlpha) / 255;\n getActiveLayer ().getData ()[dstOffset] = destColor & 0xffffff | realAlpha << 24;\n }\n }\n }\n }\n}\n\nclass CPBrushToolDodge extends CPBrushToolSimpleBrush\n{\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int opacityAlpha = opacityData[dstOffset] / 255;\n if (opacityAlpha > 0)\n {\n int destColor = undoData[dstOffset];\n if ((destColor & 0xff000000) != 0)\n {\n opacityAlpha += 255;\n int r = (destColor >>> 16 & 0xff) * opacityAlpha / 255;\n int g = (destColor >>> 8 & 0xff) * opacityAlpha / 255;\n int b = (destColor & 0xff) * opacityAlpha / 255;\n\n if (r > 255)\n {\n r = 255;\n }\n if (g > 255)\n {\n g = 255;\n }\n if (b > 255)\n {\n b = 255;\n }\n\n int newColor = destColor & 0xff000000 | r << 16 | g << 8 | b;\n getActiveLayer ().getData ()[dstOffset] = newColor;\n }\n }\n }\n }\n }\n}\n\nclass CPBrushToolBurn extends CPBrushToolSimpleBrush\n{\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int opacityAlpha = opacityData[dstOffset] / 255;\n if (opacityAlpha > 0)\n {\n int destColor = undoData[dstOffset];\n if ((destColor & 0xff000000) != 0)\n {\n // opacityAlpha = 255 - opacityAlpha;\n\n int r = destColor >>> 16 & 0xff;\n int g = destColor >>> 8 & 0xff;\n int b = destColor & 0xff;\n\n r = r - (BURN_CONSTANT - r) * opacityAlpha / 255;\n g = g - (BURN_CONSTANT - g) * opacityAlpha / 255;\n b = b - (BURN_CONSTANT - b) * opacityAlpha / 255;\n\n if (r < 0)\n {\n r = 0;\n }\n if (g < 0)\n {\n g = 0;\n }\n if (b < 0)\n {\n b = 0;\n }\n\n int newColor = destColor & 0xff000000 | r << 16 | g << 8 | b;\n getActiveLayer ().getData ()[dstOffset] = newColor;\n }\n }\n }\n }\n }\n}\n\nclass CPBrushToolBlur extends CPBrushToolSimpleBrush\n{\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int opacityAlpha = opacityData[dstOffset] / 255;\n if (opacityAlpha > 0)\n {\n int blur = BLUR_MIN + (BLUR_MAX - BLUR_MIN) * opacityAlpha / 255;\n\n int destColor = undoData[dstOffset];\n int a = blur * (destColor >>> 24 & 0xff);\n int r = blur * (destColor >>> 16 & 0xff);\n int g = blur * (destColor >>> 8 & 0xff);\n int b = blur * (destColor & 0xff);\n int sum = blur + 4;\n\n destColor = undoData[j > 0 ? dstOffset - getWidth () : dstOffset];\n a += destColor >>> 24 & 0xff;\n r += destColor >>> 16 & 0xff;\n g += destColor >>> 8 & 0xff;\n b += destColor & 0xff;\n\n destColor = undoData[j < getHeight () - 1 ? dstOffset + getWidth () : dstOffset];\n a += destColor >>> 24 & 0xff;\n r += destColor >>> 16 & 0xff;\n g += destColor >>> 8 & 0xff;\n b += destColor & 0xff;\n\n destColor = undoData[i > 0 ? dstOffset - 1 : dstOffset];\n a += destColor >>> 24 & 0xff;\n r += destColor >>> 16 & 0xff;\n g += destColor >>> 8 & 0xff;\n b += destColor & 0xff;\n\n destColor = undoData[i < getWidth () - 1 ? dstOffset + 1 : dstOffset];\n a += destColor >>> 24 & 0xff;\n r += destColor >>> 16 & 0xff;\n g += destColor >>> 8 & 0xff;\n b += destColor & 0xff;\n\n a /= sum;\n r /= sum;\n g /= sum;\n b /= sum;\n getActiveLayer ().getData ()[dstOffset] = a << 24 | r << 16 | g << 8 | b;\n }\n }\n }\n }\n}\n\n// Brushes derived from this class use the opacity buffer\n// as a simple alpha layer\nclass CPBrushToolDirectBrush extends CPBrushToolSimpleBrush\n{\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n int[] opacityData = tempBuffer.getData ();\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n for (int j = dstRect.top; j < dstRect.bottom; j++)\n {\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, dstOffset++)\n {\n int color1 = opacityData[dstOffset];\n int alpha1 = (color1 >>> 24);\n if (alpha1 <= 0)\n {\n continue;\n }\n int color2 = undoData[dstOffset];\n int alpha2 = (color2 >>> 24);\n\n int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;\n if (newAlpha > 0)\n {\n int realAlpha = alpha1 * 255 / newAlpha;\n int invAlpha = 255 - realAlpha;\n\n getActiveLayer ().getData ()[dstOffset] = newAlpha << 24\n | (((color1 >>> 16 & 0xff) * realAlpha + (color2 >>> 16 & 0xff) * invAlpha) / 255) << 16\n | (((color1 >>> 8 & 0xff) * realAlpha + (color2 >>> 8 & 0xff) * invAlpha) / 255) << 8\n | (((color1 & 0xff) * realAlpha + (color2 & 0xff) * invAlpha) / 255);\n }\n }\n }\n }\n}\n\nclass CPBrushToolWatercolor extends CPBrushToolDirectBrush\n{\n\n static final int wcMemory = 50;\n static final int wxMaxSampleRadius = 64;\n\n LinkedList<CPColorFloat> previousSamples;\n\n @Override\n public void beginStroke (float x, float y, float pressure)\n {\n previousSamples = null;\n\n super.beginStroke (x, y, pressure);\n }\n\n @Override\n void paintDabImplementation (CPRect srcRect, CPRect dstRect, CPBrushDab dab)\n {\n if (previousSamples == null)\n {\n CPColorFloat startColor = sampleColor ((dstRect.left + dstRect.right) / 2,\n (dstRect.top + dstRect.bottom) / 2, Math.max (1, Math.min (wxMaxSampleRadius,\n dstRect.getWidth () * 2 / 6)), Math.max (1, Math.min (wxMaxSampleRadius, dstRect\n .getHeight () * 2 / 6)));\n\n previousSamples = new LinkedList<CPColorFloat> ();\n for (int i = 0; i < wcMemory; i++)\n {\n previousSamples.addLast (startColor);\n }\n }\n CPColorFloat wcColor = new CPColorFloat (0, 0, 0);\n for (CPColorFloat sample : previousSamples)\n {\n wcColor.r += sample.r;\n wcColor.g += sample.g;\n wcColor.b += sample.b;\n }\n wcColor.r /= previousSamples.size ();\n wcColor.g /= previousSamples.size ();\n wcColor.b /= previousSamples.size ();\n\n // resaturation\n int color = curColor & 0xffffff;\n wcColor.mixWith (new CPColorFloat (color), curBrush.resat * curBrush.resat);\n\n int newColor = wcColor.toInt ();\n\n // bleed\n wcColor.mixWith (sampleColor ((dstRect.left + dstRect.right) / 2, (dstRect.top + dstRect.bottom) / 2, Math\n .max (1, Math.min (wxMaxSampleRadius, dstRect.getWidth () * 2 / 6)), Math.max (1, Math.min (\n wxMaxSampleRadius, dstRect.getHeight () * 2 / 6))), curBrush.bleed);\n\n previousSamples.addLast (wcColor);\n previousSamples.removeFirst ();\n\n paintDirect (srcRect, dstRect, dab.brush, dab.width, Math.max (1, dab.alpha / 4), newColor);\n mergeOpacityBuffer (0);\n if (isSampleAllLayers ())\n {\n fusionLayers ();\n }\n }\n\n void paintDirect (CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha, int color1)\n {\n int[] opacityData = tempBuffer.getData ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int alpha1 = (brush[srcOffset] & 0xff) * alpha / 255;\n if (alpha1 <= 0)\n {\n continue;\n }\n\n int color2 = opacityData[dstOffset];\n int alpha2 = (color2 >>> 24);\n\n int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;\n if (newAlpha > 0)\n {\n int realAlpha = alpha1 * 255 / newAlpha;\n int invAlpha = 255 - realAlpha;\n\n // The usual alpha blending formula C = A * alpha + B * (1 - alpha)\n // has to rewritten in the form C = A + (1 - alpha) * B - (1 - alpha) *A\n // that way the rounding up errors won't cause problems\n\n int newColor = newAlpha << 24\n | ((color1 >>> 16 & 0xff) + (((color2 >>> 16 & 0xff) * invAlpha - (color1 >>> 16 & 0xff)\n * invAlpha) / 255)) << 16\n | ((color1 >>> 8 & 0xff) + (((color2 >>> 8 & 0xff) * invAlpha - (color1 >>> 8 & 0xff)\n * invAlpha) / 255)) << 8\n | ((color1 & 0xff) + (((color2 & 0xff) * invAlpha - (color1 & 0xff) * invAlpha) / 255));\n\n opacityData[dstOffset] = newColor;\n }\n }\n }\n }\n\n CPColorFloat sampleColor (int x, int y, int dx, int dy)\n {\n LinkedList<CPColorFloat> samples = new LinkedList<CPColorFloat> ();\n\n CPLayer layerToSample = isSampleAllLayers () ? fusion : getActiveLayer ();\n\n samples.addLast (new CPColorFloat (layerToSample.getPixel (x, y) & 0xffffff));\n\n for (float r = 0.25f; r < 1.001f; r += .25f)\n {\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x + r * dx), y) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x - r * dx), y) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel (x, (int) (y + r * dy)) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel (x, (int) (y - r * dy)) & 0xffffff));\n\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x + r * .7f * dx), (int) (y + r * .7f\n * dy)) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x + r * .7f * dx), (int) (y - r * .7f\n * dy)) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x - r * .7f * dx), (int) (y + r * .7f\n * dy)) & 0xffffff));\n samples.addLast (new CPColorFloat (layerToSample.getPixel ((int) (x - r * .7f * dx), (int) (y - r * .7f\n * dy)) & 0xffffff));\n }\n\n CPColorFloat average = new CPColorFloat (0, 0, 0);\n for (CPColorFloat sample : samples)\n {\n average.r += sample.r;\n average.g += sample.g;\n average.b += sample.b;\n }\n average.r /= samples.size ();\n average.g /= samples.size ();\n average.b /= samples.size ();\n\n return average;\n }\n}\n\nclass CPBrushToolOil extends CPBrushToolDirectBrush\n{\n\n @Override\n void paintDabImplementation (CPRect srcRect, CPRect dstRect, CPBrushDab dab)\n {\n if (brushBuffer == null)\n {\n brushBuffer = new int[dab.width * dab.height];\n for (int i = brushBuffer.length - 1; --i >= 0; )\n {\n brushBuffer[i] = 0;\n }\n // activeLayer.copyRect(dstRect, brushBuffer);\n oilAccumBuffer (srcRect, dstRect, brushBuffer, dab.width, 255);\n }\n else\n {\n oilResatBuffer (srcRect, dstRect, brushBuffer, dab.width, (int) ((curBrush.resat <= 0f) ? 0 : Math.max (\n 1, (curBrush.resat * curBrush.resat) * 255)), curColor & 0xffffff);\n oilPasteBuffer (srcRect, dstRect, brushBuffer, dab.brush, dab.width, dab.alpha);\n oilAccumBuffer (srcRect, dstRect, brushBuffer, dab.width, (int) ((curBrush.bleed) * 255));\n }\n mergeOpacityBuffer (0);\n if (isSampleAllLayers ())\n {\n fusionLayers ();\n }\n }\n\n private void oilAccumBuffer (CPRect srcRect, CPRect dstRect, int[] buffer, int w, int alpha)\n {\n CPLayer layerToSample = isSampleAllLayers () ? fusion : getActiveLayer ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int color1 = layerToSample.getData ()[dstOffset];\n int alpha1 = (color1 >>> 24) * alpha / 255;\n if (alpha1 <= 0)\n {\n continue;\n }\n\n int color2 = buffer[srcOffset];\n int alpha2 = (color2 >>> 24);\n\n int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;\n if (newAlpha > 0)\n {\n int realAlpha = alpha1 * 255 / newAlpha;\n int invAlpha = 255 - realAlpha;\n\n int newColor = newAlpha << 24\n | ((color1 >>> 16 & 0xff) + (((color2 >>> 16 & 0xff) * invAlpha - (color1 >>> 16 & 0xff)\n * invAlpha) / 255)) << 16\n | ((color1 >>> 8 & 0xff) + (((color2 >>> 8 & 0xff) * invAlpha - (color1 >>> 8 & 0xff)\n * invAlpha) / 255)) << 8\n | ((color1 & 0xff) + (((color2 & 0xff) * invAlpha - (color1 & 0xff) * invAlpha) / 255));\n\n buffer[srcOffset] = newColor;\n }\n }\n }\n }\n\n private void oilResatBuffer (CPRect srcRect, CPRect dstRect, int[] buffer, int w, int alpha1, int color1)\n {\n if (alpha1 <= 0)\n {\n return;\n }\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++)\n {\n int color2 = buffer[srcOffset];\n int alpha2 = (color2 >>> 24);\n\n int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;\n if (newAlpha > 0)\n {\n int realAlpha = alpha1 * 255 / newAlpha;\n int invAlpha = 255 - realAlpha;\n\n int newColor = newAlpha << 24\n | ((color1 >>> 16 & 0xff) + (((color2 >>> 16 & 0xff) * invAlpha - (color1 >>> 16 & 0xff)\n * invAlpha) / 255)) << 16\n | ((color1 >>> 8 & 0xff) + (((color2 >>> 8 & 0xff) * invAlpha - (color1 >>> 8 & 0xff)\n * invAlpha) / 255)) << 8\n | ((color1 & 0xff) + (((color2 & 0xff) * invAlpha - (color1 & 0xff) * invAlpha) / 255));\n\n buffer[srcOffset] = newColor;\n }\n }\n }\n }\n\n private void oilPasteBuffer (CPRect srcRect, CPRect dstRect, int[] buffer, byte[] brush, int w, int alpha)\n {\n int[] opacityData = tempBuffer.getData ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int color1 = buffer[srcOffset];\n int alpha1 = (color1 >>> 24) * (brush[srcOffset] & 0xff) * alpha / (255 * 255);\n if (alpha1 <= 0)\n {\n continue;\n }\n\n int color2 = getActiveLayer ().getData ()[dstOffset];\n int alpha2 = (color2 >>> 24);\n\n int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;\n if (newAlpha > 0)\n {\n int realAlpha = alpha1 * 255 / newAlpha;\n int invAlpha = 255 - realAlpha;\n\n int newColor = newAlpha << 24\n | ((color1 >>> 16 & 0xff) + (((color2 >>> 16 & 0xff) * invAlpha - (color1 >>> 16 & 0xff)\n * invAlpha) / 255)) << 16\n | ((color1 >>> 8 & 0xff) + (((color2 >>> 8 & 0xff) * invAlpha - (color1 >>> 8 & 0xff)\n * invAlpha) / 255)) << 8\n | ((color1 & 0xff) + (((color2 & 0xff) * invAlpha - (color1 & 0xff) * invAlpha) / 255));\n\n opacityData[dstOffset] = newColor;\n\n }\n }\n }\n }\n}\n\nclass CPBrushToolSmudge extends CPBrushToolDirectBrush\n{\n\n @Override\n void paintDabImplementation (CPRect srcRect, CPRect dstRect, CPBrushDab dab)\n {\n if (brushBuffer == null)\n {\n brushBuffer = new int[dab.width * dab.height];\n smudgeAccumBuffer (srcRect, dstRect, brushBuffer, dab.width, 0);\n }\n else\n {\n smudgeAccumBuffer (srcRect, dstRect, brushBuffer, dab.width, dab.alpha);\n smudgePasteBuffer (srcRect, dstRect, brushBuffer, dab.brush, dab.width);\n\n if (isLockAlpha ())\n {\n undoManager.restoreActiveLayerAlpha (dstRect);\n }\n }\n opacityArea.makeEmpty ();\n if (isSampleAllLayers ())\n {\n fusionLayers ();\n }\n }\n\n @Override\n public void mergeOpacityBuf (CPRect dstRect, int color)\n {\n // Don't know what should be there\n }\n\n private void smudgeAccumBuffer (CPRect srcRect, CPRect dstRect, int[] buffer, int w, int alpha)\n {\n\n CPLayer layerToSample = isSampleAllLayers () ? fusion : getActiveLayer ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int layerColor = layerToSample.getData ()[dstOffset];\n int opacityAlpha = 255 - alpha;\n if (opacityAlpha > 0)\n {\n int destColor = buffer[srcOffset];\n\n int destAlpha = 255;\n int newLayerAlpha = opacityAlpha + destAlpha * (255 - opacityAlpha) / 255;\n int realAlpha = 255 * opacityAlpha / newLayerAlpha;\n int invAlpha = 255 - realAlpha;\n\n int newColor = (((layerColor >>> 24 & 0xff) * realAlpha + (destColor >>> 24 & 0xff) * invAlpha) / 255) << 24\n & 0xff000000\n | (((layerColor >>> 16 & 0xff) * realAlpha + (destColor >>> 16 & 0xff) * invAlpha) / 255) << 16\n & 0xff0000\n | (((layerColor >>> 8 & 0xff) * realAlpha + (destColor >>> 8 & 0xff) * invAlpha) / 255) << 8\n & 0xff00\n | (((layerColor & 0xff) * realAlpha + (destColor & 0xff) * invAlpha) / 255)\n & 0xff;\n\n if (newColor == destColor)\n {\n if ((layerColor & 0xff0000) > (destColor & 0xff0000))\n {\n newColor += 1 << 16;\n }\n else if ((layerColor & 0xff0000) < (destColor & 0xff0000))\n {\n newColor -= 1 << 16;\n }\n\n if ((layerColor & 0xff00) > (destColor & 0xff00))\n {\n newColor += 1 << 8;\n }\n else if ((layerColor & 0xff00) < (destColor & 0xff00))\n {\n newColor -= 1 << 8;\n }\n\n if ((layerColor & 0xff) > (destColor & 0xff))\n {\n newColor += 1;\n }\n else if ((layerColor & 0xff) < (destColor & 0xff))\n {\n newColor -= 1;\n }\n }\n\n buffer[srcOffset] = newColor;\n }\n }\n }\n\n if (srcRect.left > 0)\n {\n int fill = srcRect.left;\n for (int j = srcRect.top; j < srcRect.bottom; j++)\n {\n int offset = j * w;\n int fillColor = buffer[offset + srcRect.left];\n for (int i = 0; i < fill; i++)\n {\n buffer[offset++] = fillColor;\n }\n }\n }\n\n if (srcRect.right < w)\n {\n int fill = w - srcRect.right;\n for (int j = srcRect.top; j < srcRect.bottom; j++)\n {\n int offset = j * w + srcRect.right;\n int fillColor = buffer[offset - 1];\n for (int i = 0; i < fill; i++)\n {\n buffer[offset++] = fillColor;\n }\n }\n }\n\n for (int j = 0; j < srcRect.top; j++)\n {\n System.arraycopy (buffer, srcRect.top * w, buffer, j * w, w);\n }\n\n for (int j = srcRect.bottom; j < w; j++)\n {\n System.arraycopy (buffer, (srcRect.bottom - 1) * w, buffer, j * w, w);\n }\n }\n\n private void smudgePasteBuffer (CPRect srcRect, CPRect dstRect, int[] buffer, byte[] brush, int w)\n {\n int[] undoData = undoManager.getActiveLayerPreservedData ();\n\n int by = srcRect.top;\n for (int j = dstRect.top; j < dstRect.bottom; j++, by++)\n {\n int srcOffset = srcRect.left + by * w;\n int dstOffset = dstRect.left + j * getWidth ();\n for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++)\n {\n int bufferColor = buffer[srcOffset];\n int opacityAlpha = (bufferColor >>> 24) * (brush[srcOffset] & 0xff) / 255;\n if (opacityAlpha > 0)\n {\n int destColor = undoData[dstOffset];\n\n int realAlpha = 255;\n int invAlpha = 255 - realAlpha;\n\n int newColor = (((bufferColor >>> 24 & 0xff) * realAlpha + (destColor >>> 24 & 0xff) * invAlpha) / 255) << 24\n & 0xff000000\n | (((bufferColor >>> 16 & 0xff) * realAlpha + (destColor >>> 16 & 0xff) * invAlpha) / 255) << 16\n & 0xff0000\n | (((bufferColor >>> 8 & 0xff) * realAlpha + (destColor >>> 8 & 0xff) * invAlpha) / 255) << 8\n & 0xff00\n | (((bufferColor & 0xff) * realAlpha + (destColor & 0xff) * invAlpha) / 255)\n & 0xff;\n\n getActiveLayer ().getData ()[dstOffset] = newColor;\n }\n }\n }\n }\n}\n\n// ///////////////////////////////////////////////////////////////////////////////////\n// Layer methods\n// ///////////////////////////////////////////////////////////////////////////////////\n\npublic void setActiveLayerNumberWithoutUndo (int i) // warning, use it only if you're using other kind of layer undo\n{\n if (i < 0 || i >= getLayersVector ().size ())\n {\n return;\n }\n\n setActiveLayerNumberWithoutUpdate (i);\n activeLayer = getLayersVector ().get (i);\n callListenersLayerChange ();\n}\n\npublic void setActiveLayerNumber (int i)\n{\n undoManager.preserveActiveLayerNumber ();\n setActiveLayerNumberWithoutUndo (i);\n undoManager.activeLayerNumberChanged ();\n}\n\npublic int getActiveLayerNb ()\n{\n return getActiveLayerNum ();\n}\n\npublic CPLayer getActiveLayer ()\n{\n return activeLayer;\n}\n\npublic CPLayer getLayer (int i)\n{\n if (i < 0 || i >= getLayersVector ().size ())\n {\n return null;\n }\n\n return getLayersVector ().get (i);\n}\n\n//\n// Undo / Redo\n//\n\npublic void undo ()\n{\n if (!canUndo ())\n {\n return;\n }\n\n CPUndo undo = undoManager.getUndoList ().removeFirst ();\n undo.undo ();\n undoManager.getRedoList ().addFirst (undo);\n}\n\npublic void redo ()\n{\n if (!canRedo ())\n {\n return;\n }\n\n CPUndo redo = undoManager.getRedoList ().removeFirst ();\n redo.redo ();\n undoManager.getUndoList ().addFirst (redo);\n}\n\nboolean canUndo ()\n{\n return !undoManager.getUndoList ().isEmpty ();\n}\n\nboolean canRedo ()\n{\n return !undoManager.getRedoList ().isEmpty ();\n}\n\npublic void clearHistory ()\n{\n undoManager.getUndoList ().clear ();\n undoManager.getRedoList ().clear ();\n\n Runtime r = Runtime.getRuntime ();\n r.gc ();\n}\n\n//\n//\n//\n\npublic int colorPicker (float x, float y)\n{\n // not really necessary and could potentially the repaint\n // of the canvas to miss that area\n // fusionLayers();\n if (isSampleAllLayers ())\n return fusion.getPixel ((int) x, (int) y) & 0xffffff;\n else\n return getActiveLayer ().getPixel ((int) x, (int) y) & 0xffffff;\n}\n\npublic boolean isPointWithin (float x, float y)\n{\n return x >= 0 && y >= 0 && (int) x < getWidth () && (int) y < getHeight ();\n}\n\n// FIXME: 2007-01-13 I'm moving this to the CPRect class\n// find where this version is used and change the\n// code to use the CPRect version\n\nvoid clipSourceDest (CPRect srcRect, CPRect dstRect)\n{\n // FIXME:\n // /!\\ dstRect bottom and right are ignored and instead we clip\n // against the width, height of the layer. :/\n //\n\n // this version would be enough in most cases (when we don't need\n // srcRect bottom and right to be clipped)\n // it's left here in case it's needed to make a faster version\n // of this function\n // dstRect.right = Math.min(width, dstRect.left + srcRect.getWidth());\n // dstRect.bottom = Math.min(height, dstRect.top + srcRect.getHeight());\n\n // new dest bottom/right\n dstRect.right = dstRect.left + srcRect.getWidth ();\n if (dstRect.right > getWidth ())\n {\n srcRect.right -= dstRect.right - getWidth ();\n dstRect.right = getWidth ();\n }\n\n dstRect.bottom = dstRect.top + srcRect.getHeight ();\n if (dstRect.bottom > getHeight ())\n {\n srcRect.bottom -= dstRect.bottom - getHeight ();\n dstRect.bottom = getHeight ();\n }\n\n // new src top/left\n if (dstRect.left < 0)\n {\n srcRect.left -= dstRect.left;\n dstRect.left = 0;\n }\n\n if (dstRect.top < 0)\n {\n srcRect.top -= dstRect.top;\n dstRect.top = 0;\n }\n}\n\npublic Object[] getLayers ()\n{\n return getLayersVector ().toArray ();\n}\n\npublic int getLayersNb ()\n{\n return getLayersVector ().size ();\n}\n\npublic CPRect getSize ()\n{\n return new CPRect (getWidth (), getHeight ());\n}\n\n//\n// Selection methods\n//\n\n\n//\n//\n//\n\npublic void invalidateFusion (CPRect r)\n{\n fusionArea.union (r);\n callListenersUpdateRegion (r);\n}\n\npublic void invalidateFusion ()\n{\n invalidateFusion (new CPRect (0, 0, getWidth (), getHeight ()));\n}\n\npublic void setLayerVisibility (int layer, boolean visible)\n{\n\n boolean oldVisibility = getLayer (layer).isVisible ();\n getLayer (layer).setVisible (visible);\n invalidateFusion ();\n callListenersLayerChange ();\n undoManager.activeLayerVisibilityChanged (layer, oldVisibility);\n}\n\npublic void addLayer ()\n{\n\n CPLayer newLayer = new CPLayer (getWidth (), getHeight ());\n newLayer.setName (getDefaultLayerName ());\n getLayersVector ().add (getActiveLayerNum () + 1, newLayer);\n setActiveLayerNumberWithoutUndo (getActiveLayerNum () + 1);\n undoManager.layerWasAppended ();\n\n invalidateFusion ();\n callListenersLayerChange ();\n}\n\npublic void removeLayer ()\n{\n if (getLayersVector ().size () > 1)\n {\n undoManager.beforeLayerRemoval (getActiveLayerNum ());\n getLayersVector ().remove (getActiveLayerNum ());\n setActiveLayerNumberWithoutUndo (getActiveLayerNum () < getLayersVector ().size () ? getActiveLayerNum () : getActiveLayerNum () - 1);\n invalidateFusion ();\n callListenersLayerChange ();\n }\n}\n\npublic void toggleLayers ()\n{\n undoManager.preserveLayersCheckState ();\n int i, first_unchecked_pos = 0;\n for (i = 0; i < getLayersVector ().size (); i++)\n if (!getLayersVector ().elementAt (i).isVisible ())\n break;\n first_unchecked_pos = i;\n\n for (i = 0; i < getLayersVector ().size (); i++)\n getLayersVector ().elementAt (i).setVisible ((first_unchecked_pos < getLayersVector ().size ()));\n\n undoManager.layersCheckStateWasToggled ();\n\n invalidateFusion ();\n callListenersLayerChange ();\n}\n\npublic void duplicateLayer ()\n{\n String copySuffix = \" Copy\";\n\n CPLayer newLayer = new CPLayer (getWidth (), getHeight ());\n newLayer.copyFrom (getLayersVector ().elementAt (getActiveLayerNum ()));\n if (!newLayer.getName ().endsWith (copySuffix))\n {\n newLayer.setName (newLayer.getName () + copySuffix);\n }\n getLayersVector ().add (getActiveLayerNum () + 1, newLayer);\n\n setActiveLayerNumberWithoutUndo (getActiveLayerNum () + 1);\n undoManager.layerDuplicationTookPlace ();\n invalidateFusion ();\n callListenersLayerChange ();\n}\n\npublic void mergeDown ()\n{\n if (getLayersVector ().size () > 0 && getActiveLayerNum () > 0)\n {\n undoManager.beforeMergingLayer ();\n getLayersVector ().elementAt (getActiveLayerNum ()).fusionWithFullAlpha (getLayersVector ().elementAt (getActiveLayerNum () - 1),\n new CPRect (getWidth (), getHeight ()));\n getLayersVector ().remove (getActiveLayerNum ());\n setActiveLayerNumberWithoutUndo (getActiveLayerNum () - 1);\n\n invalidateFusion ();\n callListenersLayerChange ();\n }\n}\n\npublic void mergeAllLayers ()\n{\n if (getLayersVector ().size () > 1)\n {\n\n undoManager.beforeMergingAllLayers ();\n\n fusionLayers ();\n getLayersVector ().clear ();\n\n CPLayer layer = new CPLayer (getWidth (), getHeight ());\n layer.setName (getDefaultLayerName ());\n layer.copyDataFrom (fusion);\n getLayersVector ().add (layer);\n setActiveLayerNumberWithoutUndo (0);\n\n invalidateFusion ();\n callListenersLayerChange ();\n }\n}\n\npublic void moveLayer (int from, int to)\n{\n if (from < 0 || from >= getLayersNb () || to < 0 || to > getLayersNb () || from == to)\n {\n return;\n }\n undoManager.beforeLayerMove (from, to);\n moveLayerReal (from, to);\n}\n\nvoid moveLayerReal (int from, int to)\n{\n CPLayer layer = getLayersVector ().remove (from);\n if (to <= from)\n {\n getLayersVector ().add (to, layer);\n setActiveLayerNumberWithoutUndo (to);\n }\n else\n {\n getLayersVector ().add (to - 1, layer);\n setActiveLayerNumberWithoutUndo (to - 1);\n }\n\n invalidateFusion ();\n callListenersLayerChange ();\n}\n\npublic void setLayerAlpha (int layer, int alpha)\n{\n if (getLayer (layer).getAlpha () != alpha)\n {\n undoManager.beforeLayerAlphaChange (this, layer, alpha);\n getLayer (layer).setAlpha (alpha);\n invalidateFusion ();\n callListenersLayerChange ();\n }\n}\n\npublic void setBlendMode (int layer, int blendMode)\n{\n if (getLayer (layer).getBlendMode () != blendMode)\n {\n undoManager.beforeChangingLayerBlendMode (layer, blendMode);\n getLayer (layer).setBlendMode (blendMode);\n invalidateFusion ();\n callListenersLayerChange ();\n }\n}\n\npublic void setLayerName (int layer, String name)\n{\n if (!getLayer (layer).getName ().equals (name))\n {\n undoManager.beforeLayerRename (layer, name);\n getLayer (layer).setName (name);\n callListenersLayerChange ();\n }\n}\n\npublic void doEffectAction (boolean applyToAllLayers, CPEffect effect)\n{\n CPRect rect = curSelection.isEmpty () ? getSize () : curSelection.getBoundingRect ();\n\n if (!applyToAllLayers)\n {\n undoManager.preserveActiveLayerData ();\n effect.doEffectOn (getActiveLayer (), curSelection);\n\n undoManager.activeLayerDataChange (rect);\n }\n else\n {\n undoManager.preserveAllLayersState ();\n for (int i = 0; i < getLayersVector ().size (); i++)\n {\n effect.doEffectOn (getLayersVector ().elementAt (i), curSelection);\n }\n undoManager.allLayersChanged (rect);\n }\n\n invalidateFusion ();\n}\n\n\n// ////\n// Copy/Paste\n\n// ////////////////////////////////////////////////////\n// Miscellaneous functions\n\npublic String getDefaultLayerName ()\n{\n String prefix = \"Layer \";\n int highestLayerNb = 0;\n for (CPLayer l : getLayersVector ())\n {\n if (l.getName ().matches (\"^\" + prefix + \"[0-9]+$\"))\n {\n highestLayerNb = Math.max (highestLayerNb, Integer.parseInt (l.getName ().substring (prefix.length ())));\n }\n }\n return prefix + (highestLayerNb + 1);\n}\n\npublic boolean hasAlpha ()\n{\n return fusion.hasAlpha ();\n}\n\n// ////////////////////////////////////////////////////\n// Undo classes\npublic Vector<CPLayer> getLayersVector ()\n{\n return layers;\n}\n\npublic void setLayers (Vector<CPLayer> layers)\n{\n this.layers = layers;\n}\n\npublic int getActiveLayerNum ()\n{\n return activeLayerNumber;\n}\n\npublic boolean isLockAlpha ()\n{\n return lockAlpha;\n}\n\npublic boolean isSampleAllLayers ()\n{\n return sampleAllLayers;\n}\n\n}", "public class CPChibiFile extends CPFile\n{\nprivate static final byte[] CHIB = {67, 72, 73, 66};\nprivate static final byte[] IOEK = {73, 79, 69, 75};\nprivate static final byte[] HEAD = {72, 69, 65, 68};\nprivate static final byte[] LAYR = {76, 65, 89, 82};\nprivate static final byte[] LYER = {76, 89, 69, 82};\nprivate static final byte[] ZEND = {90, 69, 78, 68};\n\n@Override\npublic boolean isNative ()\n{\n return true; // One and only\n}\n\n@Override\npublic FileNameExtensionFilter fileFilter ()\n{\n return new FileNameExtensionFilter (\"ChibiPaintMod Files(*.chi)\", \"chi\");\n}\n\nprivate ChiWriter getWriterByVersion (int version)\n{\n switch (version)\n {\n case 0x0100:\n return new AdvancedChiWriter ();\n case 0x0000:\n return new DefaultChiWriter ();\n }\n return null;\n}\n\nprivate ChiReader getReaderByVersion (int version)\n{\n switch (version)\n {\n case 0x0100:\n return new ChiReader_v1 ();\n case 0x0000:\n return new DefaultChiReader ();\n }\n return null;\n}\n\nstatic private int LATEST_VER = 0x0100;\n\n@Override\npublic boolean write (OutputStream os, CPArtwork a)\n{\n return getWriterByVersion (a.isAppletEmulation () ? 0x0000 : LATEST_VER).write (os, a);\n}\n\nclass AdvancedChiWriter extends DefaultChiWriter\n{\n @Override\n protected void writeHeader (OutputStream os, CPArtwork a) throws IOException\n {\n os.write (HEAD); // Chunk ID\n writeInt (os, 16); // ChunkSize\n\n writeInt (os, LATEST_VER); // Actual Version\n writeInt (os, a.getWidth ());\n writeInt (os, a.getHeight ());\n writeInt (os, a.getLayersNb ());\n\n // This is not part of the legacy header:\n writeInt (os, a.getActiveLayerNum ());\n }\n\n @Override\n protected void writeLayer (OutputStream os, CPLayer l) throws IOException\n {\n byte[] title = l.getName ().getBytes (\"UTF-8\");\n\n os.write (LYER); // Chunk ID\n writeInt (os, 20 + l.getData ().length * 4 + title.length); // ChunkSize\n\n writeInt (os, 20 + title.length); // Data offset from start of header\n writeInt (os, l.getBlendMode ()); // layer blend mode\n writeInt (os, l.getAlpha ()); // layer opacity\n writeInt (os, l.isVisible () ? 1 : 0); // layer visibility and future flags\n\n writeInt (os, title.length);\n os.write (title);\n\n writeIntArray (os, l.getData ());\n }\n}\n\nprivate static void writeInt (OutputStream os, int i) throws IOException\n{\n byte[] temp = {(byte) (i >>> 24), (byte) ((i >>> 16) & 0xff), (byte) ((i >>> 8) & 0xff), (byte) (i & 0xff)};\n os.write (temp);\n}\n\ninterface ChiWriter\n{\n public abstract boolean write (OutputStream os, CPArtwork a);\n}\n\nclass DefaultChiWriter implements ChiWriter\n{\n protected void writeHeader (OutputStream os, CPArtwork a) throws IOException\n {\n os.write (HEAD); // Chunk ID\n writeInt (os, 16); // ChunkSize\n\n writeInt (os, 0x0000); // Current Version: Major: 0 Minor: 0\n writeInt (os, a.getWidth ());\n writeInt (os, a.getHeight ());\n writeInt (os, a.getLayersNb ());\n }\n\n protected void writeLayer (OutputStream os, CPLayer l) throws IOException\n {\n byte[] title = l.getName ().getBytes (\"UTF-8\");\n\n os.write (LAYR); // Chunk ID\n writeInt (os, 20 + l.getData ().length * 4 + title.length); // ChunkSize\n\n writeInt (os, 20 + title.length); // Data offset from start of header\n writeInt (os, l.getBlendMode ()); // layer blend mode\n writeInt (os, l.getAlpha ()); // layer opacity\n writeInt (os, l.isVisible () ? 1 : 0); // layer visibility and future flags\n\n writeInt (os, title.length);\n os.write (title);\n\n writeIntArray (os, l.getData ());\n }\n\n\n protected void writeIntArray (OutputStream os, int arr[]) throws IOException\n {\n byte[] temp = new byte[arr.length * 4];\n int idx = 0;\n for (int i : arr)\n {\n temp[idx++] = (byte) (i >>> 24);\n temp[idx++] = (byte) ((i >>> 16) & 0xff);\n temp[idx++] = (byte) ((i >>> 8) & 0xff);\n temp[idx++] = (byte) (i & 0xff);\n }\n\n os.write (temp);\n }\n\n private void writeMagic (OutputStream os) throws IOException\n {\n os.write (CHIB);\n os.write (IOEK);\n }\n\n private void writeEnd (OutputStream os) throws IOException\n {\n os.write (ZEND);\n writeInt (os, 0);\n }\n\n public boolean write (OutputStream os, CPArtwork a)\n {\n try\n {\n writeMagic (os);\n os.flush ();\n\n Deflater def = new Deflater (7);\n DeflaterOutputStream dos = new DeflaterOutputStream (os, def);\n // OutputStream dos = os;\n\n writeHeader (dos, a);\n\n for (Object l : a.getLayersVector ())\n {\n writeLayer (dos, (CPLayer) l);\n }\n\n writeEnd (dos);\n\n dos.flush ();\n dos.close ();\n return true;\n }\n catch (IOException e)\n {\n return false;\n }\n }\n}\n\n\ninterface ChiReader\n{\n abstract public CPArtwork read (InflaterInputStream iis, CPChibiHeader header) throws IOException;\n}\n\nclass ChiReader_v1 implements ChiReader\n{\n\n private void readLayer (InputStream is, CPChibiChunk chunk, CPArtwork a) throws IOException\n {\n CPLayer l = new CPLayer (a.getWidth (), a.getHeight ());\n\n int offset = readInt (is);\n l.setBlendMode (readInt (is)); // layer blend mode\n l.setAlpha (readInt (is));\n l.setVisible ((readInt (is) & 1) != 0);\n\n int titleLength = readInt (is);\n byte[] title = new byte[titleLength];\n realRead (is, title, titleLength);\n l.setName (new String (title, \"UTF-8\"));\n\n realSkip (is, offset - 20 - titleLength);\n readIntArray (is, l.getData (), l.getWidth () * l.getHeight ());\n\n a.getLayersVector ().add (l);\n\n realSkip (is, chunk.chunkSize - offset - l.getWidth () * l.getHeight () * 4);\n }\n\n @Override\n public CPArtwork read (InflaterInputStream iis, CPChibiHeader header) throws IOException\n {\n CPArtwork a = new CPArtwork (header.width, header.height);\n a.getLayersVector ().remove (0); // FIXME: it would be better not to have created it in the first place\n CPChibiChunk chunk;\n int activeLayerNum = readInt (iis);\n\n while (true)\n {\n chunk = new CPChibiChunk (iis);\n\n if (chunk.is (ZEND))\n {\n break;\n }\n else if (chunk.is (LYER))\n {\n readLayer (iis, chunk, a);\n }\n else\n {\n realSkip (iis, chunk.chunkSize);\n }\n }\n\n a.setActiveLayerNumberWithoutUndo (activeLayerNum);\n iis.close ();\n return a;\n }\n}\n\nclass DefaultChiReader implements ChiReader\n{\n\n private void readLayer (InputStream is, CPChibiChunk chunk, CPArtwork a) throws IOException\n {\n CPLayer l = new CPLayer (a.getWidth (), a.getHeight ());\n\n int offset = readInt (is);\n l.setBlendMode (readInt (is)); // layer blend mode\n l.setAlpha (readInt (is));\n l.setVisible ((readInt (is) & 1) != 0);\n\n int titleLength = readInt (is);\n byte[] title = new byte[titleLength];\n realRead (is, title, titleLength);\n l.setName (new String (title, \"UTF-8\"));\n\n realSkip (is, offset - 20 - titleLength);\n readIntArray (is, l.getData (), l.getWidth () * l.getHeight ());\n\n a.getLayersVector ().add (l);\n\n realSkip (is, chunk.chunkSize - offset - l.getWidth () * l.getHeight () * 4);\n }\n\n @Override\n public CPArtwork read (InflaterInputStream iis, CPChibiHeader header) throws IOException\n {\n CPArtwork a = new CPArtwork (header.width, header.height);\n a.getLayersVector ().remove (0); // FIXME: it would be better not to have created it in the first place\n CPChibiChunk chunk;\n\n while (true)\n {\n chunk = new CPChibiChunk (iis);\n\n if (chunk.is (ZEND))\n {\n break;\n }\n else if (chunk.is (LAYR))\n {\n readLayer (iis, chunk, a);\n }\n else\n {\n realSkip (iis, chunk.chunkSize);\n }\n }\n\n a.setActiveLayerNumberWithoutUndo (0);\n a.setAppletEmulation (true);\n iis.close ();\n return a;\n }\n}\n\n@Override\npublic CPArtwork read (InputStream is)\n{\n try\n\n {\n if (!readMagic (is))\n {\n return null; // not a ChibiPaintMod file\n }\n\n InflaterInputStream iis = new InflaterInputStream (is);\n CPChibiChunk chunk = new CPChibiChunk (iis);\n if (!chunk.is (HEAD))\n {\n iis.close ();\n return null; // not a valid file\n }\n\n CPChibiHeader header = new CPChibiHeader (iis, chunk);\n ChiReader reader = getReaderByVersion (header.version);\n if (reader == null)\n {\n is.close ();\n return null;\n }\n\n return reader.read (iis, header);\n }\n catch (IOException e)\n {\n return null;\n }\n catch (Exception e)\n {\n return null;\n }\n}\n\nstatic private void readIntArray (InputStream is, int[] intArray, int size) throws IOException\n{\n byte[] buffer = new byte[size * 4];\n\n realRead (is, buffer, size * 4);\n\n int off = 0;\n for (int i = 0; i < size; i++)\n {\n intArray[i] = ((buffer[off++] & 0xff) << 24) | ((buffer[off++] & 0xff) << 16)\n | ((buffer[off++] & 0xff) << 8) | (buffer[off++] & 0xff);\n }\n}\n\nprivate static int readInt (InputStream is) throws IOException\n{\n return is.read () << 24 | is.read () << 16 | is.read () << 8 | is.read ();\n}\n\nprivate static void realSkip (InputStream is, long bytesToSkip) throws IOException\n{\n long skipped = 0, value;\n while (skipped < bytesToSkip)\n {\n value = is.read ();\n if (value < 0)\n {\n throw new RuntimeException (\"EOF!\");\n }\n\n skipped++;\n skipped += is.skip (bytesToSkip - skipped);\n }\n}\n\nprivate static void realRead (InputStream is, byte[] buffer, int bytesToRead) throws IOException\n{\n int read = 0, value;\n while (read < bytesToRead)\n {\n value = is.read ();\n if (value < 0)\n {\n throw new RuntimeException (\"EOF!\");\n }\n\n buffer[read++] = (byte) value;\n read += is.read (buffer, read, bytesToRead - read);\n }\n}\n\nprivate static boolean readMagic (InputStream is) throws IOException\n{\n byte[] buffer = new byte[4];\n\n realRead (is, buffer, 4);\n if (!Arrays.equals (buffer, CHIB))\n {\n return false;\n }\n\n realRead (is, buffer, 4);\n return Arrays.equals (buffer, IOEK);\n\n}\n\nstatic class CPChibiChunk\n{\n\n final byte[] chunkType = new byte[4];\n int chunkSize;\n\n public CPChibiChunk (InputStream is) throws IOException\n {\n realRead (is, chunkType, 4);\n chunkSize = readInt (is);\n }\n\n boolean is (byte[] chunkTypeArg)\n {\n return Arrays.equals (this.chunkType, chunkTypeArg);\n }\n}\n\nstatic class CPChibiHeader\n{\n\n int version, width, height, layersNb;\n\n public CPChibiHeader (InputStream is, CPChibiChunk chunk) throws IOException\n {\n version = readInt (is);\n width = readInt (is);\n height = readInt (is);\n layersNb = readInt (is);\n\n realSkip (is, chunk.chunkSize - 16);\n }\n}\n\n@Override\npublic String ext ()\n{\n return \"CHI\";\n}\n\n}", "public class CPMainGUI\n{\n\nprivate final CPCommonController controller;\n\nclass MenuItemHashMap extends HashMap<CPCommandId, ArrayList<JMenuItem>>\n{\n public void put (CPCommandId key, JMenuItem value)\n {\n ArrayList<JMenuItem> list = this.get (key);\n if (list == null)\n {\n list = new ArrayList<JMenuItem> ();\n list.add (value);\n super.put (key, list);\n }\n else\n list.add (value);\n }\n}\n\nprivate final MenuItemHashMap menuItems = new MenuItemHashMap ();\nprivate CPPaletteManager paletteManager;\n\nprivate JMenuBar menuBar;\nprivate JMenuBar menuBarTemporary; // Temporary menu bar for safe replacement with actual one\nprivate JMenu lastMenu, lastSubMenu;\nprivate JMenu recentFilesMenuItem;\nprivate JMenuItem lastItem;\nprivate JPanel mainPanel;\nprivate JPanel bg;\n\n// FIXME: replace this hack by something better\nprivate final Map<String, JCheckBoxMenuItem> paletteItems = new HashMap<String, JCheckBoxMenuItem> ();\n\npublic CPMainGUI (CPCommonController controller)\n{\n this.controller = controller;\n controller.setMainGUI (this);\n\n // try {\n // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n // } catch (Exception ex2) {} */\n\n createMainMenu ();\n menuBar = menuBarTemporary;\n menuBarTemporary = null;\n createGUI ();\n}\n\npublic JComponent getGUI ()\n{\n return mainPanel;\n}\n\npublic JMenuBar getMenuBar ()\n{\n return menuBar;\n}\n\npublic void recreateMenuBar ()\n{\n createMainMenu ();\n menuBar = menuBarTemporary;\n menuBarTemporary = null;\n}\n\nprivate void createGUI ()\n{\n mainPanel = new JPanel (new BorderLayout ());\n\n JDesktopPane jdp = new CPDesktop ();\n setPaletteManager (new CPPaletteManager (controller, jdp));\n\n createCanvasGUI (jdp);\n mainPanel.add (jdp, BorderLayout.CENTER);\n\n JPanel statusBar = new CPStatusBar (controller);\n mainPanel.add (statusBar, BorderLayout.PAGE_END);\n // jdp.addContainerListener(this);\n}\n\nvoid createCanvasGUI (JComponent c)\n{\n CPCanvas canvas = new CPCanvas (controller);\n setBg (canvas.getCanvasContainer ());\n\n c.add (getBg ());\n canvas.grabFocus ();\n}\n\n// it's internal so boolean argument is ok\nprivate void addMenuItemInternal (String title, int mnemonic, final CPCommandId commandId, String description, final boolean isCheckable, boolean checked, final CPCommandSettings commandSettings)\n{\n JMenuItem menuItem;\n if (controller.isRunningAsApplet () && commandId.isForAppOnly ())\n return;\n\n if (controller.isRunningAsApplication () && commandId.isForAppletOnly ())\n return;\n\n if (isCheckable)\n {\n menuItem = new JCheckBoxMenuItem (title, checked);\n menuItem.setMnemonic (mnemonic);\n }\n else\n {\n menuItem = new JMenuItem (title, mnemonic);\n }\n menuItem.getAccessibleContext ().setAccessibleDescription (description);\n menuItem.addActionListener (new ActionListener ()\n {\n @Override\n public void actionPerformed (ActionEvent e)\n {\n controller.performCommand (commandId, isCheckable ? new CPCommandSettings.CheckBoxState (((JCheckBoxMenuItem) e.getSource ()).isSelected ()) : commandSettings);\n }\n });\n ArrayList<JMenuItem> list = menuItems.get (commandId);\n menuItems.put (commandId, menuItem);\n if (lastSubMenu != null)\n lastSubMenu.add (menuItem);\n else\n lastMenu.add (menuItem);\n lastItem = menuItem;\n}\n\nArrayList<JMenuItem> getMenuItemListByCmdId (CPCommandId cmdId)\n{\n return menuItems.get (cmdId);\n}\n\nvoid setEnabledByCmdId (CPCommandId cmdId, boolean value)\n{\n for (JMenuItem item : controller.getMainGUI ().getMenuItemListByCmdId (cmdId))\n item.setEnabled (value);\n}\n\nvoid setSelectedByCmdId (CPCommandId cmdId, boolean value)\n{\n for (JMenuItem item : controller.getMainGUI ().getMenuItemListByCmdId (cmdId))\n item.setSelected (value);\n}\n\nvoid setEnabledForTransform (boolean enabled)\n{\n for (Object o : menuItems.entrySet ())\n {\n Map.Entry pairs = (Map.Entry) o;\n ArrayList<JMenuItem> item = (ArrayList<JMenuItem>) pairs.getValue ();\n for (JMenuItem menuItem : item)\n {\n menuItem.setEnabled (enabled);\n }\n }\n ((CPLayersPalette) getPaletteManager ().getPalettes ().get (\"layers\")).setEnabledForTransform (enabled);\n ((CPMiscPalette) getPaletteManager ().getPalettes ().get (\"misc\")).setEnabledForTransform (enabled);\n}\n\nvoid addMenuItem (String title, int mnemonic, CPCommandId commandId)\n{\n addMenuItemInternal (title, mnemonic, commandId, \"\", false, false, null);\n}\n\nvoid addMenuItem (String title, int mnemonic, CPCommandId commandId, String description)\n{\n addMenuItemInternal (title, mnemonic, commandId, description, false, false, null);\n}\n\nvoid addMenuItem (String title, int mnemonic, CPCommandId commandId, String description, CPCommandSettings settings)\n{\n addMenuItemInternal (title, mnemonic, commandId, description, false, false, settings);\n}\n\nvoid addMenuItem (String title, int mnemonic, CPCommandId commandId, String description, KeyStroke accelerator)\n{\n addMenuItem (title, mnemonic, commandId, description);\n lastItem.setAccelerator (accelerator);\n}\n\nvoid addMenuItem (String title, int mnemonic, CPCommandId commandId, String description, KeyStroke accelerator, CPCommandSettings settings)\n{\n addMenuItemInternal (title, mnemonic, commandId, description, false, false, settings);\n lastItem.setAccelerator (accelerator);\n}\n\nvoid addCheckBoxMenuItem (String title, int mnemonic, CPCommandId commandId, String description, boolean checked)\n{\n addMenuItemInternal (title, mnemonic, commandId, description, true, checked, null);\n}\n\nvoid addCheckBoxMenuItem (String title, int mnemonic, CPCommandId commandId, boolean checked)\n{\n addMenuItemInternal (title, mnemonic, commandId, \"\", true, checked, null);\n}\n\nvoid addCheckBoxMenuItem (String title, int mnemonic, CPCommandId commandId, String description, KeyStroke accelerator, boolean checked)\n{\n addMenuItemInternal (title, mnemonic, commandId, description, true, checked, null);\n lastItem.setAccelerator (accelerator);\n}\n\nvoid addMenu (String Title, int mnemonic)\n{\n JMenu menu = new JMenu (Title);\n menu.setMnemonic (mnemonic);\n menuBarTemporary.add (menu);\n lastSubMenu = null;\n lastMenu = menu;\n}\n\nvoid addSubMenu (String Title, int mnemonic)\n{\n JMenu menu = new JMenu (Title);\n menu.setMnemonic (mnemonic);\n lastMenu.add (menu);\n lastSubMenu = menu;\n}\n\nvoid endSubMenu ()\n{\n lastSubMenu = null;\n}\n\nvoid addSeparator ()\n{\n if (lastSubMenu != null)\n lastSubMenu.add (new JSeparator ());\n else\n lastMenu.add (new JSeparator ());\n}\n\nvoid createMainMenu ()\n{\n menuBarTemporary = new JMenuBar ();\n lastMenu = null;\n lastSubMenu = null;\n menuItems.clear ();\n\n // File\n addMenu (\"File\", KeyEvent.VK_F);\n\n addMenuItem (\"Send Oekaki\", KeyEvent.VK_S, CPCommandId.Send, \"Sends the oekaki to the server and exits ChibiPaintMod\");\n\n if (controller.isRunningAsApplication ())\n {\n addMenuItem (\"New File\", KeyEvent.VK_N, CPCommandId.New, \"Create new file\");\n\n addSeparator ();\n\n addMenuItem (\"Save\", KeyEvent.VK_S, CPCommandId.Save, \"Save existing file\", KeyStroke.getKeyStroke (KeyEvent.VK_S, InputEvent.CTRL_MASK));\n addMenuItem (\"Save as...\", KeyEvent.VK_A, CPCommandId.Export, \"Save .chi File\", KeyStroke.getKeyStroke (KeyEvent.VK_S, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK), new CPCommandSettings.FileExtension (\"chi\"));\n addMenuItem (\"Open...\", KeyEvent.VK_O, CPCommandId.Import, \"Open .chi File\", KeyStroke.getKeyStroke (KeyEvent.VK_O, InputEvent.CTRL_MASK), new CPCommandSettings.FileExtension (\"chi\"));\n\n addSubMenu (\"Open Recent\", KeyEvent.VK_R);\n recentFilesMenuItem = lastSubMenu;\n endSubMenu ();\n\n updateRecentFiles ();\n\n addSeparator ();\n\n String[] importExport = {\"Import\", \"Export\"};\n CPCommandId[] loadSave = {CPCommandId.Import, CPCommandId.Export};\n int[] mnemonics = {KeyEvent.VK_I, KeyEvent.VK_X};\n String[] supportedExtensions = CPFile.getSupportedExtensions ();\n\n for (int i = 0; i < 2; i++)\n {\n addSubMenu (importExport[i], mnemonics[i]);\n CPFile file;\n for (String supportedExt : supportedExtensions)\n {\n file = CPFile.fromExtension (supportedExt);\n if (file.isNative ())\n continue;\n\n addMenuItem (supportedExt.toUpperCase () + \" File...\", 0, loadSave[i], importExport[i] + \" \" + supportedExt.toUpperCase () + \"Files\", new CPCommandSettings.FileExtension (supportedExt));\n }\n endSubMenu ();\n }\n\n addSeparator ();\n\n addMenuItem (\"Exit\", KeyEvent.VK_E, CPCommandId.Exit, \"Exit the application\", KeyStroke.getKeyStroke (KeyEvent.VK_Q, InputEvent.CTRL_MASK));\n }\n\n // Edit\n addMenu (\"Edit\", KeyEvent.VK_E);\n addMenuItem (\"Undo\", KeyEvent.VK_U, CPCommandId.Undo, \"Undo the most recent action\", KeyStroke.getKeyStroke (KeyEvent.VK_Z, InputEvent.CTRL_MASK));\n addMenuItem (\"Redo\", KeyEvent.VK_U, CPCommandId.Redo, \"Redo a previously undone action\", KeyStroke.getKeyStroke (KeyEvent.VK_Z, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));\n addMenuItem (\"Clear History\", KeyEvent.VK_H, CPCommandId.ClearHistory, \"Remove all undo/redo information to regain memory\");\n addSeparator ();\n\n addMenuItem (\"Cut\", KeyEvent.VK_T, CPCommandId.Cut, \"Cuts the selected part of the layer\", KeyStroke.getKeyStroke (KeyEvent.VK_X, InputEvent.CTRL_MASK));\n addMenuItem (\"Copy\", KeyEvent.VK_C, CPCommandId.Copy, \"Copy the selected part of the layer\", KeyStroke.getKeyStroke (KeyEvent.VK_C, InputEvent.CTRL_MASK));\n addMenuItem (\"Copy Merged\", KeyEvent.VK_Y, CPCommandId.CopyMerged, \"Copy the selected part of all the layers merged\", KeyStroke.getKeyStroke (KeyEvent.VK_C, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));\n addMenuItem (\"Paste\", KeyEvent.VK_P, CPCommandId.Paste, \"Paste the stuff that have been copied\", KeyStroke.getKeyStroke (KeyEvent.VK_V, InputEvent.CTRL_MASK));\n addSeparator ();\n\n addMenuItem (\"Select All\", KeyEvent.VK_A, CPCommandId.SelectAll, \"Selects the whole canvas\", KeyStroke.getKeyStroke (KeyEvent.VK_A, InputEvent.CTRL_MASK));\n addMenuItem (\"Alpha to Selection\", KeyEvent.VK_L, CPCommandId.AlphaToSelection, \"Transform layer's alpha to selection\");\n addMenuItem (\"Invert Selection\", KeyEvent.VK_I, CPCommandId.InvertSelection, \"Invert selection\", KeyStroke.getKeyStroke (KeyEvent.VK_I, InputEvent.CTRL_MASK));\n addMenuItem (\"Deselect\", KeyEvent.VK_D, CPCommandId.DeselectAll, \"Deselects the whole canvas\", KeyStroke.getKeyStroke (KeyEvent.VK_D, InputEvent.CTRL_MASK));\n\n // Layers\n addMenu (\"Layers\", KeyEvent.VK_L);\n addMenuItem (\"Show / Hide All Layers\", KeyEvent.VK_A, CPCommandId.LayerToggleAll, \"Toggle All Layers Visibility\", KeyStroke.getKeyStroke (KeyEvent.VK_A, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));\n addSeparator ();\n addMenuItem (\"Duplicate\", KeyEvent.VK_D, CPCommandId.LayerDuplicate, \"Creates a copySelected of the currently selected layer\", KeyStroke.getKeyStroke (KeyEvent.VK_D, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));\n addSeparator ();\n addMenuItem (\"Merge Down\", KeyEvent.VK_E, CPCommandId.LayerMergeDown, \"Merges the currently selected layer with the one directly below it\", KeyStroke.getKeyStroke (KeyEvent.VK_E, InputEvent.CTRL_MASK));\n addMenuItem (\"Merge All Layers\", KeyEvent.VK_A, CPCommandId.LayerMergeAll, \"Merges all the layers\");\n\n // Effects\n addMenu (\"Effects\", KeyEvent.VK_E);\n addMenuItem (\"Free Transform Selected\", KeyEvent.VK_T, CPCommandId.FreeTransform, \"Transform selected part of the current layer\", KeyStroke.getKeyStroke (KeyEvent.VK_T, InputEvent.CTRL_MASK));\n addSeparator ();\n addMenuItem (\"Clear\", KeyEvent.VK_C, CPCommandId.Clear, \"Clears the selected area\", KeyStroke.getKeyStroke (KeyEvent.VK_DELETE, 0));\n addMenuItem (\"Fill\", KeyEvent.VK_F, CPCommandId.Fill, \"Fills the selected area with the current color\", KeyStroke.getKeyStroke (KeyEvent.VK_F, InputEvent.CTRL_MASK));\n addMenuItem (\"Invert\", KeyEvent.VK_F, CPCommandId.FXInvert, \"Invert the image colors\");\n\n addMenuItem (\"Make Grayscale\", KeyEvent.VK_M, CPCommandId.FXMakeGrayscaleByLuma, \"Make image grayscale by Luma Formula\");\n\n addSubMenu (\"Blur\", KeyEvent.VK_B);\n addMenuItem (\"Box Blur...\", KeyEvent.VK_B, CPCommandId.FXBoxBlur, \"Box Blur Effect\");\n addMenuItem (\"Gaussian Blur...\", KeyEvent.VK_G, CPCommandId.FXGaussianBlur, \"Gaussian Blur Effect\");\n endSubMenu ();\n\n addSubMenu (\"Noise\", KeyEvent.VK_N);\n addMenuItem (\"Render Monochromatic\", KeyEvent.VK_M, CPCommandId.MNoise, \"Fills the selection with noise\");\n addMenuItem (\"Render Color\", KeyEvent.VK_C, CPCommandId.CNoise, \"Fills the selection with colored noise\");\n endSubMenu ();\n addSeparator ();\n addCheckBoxMenuItem (\"Apply to All Layers\", KeyEvent.VK_T, CPCommandId.ApplyToAllLayers, \"Apply all listed above effects to all layers instead of just current\", false);\n\n // View\n\n addMenu (\"View\", KeyEvent.VK_V);\n\n if (controller.isRunningAsApplet ())\n {\n addMenuItem (\"Floating mode\", KeyEvent.VK_F, CPCommandId.Float, \"Opens ChibiPaintMod in an independent window\");\n addSeparator ();\n }\n\n addMenuItem (\"Zoom In\", KeyEvent.VK_I, CPCommandId.ZoomIn, \"Zooms In\", KeyStroke.getKeyStroke (KeyEvent.VK_ADD, InputEvent.CTRL_MASK));\n addMenuItem (\"Zoom Out\", KeyEvent.VK_O, CPCommandId.ZoomOut, \"Zooms Out\", KeyStroke.getKeyStroke (KeyEvent.VK_SUBTRACT, InputEvent.CTRL_MASK));\n addMenuItem (\"Zoom 100%\", KeyEvent.VK_O, CPCommandId.Zoom100, \"Resets the zoom factor to 100%\", KeyStroke.getKeyStroke (KeyEvent.VK_NUMPAD0, InputEvent.CTRL_MASK));\n addMenuItem (\"Zoom...\", KeyEvent.VK_Z, CPCommandId.ZoomSpecific, \"Zoom to specified scale\", KeyStroke.getKeyStroke (KeyEvent.VK_Z, InputEvent.ALT_MASK));\n addSeparator ();\n addCheckBoxMenuItem (\"Use Linear Interpolation\", KeyEvent.VK_L, CPCommandId.LinearInterpolation, \"Linear interpolation is used to give a smoothed looked to the picture when zoomed in\", false);\n addCheckBoxMenuItem (\"Show Selection\", KeyEvent.VK_L, CPCommandId.ShowSelection, \"Show animated selection borders to better see it and operate with it\", true);\n addSeparator ();\n addCheckBoxMenuItem (\"Show Grid\", KeyEvent.VK_G, CPCommandId.ShowGrid, \"Displays a grid over the image\", KeyStroke.getKeyStroke (KeyEvent.VK_G, InputEvent.CTRL_MASK), false);\n addMenuItem (\"Grid options...\", KeyEvent.VK_D, CPCommandId.GridOptions, \"Shows the grid options dialog box\");\n addSeparator ();\n\n addSubMenu (\"Palettes\", KeyEvent.VK_P);\n addMenuItem (\"Toggle Palettes\", KeyEvent.VK_P, CPCommandId.TogglePalettes, \"Hides or shows all palettes\", KeyStroke.getKeyStroke (KeyEvent.VK_TAB, 0));\n addSeparator ();\n addCheckBoxMenuItem (\"Show Tool Preferences\", KeyEvent.VK_T, CPCommandId.PalBrush, true);\n paletteItems.put (\"ToolPreferences\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Color\", KeyEvent.VK_C, CPCommandId.PalColor, true);\n paletteItems.put (\"Color\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Layers\", KeyEvent.VK_Y, CPCommandId.PalLayers, true);\n paletteItems.put (\"Layers\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Misc\", KeyEvent.VK_M, CPCommandId.PalMisc, true);\n paletteItems.put (\"Misc\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Stroke\", KeyEvent.VK_R, CPCommandId.PalStroke, true);\n paletteItems.put (\"Stroke\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Swatches\", KeyEvent.VK_S, CPCommandId.PalSwatches, true);\n paletteItems.put (\"Color Swatches\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Textures\", KeyEvent.VK_T, CPCommandId.PalTextures, true);\n paletteItems.put (\"Textures\", (JCheckBoxMenuItem) lastItem);\n addCheckBoxMenuItem (\"Show Tools\", KeyEvent.VK_O, CPCommandId.PalTool, true);\n paletteItems.put (\"Tools\", (JCheckBoxMenuItem) lastItem);\n endSubMenu ();\n\n // Help\n addMenu (\"Help\", KeyEvent.VK_H);\n addMenuItem (\"About...\", KeyEvent.VK_A, CPCommandId.About, \"Displays some information about ChibiPaintMod\");\n}\n\npublic void showPalette (String palette, boolean show)\n{\n getPaletteManager ().showPalette (palette, show);\n}\n\npublic void togglePaletteVisibility (String palette)\n{\n getPaletteManager ().togglePaletteVisibility (palette);\n}\n\npublic void setPaletteMenuItem (String title, boolean selected)\n{\n JCheckBoxMenuItem item = paletteItems.get (title);\n if (item != null)\n {\n item.setSelected (selected);\n }\n}\n\npublic boolean togglePalettes ()\n{\n return getPaletteManager ().togglePalettes ();\n}\n\npublic CPPaletteManager getPaletteManager ()\n{\n return paletteManager;\n}\n\nvoid setPaletteManager (CPPaletteManager paletteManager)\n{\n this.paletteManager = paletteManager;\n}\n\nJPanel getBg ()\n{\n return bg;\n}\n\nvoid setBg (JPanel bg)\n{\n this.bg = bg;\n}\n\nstatic public final int RECENT_FILES_COUNT = 9;\n\npublic void updateRecentFiles ()\n{\n recentFilesMenuItem.removeAll ();\n lastSubMenu = recentFilesMenuItem;\n Preferences userRoot = Preferences.userRoot ();\n Preferences preferences = userRoot.node (\"chibipaintmod\");\n for (int i = 0; i < RECENT_FILES_COUNT; i++)\n {\n String recentFileName = preferences.get (\"Recent File[\" + i + \"]\", \"\");\n if (recentFileName.length () != 0)\n {\n File recentFile = new File (recentFileName);\n addMenuItem (recentFile.getName (), 0, CPCommandId.OpenRecent, \"Open Recent File \" + i, KeyStroke.getKeyStroke (KeyEvent.VK_0 + (i + 1) % 10, InputEvent.CTRL_MASK), new CPCommandSettings.RecentFileNumber (i));\n }\n }\n lastSubMenu = null;\n}\n\nclass CPDesktop extends JDesktopPane\n{\n\n public CPDesktop ()\n {\n addComponentListener (new ComponentAdapter ()\n {\n\n @Override\n public void componentResized (ComponentEvent e)\n {\n getBg ().setSize (getSize ());\n getBg ().validate ();\n }\n });\n }\n}\n}" ]
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.PixelGrabber; import java.net.URL; import java.net.URLConnection; import chibipaint.controller.CPCommonController; import chibipaint.controller.CPControllerApplet; import chibipaint.engine.CPArtwork; import chibipaint.file.CPChibiFile; import chibipaint.gui.CPMainGUI; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*;
/* * ChibiPaintMod * Copyright (c) 2012-2014 Sergey Semushin * Copyright (c) 2006-2008 Marc Schefer * * This file is part of ChibiPaintMod (previously ChibiPaint). * * ChibiPaintMod is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ChibiPaintMod is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ChibiPaintMod. If not, see <http://www.gnu.org/licenses/>. */ package chibipaint; public class ChibiPaint extends JApplet { /** * */ private static final long serialVersionUID = 1L; private CPControllerApplet controller; private CPMainGUI mainGUI; private boolean floatingMode = false; private JPanel floatingPlaceholder; private JFrame floatingFrame; @Override public void init () { try { SwingUtilities.invokeAndWait (new Runnable () { @Override public void run () { createApplet (); } }); } catch (Exception e) { e.printStackTrace (); } } @Override public void destroy () { // The following bit of voodoo prevents the Java plugin // from leaking too much. In many cases it will keep // a reference to this JApplet object alive forever. // So have to make sure that we remove references // to the rest of ChibiPaintMod so that they can be // garbage collected normally. setContentPane (new JPanel ()); setJMenuBar (null); floatingPlaceholder = null; floatingFrame = null; controller = null; mainGUI = null; } void createApplet () { controller = new CPControllerApplet (this); controller.setArtwork (createArtwork ()); controller.artwork.setAppletEmulation (true); // FIXME: set a default tool so that we can start drawing
controller.setTool (CPCommonController.T_PEN);
0
maxdemarzi/grittier_ext
src/main/java/com/maxdemarzi/likes/Likes.java
[ "public enum RelationshipTypes implements RelationshipType {\n BLOCKS,\n FOLLOWS,\n MUTES,\n LIKES,\n REPLIED_TO\n}", "@Path(\"/users\")\npublic class Users {\n\n private final GraphDatabaseService db;\n private static final ObjectMapper objectMapper = new ObjectMapper();\n\n public Users(@Context DatabaseManagementService dbms ) {\n this.db = dbms.database( \"neo4j\" );;\n }\n\n @GET\n @Path(\"/{username}\")\n public Response getUser(@PathParam(\"username\") final String username) throws IOException {\n Map<String, Object> results;\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n results = user.getAllProperties();\n tx.commit();\n }\n return Response.ok().entity(objectMapper.writeValueAsString(results)).build();\n }\n\n @GET\n @Path(\"/{username}/profile\")\n public Response getProfile(@PathParam(\"username\") final String username,\n @QueryParam(\"username2\") final String username2) throws IOException {\n Map<String, Object> results;\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n results = getUserAttributes(user);\n\n if (username2 != null && !username.equals(username2)) {\n Node user2 = findUser(username2, tx);\n HashSet<Node> followed = new HashSet<>();\n for (Relationship r1 : user.getRelationships(Direction.OUTGOING, RelationshipTypes.FOLLOWS)) {\n followed.add(r1.getEndNode());\n }\n HashSet<Node> followed2 = new HashSet<>();\n for (Relationship r1 : user2.getRelationships(Direction.OUTGOING, RelationshipTypes.FOLLOWS)) {\n followed2.add(r1.getEndNode());\n }\n\n boolean follows_me = followed.contains(user2);\n boolean i_follow = followed2.contains(user);\n results.put(I_FOLLOW, i_follow);\n results.put(FOLLOWS_ME, follows_me);\n\n followed.retainAll(followed2);\n\n results.put(FOLLOWERS_YOU_KNOW_COUNT, followed.size());\n ArrayList<Map<String, Object>> followers_sample = new ArrayList<>();\n int count = 0;\n for (Node follower : followed) {\n count++;\n Map<String, Object> properties = follower.getAllProperties();\n properties.remove(PASSWORD);\n properties.remove(EMAIL);\n followers_sample.add(properties);\n if (count > 10) { break; };\n }\n\n results.put(FOLLOWERS_YOU_KNOW, followers_sample);\n\n }\n\n tx.commit();\n }\n return Response.ok().entity(objectMapper.writeValueAsString(results)).build();\n }\n\n @POST\n public Response createUser(String body) throws IOException {\n HashMap parameters = UserValidator.validate(body);\n Map<String, Object> results;\n try (Transaction tx = db.beginTx()) {\n Node user = tx.findNode(Labels.User, USERNAME, parameters.get(USERNAME));\n if (user == null) {\n user = tx.findNode(Labels.User, EMAIL, parameters.get(EMAIL));\n if (user == null) {\n user = tx.createNode(Labels.User);\n user.setProperty(EMAIL, parameters.get(EMAIL));\n user.setProperty(NAME, parameters.get(NAME));\n user.setProperty(USERNAME, parameters.get(USERNAME));\n user.setProperty(PASSWORD, parameters.get(PASSWORD));\n user.setProperty(HASH, new Md5Hash(((String)parameters.get(EMAIL)).toLowerCase()).toString());\n\n LocalDateTime dateTime = LocalDateTime.now(utc);\n user.setProperty(TIME, dateTime.truncatedTo(ChronoUnit.DAYS).toEpochSecond(ZoneOffset.UTC));\n\n results = user.getAllProperties();\n } else {\n throw UserExceptions.existingEmailParameter();\n }\n } else {\n throw UserExceptions.existingUsernameParameter();\n }\n tx.commit();\n }\n return Response.ok().entity(objectMapper.writeValueAsString(results)).build();\n }\n\n @GET\n @Path(\"/{username}/followers\")\n public Response getFollowers(@PathParam(\"username\") final String username,\n @QueryParam(\"limit\") @DefaultValue(\"25\") final Integer limit,\n @QueryParam(\"since\") final Long since) throws IOException {\n ArrayList<Map<String, Object>> results = new ArrayList<>();\n // TODO: 4/3/17 Add Recent Array for Users with > 100k Followers\n LocalDateTime dateTime;\n if (since == null) {\n dateTime = LocalDateTime.now(utc);\n } else {\n dateTime = LocalDateTime.ofEpochSecond(since, 0, ZoneOffset.UTC);\n }\n Long latest = dateTime.toEpochSecond(ZoneOffset.UTC);\n\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n for (Relationship r1: user.getRelationships(Direction.INCOMING, RelationshipTypes.FOLLOWS)) {\n Long time = (Long)r1.getProperty(TIME);\n if(time < latest) {\n Node follower = r1.getStartNode();\n Map<String, Object> result = getUserAttributes(follower);\n result.put(TIME, time);\n results.add(result);\n }\n }\n tx.commit();\n }\n results.sort(Comparator.comparing(m -> (Long) m.get(TIME), reverseOrder()));\n\n return Response.ok().entity(objectMapper.writeValueAsString(\n results.subList(0, Math.min(results.size(), limit))))\n .build();\n }\n\n @GET\n @Path(\"/{username}/following\")\n public Response getFollowing(@PathParam(\"username\") final String username,\n @QueryParam(\"limit\") @DefaultValue(\"25\") final Integer limit,\n @QueryParam(\"since\") final Long since) throws IOException {\n ArrayList<Map<String, Object>> results = new ArrayList<>();\n LocalDateTime dateTime;\n if (since == null) {\n dateTime = LocalDateTime.now(utc);\n } else {\n dateTime = LocalDateTime.ofEpochSecond(since, 0, ZoneOffset.UTC);\n }\n Long latest = dateTime.toEpochSecond(ZoneOffset.UTC);\n\n\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n for (Relationship r1: user.getRelationships(Direction.OUTGOING, RelationshipTypes.FOLLOWS)) {\n Long time = (Long)r1.getProperty(TIME);\n if(time < latest) {\n Node following = r1.getEndNode();\n Map<String, Object> result = getUserAttributes(following);\n result.put(TIME, time);\n results.add(result);\n }\n }\n tx.commit();\n }\n results.sort(Comparator.comparing(m -> (Long) m.get(TIME), reverseOrder()));\n\n return Response.ok().entity(objectMapper.writeValueAsString(\n results.subList(0, Math.min(results.size(), limit))))\n .build();\n }\n\n @POST\n @Path(\"/{username}/follows/{username2}\")\n public Response createFollows(@PathParam(\"username\") final String username,\n @PathParam(\"username2\") final String username2) throws IOException {\n Map<String, Object> results;\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n Node user2 = findUser(username2, tx);\n if (user.equals(user2)) {\n throw UserExceptions.userSame();\n } else {\n HashSet<Node> blocked = new HashSet<>();\n for (Relationship r1 : user2.getRelationships(Direction.OUTGOING, RelationshipTypes.BLOCKS)) {\n blocked.add(r1.getEndNode());\n }\n\n if (blocked.contains(user)) {\n throw UserExceptions.userBlocked();\n }\n\n Relationship follows = user.createRelationshipTo(user2, RelationshipTypes.FOLLOWS);\n LocalDateTime dateTime = LocalDateTime.now(utc);\n follows.setProperty(TIME, dateTime.toEpochSecond(ZoneOffset.UTC));\n results = user2.getAllProperties();\n results.remove(EMAIL);\n results.remove(PASSWORD);\n tx.commit();\n }\n }\n return Response.ok().entity(objectMapper.writeValueAsString(results)).build();\n }\n\n @DELETE\n @Path(\"/{username}/follows/{username2}\")\n public Response removeFollows(@PathParam(\"username\") final String username,\n @PathParam(\"username2\") final String username2) throws IOException {\n Map<String, Object> results;\n try (Transaction tx = db.beginTx()) {\n Node user = findUser(username, tx);\n Node user2 = findUser(username2, tx);\n\n if (user.getDegree(RelationshipTypes.FOLLOWS, Direction.OUTGOING)\n < user2.getDegree(RelationshipTypes.FOLLOWS, Direction.INCOMING)) {\n for (Relationship r1: user.getRelationships(Direction.OUTGOING, RelationshipTypes.FOLLOWS) ) {\n if (r1.getEndNode().equals(user2)) {\n r1.delete();\n }\n }\n } else {\n for (Relationship r1 : user2.getRelationships(Direction.INCOMING, RelationshipTypes.FOLLOWS)) {\n if (r1.getStartNode().equals(user)) {\n r1.delete();\n }\n }\n }\n\n tx.commit();\n }\n return Response.noContent().build();\n }\n\n public static Node findUser(String username, Transaction tx) {\n if (username == null) { return null; }\n Node user = tx.findNode(Labels.User, USERNAME, username);\n if (user == null) { throw UserExceptions.userNotFound(); }\n return user;\n }\n\n public static Map<String, Object> getUserAttributes(Node user) {\n Map<String, Object> results;\n results = user.getAllProperties();\n results.remove(EMAIL);\n results.remove(PASSWORD);\n Integer following = user.getDegree(RelationshipTypes.FOLLOWS, Direction.OUTGOING);\n Integer followers = user.getDegree(RelationshipTypes.FOLLOWS, Direction.INCOMING);\n Integer likes = user.getDegree(RelationshipTypes.LIKES, Direction.OUTGOING);\n Integer posts = user.getDegree(Direction.OUTGOING) - following - likes;\n results.put(\"following\", following);\n results.put(\"followers\", followers);\n results.put(\"likes\", likes);\n results.put(\"posts\", posts);\n return results;\n }\n\n public static Node getPost(Node author, Long time) {\n LocalDateTime postedDateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);\n RelationshipType original = RelationshipType.withName(\"POSTED_ON_\" +\n postedDateTime.format(dateFormatter));\n Node post = null;\n for(Relationship r1 : author.getRelationships(Direction.OUTGOING, original)) {\n Node potential = r1.getEndNode();\n if (time.equals(potential.getProperty(TIME))) {\n post = potential;\n break;\n }\n }\n if(post == null) { throw PostExceptions.postNotFound(); };\n\n return post;\n }\n\n\n}", "public final class Properties {\n\n private Properties() {\n throw new IllegalAccessError(\"Utility class\");\n }\n\n public static final String COUNT = \"count\";\n public static final String EMAIL = \"email\";\n public static final String FOLLOWERS_YOU_KNOW = \"followers_you_know\";\n public static final String FOLLOWERS_YOU_KNOW_COUNT = \"followers_you_know_count\";\n public static final String HASH = \"hash\";\n public static final String I_FOLLOW = \"i_follow\";\n public static final String FOLLOWS_ME = \"follows_me\";\n public static final String LIKES = \"likes\";\n public static final String LIKED = \"liked\";\n public static final String LIKED_TIME = \"liked_time\";\n public static final String NAME = \"name\";\n public static final String PASSWORD = \"password\";\n public static final String USERNAME = \"username\";\n public static final String REPOSTS = \"reposts\";\n public static final String REPOSTED = \"reposted\";\n public static final String REPOSTED_TIME = \"reposted_time\";\n public static final String REPOSTER_NAME = \"reposter_name\";\n public static final String REPOSTER_USERNAME = \"reposter_username\";\n public static final String STATUS = \"status\";\n public static final String TIME = \"time\";\n\n}", "public static Long getLatestTime(@QueryParam(\"since\") Long since) {\n LocalDateTime dateTime;\n if (since == null) {\n dateTime = LocalDateTime.now(utc);\n } else {\n dateTime = LocalDateTime.ofEpochSecond(since, 0, ZoneOffset.UTC);\n }\n return dateTime.toEpochSecond(ZoneOffset.UTC);\n}", "public static final ZoneId utc = TimeZone.getTimeZone(\"UTC\").toZoneId();", "public static Node getAuthor(Node post, Long time) {\n LocalDateTime postedDateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);\n RelationshipType original = RelationshipType.withName(\"POSTED_ON_\" +\n postedDateTime.format(dateFormatter));\n return post.getSingleRelationship(original, Direction.INCOMING).getStartNode();\n}", "public static boolean userRepostedPost(Node user, Node post) {\n boolean alreadyReposted = false;\n\n if (post.getDegree(Direction.INCOMING) < 1000) {\n for (Relationship r1 : post.getRelationships(Direction.INCOMING)) {\n if (r1.getStartNode().equals(user) && r1.getType().name().startsWith(\"REPOSTED_ON_\")) {\n alreadyReposted = true;\n break;\n }\n }\n }\n\n LocalDateTime now = LocalDateTime.now(utc);\n LocalDateTime dateTime = LocalDateTime.ofEpochSecond((Long)post.getProperty(TIME), 0, ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS);\n\n while (dateTime.isBefore(now) && !alreadyReposted) {\n RelationshipType repostedOn = RelationshipType.withName(\"REPOSTED_ON_\" +\n dateTime.format(dateFormatter));\n\n if (user.getDegree(repostedOn, Direction.OUTGOING)\n < post.getDegree(repostedOn, Direction.INCOMING)) {\n for (Relationship r1 : user.getRelationships(Direction.OUTGOING, repostedOn)) {\n if (r1.getEndNode().equals(post)) {\n alreadyReposted = true;\n break;\n }\n }\n } else {\n for (Relationship r1 : post.getRelationships(Direction.INCOMING, repostedOn)) {\n if (r1.getStartNode().equals(user)) {\n alreadyReposted = true;\n break;\n }\n }\n }\n dateTime = dateTime.plusDays(1);\n }\n return alreadyReposted;\n}", "public static Node getPost(Node author, Long time) {\n LocalDateTime postedDateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);\n RelationshipType original = RelationshipType.withName(\"POSTED_ON_\" +\n postedDateTime.format(dateFormatter));\n Node post = null;\n for(Relationship r1 : author.getRelationships(Direction.OUTGOING, original)) {\n Node potential = r1.getEndNode();\n if (time.equals(potential.getProperty(TIME))) {\n post = potential;\n break;\n }\n }\n if(post == null) { throw PostExceptions.postNotFound(); };\n\n return post;\n}" ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.maxdemarzi.RelationshipTypes; import com.maxdemarzi.users.Users; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.graphdb.*; import javax.ws.rs.Path; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import static com.maxdemarzi.Properties.*; import static com.maxdemarzi.Time.getLatestTime; import static com.maxdemarzi.Time.utc; import static com.maxdemarzi.posts.Posts.getAuthor; import static com.maxdemarzi.posts.Posts.userRepostedPost; import static com.maxdemarzi.users.Users.getPost; import static java.util.Collections.reverseOrder;
package com.maxdemarzi.likes; @Path("/users/{username}/likes") public class Likes { private final GraphDatabaseService db; private static final ObjectMapper objectMapper = new ObjectMapper(); public Likes(@Context DatabaseManagementService dbms ) { this.db = dbms.database( "neo4j" );; } @GET public Response getLikes(@PathParam("username") final String username, @QueryParam("limit") @DefaultValue("25") final Integer limit, @QueryParam("since") final Long since, @QueryParam("username2") final String username2) throws IOException { ArrayList<Map<String, Object>> results = new ArrayList<>(); Long latest = getLatestTime(since); try (Transaction tx = db.beginTx()) {
Node user = Users.findUser(username, tx);
1
jeffprestes/brasilino
android/Brasilino/app/src/main/java/com/paypal/developer/brasilino/fragment/MainFragment.java
[ "public class Home extends ActionBarActivity implements View.OnTouchListener{\n\n private ImageView imgEsquerda;\n private ImageView imgDireita;\n private ImageView imgCima;\n private ImageView imgBaixo;\n\n private String ip;\n\n private BufferedWriter escritorLinhas = null;\n private OutputStreamWriter escritorCaracteres = null;\n private OutputStream escritorSocket = null;\n private Socket s = null;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_home);\n\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);\n ip = sp.getString(\"ip\", \"\");\n\n if (ip.endsWith(\"tht\")){\n ip = ip.substring(0, ip.length() - 3);\n }\n\n Toast.makeText(this, ip, Toast.LENGTH_LONG).show();\n\n getSupportActionBar().hide();\n\n boolean isFive = getIntent().getBooleanExtra(\"isFive\", false);\n Timer timer = new Timer();\n TimerTask tTask = new TimerTask() {\n @Override\n public void run() {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(Home.this, \"Tempo Esgotado!\", Toast.LENGTH_LONG).show();\n }\n });\n\n finish();\n }\n };\n timer.schedule(tTask, isFive?1000*60*5:1000*60*10);\n\n imgEsquerda = (ImageView) findViewById(R.id.imgEsquerda);\n imgEsquerda.setOnTouchListener(this);\n\n imgDireita = (ImageView) findViewById(R.id.imgDireita);\n imgDireita.setOnTouchListener(this);\n\n imgCima = (ImageView) findViewById(R.id.imgCima);\n imgCima.setOnTouchListener(this);\n\n imgBaixo = (ImageView) findViewById(R.id.imgBaixo);\n imgBaixo.setOnTouchListener(this);\n\n imgEsquerda.setEnabled(true);\n imgBaixo.setEnabled(true);\n imgCima.setEnabled(true);\n imgDireita.setEnabled(true);\n\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings webSettings = web.getSettings();\n webSettings.setJavaScriptEnabled(true);\n web.loadUrl(\"http://\"+ip+\":8181/camera.php\");\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n }\n\n\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (event.getAction() == MotionEvent.ACTION_DOWN){\n if (v == imgEsquerda) {\n new Assincrono().execute(\"EA;\");\n } else if (v == imgDireita) {\n new Assincrono().execute(\"DA;\");\n } else if (v == imgCima) {\n new Assincrono().execute(\"FA;\");\n } else if (v == imgBaixo) {\n new Assincrono().execute(\"TA;\");\n }\n } else if (event.getAction() == MotionEvent.ACTION_UP){\n if (v == imgEsquerda) {\n new Assincrono().execute(\"ED;\");\n } else if (v == imgDireita) {\n new Assincrono().execute(\"DD;\");\n } else if (v == imgCima) {\n new Assincrono().execute(\"FD;\");\n } else if (v == imgBaixo) {\n new Assincrono().execute(\"PP;\");\n }\n }\n return true;\n }\n\n class Assincrono extends AsyncTask<String, Void, String> {\n\n @Override\n protected String doInBackground(String... params) {\n\n Log.d(\"COMANDO_PARA_CARRINHO\", params[0]);\n\n try {\n s = new Socket(ip, 8282);\n\n escritorSocket = s.getOutputStream();\n escritorCaracteres = new OutputStreamWriter(escritorSocket);\n escritorLinhas = new BufferedWriter(escritorCaracteres);\n\n escritorLinhas.write(params[0]);\n\n escritorLinhas.flush();\n escritorLinhas.close();\n escritorCaracteres.flush();\n escritorCaracteres.close();\n escritorSocket.flush();\n escritorSocket.close();\n s.close();\n\n s=null;\n escritorLinhas = null;\n escritorCaracteres = null;\n escritorSocket = null;\n\n return \"foi\";\n\n } catch (UnknownHostException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n return \"UnknownHostException: \" + e;\n\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n return \"IOException: \"+e;\n }\n }\n\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n }\n}", "public class PermissionActivity extends ActionBarActivity {\n\n private WebView webContent;\n private ProgressBar progress;\n private Bundle receivedExtras;\n private Token token;\n\n @Override\n protected void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(outState);\n if (receivedExtras != null)\n outState.putAll(receivedExtras);\n }\n\n @SuppressLint(\"SetJavaScriptEnabled\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_permission);\n\n NotificationManagerCompat.from(getApplicationContext()).cancel(Util.NOTIFICATION_ID);\n\n if (savedInstanceState != null)\n receivedExtras = savedInstanceState;\n\n final CandieSQLiteDataSource dataSource = CarrinhoApplication.getDatasource();\n\n webContent = ((WebView) findViewById(R.id.webContent));\n webContent.setVisibility(View.INVISIBLE);\n CandiesWebViewClient webViewClient = new CandiesWebViewClient(this);\n webViewClient.setOnProcessStepListener(new CandiesWebViewClient.OnProcessStepListener() {\n @Override\n public void onProcessStarted() {\n progress.setVisibility(View.GONE);\n webContent.setVisibility(View.VISIBLE);\n }\n\n @Override\n public void onServerLoading() {\n progress.setVisibility(View.VISIBLE);\n webContent.setVisibility(View.INVISIBLE);\n }\n\n @Override\n public void onProcessFinished() {\n dataSource.saveToken(token);\n /*Intent paymentIntent = new Intent(getApplicationContext(), PaymentService.class);\n if (receivedExtras != null)\n paymentIntent.putExtras(receivedExtras);\n getApplicationContext().startService(paymentIntent);\n finish();*/\n WebServerHelper.requestUser(\n token,\n new Response.Listener<User>() {\n @Override\n public void onResponse(User response) {\n Toast.makeText(PermissionActivity.this, \"Bem vindo \" + response.getFirstName() + \" \" + response.getLastName(), Toast.LENGTH_LONG).show();\n SharedPreferences.Editor editor = CarrinhoApplication.get().getSharedPreferences().edit();\n editor.putString(\"Nome\", response.getFirstName() + \" \" + response.getLastName());\n editor.commit();\n finish();\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n }\n });;\n }\n });\n webContent.setWebViewClient(webViewClient);\n\n //We are enabling Javascript and Cookies for a better experience on the PayPal web site\n webContent.getSettings().setJavaScriptEnabled(true);\n webContent.getSettings().setAppCacheEnabled(true);\n\n progress = ((ProgressBar) findViewById(R.id.progress));\n progress.setIndeterminate(true);\n progress.setVisibility(View.VISIBLE);\n\n if (dataSource.getToken() == null) {\n WebServerHelper.requestNewToken(\n new Response.Listener<Token>() {\n @Override\n public void onResponse(Token response) {\n showWebContentForToken(response);\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n TextView errorMessage = ((TextView) findViewById(R.id.errorMessage));\n errorMessage.setVisibility(View.VISIBLE);\n progress.setVisibility(View.GONE);\n }\n });\n } else\n showWebContentForToken(dataSource.getToken());\n }\n\n private void showWebContentForToken(Token token) {\n this.token = token;\n webContent.loadUrl(token.getUrl().toString());\n\n /* WebServerHelper.requestUser(\n token,\n new Response.Listener<User>() {\n @Override\n public void onResponse(User response) {\n Log.e(CarrinhoApplication.class.getSimpleName(), \"Bem vindo \" + response.getFirstName() + \" \" +\n response.getLastName());\n Toast.makeText(PermissionActivity.this, \"Bem vindo \" + response.getFirstName() + \" \" +\n response.getLastName(), Toast.LENGTH_LONG).show();\n\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n }\n });;*/\n }\n}", "public class CarrinhoApplication extends Application {\n private static final String UNBIND_FLAG = \"UNBIND_FLAG\";\n\n private CandieSQLiteDataSource dataSource;\n private static CarrinhoApplication app;\n\n private RequestQueue queue;\n\n @Override\n public void onCreate() {\n super.onCreate();\n app = this;\n dataSource = new CandieSQLiteDataSource(app);\n }\n\n public static CandieSQLiteDataSource getDatasource() {\n if(app == null)\n return null;\n else\n return app.dataSource;\n }\n\n public static CarrinhoApplication get() {\n return app;\n }\n\n /**\n * Add a simple Volley {@link com.android.volley.Request} to the application request queue\n * @param request A valid Volley {@link com.android.volley.Request}\n */\n public void addRequestToQueue(Request<?> request) {\n addRequestToQueue(request, CarrinhoApplication.class.getSimpleName());\n }\n\n /**\n * <p>Add a Volley {@link com.android.volley.Request} to the application request queue.</p>\n * <p>But, first, associate a {@link java.lang.String} tag to the request. So, it can be\n * stopped latter</p>\n * @param request A valid Volley {@link com.android.volley.Request}\n * @param tag {@link java.lang.String} that will be associated to the specific request\n */\n public void addRequestToQueue(Request<?> request, String tag) {\n request.setTag(tag);\n request.setRetryPolicy(new DefaultRetryPolicy(\n 10000,\n DefaultRetryPolicy.DEFAULT_MAX_RETRIES,\n DefaultRetryPolicy.DEFAULT_BACKOFF_MULT\n ));\n getQueue().add(request);\n }\n\n /**\n * Get the application {@link com.android.volley.RequestQueue}. It holds all the application\n * internet request\n * @return The application {@link com.android.volley.RequestQueue}\n */\n public RequestQueue getQueue() {\n if(queue == null) {\n queue = Volley.newRequestQueue(app, new OkHttpStack());\n }\n return queue;\n }\n\n public SharedPreferences getSharedPreferences() {\n return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n }\n\n public void setFromUnbind(boolean fromUnbind)\n {\n if(fromUnbind)\n getSharedPreferences().edit().putBoolean(UNBIND_FLAG, true).apply();\n else\n getSharedPreferences().edit().remove(UNBIND_FLAG).apply();\n }\n\n}", "public class Token\n{\n @SerializedName(\"token\")\n private String token;\n @SerializedName(\"url\")\n private String url;\n\n public Token() {}\n\n public Token(Cursor cursor) {\n this.url = null;\n this.token = cursor.getString(cursor.getColumnIndex(DomainNamespace.TOKEN));\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public Uri getUrl() {\n if(url == null) return null;\n return Uri.parse(url);\n }\n\n public void setUrl(Uri url) {\n this.url = (url == null?null:url.toString());\n }\n\n public ContentValues toContentValues() {\n ContentValues values = new ContentValues();\n values.put(DomainNamespace.TOKEN, token);\n return values;\n }\n\n public static String[] getColumns() {\n return new String[]{DomainNamespace.ID, DomainNamespace.TOKEN};\n }\n\n public class DomainNamespace {\n public static final String TABLE_NAME = \"token\";\n public static final String ID = \"_id\";\n public static final String TOKEN = \"token\";\n }\n}", "public class User {\n\n @SerializedName(\"firstname\")\n private String firstName;\n @SerializedName(\"lastname\")\n private String lastName;\n @SerializedName(\"email\")\n private String email;\n @SerializedName(\"endereco\")\n private String endereco;\n @SerializedName(\"project\")\n private String project;\n @SerializedName(\"pais\")\n private String pais;\n @SerializedName(\"cidade\")\n private String cidade;\n @SerializedName(\"estado\")\n private String estado;\n\n public User() {}\n\n public String getFirstName(){\n return firstName;\n }\n\n public String getLastName(){\n return lastName;\n }\n\n}", "public class UserRoot {\n\n private List<User> userRoot;\n\n public User getUserRoot(int indice){\n return userRoot.get(indice);\n }\n\n}", "public class PaymentService extends Service {\n\n private LocalBinder mBinder = new LocalBinder();\n private PaymentStepsListener paymentStepsListener;\n private Token token = null;\n\n\n public interface PaymentStepsListener {\n public void onPaymentStarted(Token token);\n public void onPaymentFinished(Token token, boolean successful, String message);\n }\n\n\n public PaymentService() {\n token = CarrinhoApplication.getDatasource().getToken();\n }\n\n private String getStringToken() {\n return token.getToken();\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n\n final Token token = CarrinhoApplication.getDatasource().getToken();\n\n if(token != null) {\n NotificationManagerCompat.from(getApplicationContext()).cancel(Util.NOTIFICATION_ID);\n WebServerHelper.performNewPayment(\n this.getStringToken(),\n intent.getBooleanExtra(\"five\", false)?Util.PRODUCT_DEFAULT_VALUE_FIVE:Util.PRODUCT_DEFAULT_VALUE_TEN,\n this.getResponsePaymentListener(),\n this.getErrorPaymentListener()\n );\n\n if(paymentStepsListener != null) {\n paymentStepsListener.onPaymentStarted(token);\n }\n\n return START_STICKY;\n } else {\n return START_NOT_STICKY;\n }\n }\n\n\n @Override\n public IBinder onBind(Intent intent) {\n return mBinder;\n }\n\n public void setPaymentStepsListener(PaymentStepsListener paymentStepsListener) {\n this.paymentStepsListener = paymentStepsListener;\n }\n\n\n public class LocalBinder extends Binder {\n public PaymentService getService() {\n return PaymentService.this;\n }\n }\n\n\n /**\n * Return specific Response Payment listener to payment webservice call\n */\n public Response.Listener<NewTransaction> getResponsePaymentListener() {\n\n return new Response.Listener<NewTransaction>() {\n\n public void onResponse (NewTransaction response) {\n if (response.isSuccessfull()) {\n\n finishService(\"Pegar dados do usuário...\", true);\n /*WebServerHelper.sendMachineOrder(\n token,\n new Response.Listener<NewTransaction>() {\n\n @Override\n public void onResponse(NewTransaction response) {\n if(response.isSuccessfull()) {\n Util.sendMessage(\n \"/candies/payment\",\n \"success\"\n );\n finishService(\"Pegar dados do usuário...\", true);\n } else {\n finishService(\"Erro no comando à maquina.\", false);\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(PaymentService.class.getSimpleName(), \"Erro no envio à máquina\", error);\n finishService(Log.getStackTraceString(error), false);\n }\n }\n );*/\n\n } else {\n finishService(response.getMessage(), false);\n }\n }\n\n };\n }\n\n private void finishService(String message, boolean successful) {\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n\n Util.sendMessage(\n \"/candies/payment\",\n (successful?\"success\":\"fail\")\n );\n\n if (paymentStepsListener != null)\n paymentStepsListener.onPaymentFinished(token, successful, message);\n stopSelf();\n }\n\n /**\n * Specific error listener for payment webservice call\n * @return Error Listener for payment webservice call\n */\n public Response.ErrorListener getErrorPaymentListener() {\n return new Response.ErrorListener() {\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n Toast.makeText(getApplicationContext(), \"Erro no pagamento: \" + error.getLocalizedMessage() + \" | Tempo final: \" + (Calendar.getInstance().getTimeInMillis()), Toast.LENGTH_SHORT).show();\n if (paymentStepsListener != null)\n paymentStepsListener.onPaymentFinished(token, false, error.getMessage());\n stopSelf();\n }\n };\n }\n}", "public class Util\n{\n public static final int NOTIFICATION_ID = 123456;\n public static final double PRODUCT_DEFAULT_VALUE_FIVE = 1.0f;\n public static final double PRODUCT_DEFAULT_VALUE_TEN = 2.0f;\n\n public static void dispatchNotification(Context context, String uuid, String major, String minor, int productImage)\n {\n Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), productImage);\n dispatchNotification(context, uuid, major, minor, bitmap);\n bitmap.recycle();\n }\n\n public static void dispatchNotification(Context context, String uuid, String major, String minor, Bitmap productImage)\n {\n Bundle infoBundle = new Bundle();\n infoBundle.putString(IntentParameters.UUID,uuid);\n infoBundle.putString(IntentParameters.MAJOR,major);\n infoBundle.putString(IntentParameters.MINOR,minor);\n\n Intent purchaseIntent = new Intent(context, PaymentOrderReceiver.class);\n purchaseIntent.putExtras(infoBundle);\n\n PendingIntent purchasePendingIntent = PendingIntent.getBroadcast(\n context,\n RequestCode.PURCHASE,\n purchaseIntent,\n PendingIntent.FLAG_CANCEL_CURRENT);\n\n NotificationCompat.Builder builder = new NotificationCompat.Builder(context)\n .setSmallIcon(R.drawable.ic_launcher)\n .setLocalOnly(true)\n .setAutoCancel(true)\n .setCategory(NotificationCompat.CATEGORY_PROMO)\n .setPriority(NotificationCompat.PRIORITY_HIGH)\n .setContentTitle(context.getString(R.string.notification_generic_title))\n .setContentText(context.getString(R.string.notification_generic_message))\n .addAction(R.drawable.ic_logo_paypal, context.getString(R.string.action_purchase), purchasePendingIntent);\n\n Notification notification = builder.build();\n notification.defaults |= Notification.DEFAULT_ALL;\n\n NotificationManagerCompat manager = NotificationManagerCompat.from(context);\n manager.notify(NOTIFICATION_ID,notification);\n }\n\n public static boolean isServiceRunning(Class<?> serviceClass, Context context) {\n ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n\n public static void sendMessage(String path, String message) {\n Log.e(\"THTPAYPALCARRINHO\", path + \" - \" + message);\n }\n\n public static void scheduleReceiver(Context context, Class receiver) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(System.currentTimeMillis());\n calendar.set(Calendar.MILLISECOND, 500);\n\n AlarmManager alarmManager = (AlarmManager)context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);\n Intent receiverIntent = new Intent(context.getApplicationContext(), receiver);\n PendingIntent receiverPendent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, receiverIntent, 0);\n alarmManager.set(\n AlarmManager.RTC_WAKEUP,\n calendar.getTimeInMillis(),\n receiverPendent\n );\n }\n\n //TODO: Refazer a logica de desabilitar a cobrança do paypal para Ricardo\n //Criar outra variavel em SharedPreferences\n public static String retiraTHT(String ipTemp) {\n\n String trechoFinal = ipTemp.substring(ipTemp.length()-3,ipTemp.length());\n\n if (\"tht\".equalsIgnoreCase(trechoFinal)) {\n ipTemp = ipTemp.substring(0,ipTemp.length()-3);\n }\n\n return ipTemp;\n }\n}", "public class WebServerHelper {\n public static final String SERVER_AUTHORITY = \"novatrix.com.br\";\n public static final String SERVER_URL = \"https://www.novatrix.com.br/gateway\";\n public static final String PROJECT_NAME = \"carrocr\";\n\n public static final String GET_TOKEN_PATH = \"gettoken.php\";\n public static final String GET_USER_PATH = \"getuser.php\";\n public static final String TRANSACTION_PATH = \"transaction.php\";\n public static final String OPERATION_SUCCESSFUL_PATH = \"ok.php\";\n public static final String ORDER_MACHINE_PATH = \"broker.php\";\n public static final boolean LIVE_ENVIRONMET = false;\n\n public static String getTokenPost() {\n return String.format(\"{\\\"projeto\\\":\\\"%s\\\"}\", PROJECT_NAME);\n }\n\n public static String getUserPost(String token) {\n return String.format(\"{\\\"token\\\":\\\"%s\\\"}\", token);\n }\n\n public static String getTransationPost(String token, double value) {\n NumberFormat numberFormat = NumberFormat.getInstance(new Locale(\"pt\",\"BR\"));\n numberFormat.setMinimumFractionDigits(2);\n numberFormat.setMaximumFractionDigits(2);\n return String.format(\"{\\\"token\\\": \\\"%s\\\", \\\"valor\\\": \\\"%s\\\"}\",token,numberFormat.format(value));\n }\n\n public static String getMachineOrderPost(String token) {\n return String.format(\"{\\\"token\\\": \\\"%s\\\"}\", token);\n }\n\n public static void performNewPayment(String token, double value, Response.Listener<NewTransaction> responseListener, Response.ErrorListener errorListener) {\n CarrinhoApplication.get().addRequestToQueue(new GsonRequest<>(\n WebServerHelper.TRANSACTION_PATH,\n WebServerHelper.getTransationPost(token,value),\n responseListener,\n errorListener,\n NewTransaction.class\n ));\n }\n\n /*public static void sendMachineOrder(Token token, Response.Listener<NewTransaction> successResponse, Response.ErrorListener errorResponse) {\n CarrinhoApplication.get().addRequestToQueue(new GsonRequest<>(\n WebServerHelper.ORDER_MACHINE_PATH,\n WebServerHelper.getMachineOrderPost(token.getToken()),\n successResponse,\n errorResponse,\n NewTransaction.class\n ));\n }*/\n\n public static void requestNewToken(Response.Listener<Token> successResponse, Response.ErrorListener errorResponse) {\n CarrinhoApplication.get().addRequestToQueue(new GsonRequest<>(\n WebServerHelper.GET_TOKEN_PATH,\n WebServerHelper.getTokenPost(),\n successResponse,\n errorResponse,\n Token.class));\n }\n\n public static void requestUser(Token token, Response.Listener<User> successResponse, Response.ErrorListener errorResponse) {\n CarrinhoApplication.get().addRequestToQueue(new GsonRequest<>(\n WebServerHelper.GET_USER_PATH,\n WebServerHelper.getUserPost(token.getToken()),\n successResponse,\n errorResponse,\n User.class));\n }\n}" ]
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.android.volley.Response; import com.android.volley.VolleyError; import com.paypal.developer.brasilino.Home; import com.paypal.developer.brasilino.PermissionActivity; import com.paypal.developer.brasilino.R; import com.paypal.developer.brasilino.application.CarrinhoApplication; import com.paypal.developer.brasilino.domain.Token; import com.paypal.developer.brasilino.domain.User; import com.paypal.developer.brasilino.domain.UserRoot; import com.paypal.developer.brasilino.service.PaymentService; import com.paypal.developer.brasilino.util.Util; import com.paypal.developer.brasilino.util.WebServerHelper;
package com.paypal.developer.brasilino.fragment; public class MainFragment extends Fragment { private TextView mTvInformation; private Button mBtPurchase; private PaymentService paymentService; private RadioGroup rdbTime; private RadioButton rdbFive; private boolean lastTimeIsFive; public MainFragment() {} private SharedPreferences sp; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); mTvInformation = ((TextView) rootView.findViewById(R.id.tvInformation)); rdbTime = (RadioGroup) rootView.findViewById(R.id.rdb); rdbFive = (RadioButton) rootView.findViewById(R.id.rdbCinco); sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mBtPurchase = ((Button) rootView.findViewById(R.id.btPurchase)); mBtPurchase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle infoBundle = null; //TODO: Refazer a logica de desabilitar a cobrança do paypal para Ricardo //Criar outra variavel em SharedPreferences if (sp.getString("ip", "").endsWith("tht")){ goHome(); } else if(CarrinhoApplication.getDatasource().getToken() == null) {
Intent permissionIntent = new Intent(getActivity(), PermissionActivity.class);
1
GoogleCloudPlatform/bigquery-data-lineage
src/test/java/com/google/cloud/solutions/datalineage/PolicyPropagationPipelineTest.java
[ "public static <T extends Message> ImmutableList<T>\nparseAsList(Collection<String> jsons, Class<T> protoClass) {\n return jsons\n .stream()\n .map(json -> ProtoJsonConverter.parseJson(json, protoClass))\n .filter(Objects::nonNull)\n .collect(toImmutableList());\n}", "@SuppressWarnings(\"unchecked\")\npublic static <T extends Message> T parseJson(String json, Class<T> protoClass) {\n try {\n Message.Builder builder =\n (Message.Builder)\n protoClass.getMethod(\"newBuilder\")\n .invoke(null);\n\n JsonFormat.parser().merge(json, builder);\n return (T) builder.build();\n } catch (Exception protoException) {\n logger.atSevere().withCause(protoException).atMostEvery(1, TimeUnit.MINUTES)\n .log(\"error converting json:\\n%s\", json);\n return null;\n }\n}", "@AutoValue\npublic abstract class BigQueryTableEntity implements DataEntityConvertible, Serializable {\n\n public abstract String getProjectId();\n\n public abstract String getDataset();\n\n public abstract String getTable();\n\n /**\n * Returns {@code true} if the table is a temporary table.\n * <p> It uses rule dataset name starts with '_' or table name starts with '_' or 'anon'.\n */\n public final boolean isTempTable() {\n return getDataset().startsWith(\"_\")\n || getTable().startsWith(\"_\")\n || getTable().startsWith(\"anon\");\n }\n\n public static Builder builder() {\n return new AutoValue_BigQueryTableEntity.Builder();\n }\n\n public static BigQueryTableEntity create(String projectId, String dataset, String table) {\n return builder()\n .setProjectId(projectId)\n .setDataset(dataset)\n .setTable(table)\n .build();\n }\n\n @Override\n public DataEntity dataEntity() {\n return DataEntity.newBuilder()\n .setKind(DataEntityTypes.BIGQUERY_TABLE)\n .setLinkedResource(\n String.format(\"//bigquery.googleapis.com/projects/%s/datasets/%s/tables/%s\",\n getProjectId(),\n getDataset(),\n getTable()))\n .setSqlResource(\n String.format(\"bigquery.table.%s.%s.%s\", getProjectId(), getDataset(), getTable()))\n .build();\n }\n\n public String getLegacySqlName() {\n return String.format(\"%s:%s.%s\", getProjectId(), getDataset(), getTable());\n }\n\n public String getStandSqlName() {\n return String.format(\"%s.%s.%s\", getProjectId(), getDataset(), getTable());\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setProjectId(String projectId);\n\n public abstract Builder setDataset(String dataset);\n\n public abstract Builder setTable(String table);\n\n public abstract BigQueryTableEntity build();\n }\n}", "@AutoValue\n@DefaultSchema(AutoValueSchema.class)\npublic abstract class TagsForCatalog {\n\n public abstract String getEntryId();\n\n public abstract ImmutableList<String> getTagsJson();\n\n public static TagsForCatalog empty() {\n return create(\"\", ImmutableList.of());\n }\n\n public final boolean isEmpty() {\n return this.equals(empty());\n }\n\n public final ImmutableList<Tag> parsedTags() {\n return ProtoJsonConverter.parseAsList(getTagsJson(), Tag.class);\n }\n\n @SchemaCreate\n public static TagsForCatalog create(String entryId, Collection<String> tagsJson) {\n return builder()\n .setEntryId(entryId)\n .setTagsJson(ImmutableList.copyOf(tagsJson))\n .build();\n }\n\n public static Builder builder() {\n return new AutoValue_TagsForCatalog.Builder();\n }\n\n public static Builder forTags(Collection<Tag> tags) {\n return builder()\n .setTagsJson(\n tags.stream()\n .map(ProtoJsonConverter::asJsonString)\n .collect(toImmutableList()));\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setEntryId(String newEntryId);\n\n public Builder setEntry(Entry entry) {\n return setEntryId(entry.getName());\n }\n\n public abstract Builder setTagsJson(ImmutableList<String> newTagsJson);\n\n public abstract TagsForCatalog build();\n }\n}", "public final class FakeBigQueryServiceFactory implements BigQueryServiceFactory {\n\n private final String[] tableSchemas;\n\n public FakeBigQueryServiceFactory(String[] tableSchemas) {\n this.tableSchemas = tableSchemas;\n }\n\n public static FakeBigQueryServiceFactory forTableSchemas(String... tableSchemas) {\n return new FakeBigQueryServiceFactory(tableSchemas);\n }\n\n public static BigQueryServiceFactory forStub(FakeBigquery fakeService) {\n return () -> fakeService;\n }\n\n @Override\n public Bigquery buildService() {\n return FakeBigquery.forTableSchemas(tableSchemas);\n }\n}", "public final class FakeDataCatalogStub extends DataCatalogStub implements Serializable {\n\n private boolean shutdown;\n private boolean terminated;\n\n private final ImmutableMap<String, Entry> predefinedEntries;\n private final ImmutableMultimap<String, Tag> predefinedTags;\n\n public FakeDataCatalogStub(\n ImmutableCollection<Entry> predefinedEntries,\n ImmutableMultimap<String, Tag> predefinedTags) {\n this.predefinedEntries = predefinedEntries.stream()\n .collect(toImmutableMap(Entry::getLinkedResource, identity()));\n\n this.predefinedTags = predefinedTags;\n }\n\n public static FakeDataCatalogStub buildWithTestData(\n List<String> entryResourcesNames,\n List<String> tagsResourceNames) {\n\n ImmutableList<Entry> entries =\n entryResourcesNames.stream()\n .map(TestResourceLoader::load)\n .map(json -> parseJson(json, Entry.class))\n .collect(toImmutableList());\n\n ImmutableListMultimap<String, Tag> entityTags =\n tagsResourceNames.stream()\n .map(TestResourceLoader::load)\n .map(tagsJson -> parseAsList(tagsJson, Tag.class))\n .flatMap(List::stream)\n .collect(toImmutableListMultimap(TagUtility::extractParent, identity()));\n\n return new FakeDataCatalogStub(entries, entityTags);\n }\n\n\n @Override\n public UnaryCallable<LookupEntryRequest, Entry> lookupEntryCallable() {\n checkState(!shutdown, \"Stub shutdown\");\n\n return new UnaryCallable<LookupEntryRequest, Entry>() {\n\n @Override\n public ApiFuture<Entry> futureCall(LookupEntryRequest lookupEntryRequest,\n ApiCallContext apiCallContext) {\n return new FakeDataCatalogLookupEntryResponse(\n predefinedEntries.get(lookupEntryRequest.getLinkedResource()),\n lookupEntryRequest);\n }\n };\n }\n\n @Override\n public UnaryCallable<ListTagsRequest, ListTagsPagedResponse> listTagsPagedCallable() {\n checkState(!shutdown, \"Stub shutdown\");\n\n return new UnaryCallable<ListTagsRequest, ListTagsPagedResponse>() {\n @Override\n public ApiFuture<ListTagsPagedResponse> futureCall(ListTagsRequest listTagsRequest,\n ApiCallContext apiCallContext) {\n return\n new FakeDataCatalogPagesListTagsResponse(\n listTagsRequest, apiCallContext, predefinedTags.get(listTagsRequest.getParent()));\n }\n };\n }\n\n @Override\n public void close() {\n // Do nothing because this is a Fake and doesn't implement an actual gRPC operation.\n }\n\n @Override\n public void shutdown() {\n shutdown = true;\n }\n\n @Override\n public boolean isShutdown() {\n return shutdown;\n }\n\n @Override\n public boolean isTerminated() {\n return terminated;\n }\n\n @Override\n public void shutdownNow() {\n shutdown();\n }\n\n @Override\n public boolean awaitTermination(long l, TimeUnit timeUnit) {\n terminated = true;\n return true;\n }\n\n\n}", "public final class TestResourceLoader {\n\n private static final String TEST_RESOURCE_FOLDER = \"test\";\n\n public static String load(String resourceFileName) {\n try {\n byte[] bytes = Files\n .readAllBytes(Paths.get(\"src\", TEST_RESOURCE_FOLDER, \"resources\", resourceFileName));\n return new String(bytes, StandardCharsets.UTF_8);\n } catch (IOException ioException) {\n return \"\";\n }\n }\n\n private TestResourceLoader() {\n }\n}", "@AutoValue\npublic abstract class CatalogTagsPropagationTransform\n extends PTransform<PCollection<CompositeLineage>, PCollection<TagsForCatalog>> {\n\n private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();\n\n public abstract ImmutableList<String> monitoredSourceTags();\n\n @Nullable\n public abstract DataCatalogStub catalogStub();\n\n\n @Override\n public PCollection<TagsForCatalog> expand(PCollection<CompositeLineage> input) {\n return input.apply(\"Identify Source Tags\", ParDo.of(\n new DoFn<CompositeLineage, TagsForCatalog>() {\n @ProcessElement\n public void convertToTags(\n @Element CompositeLineage lineage,\n OutputReceiver<TagsForCatalog> out) {\n try {\n TagsForCatalog tags = LineageTagPropagationConverterFactory.builder()\n .lineage(lineage)\n .monitoredSourceTags(monitoredSourceTags())\n .dataCatalogService(DataCatalogService.usingStub(catalogStub()))\n .build()\n .processor()\n .propagationTags();\n if (!tags.getTagsJson().isEmpty()) {\n out.output(tags);\n }\n } catch (Exception exception) {\n logger.atWarning().withCause(exception)\n .atMostEvery(1, TimeUnit.MINUTES)\n .log(\"error expanding source tags for lineage:\\n%s\", lineage);\n }\n }\n\n\n }\n ));\n }\n\n public static CatalogTagsPropagationTransform.Builder forMonitoredTags(\n Collection<String> newMonitoredSourceTags) {\n\n if (newMonitoredSourceTags != null) {\n return builder().monitoredSourceTags(ImmutableList.copyOf(newMonitoredSourceTags));\n }\n\n return builder();\n }\n\n public static Builder builder() {\n return new AutoValue_CatalogTagsPropagationTransform.Builder()\n .monitoredSourceTags(ImmutableList.of());\n }\n\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder monitoredSourceTags(ImmutableList<String> newMonitoredSourceTags);\n\n public abstract Builder catalogStub(@Nullable DataCatalogStub catalogStub);\n\n public abstract CatalogTagsPropagationTransform build();\n }\n}", "@AutoValue\npublic abstract class PolicyTagsPropagationTransform extends\n PTransform<PCollection<CompositeLineage>, PCollection<TargetPolicyTags>> {\n\n abstract List<String> monitoredPolicyTags();\n\n abstract BigQueryServiceFactory bigQueryServiceFactory();\n\n @Override\n public PCollection<TargetPolicyTags> expand(PCollection<CompositeLineage> input) {\n\n return\n input\n .apply(\"identify policy tags\", ParDo.of(\n new DoFn<CompositeLineage, TargetPolicyTags>() {\n @ProcessElement\n public void identifyPolicyTags(\n @Element CompositeLineage lineage,\n OutputReceiver<TargetPolicyTags> out) {\n BigQueryPolicyTagService\n .usingServiceFactory(bigQueryServiceFactory())\n .finderForLineage(lineage)\n .forPolicies(monitoredPolicyTags())\n .ifPresent(out::output);\n }\n }\n ));\n }\n\n public static Builder builder() {\n return new AutoValue_PolicyTagsPropagationTransform.Builder()\n .monitoredPolicyTags(ImmutableList.of());\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder monitoredPolicyTags(List<String> monitoredPolicyTags);\n\n public abstract Builder bigQueryServiceFactory(BigQueryServiceFactory bigQueryServiceFactory);\n\n public abstract PolicyTagsPropagationTransform build();\n }\n}" ]
import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseAsList; import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseJson; import com.google.cloud.datacatalog.v1beta1.Tag; import com.google.cloud.solutions.datalineage.model.BigQueryTableEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnPolicyTags; import com.google.cloud.solutions.datalineage.model.LineageMessages.CompositeLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.DataEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.DataEntity.DataEntityTypes; import com.google.cloud.solutions.datalineage.model.LineageMessages.JobInformation; import com.google.cloud.solutions.datalineage.model.LineageMessages.TableLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.TargetPolicyTags; import com.google.cloud.solutions.datalineage.model.TagsForCatalog; import com.google.cloud.solutions.datalineage.testing.FakeBigQueryServiceFactory; import com.google.cloud.solutions.datalineage.testing.FakeDataCatalogStub; import com.google.cloud.solutions.datalineage.testing.TestResourceLoader; import com.google.cloud.solutions.datalineage.transform.CatalogTagsPropagationTransform; import com.google.cloud.solutions.datalineage.transform.PolicyTagsPropagationTransform; import com.google.common.collect.ImmutableList; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.solutions.datalineage; @RunWith(JUnit4.class) public final class PolicyPropagationPipelineTest { @Rule public final transient TestPipeline testPipeline = TestPipeline.create(); @Test public void tagPropagation_noMonitoredTags_targetEntryIdWithEmptyTags() { FakeDataCatalogStub fakeStub = FakeDataCatalogStub.buildWithTestData( ImmutableList.of("datacatalog-objects/TableA_entry.json", "datacatalog-objects/simple_report_view_entry.json", "datacatalog-objects/OutputTable_entry.json"), ImmutableList.of( "datacatalog-objects/TableA_tags.json", "datacatalog-objects/simple_report_view_tags.json")); PCollection<TagsForCatalog> tags = testPipeline .apply(Create.of( parseJson(TestResourceLoader.load( "composite-lineages/complete_composite_lineage_tableA_simple_report_view_outputTable.json"), CompositeLineage.class))) .apply(
CatalogTagsPropagationTransform
7
Piasy/decaf-mind-compiler
decaf_PA3/src/decaf/typecheck/BuildSym.java
[ "public final class Driver {\n\n\tprivate static Driver driver;\n\n\tprivate Option option;\n\n\tprivate List<DecafError> errors;\n\n\tprivate Lexer lexer;\n\n\tprivate Parser parser;\n\n\tpublic static Driver getDriver() {\n\t\treturn driver;\n\t}\n\n\tpublic void issueError(DecafError error) {\n\t\terrors.add(error);\n\t}\n\n\tpublic void checkPoint() {\n\t\tif (errors.size() > 0) {\n\t\t\tCollections.sort(errors, new Comparator<DecafError>() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic int compare(DecafError o1, DecafError o2) {\n\t\t\t\t\treturn o1.getLocation().compareTo(o2.getLocation());\n\t\t\t\t}\n\n\t\t\t});\n\t\t\tfor (DecafError error : errors) {\n\t\t\t\toption.getErr().println(error);\n\t\t\t}\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate void init() {\n\t\tlexer = new Lexer(option.getInput());\n\t\tparser = new Parser();\n\t\tlexer.setParser(parser);\n\t\tparser.setLexer(lexer);\n\t\terrors = new ArrayList<DecafError>();\n\t}\n\n\tprivate void compile() {\n\n\t\tTree.TopLevel tree = parser.parseFile();\n\t\t\n\t\tcheckPoint();\n\t\tif (option.getLevel() == Option.Level.LEVEL0) {\n\t\t\tIndentPrintWriter pw = new IndentPrintWriter(option.getOutput(), 4);\n\t\t\ttree.printTo(pw);\n\t\t\tpw.close();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tdriver = new Driver();\n\t\tdriver.option = new Option(args);\n\t\tdriver.init();\n\t\tdriver.compile();\n\t}\n\n\tpublic Option getOption() {\n\t\treturn option;\n\t}\n}", "public abstract class Tree {\n\n /**\n * Toplevel nodes, of type TopLevel, representing entire source files.\n */\n public static final int TOPLEVEL = 1;\n\n /**\n * Import clauses, of type Import.\n */\n public static final int IMPORT = TOPLEVEL + 1;\n\n /**\n * Class definitions, of type ClassDef.\n */\n public static final int CLASSDEF = IMPORT + 1;\n\n /**\n * Method definitions, of type MethodDef.\n */\n public static final int METHODDEF = CLASSDEF + 1;\n\n /**\n * Variable definitions, of type VarDef.\n */\n public static final int VARDEF = METHODDEF + 1;\n\n /**\n * The no-op statement \";\", of type Skip\n */\n public static final int SKIP = VARDEF + 1;\n\n /**\n * Blocks, of type Block.\n */\n public static final int BLOCK = SKIP + 1;\n\n /**\n * Do-while loops, of type DoLoop.\n */\n public static final int DOLOOP = BLOCK + 1;\n\n /**\n * While-loops, of type WhileLoop.\n */\n public static final int WHILELOOP = DOLOOP + 1;\n\n /**\n * For-loops, of type ForLoop.\n */\n public static final int FORLOOP = WHILELOOP + 1;\n\n /**\n * Labelled statements, of type Labelled.\n */\n public static final int LABELLED = FORLOOP + 1;\n\n /**\n * Switch statements, of type Switch.\n */\n public static final int SWITCH = LABELLED + 1;\n\n /**\n * Case parts in switch statements, of type Case.\n */\n public static final int CASE = SWITCH + 1;\n\n /**\n * Synchronized statements, of type Synchonized.\n */\n public static final int SYNCHRONIZED = CASE + 1;\n\n /**\n * Try statements, of type Try.\n */\n public static final int TRY = SYNCHRONIZED + 1;\n\n /**\n * Catch clauses in try statements, of type Catch.\n */\n public static final int CATCH = TRY + 1;\n\n /**\n * Conditional expressions, of type Conditional.\n */\n public static final int CONDEXPR = CATCH + 1;\n\n /**\n * Conditional statements, of type If.\n */\n public static final int IF = CONDEXPR + 1;\n\n /**\n * Expression statements, of type Exec.\n */\n public static final int EXEC = IF + 1;\n\n /**\n * Break statements, of type Break.\n */\n public static final int BREAK = EXEC + 1;\n\n /**\n * Continue statements, of type Continue.\n */\n public static final int CONTINUE = BREAK + 1;\n\n /**\n * Return statements, of type Return.\n */\n public static final int RETURN = CONTINUE + 1;\n\n /**\n * Throw statements, of type Throw.\n */\n public static final int THROW = RETURN + 1;\n\n /**\n * Assert statements, of type Assert.\n */\n public static final int ASSERT = THROW + 1;\n\n /**\n * Method invocation expressions, of type Apply.\n */\n public static final int APPLY = ASSERT + 1;\n\n /**\n * Class instance creation expressions, of type NewClass.\n */\n public static final int NEWCLASS = APPLY + 1;\n\n /**\n * Array creation expressions, of type NewArray.\n */\n public static final int NEWARRAY = NEWCLASS + 1;\n\n /**\n * Parenthesized subexpressions, of type Parens.\n */\n public static final int PARENS = NEWARRAY + 1;\n\n /**\n * Assignment expressions, of type Assign.\n */\n public static final int ASSIGN = PARENS + 1;\n\n /**\n * Type cast expressions, of type TypeCast.\n */\n public static final int TYPECAST = ASSIGN + 1;\n\n /**\n * Type test expressions, of type TypeTest.\n */\n public static final int TYPETEST = TYPECAST + 1;\n\n /**\n * Indexed array expressions, of type Indexed.\n */\n public static final int INDEXED = TYPETEST + 1;\n\n /**\n * Selections, of type Select.\n */\n public static final int SELECT = INDEXED + 1;\n\n /**\n * Simple identifiers, of type Ident.\n */\n public static final int IDENT = SELECT + 1;\n\n /**\n * Literals, of type Literal.\n */\n public static final int LITERAL = IDENT + 1;\n\n /**\n * Basic type identifiers, of type TypeIdent.\n */\n public static final int TYPEIDENT = LITERAL + 1;\n\n /**\n * Class types, of type TypeClass.\n */ \n public static final int TYPECLASS = TYPEIDENT + 1;\n\n /**\n * Array types, of type TypeArray.\n */\n public static final int TYPEARRAY = TYPECLASS + 1;\n\n /**\n * Parameterized types, of type TypeApply.\n */\n public static final int TYPEAPPLY = TYPEARRAY + 1;\n\n /**\n * Formal type parameters, of type TypeParameter.\n */\n public static final int TYPEPARAMETER = TYPEAPPLY + 1;\n\n /**\n * Error trees, of type Erroneous.\n */\n public static final int ERRONEOUS = TYPEPARAMETER + 1;\n\n /**\n * Unary operators, of type Unary.\n */\n public static final int POS = ERRONEOUS + 1;\n public static final int NEG = POS + 1;\n public static final int NOT = NEG + 1;\n public static final int COMPL = NOT + 1;\n public static final int PREINC = COMPL + 1;\n public static final int PREDEC = PREINC + 1;\n public static final int POSTINC = PREDEC + 1;\n public static final int POSTDEC = POSTINC + 1;\n\n /**\n * unary operator for null reference checks, only used internally.\n */\n public static final int NULLCHK = POSTDEC + 1;\n\n /**\n * Binary operators, of type Binary.\n */\n public static final int OR = NULLCHK + 1;\n public static final int AND = OR + 1;\n public static final int BITOR = AND + 1;\n public static final int BITXOR = BITOR + 1;\n public static final int BITAND = BITXOR + 1;\n public static final int EQ = BITAND + 1;\n public static final int NE = EQ + 1;\n public static final int LT = NE + 1;\n public static final int GT = LT + 1;\n public static final int LE = GT + 1;\n public static final int GE = LE + 1;\n public static final int SL = GE + 1;\n public static final int SR = SL + 1;\n public static final int USR = SR + 1;\n public static final int PLUS = USR + 1;\n public static final int MINUS = PLUS + 1;\n public static final int MUL = MINUS + 1;\n public static final int DIV = MUL + 1;\n public static final int MOD = DIV + 1;\n\n public static final int NULL = MOD + 1;\n public static final int CALLEXPR = NULL + 1;\n public static final int THISEXPR = CALLEXPR + 1;\n public static final int READINTEXPR = THISEXPR + 1;\n public static final int READLINEEXPR = READINTEXPR + 1;\n public static final int PRINT = READLINEEXPR + 1;\n \n /**\n * Tags for Literal and TypeLiteral\n */\n public static final int VOID = 0; \n public static final int INT = VOID + 1; \n public static final int BOOL = INT + 1; \n public static final int STRING = BOOL + 1; \n\n\n public Location loc;\n public Type type;\n public int tag;\n \n /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n /**\n * Tag for repeat until loop\n * */\n public static final int REPEAT_UNTIL_LOOP = PRINT + 1;\n public static final int DOUBLE = STRING + 1;\n /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n \n\n /**\n * Initialize tree with given tag.\n */\n public Tree(int tag, Location loc) {\n super();\n this.tag = tag;\n this.loc = loc;\n }\n\n\tpublic Location getLocation() {\n\t\treturn loc;\n\t}\n\n /**\n * Set type field and return this tree.\n */\n public Tree setType(Type type) {\n this.type = type;\n return this;\n }\n\n /**\n * Visit this tree with a given visitor.\n */\n public void accept(Visitor v) {\n v.visitTree(this);\n }\n\n\tpublic abstract void printTo(IndentPrintWriter pw);\n\n public static class TopLevel extends Tree {\n\n\t\tpublic List<ClassDef> classes;\n\t\tpublic Class main;\n\t\tpublic GlobalScope globalScope;\n\t\t\n\t\tpublic TopLevel(List<ClassDef> classes, Location loc) {\n\t\t\tsuper(TOPLEVEL, loc);\n\t\t\tthis.classes = classes;\n\t\t}\n\n \t@Override\n public void accept(Visitor v) {\n v.visitTopLevel(this);\n }\n\n\t\t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"program\");\n \t\tpw.incIndent();\n \t\tfor (ClassDef d : classes) {\n \t\t\td.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n public static class ClassDef extends Tree {\n \t\n \tpublic String name;\n \tpublic String parent;\n \tpublic List<Tree> fields;\n \tpublic Class symbol;\n\n public ClassDef(String name, String parent, List<Tree> fields,\n \t\t\tLocation loc) {\n \t\tsuper(CLASSDEF, loc);\n \t\tthis.name = name;\n \t\tthis.parent = parent;\n \t\tthis.fields = fields;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitClassDef(this);\n }\n \n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"class \" + name + \" \"\n \t\t\t\t+ (parent != null ? parent : \"<empty>\"));\n \t\tpw.incIndent();\n \t\tfor (Tree f : fields) {\n \t\t\tf.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n public static class MethodDef extends Tree {\n \t\n \tpublic boolean statik;\n \tpublic String name;\n \tpublic TypeLiteral returnType;\n \tpublic List<VarDef> formals;\n \tpublic Block body;\n \tpublic Function symbol;\n \t\n public MethodDef(boolean statik, String name, TypeLiteral returnType,\n \t\tList<VarDef> formals, Block body, Location loc) {\n super(METHODDEF, loc);\n \t\tthis.statik = statik;\n \t\tthis.name = name;\n \t\tthis.returnType = returnType;\n \t\tthis.formals = formals;\n \t\tthis.body = body;\n }\n\n public void accept(Visitor v) {\n v.visitMethodDef(this);\n }\n \t\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tif (statik) {\n \t\t\tpw.print(\"static \");\n \t\t}\n \t\tpw.print(\"func \" + name + \" \");\n \t\treturnType.printTo(pw);\n \t\tpw.println();\n \t\tpw.incIndent();\n \t\tpw.println(\"formals\");\n \t\tpw.incIndent();\n \t\tfor (VarDef d : formals) {\n \t\t\td.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t\tbody.printTo(pw);\n \t\tpw.decIndent();\n \t}\n }\n\n public static class VarDef extends Tree {\n \t\n \tpublic String name;\n \tpublic TypeLiteral type;\n \tpublic Variable symbol;\n\n public VarDef(String name, TypeLiteral type, Location loc) {\n super(VARDEF, loc);\n \t\tthis.name = name;\n \t\tthis.type = type;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitVarDef(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.print(\"vardef \" + name + \" \");\n \t\ttype.printTo(pw);\n \t\tpw.println();\n \t}\n }\n\n /**\n * A no-op statement \";\".\n */\n public static class Skip extends Tree {\n\n public Skip(Location loc) {\n super(SKIP, loc);\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitSkip(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\t//print nothing\n \t}\n }\n\n public static class Block extends Tree {\n\n \tpublic List<Tree> block;\n \tpublic LocalScope associatedScope;\n\n public Block(List<Tree> block, Location loc) {\n super(BLOCK, loc);\n \t\tthis.block = block;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitBlock(this);\n }\n \t\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"stmtblock\");\n \t\tpw.incIndent();\n \t\tfor (Tree s : block) {\n \t\t\ts.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n /**\n * A while loop\n */\n public static class WhileLoop extends Tree {\n\n \tpublic Expr condition;\n \tpublic Tree loopBody;\n\n public WhileLoop(Expr condition, Tree loopBody, Location loc) {\n super(WHILELOOP, loc);\n this.condition = condition;\n this.loopBody = loopBody;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitWhileLoop(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"while\");\n \t\tpw.incIndent();\n \t\tcondition.printTo(pw);\n \t\tif (loopBody != null) {\n \t\t\tloopBody.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n \n /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n /**\n * A repeat until loop\n * */\n public static class RepeatLoop extends Tree\n {\n \tpublic Expr condition;\n \tpublic Tree loopBody;\n \t\n\t\tpublic RepeatLoop(Expr condition, Tree loopBody, Location loc)\n\t\t{\n\t\t\tsuper(REPEAT_UNTIL_LOOP, loc);\n\t\t\tthis.condition = condition;\n\t\t\tthis.loopBody = loopBody;\n\t\t}\n\t\t\n\t\t@Override\n public void accept(Visitor v) {\n v.visitRepeatLoop(this);\n }\n\n\t\t@Override\n\t\tpublic void printTo(IndentPrintWriter pw)\n\t\t{\n\t\t\tpw.println(\"repeatLoop\");\n \t\tpw.incIndent();\n \t\tif (loopBody != null) {\n \t\t\tloopBody.printTo(pw);\n \t\t}\n \t\t//pw.decIndent();\n \t\t//pw.println(\"until\");\n \t\t//pw.incIndent();\n \t\tcondition.printTo(pw);\n \t\tpw.decIndent();\n\t\t}\n \t\n }\n /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n \n \n \n \n \n \n /**\n * A for loop.\n */\n public static class ForLoop extends Tree {\n\n \tpublic Tree init;\n \tpublic Expr condition;\n \tpublic Tree update;\n \tpublic Tree loopBody;\n\n public ForLoop(Tree init, Expr condition, Tree update,\n \t\tTree loopBody, Location loc) {\n super(FORLOOP, loc);\n \t\tthis.init = init;\n \t\tthis.condition = condition;\n \t\tthis.update = update;\n \t\tthis.loopBody = loopBody;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitForLoop(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"for\");\n \t\tpw.incIndent();\n \t\tif (init != null) {\n \t\t\tinit.printTo(pw);\n \t\t} else {\n \t\t\tpw.println(\"<emtpy>\");\n \t\t}\n \t\tcondition.printTo(pw);\n \t\tif (update != null) {\n \t\t\tupdate.printTo(pw);\n \t\t} else {\n \t\t\tpw.println(\"<empty>\");\n \t\t}\n \t\tif (loopBody != null) {\n \t\t\tloopBody.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n /**\n * An \"if ( ) { } else { }\" block\n */\n public static class If extends Tree {\n \t\n \tpublic Expr condition;\n \tpublic Tree trueBranch;\n \tpublic Tree falseBranch;\n\n public If(Expr condition, Tree trueBranch, Tree falseBranch,\n \t\t\tLocation loc) {\n super(IF, loc);\n this.condition = condition;\n \t\tthis.trueBranch = trueBranch;\n \t\tthis.falseBranch = falseBranch;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitIf(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"if\");\n \t\tpw.incIndent();\n \t\tcondition.printTo(pw);\n \t\tif (trueBranch != null) {\n \t\t\ttrueBranch.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t\tif (falseBranch != null) {\n \t\t\tpw.println(\"else\");\n \t\t\tpw.incIndent();\n \t\t\tfalseBranch.printTo(pw);\n \t\t\tpw.decIndent();\n \t\t}\n \t}\n }\n\n /**\n * an expression statement\n * @param expr expression structure\n */\n public static class Exec extends Tree {\n\n \tpublic Expr expr;\n\n public Exec(Expr expr, Location loc) {\n super(EXEC, loc);\n this.expr = expr;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitExec(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\texpr.printTo(pw);\n \t}\n }\n\n /**\n * A break from a loop.\n */\n public static class Break extends Tree {\n\n public Break(Location loc) {\n super(BREAK, loc);\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitBreak(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"break\");\n \t}\n }\n\n /**\n * A return statement.\n */\n public static class Print extends Tree {\n\n \tpublic List<Expr> exprs;\n\n \tpublic Print(List<Expr> exprs, Location loc) {\n \t\tsuper(PRINT, loc);\n \t\tthis.exprs = exprs;\n \t}\n\n @Override\n public void accept(Visitor v) {\n v.visitPrint(this);\n }\n\n @Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"print\");\n \t\tpw.incIndent();\n \t\tfor (Expr e : exprs) {\n \t\t\te.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n }\n }\n\n /**\n * A return statement.\n */\n public static class Return extends Tree {\n\n \tpublic Expr expr;\n\n public Return(Expr expr, Location loc) {\n super(RETURN, loc);\n this.expr = expr;\n }\n\n @Override\n public void accept(Visitor v) {\n v.visitReturn(this);\n }\n\n @Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"return\");\n \t\tif (expr != null) {\n \t\t\tpw.incIndent();\n \t\t\texpr.printTo(pw);\n \t\t\tpw.decIndent();\n \t\t}\n \t}\n }\n\n public abstract static class Expr extends Tree {\n\n \tpublic Type type;\n\t\tpublic Temp val;\n \tpublic boolean isClass;\n \tpublic boolean usedForRef;\n \t\n \tpublic Expr(int tag, Location loc) {\n \t\tsuper(tag, loc);\n \t}\n }\n\n /**\n * A method invocation\n */\n public static class Apply extends Expr {\n\n \tpublic Expr receiver;\n \tpublic String method;\n \tpublic List<Expr> actuals;\n \tpublic Function symbol;\n \tpublic boolean isArrayLength;\n\n public Apply(Expr receiver, String method, List<Expr> actuals,\n \t\t\tLocation loc) {\n super(APPLY, loc);\n \t\tthis.receiver = receiver;\n \t\tthis.method = method;\n \t\tthis.actuals = actuals;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitApply(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"call \" + method);\n \t\tpw.incIndent();\n \t\tif (receiver != null) {\n \t\t\treceiver.printTo(pw);\n \t\t} else {\n \t\t\tpw.println(\"<empty>\");\n \t\t}\n \t\t\n \t\tfor (Expr e : actuals) {\n \t\t\te.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n /**\n * A new(...) operation.\n */\n public static class NewClass extends Expr {\n\n \tpublic String className;\n \tpublic Class symbol;\n\n public NewClass(String className, Location loc) {\n super(NEWCLASS, loc);\n \t\tthis.className = className;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitNewClass(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"newobj \" + className);\n \t}\n }\n\n /**\n * A new[...] operation.\n */\n public static class NewArray extends Expr {\n\n \tpublic TypeLiteral elementType;\n \tpublic Expr length;\n\n public NewArray(TypeLiteral elementType, Expr length, Location loc) {\n super(NEWARRAY, loc);\n \t\tthis.elementType = elementType;\n \t\tthis.length = length;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitNewArray(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.print(\"newarray \");\n \t\telementType.printTo(pw);\n \t\tpw.println();\n \t\tpw.incIndent();\n \t\tlength.printTo(pw);\n \t\tpw.decIndent();\n \t}\n }\n\n public abstract static class LValue extends Expr {\n\n \tpublic enum Kind {\n \t\tLOCAL_VAR, PARAM_VAR, MEMBER_VAR, ARRAY_ELEMENT\n \t}\n \tpublic Kind lvKind;\n \t\n \tLValue(int tag, Location loc) {\n \t\tsuper(tag, loc);\n \t}\n }\n\n /**\n * A assignment with \"=\".\n */\n public static class Assign extends Tree {\n\n \tpublic LValue left;\n \tpublic Expr expr;\n\n public Assign(LValue left, Expr expr, Location loc) {\n super(ASSIGN, loc);\n \t\tthis.left = left;\n \t\tthis.expr = expr;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitAssign(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"assign\");\n \t\tpw.incIndent();\n \t\tleft.printTo(pw);\n \t\texpr.printTo(pw);\n \t\tpw.decIndent();\n \t}\n }\n\n /**\n * A unary operation.\n */\n public static class Unary extends Expr {\n\n \tpublic Expr expr;\n\n public Unary(int kind, Expr expr, Location loc) {\n super(kind, loc);\n \t\tthis.expr = expr;\n }\n\n \tprivate void unaryOperatorToString(IndentPrintWriter pw, String op) {\n \t\tpw.println(op);\n \t\tpw.incIndent();\n \t\texpr.printTo(pw);\n \t\tpw.decIndent();\n \t}\n\n \t@Override\n public void accept(Visitor v) {\n v.visitUnary(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tswitch (tag) {\n \t\tcase NEG:\n \t\t\tunaryOperatorToString(pw, \"neg\");\n \t\t\tbreak;\n \t\tcase NOT:\n \t\t\tunaryOperatorToString(pw, \"not\");\n \t\t\tbreak;\n\t\t\t}\n \t}\n }\n\n /**\n * A binary operation.\n */\n public static class Binary extends Expr {\n\n \tpublic Expr left;\n \tpublic Expr right;\n\n public Binary(int kind, Expr left, Expr right, Location loc) {\n super(kind, loc);\n \t\tthis.left = left;\n \t\tthis.right = right;\n }\n\n \tprivate void binaryOperatorPrintTo(IndentPrintWriter pw, String op) {\n \t\tpw.println(op);\n \t\tpw.incIndent();\n \t\tleft.printTo(pw);\n \t\tright.printTo(pw);\n \t\tpw.decIndent();\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitBinary(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tswitch (tag) {\n \t\tcase PLUS:\n \t\t\tbinaryOperatorPrintTo(pw, \"add\");\n \t\t\tbreak;\n \t\tcase MINUS:\n \t\t\tbinaryOperatorPrintTo(pw, \"sub\");\n \t\t\tbreak;\n \t\tcase MUL:\n \t\t\tbinaryOperatorPrintTo(pw, \"mul\");\n \t\t\tbreak;\n \t\tcase DIV:\n \t\t\tbinaryOperatorPrintTo(pw, \"div\");\n \t\t\tbreak;\n \t\tcase MOD:\n \t\t\tbinaryOperatorPrintTo(pw, \"mod\");\n \t\t\tbreak;\n \t\tcase AND:\n \t\t\tbinaryOperatorPrintTo(pw, \"and\");\n \t\t\tbreak;\n \t\tcase OR:\n \t\t\tbinaryOperatorPrintTo(pw, \"or\");\n \t\t\tbreak;\n \t\tcase EQ:\n \t\t\tbinaryOperatorPrintTo(pw, \"equ\");\n \t\t\tbreak;\n \t\tcase NE:\n \t\t\tbinaryOperatorPrintTo(pw, \"neq\");\n \t\t\tbreak;\n \t\tcase LT:\n \t\t\tbinaryOperatorPrintTo(pw, \"les\");\n \t\t\tbreak;\n \t\tcase LE:\n \t\t\tbinaryOperatorPrintTo(pw, \"leq\");\n \t\t\tbreak;\n \t\tcase GT:\n \t\t\tbinaryOperatorPrintTo(pw, \"gtr\");\n \t\t\tbreak;\n \t\tcase GE:\n \t\t\tbinaryOperatorPrintTo(pw, \"geq\");\n \t\t\tbreak;\n \t\t}\n \t}\n }\n\n public static class CallExpr extends Expr {\n\n \tpublic Expr receiver;\n\n \tpublic String method;\n\n \tpublic List<Expr> actuals;\n\n \tpublic Function symbol;\n\n \tpublic boolean isArrayLength;\n\n \tpublic CallExpr(Expr receiver, String method, List<Expr> actuals,\n \t\t\tLocation loc) {\n \t\tsuper(CALLEXPR, loc);\n \t\tthis.receiver = receiver;\n \t\tthis.method = method;\n \t\tthis.actuals = actuals;\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitCallExpr(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"call \" + method);\n \t\tpw.incIndent();\n \t\tif (receiver != null) {\n \t\t\treceiver.printTo(pw);\n \t\t} else {\n \t\t\tpw.println(\"<empty>\");\n \t\t}\n \t\t\n \t\tfor (Expr e : actuals) {\n \t\t\te.printTo(pw);\n \t\t}\n \t\tpw.decIndent();\n \t}\n }\n\n public static class ReadIntExpr extends Expr {\n\n \tpublic ReadIntExpr(Location loc) {\n \t\tsuper(READINTEXPR, loc);\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitReadIntExpr(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"readint\");\n \t}\n }\n\n public static class ReadLineExpr extends Expr {\n\n \tpublic ReadLineExpr(Location loc) {\n \t\tsuper(READLINEEXPR, loc);\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitReadLineExpr(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"readline\");\n \t}\n }\n\n public static class ThisExpr extends Expr {\n\n \tpublic ThisExpr(Location loc) {\n \t\tsuper(THISEXPR, loc);\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitThisExpr(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"this\");\n \t}\n }\n\n /**\n * A type cast.\n */\n public static class TypeCast extends Expr {\n\n \tpublic String className;\n \tpublic Expr expr;\n \tpublic Class symbol;\n\n public TypeCast(String className, Expr expr, Location loc) {\n super(TYPECAST, loc);\n \t\tthis.className = className;\n \t\tthis.expr = expr;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitTypeCast(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"classcast\");\n \t\tpw.incIndent();\n \t\tpw.println(className);\n \t\texpr.printTo(pw);\n \t\tpw.decIndent();\n \t}\n }\n\n /////////////////////////////////////////////////////////////////////////////////////////////////////////\n// /**\n// * instanceof expression\n// */\n// public static class TypeTest extends Expr {\n// \t\n// \tpublic Expr instance;\n// \tpublic String className;\n// \tpublic Class symbol;\n//\n// public TypeTest(Expr instance, String className, Location loc) {\n// super(TYPETEST, loc);\n// \t\tthis.instance = instance;\n// \t\tthis.className = className;\n// }\n//\n// \t@Override\n// public void accept(Visitor v) {\n// v.visitTypeTest(this);\n// }\n//\n// \t@Override\n// \tpublic void printTo(IndentPrintWriter pw) {\n// \t\tpw.println(\"instanceof\");\n// \t\tpw.incIndent();\n// \t\tinstance.printTo(pw);\n// \t\tpw.println(className);\n// \t\tpw.decIndent();\n// \t}\n// }\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n /**\n * An array selection\n */\n public static class Indexed extends LValue {\n\n \tpublic Expr array;\n \tpublic Expr index;\n\n public Indexed(Expr array, Expr index, Location loc) {\n super(INDEXED, loc);\n \t\tthis.array = array;\n \t\tthis.index = index;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitIndexed(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"arrref\");\n \t\tpw.incIndent();\n \t\tarray.printTo(pw);\n \t\tindex.printTo(pw);\n \t\tpw.decIndent();\n \t}\n }\n\n /**\n * An identifier\n */\n public static class Ident extends LValue {\n\n \tpublic Expr owner;\n \tpublic String name;\n \tpublic Variable symbol;\n \tpublic boolean isDefined;\n\n public Ident(Expr owner, String name, Location loc) {\n super(IDENT, loc);\n \t\tthis.owner = owner;\n \t\tthis.name = name;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitIdent(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.println(\"varref \" + name);\n \t\tif (owner != null) {\n \t\t\tpw.incIndent();\n \t\t\towner.printTo(pw);\n \t\t\tpw.decIndent();\n \t\t}\n \t}\n }\n\n /**\n * A constant value given literally.\n * @param value value representation\n */\n public static class Literal extends Expr {\n\n \tpublic int typeTag;\n public Object value;\n\n public Literal(int typeTag, Object value, Location loc) {\n super(LITERAL, loc);\n this.typeTag = typeTag;\n this.value = value;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitLiteral(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tswitch (typeTag) {\n \t\tcase INT:\n \t\t\tpw.println(\"intconst \" + value);\n \t\t\tbreak;\n \t\tcase DOUBLE:\n \t\t\tpw.println(\"doubleconst \" + value);\n \t\t\tbreak;\n \t\tcase BOOL:\n \t\t\tpw.println(\"boolconst \" + value);\n \t\t\tbreak;\n \t\tdefault:\n \t\t\tpw.println(\"stringconst \" + MiscUtils.quote((String)value));\n \t\t}\n \t}\n }\n public static class Null extends Expr {\n\n public Null(Location loc) {\n super(NULL, loc);\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitNull(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\t\tpw.println(\"null\");\n \t}\n }\n\n public static abstract class TypeLiteral extends Tree {\n \t\n \tpublic Type type;\n \t\n \tpublic TypeLiteral(int tag, Location loc){\n \t\tsuper(tag, loc);\n \t}\n }\n \n /**\n * Identifies a basic type.\n * @param tag the basic type id\n * @see SemanticConstants\n */\n public static class TypeIdent extends TypeLiteral {\n \t\n public int typeTag;\n\n public TypeIdent(int typeTag, Location loc) {\n super(TYPEIDENT, loc);\n this.typeTag = typeTag;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitTypeIdent(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tswitch (typeTag){\n \t\tcase INT:\n \t\t\tpw.print(\"inttype\");\n \t\t\tbreak;\n \t\tcase BOOL:\n \t\t\tpw.print(\"booltype\");\n \t\t\tbreak;\n \t\tcase VOID:\n \t\t\tpw.print(\"voidtype\");\n \t\t\tbreak;\n \t\tcase DOUBLE:\n \t\t\tpw.print(\"doubletype\");\n \t\t\tbreak;\n \t\tdefault:\n \t\t\tpw.print(\"stringtype\");\n \t\t}\n \t}\n }\n\n public static class TypeClass extends TypeLiteral {\n\n \tpublic String name;\n\n \tpublic TypeClass(String name, Location loc) {\n \t\tsuper(TYPECLASS, loc);\n \t\tthis.name = name;\n \t}\n\n \t@Override\n \tpublic void accept(Visitor visitor) {\n \t\tvisitor.visitTypeClass(this);\n \t}\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.print(\"classtype \" + name);\n \t}\n }\n\n /**\n * An array type, A[]\n */\n public static class TypeArray extends TypeLiteral {\n\n \tpublic TypeLiteral elementType;\n\n public TypeArray(TypeLiteral elementType, Location loc) {\n super(TYPEARRAY, loc);\n \t\tthis.elementType = elementType;\n }\n\n \t@Override\n public void accept(Visitor v) {\n v.visitTypeArray(this);\n }\n\n \t@Override\n \tpublic void printTo(IndentPrintWriter pw) {\n \t\tpw.print(\"arrtype \");\n \t\telementType.printTo(pw);\n \t}\n }\n\n /**\n * A generic visitor class for trees.\n */\n public static abstract class Visitor {\n\n public Visitor() {\n super();\n }\n\n public void visitTopLevel(TopLevel that) {\n visitTree(that);\n }\n\n public void visitClassDef(ClassDef that) {\n visitTree(that);\n }\n\n public void visitMethodDef(MethodDef that) {\n visitTree(that);\n }\n\n public void visitVarDef(VarDef that) {\n visitTree(that);\n }\n\n public void visitSkip(Skip that) {\n visitTree(that);\n }\n\n public void visitBlock(Block that) {\n visitTree(that);\n }\n\n public void visitWhileLoop(WhileLoop that) {\n visitTree(that);\n }\n \n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n public void visitRepeatLoop(RepeatLoop that)\n\t\t{\n\t\t\tvisitTree(that);\n\t\t}\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n \n\n public void visitForLoop(ForLoop that) {\n visitTree(that);\n }\n\n public void visitIf(If that) {\n visitTree(that);\n }\n\n public void visitExec(Exec that) {\n visitTree(that);\n }\n\n public void visitBreak(Break that) {\n visitTree(that);\n }\n\n public void visitReturn(Return that) {\n visitTree(that);\n }\n\n public void visitApply(Apply that) {\n visitTree(that);\n }\n\n public void visitNewClass(NewClass that) {\n visitTree(that);\n }\n\n public void visitNewArray(NewArray that) {\n visitTree(that);\n }\n\n public void visitAssign(Assign that) {\n visitTree(that);\n }\n\n public void visitUnary(Unary that) {\n visitTree(that);\n }\n\n public void visitBinary(Binary that) {\n visitTree(that);\n }\n\n public void visitCallExpr(CallExpr that) {\n visitTree(that);\n }\n\n public void visitReadIntExpr(ReadIntExpr that) {\n visitTree(that);\n }\n\n public void visitReadLineExpr(ReadLineExpr that) {\n visitTree(that);\n }\n\n public void visitPrint(Print that) {\n visitTree(that);\n }\n\n public void visitThisExpr(ThisExpr that) {\n visitTree(that);\n }\n\n public void visitLValue(LValue that) {\n visitTree(that);\n }\n\n public void visitTypeCast(TypeCast that) {\n visitTree(that);\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n// public void visitTypeTest(TypeTest that) {\n// visitTree(that);\n// }\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n public void visitIndexed(Indexed that) {\n visitTree(that);\n }\n\n public void visitIdent(Ident that) {\n visitTree(that);\n }\n\n public void visitLiteral(Literal that) {\n visitTree(that);\n }\n\n public void visitNull(Null that) {\n visitTree(that);\n }\n\n public void visitTypeIdent(TypeIdent that) {\n visitTree(that);\n }\n\n public void visitTypeClass(TypeClass that) {\n visitTree(that);\n }\n\n public void visitTypeArray(TypeArray that) {\n visitTree(that);\n }\n\n public void visitTree(Tree that) {\n assert false;\n }\n }\n}", "public class LocalScope extends Scope {\n\n\tprivate Block node;\n\n\tpublic LocalScope(Block node) {\n\t\tthis.node = node;\n\t}\n\n\t@Override\n\tpublic Kind getKind() {\n\t\treturn Kind.LOCAL;\n\t}\n\n\t@Override\n\tpublic void printTo(IndentPrintWriter pw) {\n\t\tpw.println(\"LOCAL SCOPE:\");\n\t\tpw.incIndent();\n\t\tfor (Symbol symbol : symbols.values()) {\n\t\t\tpw.println(symbol);\n\t\t}\n\n\t\tfor (Tree s : node.block) {\n\t\t\tif (s instanceof Block) {\n\t\t\t\t((Block) s).associatedScope.printTo(pw);\n\t\t\t}\n\t\t}\n\t\tpw.decIndent();\n\t}\n\n\t@Override\n\tpublic boolean isLocalScope() {\n\t\treturn true;\n\t}\n}", "public class Class extends Symbol {\n\n\tprivate String parentName;\n\n\tprivate ClassScope associatedScope;\n\n\tprivate int order;\n\n\tprivate boolean check;\n\n\tprivate int numNonStaticFunc;\n\n\tprivate int numVar;\n\n\tprivate int size;\n\n\tpublic int getSize() {\n\t\treturn size;\n\t}\n\n\tpublic void setSize(int size) {\n\t\tthis.size = size;\n\t}\n\n\tpublic int getNumNonStaticFunc() {\n\t\treturn numNonStaticFunc;\n\t}\n\n\tpublic void setNumNonStaticFunc(int numNonStaticFunc) {\n\t\tthis.numNonStaticFunc = numNonStaticFunc;\n\t}\n\n\tpublic int getNumVar() {\n\t\treturn numVar;\n\t}\n\n\tpublic void setNumVar(int numVar) {\n\t\tthis.numVar = numVar;\n\t}\n\n\tpublic Class(String name, String parentName, Location location) {\n\t\tthis.name = name;\n\t\tthis.parentName = parentName;\n\t\tthis.location = location;\n\t\tthis.order = -1;\n\t\tthis.check = false;\n\t\tthis.numNonStaticFunc = -1;\n\t\tthis.numVar = -1;\n\t\tthis.associatedScope = new ClassScope(this);\n\t}\n\n\tpublic void createType() {\n\t\tClass p = getParent();\n\t\tif (p == null) {\n\t\t\ttype = new ClassType(this, null);\n\t\t} else {\n\t\t\tif (p.getType() == null) {\n\t\t\t\tp.createType();\n\t\t\t}\n\t\t\ttype = new ClassType(this, (ClassType) p.getType());\n\t\t}\n\t}\n\n\t@Override\n\tpublic ClassType getType() {\n\t\tif (type == null) {\n\t\t\tcreateType();\n\t\t}\n\t\treturn (ClassType) type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder(location + \" -> class \" + name);\n\t\tif (parentName != null) {\n\t\t\tsb.append(\" : \" + parentName);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic ClassScope getAssociatedScope() {\n\t\treturn associatedScope;\n\t}\n\n\tpublic Class getParent() {\n\t\treturn Driver.getDriver().getTable().lookupClass(parentName);\n\t}\n\n\t@Override\n\tpublic boolean isClass() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic GlobalScope getScope() {\n\t\treturn (GlobalScope) definedIn;\n\t}\n\n\tpublic int getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(int order) {\n\t\tthis.order = order;\n\t}\n\n\tpublic void dettachParent() {\n\t\tparentName = null;\n\t}\n\n\tpublic boolean isCheck() {\n\t\treturn check;\n\t}\n\n\tpublic void setCheck(boolean check) {\n\t\tthis.check = check;\n\t}\n\n\t@Override\n\tpublic boolean isFunction() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isVariable() {\n\t\treturn false;\n\t}\n}", "public class Function extends Symbol {\n\n\tprivate FormalScope associatedScope;\n\n\tprivate boolean statik;\n\n\tprivate boolean isMain;\n\n\tpublic boolean isMain() {\n\t\treturn isMain;\n\t}\n\n\tpublic void setMain(boolean isMain) {\n\t\tthis.isMain = isMain;\n\t}\n\n\tpublic boolean isStatik() {\n\t\treturn statik;\n\t}\n\n\tpublic void setStatik(boolean statik) {\n\t\tthis.statik = statik;\n\t}\n\n\tprivate int offset;\n\n\tpublic int getOffset() {\n\t\treturn offset;\n\t}\n\n\tpublic void setOffset(int offset) {\n\t\tthis.offset = offset;\n\t}\n\n\tpublic Function(boolean statik, String name, Type returnType,\n\t\t\tBlock node, Location location) {\n\t\tthis.name = name;\n\t\tthis.location = location;\n\n\t\ttype = new FuncType(returnType);\n\t\tassociatedScope = new FormalScope(this, node);\n\t\tClassScope cs = (ClassScope) Driver.getDriver().getTable()\n\t\t\t\t.lookForScope(Scope.Kind.CLASS);\n\t\tthis.statik = statik;\n\t\tif (!statik) {\n\t\t\tVariable _this = new Variable(\"this\", cs.getOwner().getType(),\n\t\t\t\t\tlocation);\n\t\t\tassociatedScope.declare(_this);\n\t\t\tappendParam(_this);\n\t\t}\n\n\t}\n\n\tpublic FormalScope getAssociatedScope() {\n\t\treturn associatedScope;\n\t}\n\n\tpublic Type getReturnType() {\n\t\treturn getType().getReturnType();\n\t}\n\n\tpublic void appendParam(Variable arg) {\n\t\targ.setOrder(getType().numOfParams());\n\t\tgetType().appendParam(arg.getType());\n\t}\n\n\t@Override\n\tpublic ClassScope getScope() {\n\t\treturn (ClassScope) definedIn;\n\t}\n\n\t@Override\n\tpublic FuncType getType() {\n\t\treturn (FuncType) type;\n\t}\n\n\t@Override\n\tpublic boolean isFunction() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn location + \" -> \" + (statik ? \"static \" : \"\") + \"function \"\n\t\t\t\t+ name + \" : \" + type;\n\t}\n\n\t@Override\n\tpublic boolean isClass() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isVariable() {\n\t\treturn false;\n\t}\n\n}", "public abstract class Symbol {\n\tprotected String name;\n\n\tprotected Scope definedIn;\n\n\tprotected Type type;\n\n\tprotected int order;\n\n\tprotected Location location;\n\n\tpublic static final Comparator<Symbol> LOCATION_COMPARATOR = new Comparator<Symbol>() {\n\n\t\t@Override\n\t\tpublic int compare(Symbol o1, Symbol o2) {\n\t\t\treturn o1.location.compareTo(o2.location);\n\t\t}\n\n\t};\n\n\tpublic static final Comparator<Symbol> ORDER_COMPARATOR = new Comparator<Symbol>() {\n\n\t\t@Override\n\t\tpublic int compare(Symbol o1, Symbol o2) {\n\t\t\treturn o1.order > o2.order ? 1 : o1.order == o2.order ? 0 : -1;\n\t\t}\n\n\t};\n\n\tpublic Scope getScope() {\n\t\treturn definedIn;\n\t}\n\n\tpublic void setScope(Scope definedIn) {\n\t\tthis.definedIn = definedIn;\n\t}\n\n\tpublic int getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(int order) {\n\t\tthis.order = order;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(Location location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic abstract boolean isVariable();\n\n\tpublic abstract boolean isClass();\n\n\tpublic abstract boolean isFunction();\n\n\tpublic abstract String toString();\n}", "public class Variable extends Symbol {\n\t\n\tprivate int offset;\n\n\tpublic int getOffset() {\n\t\treturn offset;\n\t}\n\n\tpublic void setOffset(int offset) {\n\t\tthis.offset = offset;\n\t}\n\n\tpublic Variable(String name, Type type, Location location) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t\tthis.location = location;\n\t}\n\n\tpublic boolean isLocalVar() {\n\t\treturn definedIn.isLocalScope();\n\t}\n\n\tpublic boolean isMemberVar() {\n\t\treturn definedIn.isClassScope();\n\t}\n\n\t@Override\n\tpublic boolean isVariable() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn location + \" -> variable \" + (isParam() ? \"@\" : \"\") + name\n\t\t\t\t+ \" : \" + type;\n\t}\n\n\tpublic boolean isParam() {\n\t\treturn definedIn.isFormalScope();\n\t}\n\n\t@Override\n\tpublic boolean isClass() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isFunction() {\n\t\treturn false;\n\t}\n\n}", "public class BaseType extends Type {\n\n\tprivate final String typeName;\n\n\tprivate BaseType(String typeName) {\n\t\tthis.typeName = typeName;\n\t}\n\n\tpublic static final BaseType INT = new BaseType(\"int\");\n\t\n\tpublic static final BaseType BOOL = new BaseType(\"bool\");\n\n\tpublic static final BaseType NULL = new BaseType(\"null\");\n\n\tpublic static final BaseType ERROR = new BaseType(\"Error\");\n\t\n\tpublic static final BaseType STRING = new BaseType(\"string\");\n\t\n\tpublic static final BaseType VOID = new BaseType(\"void\");\n\t\n\t////////////////////////////////////////////////////////////////////////////////////////\n\tpublic static final BaseType DOUBLE = new BaseType(\"double\");\n\t////////////////////////////////////////////////////////////////////////////////////////\n\n\t@Override\n\tpublic boolean isBaseType() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean compatible(Type type) {\n\t\tif (equal(ERROR) || type.equal(ERROR)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (equal(NULL) && type.isClassType()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn equal(type);\n\t}\n\n\t@Override\n\tpublic boolean equal(Type type) {\n\t\treturn this == type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn typeName;\n\t}\n\n}", "public class FuncType extends Type {\n\n\tprivate Type returnType;\n\n\tprivate List<Type> argList;\n\n\tpublic FuncType(Type returnType) {\n\t\tthis.returnType = returnType;\n\t\targList = new ArrayList<Type>();\n\t}\n\n\tpublic int numOfParams() {\n\t\treturn argList.size();\n\t}\n\n\tpublic void appendParam(Type type) {\n\t\targList.add(type);\n\t}\n\n\t@Override\n\tpublic boolean compatible(Type type) {\n\t\tif (type.equal(BaseType.ERROR)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!type.isFuncType()) {\n\t\t\treturn false;\n\t\t}\n\t\tFuncType ft = (FuncType) type;\n\t\tif (!returnType.compatible(ft.returnType)\n\t\t\t\t|| argList.size() != ft.argList.size()) {\n\t\t\treturn false;\n\t\t}\n\t\tIterator<Type> iter1 = argList.iterator();\n\t\titer1.next();\n\t\tIterator<Type> iter2 = ft.argList.iterator();\n\t\titer2.next();\n\t\twhile (iter1.hasNext()) {\n\t\t\tif (!iter2.next().compatible(iter1.next())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean equal(Type type) {\n\t\treturn equals(type);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (Type type : argList) {\n\t\t\tsb.append(type + \"->\");\n\t\t}\n\t\tsb.append(returnType);\n\t\treturn sb.toString();\n\t}\n\n\tpublic Type getReturnType() {\n\t\treturn returnType;\n\t}\n\n\t@Override\n\tpublic boolean isFuncType() {\n\t\treturn true;\n\t}\n\n\tpublic List<Type> getArgList() {\n\t\treturn argList;\n\t}\n}" ]
import java.util.Iterator; import decaf.Driver; import decaf.tree.Tree; import decaf.error.BadArrElementError; import decaf.error.BadInheritanceError; import decaf.error.BadOverrideError; import decaf.error.BadVarTypeError; import decaf.error.ClassNotFoundError; import decaf.error.DecafError; import decaf.error.DeclConflictError; import decaf.error.NoMainClassError; import decaf.error.OverridingVarError; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.scope.LocalScope; import decaf.scope.ScopeStack; import decaf.symbol.Class; import decaf.symbol.Function; import decaf.symbol.Symbol; import decaf.symbol.Variable; import decaf.type.BaseType; import decaf.type.FuncType;
issueError(new NoMainClassError(Driver.getDriver().getOption() .getMainClassName())); } table.close(); } // visiting declarations @Override public void visitClassDef(Tree.ClassDef classDef) { table.open(classDef.symbol.getAssociatedScope()); for (Tree f : classDef.fields) { f.accept(this); } table.close(); } @Override public void visitVarDef(Tree.VarDef varDef) { varDef.type.accept(this); if (varDef.type.type.equal(BaseType.VOID)) { issueError(new BadVarTypeError(varDef.getLocation(), varDef.name)); // for argList varDef.symbol = new Variable(".error", BaseType.ERROR, varDef .getLocation()); return; } Variable v = new Variable(varDef.name, varDef.type.type, varDef.getLocation()); Symbol sym = table.lookup(varDef.name, true); if (sym != null) { if (table.getCurrentScope().equals(sym.getScope())) { issueError(new DeclConflictError(v.getLocation(), v.getName(), sym.getLocation())); } else if ((sym.getScope().isFormalScope() || sym.getScope() .isLocalScope())) { issueError(new DeclConflictError(v.getLocation(), v.getName(), sym.getLocation())); } else { table.declare(v); } } else { table.declare(v); } varDef.symbol = v; } @Override public void visitMethodDef(Tree.MethodDef funcDef) { funcDef.returnType.accept(this); Function f = new Function(funcDef.statik, funcDef.name, funcDef.returnType.type, funcDef.body, funcDef.getLocation()); funcDef.symbol = f; Symbol sym = table.lookup(funcDef.name, false); if (sym != null) { issueError(new DeclConflictError(funcDef.getLocation(), funcDef.name, sym.getLocation())); } else { table.declare(f); } table.open(f.getAssociatedScope()); for (Tree.VarDef d : funcDef.formals) { d.accept(this); f.appendParam(d.symbol); } funcDef.body.accept(this); table.close(); } // visiting types @Override public void visitTypeIdent(Tree.TypeIdent type) { switch (type.typeTag) { case Tree.VOID: type.type = BaseType.VOID; break; case Tree.INT: type.type = BaseType.INT; break; case Tree.BOOL: type.type = BaseType.BOOL; break; ////////////////////////////////////////////////////////////////////////////////////////////// case Tree.DOUBLE: type.type = BaseType.DOUBLE; break; ////////////////////////////////////////////////////////////////////////////////////////////// default: type.type = BaseType.STRING; } } @Override public void visitTypeClass(Tree.TypeClass typeClass) { Class c = table.lookupClass(typeClass.name); if (c == null) { issueError(new ClassNotFoundError(typeClass.getLocation(), typeClass.name)); typeClass.type = BaseType.ERROR; } else { typeClass.type = c.getType(); } } @Override public void visitTypeArray(Tree.TypeArray typeArray) { typeArray.elementType.accept(this); if (typeArray.elementType.type.equal(BaseType.ERROR)) { typeArray.type = BaseType.ERROR; } else if (typeArray.elementType.type.equal(BaseType.VOID)) { issueError(new BadArrElementError(typeArray.getLocation())); typeArray.type = BaseType.ERROR; } else { typeArray.type = new decaf.type.ArrayType( typeArray.elementType.type); } } // for VarDecl in LocalScope @Override public void visitBlock(Tree.Block block) {
block.associatedScope = new LocalScope(block);
2
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/impl/NoteOpsTextImpl.java
[ "public class Messages extends NLS {\n\n private static final String BUNDLE_NAME = \"messages\"; //$NON-NLS-1$\n\n public static String Plugin_Configs_Shell_Title;\n public static String Plugin_Configs_QuickOrgnize_Shell_Title;\n public static String Plugin_Configs_Title;\n public static String Plugin_Configs_Message;\n public static String Plugin_Configs_Organize;\n public static String Plugin_Configs_Notebook;\n public static String Plugin_Configs_Note;\n public static String Plugin_Configs_Tags;\n public static String Plugin_Configs_Notebook_Hint;\n public static String Plugin_Configs_Note_Hint;\n public static String Plugin_Configs_Tags_Hint;\n public static String Plugin_Configs_Comments;\n public static String Plugin_Configs_Refresh;\n public static String Plugin_Configs_Authenticating;\n public static String Plugin_Configs_FetchingNotebooks;\n public static String Plugin_Configs_FetchingNotes;\n public static String Plugin_Configs_FetchingTags;\n public static String Plugin_Runtime_ClipFileToEvernote;\n public static String Plugin_Runtime_ClipSelectionToEvernote;\n public static String Plugin_Runtime_ClipScreenshotToEvernote_Hint;\n public static String Plugin_Runtime_CreateNewNote;\n public static String Plugin_Runtime_CreateNewNoteInNotebook;\n public static String Plugin_Runtime_ClipToDefault;\n public static String Plugin_Runtime_CreateNewNoteWithGivenName;\n public static String Plugin_Runtime_CreateNewNoteWithGivenNameInNotebook;\n public static String Plugin_Runtime_ClipToNotebook_Default;\n public static String Plugin_OutOfDate;\n public static String Plugin_Error_Occurred;\n public static String Plugin_Error_OutOfDate;\n public static String Plugin_Error_NoFile;\n public static String Plugin_Error_NoText;\n public static String Plugin_OAuth_Cancel;\n public static String Plugin_OAuth_Copy;\n\n public static String Plugin_OAuth_TokenNotConfigured;\n public static String Plugin_OAuth_Title;\n public static String Plugin_OAuth_Configure;\n public static String Plugin_OAuth_NotNow;\n public static String Plugin_OAuth_Waiting;\n public static String Plugin_OAuth_Confirm;\n public static String Plugin_OAuth_AuthExpired_Message;\n public static String Plugin_OAuth_AuthExpired_Title;\n public static String Plugin_OAuth_AuthExpired_ReAuth;\n public static String Plugin_OAuth_DoItManually;\n public static String Plugin_OAuth_SWITCH_YXBJ;\n public static String Plugin_OAuth_SWITCH_INTL;\n\n public static String DOM_Error0;\n public static String DOM_Error1;\n public static String DOM_Error2;\n public static String DOM_Error3;\n public static String DOM_Error4;\n public static String DOM_Error5;\n public static String DOM_Error6;\n public static String DOM_Error7;\n public static String DOM_Error8;\n public static String DOM_Error9;\n public static String Throwable_IllegalArgumentException_Message;\n public static String Throwable_NotSerializable_Message;\n\n // For Debug\n public static String Plugin_Debug_Default_Font_Style;\n public static String Plugin_Debug_StyleRange_Font_Style;\n public static String Plugin_Debug_FinalConcluded_Font_Style;\n public static String Plugin_Debug_NewClipper;\n public static String Plugin_Debug_IsFullScreenSupported;\n public static String Plugin_Debug_CapturedScreenshot;\n public static String Plugin_Debug_NoScreenCaptureProcessor;\n\n static {\n // initialize resource bundle\n NLS.initializeMessages(BUNDLE_NAME, Messages.class);\n }\n\n private Messages() {\n }\n\n}", "public abstract class NoteOps {\n\n private final StoreClientFactory factory;\n\n public NoteOps(final StoreClientFactory factory) {\n this.factory = factory;\n }\n\n public abstract void updateOrCreate(ENNote args) throws Exception;\n\n protected NoteStoreClient getNoteStoreClient(final ENNote args) throws EDAMUserException, EDAMSystemException, TException, EDAMNotFoundException {\n NoteStoreClient client;\n if (args.getNotebook().getType() == ENObjectType.LINKED) {\n // args.getNotebook().getLinkedObject() should NOT be null\n client = factory.getLinkedNoteStoreClient((LinkedNotebook) args.getNotebook().getLinkedObject());\n } else {\n client = factory.getNoteStoreClient();\n }\n return client;\n }\n\n}", "public class StoreClientFactory {\n\n private final ClientFactory factory;\n\n private NoteStoreClient noteStoreClient;\n private UserStoreClient userStoreClient;\n\n public StoreClientFactory(final String token) throws TException, OutOfDateException {\n factory = auth(token);\n checkVersion();\n }\n\n private ClientFactory auth(final String token) {\n EvernoteAuth evernoteAuth = new EvernoteAuth(EvernoteUtil.evernoteService(), token);\n return new ClientFactory(evernoteAuth);\n }\n\n private void checkVersion() throws TException, OutOfDateException {\n UserStoreClient userStore = getUserStoreClient();\n boolean versionOk = userStore.checkVersion(EemoryPlugin.getName(), com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR, com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);\n if (!versionOk) {\n throw new OutOfDateException(Messages.Plugin_Error_OutOfDate);\n }\n }\n\n public NoteStoreClient getNoteStoreClient() throws EDAMUserException, EDAMSystemException, TException {\n if (noteStoreClient == null) {\n synchronized (StoreClientFactory.class) {\n if (noteStoreClient == null) {\n noteStoreClient = factory.createNoteStoreClient();\n }\n }\n }\n return noteStoreClient;\n }\n\n public NoteStoreClient getLinkedNoteStoreClient(final LinkedNotebook linkedNotebook) throws EDAMUserException, EDAMSystemException, TException, EDAMNotFoundException {\n return factory.createLinkedNoteStoreClient(linkedNotebook).getClient();\n }\n\n public UserStoreClient getUserStoreClient() throws TTransportException {\n if (userStoreClient == null) {\n synchronized (StoreClientFactory.class) {\n if (userStoreClient == null) {\n userStoreClient = factory.createUserStoreClient();\n }\n }\n }\n return userStoreClient;\n }\n\n}", "public class EDAMLimits {\n\n public static final int EDAM_NOTE_TITLE_LEN_MAX = 255;\n public static final int EDAM_NOTEBOOK_NAME_LEN_MAX = 100;\n public static final int EDAM_TAG_NAME_LEN_MAX = 100;\n\n}", "public interface ENNote extends ENObject {\n\n public ENObject getNotebook();\n\n public void setNotebook(ENObject notebook);\n\n public List<List<StyleText>> getContent();\n\n public void setContent(List<List<StyleText>> content);\n\n public List<File> getAttachments();\n\n public void setAttachments(List<File> files);\n\n public List<String> getTags();\n\n public abstract void setTags(List<String> tags);\n\n public abstract String getComments();\n\n public abstract void setComments(String comments);\n\n public abstract int getTabWidth();\n\n public abstract void setTabWidth(int tabWidth);\n\n}", "public enum EDAMDataModel {\n\n Note_noteGuid {\n @Override\n public String toString() {\n return Constants.ENML_MODEL_NOTE_NOTEGUID;\n }\n },\n\n Note_notebookGuid {\n @Override\n public String toString() {\n return Constants.ENML_MODEL_NOTE_NOTEBOOKGUID;\n }\n },\n\n Notebook_guid {\n @Override\n public String toString() {\n return Constants.ENML_MODEL_NOTEBOOKGUID;\n }\n };\n\n public static EDAMDataModel forName(final String name) throws IllegalArgumentException {\n EDAMDataModel[] values = EDAMDataModel.values();\n for (EDAMDataModel value : values) {\n if (value.toString().equalsIgnoreCase(name)) {\n return value;\n }\n }\n throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name));\n }\n}", "public final class ListUtil {\n\n public static String[] toStringArray(final Collection<String> list) {\n if (list == null) {\n return null;\n }\n String[] array = new String[list.size()];\n return list.toArray(array);\n }\n\n public static String[] toStringArray(final List<?> list, final ListStringizer stringizer) {\n if (list == null) {\n return null;\n }\n String[] array = new String[list.size()];\n for (int i = 0; i < list.size(); i++) {\n array[i] = stringizer.element(list.get(i));\n }\n return array;\n }\n\n public static List<String> toStringList(final List<?> list, final ListStringizer stringizer) {\n if (list == null) {\n return null;\n }\n List<String> strList = list();\n for (int i = 0; i < list.size(); i++) {\n strList.add(stringizer.element(list.get(i)));\n }\n return strList;\n }\n\n public static Map<String, String> toStringMap(final List<?> list, final MapStringizer stringizer) {\n if (list == null) {\n return null;\n }\n Map<String, String> map = MapUtil.map();\n for (int i = 0; i < list.size(); i++) {\n map.put(stringizer.key(list.get(i)), stringizer.value(list.get(i)));\n }\n return map;\n }\n\n public static <T> List<T> toList(final T[] array) {\n List<T> l = list(array.length);\n l.addAll(Arrays.asList(array));\n return l;\n }\n\n public static <T> List<T> list(final int initialCapacity) {\n return new ArrayList<T>(initialCapacity);\n }\n\n public static <T> List<T> list() {\n return new ArrayList<T>();\n }\n\n @SafeVarargs\n public static <T> List<T> list(final T... objects) {\n List<T> l = list();\n l.addAll(toList(objects));\n return l;\n }\n\n public static boolean isNullOrEmptyList(final List<?> list) {\n return list == null || list.size() == 0;\n }\n\n public static boolean isNullList(final Collection<?> list) {\n return list == null;\n }\n\n public static <T> boolean isIndexOutOfBounds(final List<T> list, final int index) {\n return isNullList(list) || index >= 0 && index < list.size();\n }\n\n public static <T> void replace(final List<T> list, final T newElement, final int index) {\n if (!isIndexOutOfBounds(list, index)) {\n list.remove(index);\n list.add(index, newElement);\n }\n }\n\n public static boolean isEqualList(final List<?> one, final List<?> other) {\n return isEqualList(one, other, false);\n }\n\n public static boolean isEqualList(final List<?> one, final List<?> other, final boolean compareOrder) {\n if (one == other) {\n return true;\n }\n if (isNullList(one) || isNullList(other)) {\n return false;\n }\n if (one.size() != other.size()) {\n return false;\n }\n if (compareOrder) {\n Iterator<?> iter1 = one.iterator();\n Iterator<?> iter2 = other.iterator();\n while (iter1.hasNext() && iter2.hasNext()) {\n if (!ObjectUtil.isEqualObject(iter1.next(), iter2.next())) {\n return false;\n }\n }\n } else {\n List<Integer> matchedIndex = ListUtil.list();\n andContinue: for (Object o1 : one) {\n for (int i = 0; i < other.size(); i++) {\n if (matchedIndex.contains(i)) {\n continue;\n }\n if (ObjectUtil.isEqualObject(o1, other.get(i), compareOrder)) {\n matchedIndex.add(i);\n break andContinue;\n }\n }\n return false;\n }\n }\n return true;\n }\n\n public static <E> List<E> cloneList(final ArrayList<E> source) {\n return cloneList(source, false);\n }\n\n public static <E> List<E> cloneList(final ArrayList<E> source, final boolean deep) {\n if (!deep) {\n return ObjectUtils.clone(source);\n }\n if (isNullList(source)) {\n return null;\n }\n List<E> list = list(source.size());\n for (E e : source) {\n list.add(ObjectUtil.cloneObject(e, deep));\n }\n return list;\n }\n\n}" ]
import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.Messages; import org.lttpp.eemory.client.NoteOps; import org.lttpp.eemory.client.StoreClientFactory; import org.lttpp.eemory.client.metadata.EDAMLimits; import org.lttpp.eemory.client.model.ENNote; import org.lttpp.eemory.enml.ENML; import org.lttpp.eemory.exception.EDAMDataModel; import org.lttpp.eemory.exception.NoDataFoundException; import org.lttpp.eemory.util.ListUtil; import org.w3c.dom.DOMException; import org.xml.sax.SAXException; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.Note; import com.evernote.thrift.TException;
package org.lttpp.eemory.client.impl; public class NoteOpsTextImpl extends NoteOps { public NoteOpsTextImpl(final StoreClientFactory factory) { super(factory); } @Override public void updateOrCreate(final ENNote args) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException, ParserConfigurationException, SAXException, IOException, DOMException, NoDataFoundException { if (ListUtil.isNullOrEmptyList(args.getContent())) { throw new NoDataFoundException(Messages.Plugin_Error_NoText); } if (shouldUpdate(args)) { update(args); } else { create(args); } } private void create(final ENNote args) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException, ParserConfigurationException, SAXException, IOException { Note note = new Note();
note.setTitle(StringUtils.abbreviate(args.getName(), EDAMLimits.EDAM_NOTE_TITLE_LEN_MAX));
3
data-integrations/salesforce
src/main/java/io/cdap/plugin/salesforce/plugin/source/batch/SalesforceBulkRecordReader.java
[ "public class BulkAPIBatchException extends RuntimeException {\n private BatchInfo batchInfo;\n\n public BulkAPIBatchException(String message, BatchInfo batchInfo) {\n super(String.format(\"%s. BatchId='%s', Reason='%s'\", message, batchInfo.getId(), batchInfo.getStateMessage()));\n this.batchInfo = batchInfo;\n }\n\n public BatchInfo getBatchInfo() {\n return batchInfo;\n }\n}", "public class SalesforceConnectionUtil {\n\n /**\n * Based on given Salesforce credentials, attempt to establish {@link PartnerConnection}.\n * This is mainly used to obtain sObject describe results.\n *\n * @param credentials Salesforce credentials\n * @return partner connection instance\n * @throws ConnectionException in case error when establishing connection\n */\n public static PartnerConnection getPartnerConnection(AuthenticatorCredentials credentials)\n throws ConnectionException {\n ConnectorConfig connectorConfig = Authenticator.createConnectorConfig(credentials);\n return new PartnerConnection(connectorConfig);\n }\n\n /**\n * Creates {@link AuthenticatorCredentials} instance based on given {@link Configuration}.\n *\n * @param conf hadoop job configuration\n * @return authenticator credentials\n */\n public static AuthenticatorCredentials getAuthenticatorCredentials(Configuration conf) {\n String oAuthToken = conf.get(SalesforceConstants.CONFIG_OAUTH_TOKEN);\n String instanceURL = conf.get(SalesforceConstants.CONFIG_OAUTH_INSTANCE_URL);\n if (oAuthToken != null && instanceURL != null) {\n return new AuthenticatorCredentials(new OAuthInfo(oAuthToken, instanceURL));\n }\n\n return new AuthenticatorCredentials(conf.get(SalesforceConstants.CONFIG_USERNAME),\n conf.get(SalesforceConstants.CONFIG_PASSWORD),\n conf.get(SalesforceConstants.CONFIG_CONSUMER_KEY),\n conf.get(SalesforceConstants.CONFIG_CONSUMER_SECRET),\n conf.get(SalesforceConstants.CONFIG_LOGIN_URL));\n }\n}", "public class Authenticator {\n private static final Gson GSON = new Gson();\n\n /**\n * Authenticates via oauth2 to salesforce and returns a connectorConfig\n * which can be used by salesforce libraries to make a connection.\n *\n * @param credentials information to log in\n *\n * @return ConnectorConfig which can be used to create BulkConnection and PartnerConnection\n */\n public static ConnectorConfig createConnectorConfig(AuthenticatorCredentials credentials) {\n try {\n OAuthInfo oAuthInfo = getOAuthInfo(credentials);\n ConnectorConfig connectorConfig = new ConnectorConfig();\n connectorConfig.setSessionId(oAuthInfo.getAccessToken());\n String apiVersion = SalesforceConstants.API_VERSION;\n String restEndpoint = String.format(\"%s/services/async/%s\", oAuthInfo.getInstanceURL(), apiVersion);\n String serviceEndPoint = String.format(\"%s/services/Soap/u/%s\", oAuthInfo.getInstanceURL(), apiVersion);\n connectorConfig.setRestEndpoint(restEndpoint);\n connectorConfig.setServiceEndpoint(serviceEndPoint);\n // This should only be false when doing debugging.\n connectorConfig.setCompression(true);\n // Set this to true to see HTTP requests and responses on stdout\n connectorConfig.setTraceMessage(false);\n\n return connectorConfig;\n } catch (Exception e) {\n throw new RuntimeException(\"Connection to salesforce with plugin configurations failed\", e);\n }\n }\n\n /**\n * Authenticate via oauth2 to salesforce and return response to auth request.\n *\n * @param credentials information to log in\n *\n * @return AuthResponse response to http request\n */\n public static OAuthInfo getOAuthInfo(AuthenticatorCredentials credentials) throws Exception {\n OAuthInfo oAuthInfo = credentials.getOAuthInfo();\n if (oAuthInfo != null) {\n return oAuthInfo;\n }\n\n SslContextFactory sslContextFactory = new SslContextFactory();\n HttpClient httpClient = new HttpClient(sslContextFactory);\n try {\n httpClient.start();\n String response = httpClient.POST(credentials.getLoginUrl()).param(\"grant_type\", \"password\")\n .param(\"client_id\", credentials.getConsumerKey())\n .param(\"client_secret\", credentials.getConsumerSecret())\n .param(\"username\", credentials.getUsername())\n .param(\"password\", credentials.getPassword()).send().getContentAsString();\n\n AuthResponse authResponse = GSON.fromJson(response, AuthResponse.class);\n\n if (!Strings.isNullOrEmpty(authResponse.getError())) {\n throw new IllegalArgumentException(\n String.format(\"Cannot authenticate to Salesforce with given credentials. ServerResponse='%s'\", response));\n }\n\n return new OAuthInfo(authResponse.getAccessToken(), authResponse.getInstanceUrl());\n } finally {\n httpClient.stop();\n }\n }\n}", "public class AuthenticatorCredentials implements Serializable {\n\n private final OAuthInfo oAuthInfo;\n private final String username;\n private final String password;\n private final String consumerKey;\n private final String consumerSecret;\n private final String loginUrl;\n\n public AuthenticatorCredentials(OAuthInfo oAuthInfo) {\n this(Objects.requireNonNull(oAuthInfo), null, null, null, null, null);\n }\n\n public AuthenticatorCredentials(String username, String password,\n String consumerKey, String consumerSecret, String loginUrl) {\n this(null, Objects.requireNonNull(username), Objects.requireNonNull(password), Objects.requireNonNull(consumerKey),\n Objects.requireNonNull(consumerSecret), Objects.requireNonNull(loginUrl));\n }\n\n private AuthenticatorCredentials(@Nullable OAuthInfo oAuthInfo,\n @Nullable String username,\n @Nullable String password,\n @Nullable String consumerKey,\n @Nullable String consumerSecret,\n @Nullable String loginUrl) {\n this.oAuthInfo = oAuthInfo;\n this.username = username;\n this.password = password;\n this.consumerKey = consumerKey;\n this.consumerSecret = consumerSecret;\n this.loginUrl = loginUrl;\n }\n\n @Nullable\n public OAuthInfo getOAuthInfo() {\n return oAuthInfo;\n }\n\n @Nullable\n public String getUsername() {\n return username;\n }\n\n @Nullable\n public String getPassword() {\n return password;\n }\n\n @Nullable\n public String getConsumerKey() {\n return consumerKey;\n }\n\n @Nullable\n public String getConsumerSecret() {\n return consumerSecret;\n }\n\n @Nullable\n public String getLoginUrl() {\n return loginUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n AuthenticatorCredentials that = (AuthenticatorCredentials) o;\n\n return Objects.equals(username, that.username) &&\n Objects.equals(password, that.password) &&\n Objects.equals(consumerKey, that.consumerKey) &&\n Objects.equals(consumerSecret, that.consumerSecret) &&\n Objects.equals(loginUrl, that.loginUrl);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(username, password, consumerKey, consumerSecret, loginUrl);\n }\n}", "public class SalesforceSourceConstants {\n\n public static final String PROPERTY_DATETIME_AFTER = \"datetimeAfter\";\n public static final String PROPERTY_DATETIME_BEFORE = \"datetimeBefore\";\n public static final String PROPERTY_DURATION = \"duration\";\n public static final String PROPERTY_OFFSET = \"offset\";\n public static final String PROPERTY_SCHEMA = \"schema\";\n\n public static final String PROPERTY_QUERY = \"query\";\n public static final String PROPERTY_SOBJECT_NAME = \"sObjectName\";\n public static final String PROPERTY_OPERATION = \"operation\";\n\n public static final String PROPERTY_PK_CHUNK_ENABLE_NAME = \"enablePKChunk\";\n public static final String PROPERTY_CHUNK_SIZE_NAME = \"chunkSize\";\n public static final String PROPERTY_PARENT_NAME = \"parent\";\n\n public static final String PROPERTY_WHITE_LIST = \"whiteList\";\n public static final String PROPERTY_BLACK_LIST = \"blackList\";\n public static final String PROPERTY_SOBJECT_NAME_FIELD = \"sObjectNameField\";\n\n public static final String CONFIG_SCHEMAS = \"mapred.salesforce.input.schemas\";\n public static final String CONFIG_QUERY_SPLITS = \"mapred.salesforce.input.query.splits\";\n\n public static final String HEADER_ENABLE_PK_CHUNK = \"Sforce-Enable-PKChunking\";\n public static final String HEADER_VALUE_PK_CHUNK = \"chunkSize=%d\";\n public static final String HEADER_PK_CHUNK_PARENT = \"parent=%s\";\n\n public static final String CONFIG_SOBJECT_NAME_FIELD = \"mapred.salesforce.input.sObjectNameField\";\n\n public static final int WIDE_QUERY_MAX_BATCH_COUNT = 2000;\n // https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/\n // async_api_headers_enable_pk_chunking.htm\n public static final int MAX_PK_CHUNK_SIZE = 250000;\n public static final int DEFAULT_PK_CHUNK_SIZE = 100000;\n public static final int MIN_PK_CHUNK_SIZE = 1;\n // https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/\n // async_api_headers_enable_pk_chunking.htm\n public static final List<String> SUPPORTED_OBJECTS_WITH_PK_CHUNK = Arrays.asList(\"Account\",\n \"AccountContactRelation\",\n \"AccountTeamMember\",\n \"AiVisitSummary\",\n \"Asset\",\n \"B2BMktActivity\",\n \"B2BMktProspect\",\n \"Campaign\",\n \"CampaignMember\",\n \"CandidateAnswer\",\n \"Case\",\n \"CaseArticle\",\n \"CaseComment\",\n \"Claim\",\n \"ClaimParticipant\",\n \"Contact\",\n \"ContractLineItem\",\n \"ConversationEntry\",\n \"CustomerProperty\",\n \"EinsteinAnswerFeedback\",\n \"EmailMessage\",\n \"EngagementScore\",\n \"Event\",\n \"EventRelation\",\n \"FeedItem\",\n \"Individual\",\n \"InsurancePolicy\",\n \"InsurancePolicyAsset\",\n \"InsurancePolicyParticipant\",\n \"Lead\",\n \"LeadInsight\",\n \"LiveChatTranscript\",\n \"LoginHistory\",\n \"LoyaltyLedger\",\n \"LoyaltyMemberCurrency\",\n \"LoyaltyMemberTier\",\n \"LoyaltyPartnerProduct\",\n \"LoyaltyProgramMember\",\n \"LoyaltyProgramPartner\",\n \"Note\",\n \"ObjectTerritory2Association\",\n \"Opportunity\",\n \"OpportunityContactRole\",\n \"OpportunityHistory\",\n \"OpportunityLineItem\",\n \"OpportunitySplit\",\n \"OpportunityTeamMember\",\n \"Pricebook2\",\n \"PricebookEntry\",\n \"Product2\",\n \"ProductConsumed\",\n \"ProductRequired\",\n \"QuickText\",\n \"Quote\",\n \"QuoteLineItem\",\n \"ReplyText\",\n \"ScoreIntelligence\",\n \"ServiceContract\",\n \"Task\",\n \"TermDocumentFrequency\",\n \"TransactionJournal\",\n \"User\",\n \"UserRole\",\n \"VoiceCall\",\n \"WorkOrder\",\n \"WorkOrderLineItem\");\n\n /**\n * Salesforce Bulk API has a limitation, which is 10 minutes per processing of a batch\n */\n public static final long GET_BATCH_WAIT_TIME_SECONDS = 600;\n /**\n * Sleep time between polling the batch status\n */\n public static final long GET_BATCH_RESULTS_SLEEP_MS = 500;\n /**\n * Number of tries while polling the batch status\n */\n public static final long GET_BATCH_RESULTS_TRIES = GET_BATCH_WAIT_TIME_SECONDS * (1000 / GET_BATCH_RESULTS_SLEEP_MS);\n}" ]
import com.google.common.annotations.VisibleForTesting; import com.sforce.async.AsyncApiException; import com.sforce.async.BatchInfo; import com.sforce.async.BatchStateEnum; import com.sforce.async.BulkConnection; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.salesforce.BulkAPIBatchException; import io.cdap.plugin.salesforce.SalesforceConnectionUtil; import io.cdap.plugin.salesforce.authenticator.Authenticator; import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials; import io.cdap.plugin.salesforce.plugin.source.batch.util.SalesforceSourceConstants; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.csv.QuoteMode; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map;
/* * Copyright © 2019 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.salesforce.plugin.source.batch; /** * RecordReader implementation, which reads a single Salesforce batch from bulk job * provided in InputSplit */ public class SalesforceBulkRecordReader extends RecordReader<Schema, Map<String, ?>> { private static final Logger LOG = LoggerFactory.getLogger(SalesforceBulkRecordReader.class); private final Schema schema; private CSVParser csvParser; private Iterator<CSVRecord> parserIterator; private Map<String, ?> value; private String jobId; private BulkConnection bulkConnection; private String batchId; private String[] resultIds; private int resultIdIndex; public SalesforceBulkRecordReader(Schema schema) { this(schema, null, null, null); } @VisibleForTesting SalesforceBulkRecordReader(Schema schema, String jobId, String batchId, String[] resultIds) { this.schema = schema; this.resultIdIndex = 0; this.jobId = jobId; this.batchId = batchId; this.resultIds = resultIds; } /** * Get csv from a single Salesforce batch * * @param inputSplit specifies batch details * @param taskAttemptContext task context * @throws IOException can be due error during reading query * @throws InterruptedException interrupted sleep while waiting for batch results */ @Override public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { SalesforceSplit salesforceSplit = (SalesforceSplit) inputSplit; jobId = salesforceSplit.getJobId(); batchId = salesforceSplit.getBatchId(); LOG.debug("Executing Salesforce Batch Id: '{}' for Job Id: '{}'", batchId, jobId); Configuration conf = taskAttemptContext.getConfiguration(); try { AuthenticatorCredentials credentials = SalesforceConnectionUtil.getAuthenticatorCredentials(conf); bulkConnection = new BulkConnection(Authenticator.createConnectorConfig(credentials)); resultIds = waitForBatchResults(bulkConnection); LOG.debug("Batch {} returned {} results", batchId, resultIds.length); setupParser(); } catch (AsyncApiException e) { throw new RuntimeException("There was issue communicating with Salesforce", e); } } /** * Reads single record from csv. * * @return returns false if no more data to read */ @Override public boolean nextKeyValue() throws IOException { if (parserIterator == null) { return false; } while (!parserIterator.hasNext()) { if (resultIdIndex == resultIds.length) { // No more result ids to process. return false; } // Close CSV parser for previous result. if (csvParser != null && !csvParser.isClosed()) { // this also closes the inputStream csvParser.close(); csvParser = null; } try { // Parse the next result. setupParser(); } catch (AsyncApiException e) { throw new IOException("Failed to query results", e); } } value = parserIterator.next().toMap(); return true; } @Override public Schema getCurrentKey() { return schema; } @Override public Map<String, ?> getCurrentValue() { return value; } @Override public float getProgress() { return 0.0f; } @Override public void close() throws IOException { if (csvParser != null && !csvParser.isClosed()) { // this also closes the inputStream csvParser.close(); csvParser = null; } } @VisibleForTesting void setupParser() throws IOException, AsyncApiException { if (resultIdIndex >= resultIds.length) { throw new IllegalArgumentException(String.format("Invalid resultIdIndex %d, should be less than %d", resultIdIndex, resultIds.length)); } InputStream queryResponseStream = bulkConnection.getQueryResultStream(jobId, batchId, resultIds[resultIdIndex]); CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader() .withQuoteMode(QuoteMode.ALL) .withAllowMissingColumnNames(false); csvParser = CSVParser.parse(queryResponseStream, StandardCharsets.UTF_8, csvFormat); if (csvParser.getHeaderMap().isEmpty()) { throw new IllegalStateException("Empty response was received from Salesforce, but csv header was expected."); } parserIterator = csvParser.iterator(); resultIdIndex++; } /** * Wait until a batch with given batchId succeeds, or throw an exception * * @param bulkConnection bulk connection instance * @return array of batch result ids * @throws AsyncApiException if there is an issue creating the job * @throws InterruptedException sleep interrupted */ private String[] waitForBatchResults(BulkConnection bulkConnection) throws AsyncApiException, InterruptedException { BatchInfo info = null; for (int i = 0; i < SalesforceSourceConstants.GET_BATCH_RESULTS_TRIES; i++) { try { info = bulkConnection.getBatchInfo(jobId, batchId); } catch (AsyncApiException e) { if (i == SalesforceSourceConstants.GET_BATCH_RESULTS_TRIES - 1) { throw e; } LOG.warn("Failed to get info for batch {}. Will retry after some time.", batchId, e); continue; } if (info.getState() == BatchStateEnum.Completed) { return bulkConnection.getQueryResultList(jobId, batchId).getResult(); } else if (info.getState() == BatchStateEnum.Failed) {
throw new BulkAPIBatchException("Batch failed", info);
0
JanWiemer/jacis
src/test/java/org/jacis/objectadapter/microstream/JacisStoreWithMicrostreamCloningTxTest.java
[ "@JacisApi\r\npublic class JacisTransactionHandle {\r\n\r\n /** The id of the transaction */\r\n private final String txId;\r\n /** Description for the transaction giving some more information about the purpose of the transaction (for logging and debugging) */\r\n private final String txDescription;\r\n /** A reference to the external (global) transaction (e.g. a JTA transaction) */\r\n private final Object externalTransaction;\r\n /** Creation timestamp in milliseconds (<code>System.currentTimeMillis()</code>) */\r\n private final long creationTimestampMs;\r\n\r\n /**\r\n * Creates a transaction handle with the passed parameters.\r\n *\r\n * @param txId The id of the transaction\r\n * @param txDescription A description for the transaction giving some more information about the purpose of the transaction (for logging and debugging)\r\n * @param externalTransaction A reference to the external (global) transaction (e.g. a JTA transaction) this handle represents\r\n */\r\n public JacisTransactionHandle(String txId, String txDescription, Object externalTransaction) {\r\n this.txId = txId;\r\n this.txDescription = txDescription;\r\n this.externalTransaction = externalTransaction;\r\n this.creationTimestampMs = System.currentTimeMillis();\r\n }\r\n\r\n /** @return The id of the transaction */\r\n public String getTxId() {\r\n return txId;\r\n }\r\n\r\n /** @return A description for the transaction giving some more information about the purpose of the transaction (for logging and debugging) */\r\n public String getTxDescription() {\r\n return txDescription;\r\n }\r\n\r\n /** @return A reference to the external (global) transaction (e.g. a JTA transaction) this handle represents */\r\n public Object getExternalTransaction() {\r\n return externalTransaction;\r\n }\r\n\r\n /** @return Creation timestamp in milliseconds (System.currentTimeMillis()) */\r\n public long getCreationTimestampMs() {\r\n return creationTimestampMs;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return externalTransaction.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n } else if (obj == null) {\r\n return false;\r\n } else if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n JacisTransactionHandle that = (JacisTransactionHandle) obj;\r\n return externalTransaction == null ? that.externalTransaction == null : externalTransaction.equals(that.externalTransaction);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"TX(\" + txId + \": \" + txDescription + \")\";\r\n }\r\n\r\n}\r", "@JacisApi\r\npublic class JacisStaleObjectException extends RuntimeException {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n /** detail message describing the reason for the stale object exception */\r\n private String details;\r\n\r\n public JacisStaleObjectException(String message) {\r\n super(message);\r\n }\r\n\r\n public String getDetails() {\r\n return details;\r\n }\r\n\r\n public JacisStaleObjectException setDetails(String details) {\r\n this.details = details;\r\n return this;\r\n }\r\n\r\n}\r", "@JacisApi\r\npublic class JacisLocalTransaction {\r\n\r\n /**\r\n * Unique id for the transaction (set with the constructor)\r\n */\r\n private final String txId;\r\n /** Reference to the container this local transaction belongs to (needed to commit / rollback a transaction) */\r\n private JacisContainer jacisContainer;\r\n /** The transaction handle for this local transaction. Transaction handles are used inside the store to represent local or external transactions. */\r\n private JacisTransactionHandle jacisTransactionHandle;\r\n /** A flag indicating if the transaction already has been destroyed. */\r\n private boolean destroyed = false;\r\n\r\n JacisLocalTransaction(String txId) {\r\n this.txId = txId;\r\n }\r\n\r\n JacisLocalTransaction associateWithJacisTransaction(JacisTransactionHandle txHandle, JacisContainer container) {\r\n if (!txId.equals(txHandle.getTxId())) {\r\n throw new IllegalArgumentException(\"Passed txHandle \" + txHandle + \" does not match the id of the local transaction \" + txId);\r\n }\r\n this.jacisTransactionHandle = txHandle;\r\n this.jacisContainer = container;\r\n return this;\r\n }\r\n\r\n /** @return A description of the transaction (given when creating the transaction) */\r\n public String getTxDescription() {\r\n return jacisTransactionHandle == null ? null : jacisTransactionHandle.getTxDescription();\r\n }\r\n\r\n /**\r\n * Prepare the local transaction.\r\n * This method is calling the {@link JacisContainer#internalPrepare(JacisTransactionHandle)} method on the container\r\n * with the transaction handle associated with this local transaction.\r\n * \r\n * @throws JacisNoTransactionException Thrown if this local transaction is no longer active.\r\n */\r\n public void prepare() throws JacisNoTransactionException {\r\n checkActive();\r\n jacisContainer.internalPrepare(jacisTransactionHandle);\r\n }\r\n\r\n /**\r\n * Commit the local transaction.\r\n * This method is calling the {@link JacisContainer#internalCommit(JacisTransactionHandle)} method on the container\r\n * with the transaction handle associated with this local transaction.\r\n * \r\n * @throws JacisNoTransactionException Thrown if this local transaction is no longer active.\r\n */\r\n public void commit() throws JacisNoTransactionException {\r\n checkActive();\r\n jacisContainer.internalCommit(jacisTransactionHandle);\r\n destroy();\r\n }\r\n\r\n /**\r\n * Rollback the local transaction.\r\n * This method is calling the {@link JacisContainer#internalRollback(JacisTransactionHandle)} method on the container\r\n * with the transaction handle associated with this local transaction.\r\n * \r\n * @throws JacisNoTransactionException Thrown if this local transaction is no longer active.\r\n */\r\n public void rollback() throws JacisNoTransactionException {\r\n checkActive();\r\n jacisContainer.internalRollback(jacisTransactionHandle);\r\n destroy();\r\n }\r\n\r\n private void checkActive() throws JacisNoTransactionException {\r\n if (destroyed) {\r\n throw new JacisNoTransactionException(\"Transaction already destroyed: \" + this);\r\n }\r\n }\r\n\r\n private void destroy() {\r\n jacisContainer = null;\r\n jacisTransactionHandle = null;\r\n destroyed = true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return txId.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n } else if (obj == null) {\r\n return false;\r\n } else if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n JacisLocalTransaction that = (JacisLocalTransaction) obj;\r\n return txId == null ? that.txId == null : txId.equals(that.txId);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"TX(\" + txId + \")\";\r\n }\r\n\r\n}\r", "@JacisApi\r\npublic interface JacisStore<K, TV> {\r\n\r\n /** @return the reference to the JACIS container this store belongs to */\r\n JacisContainer getContainer();\r\n\r\n /** @return the store identifier uniquely identifying this store inside the container */\r\n JacisContainer.StoreIdentifier getStoreIdentifier();\r\n\r\n /** @return the object type specification for the objects stored in this store */\r\n JacisObjectTypeSpec<K, TV, ?> getObjectTypeSpec();\r\n\r\n /** @return the object adapter defining how to copy objects from the committed view to a transactional view and back */\r\n JacisObjectAdapter<TV, ?> getObjectAdapter();\r\n\r\n /** @return the list of listeners notified on each modification on the committed values in the store */\r\n List<JacisModificationListener<K, TV>> getModificationListeners();\r\n\r\n /**\r\n * Add the passed listener (implementing the interface {@link JacisModificationListener}).\r\n * The listener will be notified on each modification on the committed values in the store.\r\n *\r\n * @param listener the listener to notify\r\n * @return this store for method chaining\r\n */\r\n JacisStore<K, TV> registerModificationListener(JacisModificationListener<K, TV> listener);\r\n\r\n /** @return the registry of tracked views for this store that are kept up to date on each commit automatically */\r\n TrackedViewRegistry<K, TV> getTrackedViewRegistry();\r\n\r\n /**\r\n * Create and register a non-unique Index to access the values in the store by an index key.\r\n * \r\n * @param <IK> The type of the index key.\r\n * @param indexName The Name of the index (has to be unique).\r\n * @param indexKeyFunction The function to extract the index key from a value.\r\n * @return An object representing the index and providing methods to access objects by the index key.\r\n */\r\n <IK> JacisNonUniqueIndex<IK, K, TV> createNonUniqueIndex(String indexName, Function<TV, IK> indexKeyFunction);\r\n\r\n /**\r\n * Get a registered non-unique Index to access the values in the store by an index key.\r\n * \r\n * @param <IK> The type of the index key.\r\n * @param indexName The Name of the index (an index has to be registered with this name).\r\n * @return An object representing the index and providing methods to access objects by the index key.\r\n */\r\n <IK> JacisNonUniqueIndex<IK, K, TV> getNonUniqueIndex(String indexName);\r\n\r\n /**\r\n * Create and register an unique Index to access the values in the store by an index key.\r\n * \r\n * @param <IK> The type of the index key.\r\n * @param indexName The Name of the index (has to be unique).\r\n * @param indexKeyFunction The function to extract the index key from a value.\r\n * @return An object representing the index and providing methods to access objects by the index key.\r\n */\r\n <IK> JacisUniqueIndex<IK, K, TV> createUniqueIndex(String indexName, Function<TV, IK> indexKeyFunction);\r\n\r\n /**\r\n * Get a registered unique Index to access the values in the store by an index key.\r\n * \r\n * @param <IK> The type of the index key.\r\n * @param indexName The Name of the index (an index has to be registered with this name).\r\n * @return An object representing the index and providing methods to access objects by the index key.\r\n */\r\n <IK> JacisUniqueIndex<IK, K, TV> getUniqueIndex(String indexName);\r\n\r\n /**\r\n * Create a read only view of the current transaction context that can be used (read only) in a different thread.\r\n * This can be used to share one single transaction view in several threads.\r\n * Before accessing the object store the other thread should set the returned context\r\n * with the method {@link #startReadOnlyTransactionWithContext(JacisReadOnlyTransactionContext)}.\r\n * Note: the returned context is threadsafe!\r\n *\r\n * @param withTxName transaction name used for the read only view.\r\n * @return a read only view of the current transaction context.\r\n */\r\n JacisReadOnlyTransactionContext createReadOnlyTransactionView(String withTxName);\r\n\r\n /**\r\n * Create a read only view of the current transaction context that can be used (read only) in a different thread.\r\n * This can be used to share one single transaction view in several threads.\r\n * Before accessing the object store the other thread should set the returned context\r\n * with the method {@link #startReadOnlyTransactionWithContext(JacisReadOnlyTransactionContext)}.\r\n * Note: the returned context is *not* threadsafe!\r\n *\r\n * @param withTxName transaction name used for the read only view.\r\n * @return a read only view of the current transaction context.\r\n */\r\n JacisReadOnlyTransactionContext createReadOnlyTransactionViewUnsafe(String withTxName);\r\n\r\n /**\r\n * Starts a new (read only) transaction with the passed transaction context.\r\n * The new transaction will work on a read only snapshot of the original transaction (where the context is obtained from).\r\n *\r\n * @param readOnlyTxContext the transaction context of the original transaction.\r\n */\r\n void startReadOnlyTransactionWithContext(JacisReadOnlyTransactionContext readOnlyTxContext);\r\n\r\n /**\r\n * Returns if the store contains an entry for the passed key.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n *\r\n * @param key The key of the entry to check.\r\n * @return if the store contains an entry for the passed key.\r\n */\r\n boolean containsKey(K key);\r\n\r\n /**\r\n * Returns if the object for the passed key has been updated in the current transaction.\r\n * Note that an update has to be explicitly called for an object (by calling {@link #update(Object, Object)}).\r\n * The check returns true if there exists a transactional view\r\n * and the updated flag of this entry (see {@link StoreEntryTxView#updated}) is set (set by the 'update' method).\r\n * Note that this method does not cause the referred object to be copied to the transactional view.\r\n *\r\n * @param key The key of the entry to check.\r\n * @return if the object for the passed key has been updated in the current transaction.\r\n */\r\n boolean isUpdated(K key);\r\n\r\n /**\r\n * Returns if the object for the passed key is stale.\r\n * An object is considered to be stale if after first reading it in the current transaction,\r\n * an updated version of the same object has been committed by another transaction.\r\n * Note that this method does not cause the referred object to be copied to the transactional view.\r\n *\r\n * @param key The key of the entry to check.\r\n * @return if the object for the passed key is stale.\r\n */\r\n boolean isStale(K key);\r\n\r\n /**\r\n * Checks if the object for the passed key is stale and throws a {@link JacisStaleObjectException} if so.\r\n * An object is considered to be stale if after first reading it in the current transaction,\r\n * an updated version of the same object has been committed by another transaction.\r\n * Note that this method does not cause the referred object to be copied to the transactional view.\r\n *\r\n * @param key The key of the entry to check.\r\n * @throws JacisStaleObjectException thrown if the object for the passed key is stale.\r\n */\r\n void checkStale(K key) throws JacisStaleObjectException;\r\n\r\n /**\r\n * Returns the value for the passed key.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n * If the transactional view did not already contain the entry for the key it is copied to the transactional view now.\r\n *\r\n * @param key The key of the desired entry.\r\n * @return the value for the passed key.\r\n */\r\n TV get(K key);\r\n\r\n /**\r\n * Returns the value for the passed key.\r\n * If the object is already stored in the transactional view of the current transaction this value is returned.\r\n * Otherwise the behavior depends on the object type:\r\n * If the object adapter for the store supports a read only mode, then a read only view on the committed value is returned.\r\n * Otherwise the committed entry for the key it is copied to the transactional view now.\r\n *\r\n * @param key The key of the desired entry.\r\n * @return the value for the passed key.\r\n */\r\n TV getReadOnly(K key);\r\n\r\n /**\r\n * Returns a read only projection of the object for the passed value.\r\n * First a read only view (if supported) of the object is obtained by the {@link #getReadOnly(Object)} method.\r\n * The projected is computed from the object by applying the passed projection function.\r\n *\r\n * @param key The key of the desired entry.\r\n * @param projection The projection function computing the desired return value (of the passed type 'P') from the object.\r\n * @param <P> The result type of the projection\r\n * @return a read only projection of the object for the passed value.\r\n */\r\n <P> P getProjectionReadOnly(K key, Function<TV, P> projection);\r\n\r\n /**\r\n * Returns a stream of all objects (not <code>null</code>) currently stored in the store.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n * If the transactional view did not already contain an entry it is copied to the transactional view now.\r\n *\r\n * @return a stream of all objects (not <code>null</code>) currently stored in the store.\r\n */\r\n Stream<TV> stream();\r\n\r\n /**\r\n * Returns a stream of read only views for all objects (not <code>null</code>) currently stored in the store.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n * Further note that the behavior of the method is equivalent to the behavior of the {@link #getReadOnly} method for a single object.\r\n *\r\n * @return a stream of all objects (not <code>null</code>) currently stored in the store.\r\n */\r\n Stream<TV> streamReadOnly();\r\n\r\n /**\r\n * Returns a stream of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n * If supported the filter predicate is checked on a read only view of the object (without cloning it).\r\n * Only the objects passing the filter are is copied to the transactional view (if they are not yet contained there).\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting stream (<code>null</code> means all objects should be contained)\r\n * @return a stream of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n Stream<TV> stream(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a stream of read only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * Note that the method operates on the committed values merged with the current transactional view (see class description).\r\n * If supported the filter predicate is checked on a read only view of the object (without cloning it).\r\n * Further note that the behavior of the method is equivalent to the behavior of the {@link #getReadOnly} method for a single object\r\n * (only the objects passing the filter may be copied to the transactional view if no read only view is supported (and they are not yet contained there)).\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting stream (<code>null</code> means all objects should be contained)\r\n * @return a stream of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n Stream<TV> streamReadOnly(Predicate<TV> filter);\r\n\r\n /**\r\n * Stream all store entries updated in the current transaction (update method has been called).\r\n * \r\n * @param filter an optional filter on the updated values (null means all updated entries are included in the result).\r\n * @return a stream of key value pairs for all updated objects (the value may be null if the object has been deleted in this transaction).\r\n */\r\n Stream<KeyValuePair<K, TV>> streamAllUpdated(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of all objects (not <code>null</code>) currently stored in the store.\r\n *\r\n * @return a list of all objects (not <code>null</code>) currently stored in the store.\r\n */\r\n List<TV> getAll();\r\n\r\n /**\r\n * Returns a list of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method uses the {@link #stream(Predicate)} method and collects the results to a list.\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getAll(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store.\r\n *\r\n * @return a list of read-only views for all objects (not <code>null</code>) currently stored in the store.\r\n */\r\n List<TV> getAllReadOnly();\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method uses the {@link #streamReadOnly(Predicate)} method and collects the results to a list.\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getAllReadOnly(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store.\r\n * The method is independent from an active transaction and takes a read only snapshot of the objects committed in the store.\r\n *\r\n * @return a list of read-only views for all committed objects (not <code>null</code>) currently stored in the store.\r\n */\r\n List<TV> getReadOnlySnapshot();\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method is independent from an active transaction and takes a read only snapshot of the objects committed in the store.\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of read-only views for all committed objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getReadOnlySnapshot(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method executes the {@link #getAll(Predicate)} method as an atomic operations.\r\n * Therefore this method is passed as functional parameter to the {@link #computeAtomic(Supplier)} method.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getAllAtomic(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method executes the {@link #getAllReadOnly(Predicate)} method as an atomic operations.\r\n * Therefore this method is passed as functional parameter to the {@link #computeAtomic(Supplier)} method.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getAllReadOnlyAtomic(Predicate<TV> filter);\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store.\r\n * The method is independent from an active transaction and takes a read only snapshot of the objects committed in the store.\r\n * The method executes the {@link #getReadOnlySnapshot()} method as an atomic operations\r\n * (using this method it is possible to get a snapshot without 'phantom reads').\r\n * . * Therefore this method is passed as functional parameter to the {@link #computeAtomic(Supplier)} method.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n *\r\n * @return a list of read-only views for all objects (not <code>null</code>) currently stored in the store.\r\n */\r\n List<TV> getReadOnlySnapshotAtomic();\r\n\r\n /**\r\n * Returns a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n * The method is independent from an active transaction and takes a read only snapshot of the objects committed in the store.\r\n * The method executes the {@link #getReadOnlySnapshot(Predicate)} method as an atomic operations\r\n * (using this method it is possible to get a snapshot without 'phantom reads').\r\n * Therefore this method is passed as functional parameter to the {@link #computeAtomic(Supplier)} method.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the resulting list (<code>null</code> means all objects should be contained)\r\n * @return a list of read-only views for all objects (not <code>null</code>) currently stored in the store filtered by the passed filter.\r\n */\r\n List<TV> getReadOnlySnapshotAtomic(Predicate<TV> filter);\r\n\r\n /**\r\n * Helper method to get a paging access to the elements (read only versions) stored in the store.\r\n * First the elements are filtered and sorted according to the passed predicate and comparator,\r\n * afterwards the desired page is extracted according to the passed offset and page size.\r\n *\r\n * @param filter a filter predicate deciding if an object should be contained in the paged date (<code>null</code> means all objects should be contained)\r\n * @param comparator a comparator to sort the object.\r\n * @param offset The offset of the desired page in the sorted and filtered list of objects.\r\n * @param pageSize The size of the desired page.\r\n * @return the page of n (=pageSize) objects starting at the offset in the filtered and sorted list\r\n */\r\n List<TV> getPageReadOnly(Predicate<TV> filter, Comparator<TV> comparator, long offset, long pageSize);\r\n\r\n /**\r\n * Helper method to get a paging access to the elements (read only versions) stored in the store.\r\n * The method returns wrapped (or transformed) versions of the objects.\r\n * This way the information in the objects can e.g. be enriched by additional information.\r\n * First the elements are filtered and sorted according to the passed predicate and comparator,\r\n * afterwards the desired page is extracted according to the passed offset and page size.\r\n *\r\n * @param wrapper a function used to wrap a (read only) object before filtering, sorting and returning them\r\n * @param filter a filter predicate deciding if an object should be contained in the paged date (<code>null</code> means all objects should be contained)\r\n * @param comparator a comparator to sort the object.\r\n * @param offset The offset of the desired page in the sorted and filtered list of objects.\r\n * @param pageSize The size of the desired page.\r\n * @param <PV> The type of the wrapper object used in the returned page\r\n * @return the page of n (=pageSize) wrapped objects starting at the offset in the filtered and sorted list\r\n */\r\n <PV> List<PV> getWrapperPageReadOnly(Function<TV, PV> wrapper, Predicate<PV> filter, Comparator<PV> comparator, long offset, long pageSize);\r\n\r\n /**\r\n * Update the object for the passed key with the passed object value.\r\n * Note that the passed object instance may be the same (modified) instance obtained from the store before,\r\n * but also can be another instance.\r\n * Internally the value of the transactional view (see {@link StoreEntryTxView#txValue}) for this object is replaced with the passed value\r\n * and the transactional view is marked as updated (see {@link StoreEntryTxView#updated}).\r\n *\r\n * @param key The key of the object to update.\r\n * @param value The updated object instance.\r\n * @throws JacisTransactionAlreadyPreparedForCommitException if the current transaction has already been prepared for commit\r\n */\r\n void update(K key, TV value) throws JacisTransactionAlreadyPreparedForCommitException;\r\n\r\n /**\r\n * This method updates or inserts all passed values as a bulk update / insert.\r\n * The keys for the objects is computed using the mandatory keyExtractor function.\r\n * The functionality is similar to the update method for a single object (see {@link #update(Object, Object)}).\r\n * \r\n * @param values The set of objects to update or insert.\r\n * @param keyExtractor The function computing the key for each object to update or insert.\r\n * @throws JacisTransactionAlreadyPreparedForCommitException if the current transaction has already been prepared for commit\r\n */\r\n void update(Collection<TV> values, Function<TV, K> keyExtractor) throws JacisTransactionAlreadyPreparedForCommitException;\r\n\r\n /**\r\n * Remove the object for the passed key from the store (first only in the transactional view of course).\r\n * The method is equivalent to simply calling the {@link #update(Object, Object)} method with a <code>null</code> value.\r\n *\r\n * @param key The key of the object to remove.\r\n * @throws JacisTransactionAlreadyPreparedForCommitException if the current transaction has already been prepared for commit\r\n */\r\n void remove(K key) throws JacisTransactionAlreadyPreparedForCommitException;\r\n\r\n /**\r\n * Refresh the object for the passed key from the committed values. Note that all earlier modifications in the current transaction are lost.\r\n * First the current transactional view (if updated or not) is discarded.\r\n * Afterwards a fresh copy of the current committed value is stored in the transactional view by calling the {@link #get(Object)} method.\r\n *\r\n * @param key The key of the object to refresh.\r\n * @return the object for the passed key refreshed from the committed values. Note that all earlier modifications in the current transaction are lost.\r\n */\r\n TV refresh(K key);\r\n\r\n /**\r\n * Refresh the object for the passed key from the committed values if the object is not marked as updated.\r\n * Note that all earlier modifications in the current transaction are lost if the object is not marked as updated.\r\n * First the current transactional view (if updated or not) is discarded.\r\n * Afterwards a fresh copy of the current committed value is stored in the transactional view by calling the {@link #get(Object)} method.\r\n *\r\n * @param key The key of the object to refresh.\r\n * @return the object for the passed key refreshed from the committed values if the object is not marked as updated.\r\n */\r\n TV refreshIfNotUpdated(K key);\r\n\r\n /**\r\n * Initialize the store with the passed entries.\r\n * The actual key and value inserted into the store is computed by the passed extractor functions.\r\n * Note that the method initializes the store in a non transactional manner.\r\n * The store has to be empty before. During initialization all commits are blocked.\r\n * By passing the number of threads that shall insert the passed values\r\n * \r\n * @param entries The entries from which the store is initialized.\r\n * @param keyExtractor Method to extract the key from an entry.\r\n * @param valueExtractor Method to extract the value from an entry.\r\n * @param <ST> The type of the entries\r\n * @param nThreads Number of threads to use for multythreaded inserts.\r\n */\r\n <ST> void initStoreNonTransactional(List<ST> entries, Function<ST, K> keyExtractor, Function<ST, TV> valueExtractor, int nThreads);\r\n\r\n /**\r\n * Initialize the store with the passed values.\r\n * The key is computed by the passed extractor function.\r\n * Note that the method initializes the store in a non transactional manner.\r\n * The store has to be empty before. During initialization all commits are blocked.\r\n * By passing the number of threads that shall insert the passed values\r\n * \r\n * @param values The values the store is initialized with.\r\n * @param keyExtractor Method to extract the key from a value.\r\n * @param nThreads Number of threads to use for multythreaded inserts.\r\n */\r\n void initStoreNonTransactional(List<TV> values, Function<TV, K> keyExtractor, int nThreads);\r\n\r\n /**\r\n * Initialize the store with the passed key-value pairs.\r\n * Note that the method initializes the store in a non transactional manner.\r\n * The store has to be empty before. During initialization all commits are blocked.\r\n * By passing the number of threads that shall insert the passed values\r\n * \r\n * @param entries The entries (key value pairs) from which the store is initialized.\r\n * @param nThreads Number of threads to use for multythreaded inserts.\r\n */\r\n void initStoreNonTransactional(List<KeyValuePair<K, TV>> entries, int nThreads);\r\n\r\n /**\r\n * Returns the current size of the store.\r\n * Note that the size is not exact because all entries in the committed values are counted.\r\n * Since objects created or deleted in a pending transaction also have an entry with null value in the committed values\r\n * these objects are counted as well.\r\n *\r\n * @return The current size of the store.\r\n */\r\n int size();\r\n\r\n /**\r\n * Execute the passed operation (without return value) as an atomic operation.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n * Note that this operation ensures only to be atomic for the current store. It does not guarantee that e.g. simultaneously a commit for another store is done.\r\n *\r\n * @param atomicOperation The operation to execute atomically\r\n */\r\n void executeAtomic(Runnable atomicOperation);\r\n\r\n /**\r\n * Execute the passed operation (with return value) as an atomic operation.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n * Note that this operation ensures only to be atomic for the current store. It does not guarantee that e.g. simultaneously a commit for another store is done.\r\n *\r\n * @param atomicOperation The operation to execute atomically\r\n * @param <R> The return type of the operation\r\n * @return The return value of the operation\r\n */\r\n <R> R computeAtomic(Supplier<R> atomicOperation);\r\n\r\n /**\r\n * Execute the passed operation (without return value) as a global atomic operation (atomic over all stores).\r\n * The execution of global atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap),\r\n * even if the commit is (currently) executed for any other store belonging to the same JACIS container.\r\n *\r\n * @param atomicOperation The operation to execute atomically\r\n */\r\n void executeGlobalAtomic(Runnable atomicOperation);\r\n\r\n /**\r\n * Execute the passed operation (with return value) as an global atomic operation (atomic over all stores).\r\n * The execution of global atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap),\r\n * even if the commit is (currently) executed for any other store belonging to the same JACIS container.\r\n *\r\n * @param atomicOperation The operation to execute atomically\r\n * @param <R> The return type of the operation\r\n * @return The return value of the operation\r\n */\r\n <R> R computeGlobalAtomic(Supplier<R> atomicOperation);\r\n\r\n /**\r\n * Accumulate a value from all objects with the passed accumulator function.\r\n * The accumulation starts with the initial value passed to the 'target' parameter.\r\n * For all objects the accumulator method is called with the current value of the target and the object.\r\n * Inside the accumulator method the target value is updated.\r\n * The objects are passed to the accumulator in read-only mode if supported.\r\n * The objects are collected by calling the {@link #getAllReadOnly(Predicate)} with <code>null</code> as predicate.\r\n * <p>\r\n * Example (simply counting the objects):\r\n * </p>\r\n * \r\n * <pre>\r\n * int objectCount = store.accumulate(new AtomicInteger(), (i, o) -&gt; i.incrementAndGet()).get();\r\n * </pre>\r\n *\r\n * @param target The initial value for the target\r\n * @param accumulator The accumulator method getting the current value of the accumulation target (type 'C') and an object (type 'TV').\r\n * @param <C> The type of the accumulation target.\r\n * @return The accumulation result.\r\n */\r\n <C> C accumulate(C target, BiConsumer<C, TV> accumulator);\r\n\r\n /**\r\n * Accumulate a value from all objects with the passed accumulator function as an atomic operation.\r\n * The method executes the {@link #accumulate(Object, BiConsumer)} method as an atomic operations.\r\n * Therefore this method is passed as functional parameter to the {@link #computeAtomic(Supplier)} method.\r\n * The execution of atomic operations can not overlap with the execution of a commit (changing the visible data) of another transaction (but normal operations on other transactions may overlap).\r\n *\r\n * @param target The initial value for the target\r\n * @param accumulator The accumulator method getting the current value of the accumulation target (type 'C') and an object (type 'TV').\r\n * @param <C> The type of the accumulation target.\r\n * @return The accumulation result (computed as an atomic operation).\r\n */\r\n <C> C accumulateAtomic(C target, BiConsumer<C, TV> accumulator);\r\n\r\n /**\r\n * Returns the value that was valid as the object was first accessed by the current TX (null if untouched).\r\n *\r\n * @param key The key of the desired object.\r\n * @return the value that was valid as the object was first accessed by the current TX (null if untouched).\r\n */\r\n TV getTransactionStartValue(K key);\r\n\r\n /**\r\n * Returns a read only version of the currently committed value of the object.\r\n * The method can be called inside or outside of a transaction.\r\n * \r\n * Calling this method does not affect the current transaction view of the object.\r\n * If before the call the transaction has no own view of the object it will not have one after the call.\r\n * If before the call the transaction has an own view of the object this is ignored and a different instance\r\n * cloned from the currently committed version (this may be committed before or after the TX view has been created).\r\n *\r\n * @param key The key of the desired object.\r\n * @return a read only version of the currently committed value of the object.\r\n */\r\n TV getCommittedValue(K key);\r\n\r\n /**\r\n * Returns if there is a transaction local view existing for the passed key in the current transaction.\r\n * \r\n * @param key The key of the desired object.\r\n * @return if there is a transaction local view existing for the passed key in the current transaction.\r\n */\r\n boolean hasTransactionView(K key);\r\n\r\n /**\r\n * Returns the original version of the object at the point of time it was cloned to the transactional view of the object.\r\n * \r\n * @param key The key of the desired object.\r\n * @return the original version of the object at the point of time it was cloned to the transactional view of the object.\r\n */\r\n long getTransactionViewVersion(K key);\r\n\r\n /**\r\n * Returns the version of the currently committed object.\r\n * \r\n * @param key The key of the desired object.\r\n * @return the version of the currently committed object.\r\n */\r\n long getCommittedVersion(K key);\r\n\r\n /**\r\n * Returns a info object (type {@link StoreEntryInfo}) containing information regarding the current state of the object\r\n * (regarding the committed values and the current transactional view).\r\n *\r\n * @param key The key of the desired object.\r\n * @return a info object (type {@link StoreEntryInfo}) containing information regarding the current state of the object.\r\n */\r\n StoreEntryInfo<K, TV> getObjectInfo(K key);\r\n\r\n /**\r\n * Clear the complete store, remove all committed values and invalidate all pending transactions.\r\n */\r\n void clear();\r\n}\r", "@SuppressWarnings(\"WeakerAccess\")\r\npublic class JacisTestHelper {\r\n\r\n private TestTxAdapter testTxAdapter;\r\n\r\n public JacisContainer createTestContainer() {\r\n testTxAdapter = new TestTxAdapter();\r\n return new JacisContainer(testTxAdapter);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithCloning() {\r\n JacisContainer container = createTestContainer();\r\n return createTestStoreWithCloning(container);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithCloning(JacisContainer container) {\r\n JacisCloningObjectAdapter<TestObject> cloningAdapter = new JacisCloningObjectAdapter<>();\r\n JacisObjectTypeSpec<String, TestObject, TestObject> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, TestObject.class, cloningAdapter);\r\n container.createStore(objectTypeSpec);\r\n return container.getStore(String.class, TestObject.class);\r\n }\r\n\r\n public JacisStore<String, TestObjectWithoutReadOnlyMode> createTestStoreWithCloningAndWithoutReadonlyMode() {\r\n JacisContainer container = createTestContainer();\r\n return createTestStoreWithCloningAndWithoutReadonlyMode(container);\r\n }\r\n\r\n public JacisStore<String, TestObjectWithoutReadOnlyMode> createTestStoreWithCloningAndWithoutReadonlyMode(JacisContainer container) {\r\n JacisCloningObjectAdapter<TestObjectWithoutReadOnlyMode> cloningAdapter = new JacisCloningObjectAdapter<>();\r\n JacisObjectTypeSpec<String, TestObjectWithoutReadOnlyMode, TestObjectWithoutReadOnlyMode> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, TestObjectWithoutReadOnlyMode.class, cloningAdapter);\r\n container.createStore(objectTypeSpec);\r\n return container.getStore(String.class, TestObjectWithoutReadOnlyMode.class);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithMicrostreamCloning() {\r\n JacisContainer container = createTestContainer();\r\n return createTestStoreWithMicrostreamCloning(container);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithMicrostreamCloning(JacisContainer container) {\r\n JacisMicrostreamCloningObjectAdapter<TestObject> cloningAdapter = new JacisMicrostreamCloningObjectAdapter<>();\r\n JacisObjectTypeSpec<String, TestObject, TestObject> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, TestObject.class, cloningAdapter);\r\n container.createStore(objectTypeSpec);\r\n return container.getStore(String.class, TestObject.class);\r\n }\r\n\r\n public JacisStore<String, TestObjectWithoutReadOnlyMode> createTestStoreWithMicrostreamCloningAndWithoutReadonlyMode() {\r\n JacisContainer container = createTestContainer();\r\n return createTestStoreWithMicrostreamCloningAndWithoutReadonlyMode(container);\r\n }\r\n\r\n public JacisStore<String, TestObjectWithoutReadOnlyMode> createTestStoreWithMicrostreamCloningAndWithoutReadonlyMode(JacisContainer container) {\r\n JacisMicrostreamCloningObjectAdapter<TestObjectWithoutReadOnlyMode> cloningAdapter = new JacisMicrostreamCloningObjectAdapter<>();\r\n JacisObjectTypeSpec<String, TestObjectWithoutReadOnlyMode, TestObjectWithoutReadOnlyMode> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, TestObjectWithoutReadOnlyMode.class, cloningAdapter);\r\n container.createStore(objectTypeSpec);\r\n return container.getStore(String.class, TestObjectWithoutReadOnlyMode.class);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithSerialization() {\r\n JacisContainer container = createTestContainer();\r\n return createTestStoreWithSerialization(container);\r\n }\r\n\r\n public JacisStore<String, TestObject> createTestStoreWithSerialization(JacisContainer container) {\r\n JacisSerializationObjectAdapter<TestObject> serializationAdapter = new JacisJavaSerializationObjectAdapter<>();\r\n JacisObjectTypeSpec<String, TestObject, byte[]> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, TestObject.class, serializationAdapter);\r\n return container.createStore(objectTypeSpec).getStore();\r\n }\r\n\r\n public JacisTransactionHandle suspendTx() {\r\n return testTxAdapter.suspendTx();\r\n }\r\n\r\n public void resumeTx(JacisTransactionHandle tx) {\r\n testTxAdapter.resumeTx(tx);\r\n }\r\n\r\n public long getRandBetween(long min, long max) {\r\n return max <= min ? min : min + Math.round((max - min) * Math.random());\r\n }\r\n\r\n public void sleep(int ms) {\r\n try {\r\n Thread.sleep(ms);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n }\r\n }\r\n\r\n private static class TestTxAdapter extends JacisTransactionAdapterLocal {\r\n\r\n JacisTransactionHandle suspendTx() {\r\n JacisTransactionHandle currentTx = transaction.get();\r\n if (currentTx == null) {\r\n throw new JacisNoTransactionException(\"No active transaction to suspend!\");\r\n }\r\n transaction.remove();\r\n return currentTx;\r\n }\r\n\r\n void resumeTx(JacisTransactionHandle tx) {\r\n JacisTransactionHandle currentTx = transaction.get();\r\n if (currentTx != null) {\r\n throw new JacisTransactionAlreadyStartedException(\"Failed to resume tx \" + tx + \" because another one is still active: \" + currentTx);\r\n }\r\n transaction.set(tx);\r\n }\r\n\r\n }\r\n}\r", "public class TestObject extends AbstractReadOnlyModeAndDirtyCheckSupportingObject implements JacisCloneable<TestObject>, Serializable {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n private String name;\r\n private long value;\r\n private String strValue;\r\n\r\n public TestObject(String name, long value) {\r\n this.name = name;\r\n this.value = value;\r\n strValue = null;\r\n }\r\n\r\n public TestObject(String name) {\r\n this(name, 1);\r\n }\r\n\r\n @Override\r\n public TestObject clone() {\r\n return (TestObject) super.clone();\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public TestObject setName(String name) {\r\n checkWritable();\r\n this.name = name;\r\n return this;\r\n }\r\n\r\n public long getValue() {\r\n return value;\r\n }\r\n\r\n public TestObject setValue(long value) {\r\n checkWritable();\r\n this.value = value;\r\n return this;\r\n }\r\n\r\n public String getStrValue() {\r\n return strValue;\r\n }\r\n\r\n public TestObject setStrValue(String strValue) {\r\n this.strValue = strValue;\r\n return this;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder b = new StringBuilder();\r\n b.append(getClass().getSimpleName());\r\n b.append(\"(\").append(name).append(\":\").append(value);\r\n if (strValue != null) {\r\n b.append(\", strVal=\").append(strValue);\r\n }\r\n b.append(\")\");\r\n return b.toString();\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ((name == null) ? 0 : name.hashCode());\r\n result = prime * result + (int) (value ^ (value >>> 32));\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj == null)\r\n return false;\r\n if (getClass() != obj.getClass())\r\n return false;\r\n TestObject other = (TestObject) obj;\r\n if (name == null) {\r\n if (other.name != null)\r\n return false;\r\n } else if (!name.equals(other.name))\r\n return false;\r\n return value == other.value;\r\n }\r\n\r\n}\r" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jacis.container.JacisTransactionHandle; import org.jacis.exception.JacisStaleObjectException; import org.jacis.plugin.txadapter.local.JacisLocalTransaction; import org.jacis.store.JacisStore; import org.jacis.testhelper.JacisTestHelper; import org.jacis.testhelper.TestObject; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (c) 2016. Jan Wiemer */ package org.jacis.objectadapter.microstream; @SuppressWarnings("CodeBlock2Expr") public class JacisStoreWithMicrostreamCloningTxTest { private static final Logger log = LoggerFactory.getLogger(JacisStoreWithMicrostreamCloningTxTest.class);
protected JacisStore<String, TestObject> createTestStore(JacisTestHelper testHelper) {
3
eckig/graph-editor
core/src/main/java/de/tesis/dynaware/grapheditor/core/skins/defaults/DefaultConnectorSkin.java
[ "public abstract class GConnectorSkin extends GSkin<GConnector> {\n\n /**\n * Creates a new {@link GConnectorSkin}.\n *\n * @param connector the {@link GConnector} represented by the skin\n */\n public GConnectorSkin(final GConnector connector) {\n super(connector);\n }\n\n /**\n * Gets the width of the connector skin.\n *\n * @return the width of the connector skin\n */\n public abstract double getWidth();\n\n /**\n * Gets the height of the connector skin.\n *\n * @return the height of the connector skin\n */\n public abstract double getHeight();\n\n /**\n * Applys the specified style to the connector.\n *\n * <p>\n * This is called by the library during various mouse events. For example when a connector is dragged over another\n * connector in an attempt to create a new connection.\n * </p>\n *\n * @param style the {@link GConnectorStyle} to apply\n */\n public abstract void applyStyle(GConnectorStyle style);\n}", "public enum GConnectorStyle\n{\n /**\n * Default style\n */\n DEFAULT,\n /**\n * Drag over allowed\n */\n DRAG_OVER_ALLOWED,\n /**\n * Drag over forbidden\n */\n DRAG_OVER_FORBIDDEN;\n}", "public final class DefaultConnectorTypes\r\n{\r\n\r\n private DefaultConnectorTypes()\r\n {\r\n // Auto-generated constructor stub\r\n }\r\n\r\n /**\r\n * Type string for an input connector positioned at the top of a node.\r\n */\r\n public static final String TOP_INPUT = \"top-input\";\r\n\r\n /**\r\n * Type string for an output connector positioned at the top of a node.\r\n */\r\n public static final String TOP_OUTPUT = \"top-output\";\r\n\r\n /**\r\n * Type string for an input connector positioned on the right side of a\r\n * node.\r\n */\r\n public static final String RIGHT_INPUT = \"right-input\";\r\n\r\n /**\r\n * Type string for an output connector positioned on the right side of a\r\n * node.\r\n */\r\n public static final String RIGHT_OUTPUT = \"right-output\";\r\n\r\n /**\r\n * Type string for an input connector positioned at the bottom of a node.\r\n */\r\n public static final String BOTTOM_INPUT = \"bottom-input\";\r\n\r\n /**\r\n * Type string for an output connector positioned at the bottom of a node.\r\n */\r\n public static final String BOTTOM_OUTPUT = \"bottom-output\";\r\n\r\n /**\r\n * Type string for an input connector positioned on the left side of a node.\r\n */\r\n public static final String LEFT_INPUT = \"left-input\";\r\n\r\n /**\r\n * Type string for an output connector positioned on the left side of a\r\n * node.\r\n */\r\n public static final String LEFT_OUTPUT = \"left-output\";\r\n\r\n private static final String LEFT_SIDE = \"left\";\r\n private static final String RIGHT_SIDE = \"right\";\r\n private static final String TOP_SIDE = \"top\";\r\n private static final String BOTTOM_SIDE = \"bottom\";\r\n\r\n private static final String INPUT = \"input\";\r\n private static final String OUTPUT = \"output\";\r\n\r\n /**\r\n * Returns true if the type is supported by the default skins.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the type is supported by the default skins\r\n */\r\n public static boolean isValid(final String type)\r\n {\r\n final boolean hasSide = type != null && (isTop(type) || isRight(type) || isBottom(type) || isLeft(type));\r\n final boolean inputOrOutput = type != null && (isInput(type) || isOutput(type));\r\n return hasSide && inputOrOutput;\r\n }\r\n\r\n /**\r\n * Gets the side corresponding to the given connector type.\r\n *\r\n * @param type\r\n * a non-null connector type\r\n * @return the {@link Side} the connector type is on\r\n */\r\n public static Side getSide(final String type)\r\n {\r\n if (isTop(type))\r\n {\r\n return Side.TOP;\r\n }\r\n else if (isRight(type))\r\n {\r\n return Side.RIGHT;\r\n }\r\n else if (isBottom(type))\r\n {\r\n return Side.BOTTOM;\r\n }\r\n else if (isLeft(type))\r\n {\r\n return Side.LEFT;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to a connector positioned at the top\r\n * of a node.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector will be positioned at the top of a\r\n * node\r\n */\r\n public static boolean isTop(final String type)\r\n {\r\n return type.contains(TOP_SIDE);\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to a connector positioned on the\r\n * right side of a node.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector will be positioned on the right\r\n * side of a node\r\n */\r\n public static boolean isRight(final String type)\r\n {\r\n return type.contains(RIGHT_SIDE);\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to a connector positioned at the\r\n * bottom of a node.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector will be positioned at the bottom of\r\n * a node\r\n */\r\n public static boolean isBottom(final String type)\r\n {\r\n return type.contains(BOTTOM_SIDE);\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to a connector positioned on the\r\n * left side of a node.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector will be positioned on the left side\r\n * of a node\r\n */\r\n public static boolean isLeft(final String type)\r\n {\r\n return type.contains(LEFT_SIDE);\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to an input connector.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector is any kind of input\r\n */\r\n public static boolean isInput(final String type)\r\n {\r\n return type.contains(INPUT);\r\n }\r\n\r\n /**\r\n * Returns true if the type corresponds to an output connector.\r\n *\r\n * @param type\r\n * a connector's type string\r\n * @return {@code true} if the connector is any kind of output\r\n */\r\n public static boolean isOutput(final String type)\r\n {\r\n return type.contains(OUTPUT);\r\n }\r\n\r\n /**\r\n * Returns true if the two given types are on the same side of a node.\r\n *\r\n * @param firstType\r\n * the first connector type\r\n * @param secondType\r\n * the second connector type\r\n * @return {@code true} if the connectors are on the same side of a node\r\n */\r\n public static boolean isSameSide(final String firstType, final String secondType)\r\n {\r\n return getSide(firstType) != null && getSide(firstType).equals(getSide(secondType));\r\n }\r\n}\r", "public class ColorAnimationUtils {\n\n private static final String TIMELINE_KEY = \"color-animation-utils-timeline\";\n\n private static final String COLOR_FORMAT = \"#%02x%02x%02x\";\n\n /**\n * Adds animated color properties to the given node that can be accessed from CSS.\n * \n * @param node the node to be styled with animated colors\n * @param data a {@link AnimatedColor} object storing the animation parameters\n */\n public static void animateColor(final Node node, final AnimatedColor data) {\n\n removeAnimation(node);\n\n final ObjectProperty<Color> baseColor = new SimpleObjectProperty<>();\n\n final KeyValue firstkeyValue = new KeyValue(baseColor, data.getFirstColor());\n final KeyValue secondKeyValue = new KeyValue(baseColor, data.getSecondColor());\n final KeyFrame firstKeyFrame = new KeyFrame(Duration.ZERO, firstkeyValue);\n final KeyFrame secondKeyFrame = new KeyFrame(data.getInterval(), secondKeyValue);\n final Timeline timeline = new Timeline(firstKeyFrame, secondKeyFrame);\n\n baseColor.addListener((v, o, n) -> {\n\n final int redValue = (int) (n.getRed() * 255);\n final int greenValue = (int) (n.getGreen() * 255);\n final int blueValue = (int) (n.getBlue() * 255);\n\n final String format = data.getProperty() + \": \" + COLOR_FORMAT + \";\";\n node.setStyle(String.format(format, redValue, greenValue, blueValue));\n });\n\n node.getProperties().put(TIMELINE_KEY, timeline);\n\n timeline.setAutoReverse(true);\n timeline.setCycleCount(Animation.INDEFINITE);\n timeline.play();\n }\n\n /**\n * Removes an animated color from this node, if one has been set on it.\n */\n public static void removeAnimation(final Node node) {\n\n // Stopping the timeline should allow object properties that depend on it to be garbage collected.\n if (node.getProperties().get(TIMELINE_KEY) instanceof Timeline tl) {\n tl.stop();\n }\n }\n}", "public interface GConnector extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Parent</b></em>' container reference.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GNode#getConnectors <em>Connectors</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Parent</em>' container reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Parent</em>' container reference.\n\t * @see #setParent(GNode)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Parent()\n\t * @see de.tesis.dynaware.grapheditor.model.GNode#getConnectors\n\t * @model opposite=\"connectors\" required=\"true\" transient=\"false\"\n\t * @generated\n\t */\n\tGNode getParent();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getParent <em>Parent</em>}' container reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Parent</em>' container reference.\n\t * @see #getParent()\n\t * @generated\n\t */\n\tvoid setParent(GNode value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connections</b></em>' reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnection}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connections</em>' reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connections</em>' reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Connections()\n\t * @model\n\t * @generated\n\t */\n\tEList<GConnection> getConnections();\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_X()\n\t * @model\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_Y()\n\t * @model\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connection Detached On Drag</b></em>' attribute.\n\t * The default value is <code>\"true\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connection Detached On Drag</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connection Detached On Drag</em>' attribute.\n\t * @see #setConnectionDetachedOnDrag(boolean)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnector_ConnectionDetachedOnDrag()\n\t * @model default=\"true\" required=\"true\"\n\t * @generated\n\t */\n\tboolean isConnectionDetachedOnDrag();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnector#isConnectionDetachedOnDrag <em>Connection Detached On Drag</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Connection Detached On Drag</em>' attribute.\n\t * @see #isConnectionDetachedOnDrag()\n\t * @generated\n\t */\n\tvoid setConnectionDetachedOnDrag(boolean value);\n\n} // GConnector" ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.tesis.dynaware.grapheditor.GConnectorSkin; import de.tesis.dynaware.grapheditor.GConnectorStyle; import de.tesis.dynaware.grapheditor.core.connectors.DefaultConnectorTypes; import de.tesis.dynaware.grapheditor.core.skins.defaults.utils.AnimatedColor; import de.tesis.dynaware.grapheditor.core.skins.defaults.utils.ColorAnimationUtils; import de.tesis.dynaware.grapheditor.model.GConnector; import javafx.css.PseudoClass; import javafx.scene.Node; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.util.Duration;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.core.skins.defaults; /** * The default connector skin. * * <p> * A connector that uses this skin must have one of the 8 types defined in {@link DefaultConnectorTypes}. If the * connector does not have one of these types, it will be set to <b>left-input</b>. * </p> */ public class DefaultConnectorSkin extends GConnectorSkin { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultConnectorSkin.class); private static final String STYLE_CLASS_BASE = "default-connector"; private static final PseudoClass PSEUDO_CLASS_ALLOWED = PseudoClass.getPseudoClass("allowed"); private static final PseudoClass PSEUDO_CLASS_FORBIDDEN = PseudoClass.getPseudoClass("forbidden"); private static final String ALLOWED = "-animated-color-allowed"; private static final String FORBIDDEN = "-animated-color-forbidden"; private static final double SIZE = 25; private final Pane root = new Pane(); private final Polygon polygon = new Polygon(); private final AnimatedColor animatedColorAllowed; private final AnimatedColor animatedColorForbidden; /** * Creates a new default connector skin instance. * * @param connector the {@link GConnector} the skin is being created for */
public DefaultConnectorSkin(final GConnector connector) {
4
idega/com.idega.company
src/java/com/idega/company/companyregister/business/CompanyRegisterBusinessBean.java
[ "public interface Company extends IDOEntity {\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getGroup\n\t */\n\tpublic Group getGroup();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getType\n\t */\n\tpublic CompanyType getType();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getName\n\t */\n\tpublic String getName();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getPersonalID\n\t */\n\tpublic String getPersonalID();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getWebPage\n\t */\n\tpublic String getWebPage();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getBankAccount\n\t */\n\tpublic String getBankAccount();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getExtraInfo\n\t */\n\tpublic String getExtraInfo();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#isValid\n\t */\n\tpublic boolean isValid();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#isOpen\n\t */\n\tpublic boolean isOpen();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getAddress\n\t */\n\tpublic Address getAddress();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getPhone\n\t */\n\tpublic Phone getPhone();\n\t\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#updatePhone\n\t */\n\tpublic void updatePhone(Phone newPhone);\n\n\t/**\n\t * \n\t * @return mobile phone of {@link Company} or <code>null</code> on failure.\n\t * @author <a href=\"mailto:[email protected]\">Martynas Stakė</a>\n\t */\n\tpublic Phone getMobilePhone();\n\t\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getFax\n\t */\n\tpublic Phone getFax();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#updateFax\n\t */\n\tpublic void updateFax(Phone newFax);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getEmail\n\t */\n\tpublic Email getEmail();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#updateEmail\n\t */\n\tpublic void updateEmail(Email newEmail);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setGroup\n\t */\n\tpublic void setGroup(Group group);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setType\n\t */\n\tpublic void setType(CompanyType type);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setName\n\t */\n\tpublic void setName(String name);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setPersonalID\n\t */\n\tpublic void setPersonalID(String personalID);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setWebPage\n\t */\n\tpublic void setWebPage(String webPage);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setBankAccount\n\t */\n\tpublic void setBankAccount(String bankAccount);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setExtraInfo\n\t */\n\tpublic void setExtraInfo(String extraInfo);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setValid\n\t */\n\tpublic void setValid(boolean valid);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setOpen\n\t */\n\tpublic void setOpen(boolean open);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#store\n\t */\n\t@Override\n\tpublic void store() throws IDOStoreException;\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getGeneralGroup\n\t */\n\tpublic Group getGeneralGroup();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getRecipientId\n\t */\n\tpublic String getRecipientId();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getRecipientName\n\t */\n\tpublic String getRecipientName();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setRecipientId\n\t */\n\tpublic void setRecipientId(String recipient);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setRecipientName\n\t */\n\tpublic void setRecipientName(String recipient);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getBanMarking\n\t */\n\tpublic String getBanMarking();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getCEO\n\t */\n\tpublic User getCEO();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setCEO\n\t */\n\tpublic void setCEO(User ceo);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getIndustryCode\n\t */\n\tpublic IndustryCode getIndustryCode();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setIndustryCode\n\t */\n\tpublic void setIndustryCode(IndustryCode industryCode);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getLastChange\n\t */\n\tpublic Date getLastChange();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setLastChange\n\t */\n\tpublic void setLastChange(Date lastChange);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getLegalCommune\n\t */\n\tpublic Commune getLegalCommune();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setLegalCommune\n\t */\n\tpublic void setLegalCommune(Commune legalCommune);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getOperation\n\t */\n\tpublic String getOperation();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setOperation\n\t */\n\tpublic void setOperation(String operation);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getOperationForm\n\t */\n\tpublic OperationForm getOperationForm();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setOperationForm\n\t */\n\tpublic void setOperationForm(OperationForm operationForm);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getOrderAreaForName\n\t */\n\tpublic String getOrderAreaForName();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setOrderAreaForName\n\t */\n\tpublic void setOrderAreaForName(String orderAreaForName);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getRegisterDate\n\t */\n\tpublic Date getRegisterDate();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setRegisterDate\n\t */\n\tpublic void setRegisterDate(Date registerDate);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getUnregisterDate\n\t */\n\tpublic Date getUnregisterDate();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setUnregisterDate\n\t */\n\tpublic void setUnregisterDate(Date unregisterDate);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getUnregisterType\n\t */\n\tpublic UnregisterType getUnregisterType();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setUnregisterType\n\t */\n\tpublic void setUnregisterType(UnregisterType unregisterType);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getVATNumber\n\t */\n\tpublic String getVATNumber();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setVATNumber\n\t */\n\tpublic void setVATNumber(String number);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getWorkingArea\n\t */\n\tpublic Commune getWorkingArea();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setWorkingArea\n\t */\n\tpublic void setWorkingArea(Commune workingArea);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setAddress\n\t */\n\tpublic void setAddress(Address address);\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#setBanMarking\n\t */\n\tpublic void setBanMarking(String banMarking);\n}", "public interface CompanyHome extends IDOHome {\n\tpublic Company findByPrimaryKey(Object pk) throws FinderException;\n\n\tpublic Company create() throws CreateException;\n\n\tpublic Company findByPersonalID(String personalID) throws FinderException;\n\n\tpublic Company findByName(String name) throws FinderException;\n\n\tpublic Collection<Company> findAll(Boolean valid) throws FinderException;\n\n\tpublic Collection<Company> findAllWithOpenStatus() throws FinderException;\n\n\tpublic Collection<Company> findAllActiveWithOpenStatus()\n\t\t\tthrows FinderException;\n\n\t/**\n\t * \n\t * <p>Searches {@link Company}s, where given {@link User} ir CEO.</p>\n\t * @param user - {@link Company#getCEO()}.\n\t * @return {@link List} of {@link Company}s, where user is CEO or \n\t * <code>null</code> on failure.\n\t * @author <a href=\"mailto:[email protected]\">Martynas Stakė</a>\n\t */\n\tpublic Collection<Company> findAll(User user);\n}", "public interface IndustryCode extends IDOEntity {\n\t/**\n\t * @see com.idega.company.data.IndustryCodeBMPBean#getISATCode\n\t */\n\tpublic String getISATCode();\n\n\t/**\n\t * @see com.idega.company.data.IndustryCodeBMPBean#getISATDescription\n\t */\n\tpublic String getISATDescription();\n\n\t/**\n\t * @see com.idega.company.data.IndustryCodeBMPBean#setISATCode\n\t */\n\tpublic void setISATCode(String code);\n\n\t/**\n\t * @see com.idega.company.data.IndustryCodeBMPBean#setISATDescription\n\t */\n\tpublic void setISATDescription(String description);\n}", "public interface IndustryCodeHome extends IDOHome {\n\tpublic IndustryCode create() throws CreateException;\n\n\tpublic IndustryCode findByPrimaryKey(Object pk) throws FinderException;\n\n\tpublic Collection findAllIndustryCodes() throws FinderException, RemoteException;\n\n\tpublic IndustryCode findIndustryByUniqueCode(String uniqueId) throws FinderException;\n}", "public interface OperationForm extends IDOEntity {\n\t/**\n\t * @see com.idega.company.data.OperationFormBMPBean#getDescription\n\t */\n\tpublic String getDescription();\n\n\t/**\n\t * @see com.idega.company.data.OperationFormBMPBean#getCode\n\t */\n\tpublic String getCode();\n\n\t/**\n\t * @see com.idega.company.data.OperationFormBMPBean#setDescription\n\t */\n\tpublic void setDescription(String description);\n\n\t/**\n\t * @see com.idega.company.data.OperationFormBMPBean#setCode\n\t */\n\tpublic void setCode(String code);\n}", "public interface OperationFormHome extends IDOHome {\n\tpublic OperationForm create() throws CreateException;\n\n\tpublic OperationForm findByPrimaryKey(Object pk) throws FinderException;\n\n\tpublic Collection findAllOperationForms() throws FinderException, RemoteException;\n\n\tpublic OperationForm findOperationFormByUniqueCode(String uniqueId) throws FinderException;\n}", "public interface UnregisterType extends IDOEntity {\n\t/**\n\t * @see com.idega.company.data.UnregisterTypeBMPBean#getDescription\n\t */\n\tpublic String getDescription();\n\n\t/**\n\t * @see com.idega.company.data.UnregisterTypeBMPBean#getCode\n\t */\n\tpublic String getCode();\n\n\t/**\n\t * @see com.idega.company.data.UnregisterTypeBMPBean#setDescription\n\t */\n\tpublic void setDescription(String description);\n\n\t/**\n\t * @see com.idega.company.data.UnregisterTypeBMPBean#setCode\n\t */\n\tpublic void setCode(String code);\n}", "public interface UnregisterTypeHome extends IDOHome {\n\tpublic UnregisterType create() throws CreateException;\n\n\tpublic UnregisterType findByPrimaryKey(Object pk) throws FinderException;\n\n\tpublic Collection findAllUnregisterTypes() throws FinderException, RemoteException;\n\n\tpublic UnregisterType findUnregisterTypeByUniqueCode(String uniqueId) throws FinderException;\n}" ]
import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.FinderException; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.business.IBOServiceBean; import com.idega.company.data.Company; import com.idega.company.data.CompanyHome; import com.idega.company.data.IndustryCode; import com.idega.company.data.IndustryCodeHome; import com.idega.company.data.OperationForm; import com.idega.company.data.OperationFormHome; import com.idega.company.data.UnregisterType; import com.idega.company.data.UnregisterTypeHome; import com.idega.core.location.business.AddressBusiness; import com.idega.core.location.data.Address; import com.idega.core.location.data.AddressHome; import com.idega.core.location.data.Commune; import com.idega.core.location.data.CommuneHome; import com.idega.core.location.data.PostalCode; import com.idega.core.location.data.PostalCodeHome; import com.idega.data.IDOLookup; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.user.data.UserHome;
if(address != null) { address = address.trim(); if(!address.equals("")) { addressBean.setStreetName(addressBusiness.getStreetNameFromAddressString(address)); addressBean.setStreetNumber(addressBusiness.getStreetNumberFromAddressString(address)); } } } catch(Exception re) { logger.log(Level.SEVERE, "Exception while handling company address", re); } Commune communeBean = addressBean.getCommune(); if(communeBean == null) { try { if(commune != null) { commune = commune.trim(); if(!commune.equals("")) { communeBean = getCommuneHome().findByCommuneCode(commune); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding commune entry", re); } } addressBean.setCommune(communeBean); company_registry.setLastChange(CompanyRegisterImportFile.getSQLDateFromStringFormat(dateOfLastChange.trim(), logger, RECORDS_DATE_FORMAT)); company_registry.setRegisterDate(CompanyRegisterImportFile.getSQLDateFromStringFormat(registerDate.trim(), logger, RECORDS_DATE_FORMAT)); company_registry.setUnregisterDate(CompanyRegisterImportFile.getSQLDateFromStringFormat(unregistrationDate.trim(), logger, RECORDS_DATE_FORMAT)); PostalCode postalCodeBean = addressBean.getPostalCode(); if(postalCodeBean == null) { try { if(postalCode != null) { postalCode = postalCode.trim(); if(!postalCode.equals("")) { postalCodeBean = getPostalCodeHome().findByPostalCode(postalCode); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a postal code entry", re); } } addressBean.setPostalCode(postalCodeBean); addressBean.store(); try { @SuppressWarnings("unchecked") Collection<Address> addreses = company_registry.getGeneralGroup().getAddresses(getAddressHome().getAddressType1()); String pk1 = ((Integer) addressBean.getPrimaryKey()).toString(); boolean addressSet = false; for(Iterator<Address> it = addreses.iterator(); it.hasNext(); ) { Address adr = it.next(); String pk2 = ((Integer) adr.getPrimaryKey()).toString(); if(pk1.equals(pk2)) { addressSet = true; break; } } if(!addressSet) { company_registry.setAddress(addressBean); } } catch(Exception e) { logger.log(Level.SEVERE, "Exception while all address entries for a company", e); } Commune legalCommune = company_registry.getLegalCommune(); if(legalCommune == null) { try { if(legalAddress != null) { legalAddress = legalAddress.trim(); if(!legalAddress.equals("")) { legalCommune = getCommuneHome().findByCommuneCode(legalAddress); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a commune entry", re); } } company_registry.setLegalCommune(legalCommune); Commune workCommune = company_registry.getWorkingArea(); if(workCommune == null) { try { if(workingArea != null) { workingArea = workingArea.trim(); if(!workingArea.equals("")) { workCommune = getCommuneHome().findByCommuneCode(workingArea); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a commune entry", re); } } company_registry.setWorkingArea(workCommune); try { OperationForm operationFormBean = ((OperationFormHome) IDOLookup.getHome(OperationForm.class)).findOperationFormByUniqueCode(operationForm); if(operationFormBean != null) { company_registry.setOperationForm(operationFormBean); } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a OperationForm entry", re); } try { IndustryCode industryCodeBean = ((IndustryCodeHome) IDOLookup.getHome(IndustryCode.class)).findIndustryByUniqueCode(industryCode); if(industryCodeBean != null) { company_registry.setIndustryCode(industryCodeBean); } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a IndustryCode entry", re); } try {
UnregisterType unregisterTypeBean = ((UnregisterTypeHome) IDOLookup.getHome(UnregisterType.class)).findUnregisterTypeByUniqueCode(unregistrationType);
7
ProjectInfinity/ReportRTS
src/main/java/com/nyancraft/reportrts/command/sub/BroadcastMessage.java
[ "public class RTSFunctions {\n\n private static ReportRTS plugin = ReportRTS.getPlugin();\n private static DataProvider data = plugin.getDataProvider();\n\n private static final int SECOND_MILLIS = 1000;\n private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;\n private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;\n private static final int DAY_MILLIS = 24 * HOUR_MILLIS;\n\n public static String cleanUpSign(String[] lines) {\n\n String out = \"\";\n for(String part : lines) {\n if(!part.isEmpty()) out = out + part.trim() + \" \";\n }\n return out;\n }\n /***\n * Message all online staff on the server\n * @param message - message to be displayed\n * @param playSound - boolean play sound or not.\n */\n public static void messageStaff(String message, boolean playSound) {\n\n for(UUID uuid : ReportRTS.getPlugin().staff) {\n\n Player player = ReportRTS.getPlugin().getServer().getPlayer(uuid);\n\n if(player == null) return;\n\n player.sendMessage(message);\n\n if(ReportRTS.getPlugin().notificationSound && playSound) player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 0);\n }\n\n // Make sure Console sees this too!\n plugin.getServer().getConsoleSender().sendMessage(message);\n\n }\n\n /**\n * Synchronizes ticket data from the given ticket ID.\n * @param ticketId - ticket ID to be synchronized.\n */\n public static boolean syncTicket(int ticketId) {\n\n Ticket ticket = ReportRTS.getPlugin().getDataProvider().getTicket(ticketId);\n\n plugin.tickets.put(ticketId, ticket);\n\n return plugin.tickets.get(ticketId).equals(ticket);\n\n }\n\n /**\n * Synchronizes everything.\n */\n public static void sync() {\n ReportRTS.getPlugin().tickets.clear();\n ReportRTS.getPlugin().notifications.clear();\n ReportRTS.getPlugin().staff.clear();\n\n data.load();\n\n RTSFunctions.populateStaffMap();\n }\n\n /**\n * Returns true if the person is online.\n * @param uuid - UUID of player\n * @return boolean\n */\n public static boolean isUserOnline(UUID uuid){\n return plugin.getServer().getPlayer(uuid) != null;\n }\n\n /**\n * Get number of open request by the specified user.\n * @param uuid - UUID of user that sent the command.\n * @return amount of open requests by a specific user\n */\n public static int getOpenTicketsByUser(UUID uuid){\n int i = 0;\n for(Map.Entry<Integer, Ticket> entry : ReportRTS.getPlugin().tickets.entrySet()){\n if(entry.getValue().getUUID().equals(uuid)) i++;\n }\n return i;\n }\n\n public static long checkTimeBetweenTickets(UUID uuid){\n for(Map.Entry<Integer, Ticket> entry : ReportRTS.getPlugin().tickets.entrySet()){\n if(entry.getValue().getUUID().equals(uuid)){\n if(entry.getValue().getTimestamp() > ((System.currentTimeMillis() / 1000) - ReportRTS.getPlugin().ticketDelay)) return entry.getValue().getTimestamp() - (System.currentTimeMillis() / 1000 - ReportRTS.getPlugin().ticketDelay);\n }\n }\n return 0;\n }\n\n public static String getTimeSpent(double start){\n DecimalFormat decimal = new DecimalFormat(\"##.###\");\n return decimal.format((System.nanoTime() - start) / 1000000);\n }\n\n public static String shortenMessage(String message){\n if (message.length() >= 20) {\n message = message.substring(0, 20) + \"...\";\n }\n return message;\n }\n\n public static void populateStaffMap(){\n for(Player player : ReportRTS.getPlugin().getServer().getOnlinePlayers()){\n if(RTSPermissions.isStaff(player)) ReportRTS.getPlugin().staff.add(player.getUniqueId());\n }\n }\n\n /**\n * Check if the provided String is a number or not.\n * @param number as a String\n * @return true if String is a number\n */\n public static boolean isNumber(String number){\n return (number.matches(\"-?\\\\d+\") && !(Long.parseLong((number)) <= 0L) && (Long.parseLong((number)) < Integer.MAX_VALUE));\n }\n\n /**\n * Separate text whenever a certain amount of words are reached.\n * PS: If you know how to stop Windows servers from printing the CR (Carriage Return)\n * character, please let me know!\n * @param text that you want to separate.\n * @param when X amount of words have been displayed.\n * @return String with line separators.\n */\n public static String separateText(String text, int when) {\n int i = 0;\n StringBuilder message = new StringBuilder();\n for(String t : text.split(\" \")) {\n if(i >= when) {\n i = 0;\n message.append(ReportRTS.getPlugin().lineSeparator);\n }\n message.append(t).append(\" \");\n i++;\n }\n return message.toString().trim();\n }\n\n /**\n * Retrieves relative time for use in /ticket read.\n * @param time Since specified time\n * @return String with relative time\n */\n public static String getTimeAgo(long time) {\n if (time < 1000000000000L) {\n // if timestamp given in seconds, convert to millis\n time *= 1000;\n }\n\n long now = System.currentTimeMillis();\n if (time > now || time <= 0) return null;\n\n final long diff = now - time;\n if (diff < MINUTE_MILLIS) {\n return ChatColor.GREEN + \"just now\" + ChatColor.GOLD;\n } else if (diff < 2 * MINUTE_MILLIS) {\n return ChatColor.GREEN + \"1 minute ago\" + ChatColor.GOLD; // a minute ago\n } else if (diff < 50 * MINUTE_MILLIS) {\n return \"\" + ChatColor.GREEN + diff / MINUTE_MILLIS + \" min ago\" + ChatColor.GOLD;\n } else if (diff < 90 * MINUTE_MILLIS) {\n return ChatColor.GREEN + \"1 hour ago\" + ChatColor.GOLD;\n } else if (diff < 24 * HOUR_MILLIS) {\n return \"\" + ChatColor.YELLOW + diff / HOUR_MILLIS + \" hours ago\" + ChatColor.GOLD;\n } else if (diff < 48 * HOUR_MILLIS) {\n return ChatColor.RED + \"yesterday\" + ChatColor.GOLD;\n } else {\n return \"\" + ChatColor.RED + diff / DAY_MILLIS + \" days ago\" + ChatColor.GOLD;\n }\n }\n}", "public class RTSPermissions {\n\n public static boolean isStaff(Player player) {\n if(ReportRTS.permission != null) return ReportRTS.permission.playerHas(player, \"reportrts.staff\");\n return player.hasPermission(\"reportrts.staff\");\n }\n\n public static boolean canOpenTicket(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.open\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.open\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.open\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.open\"));\n return false;\n }\n return true;\n }\n\n public static boolean canReadAll(CommandSender sender) {\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.command.read\");\n return sender.hasPermission(\"reportrts.command.read\");\n }\n\n public static boolean canReadOwn(CommandSender sender) {\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.command.read.self\");\n return sender.hasPermission(\"reportrts.command.read.self\");\n }\n\n public static boolean canReadOwnClosed(CommandSender sender) {\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.command.read.self.open\");\n return sender.hasPermission(\"reportrts.command.read.self.open\");\n }\n\n public static boolean canCloseTicket(CommandSender sender) {\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.command.close\");\n return sender.hasPermission(\"reportrts.command.close\");\n }\n\n public static boolean canCloseOwnTicket(CommandSender sender) {\n if(!(sender instanceof Player)) return false;\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.command.close.self\");\n return sender.hasPermission(\"reportrts.command.close.self\");\n }\n\n public static boolean canTeleport(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.teleport\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.teleport\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.teleport\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.teleport\"));\n return false;\n }\n return true;\n }\n\n public static boolean canReloadPlugin(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.reload\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reload\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.reload\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reload\"));\n return false;\n }\n return true;\n }\n\n public static boolean canBanUser(CommandSender sender) {\n if(ReportRTS.permission != null){\n if(!ReportRTS.permission.has(sender, \"reportrts.command.ban\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.ban\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.ban\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.ban\"));\n return false;\n }\n return true;\n }\n\n public static boolean canResetPlugin(CommandSender sender) {\n if(ReportRTS.permission != null){\n if(!ReportRTS.permission.has(sender, \"reportrts.command.reset\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reset\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.reset\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reset\"));\n return false;\n }\n return true;\n }\n\n public static boolean canPutTicketOnHold(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.hold\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.hold\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.hold\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.hold\"));\n return false;\n }\n return true;\n }\n\n public static boolean canClaimTicket(CommandSender sender) {\n if(ReportRTS.permission != null){\n if(!ReportRTS.permission.has(sender, \"reportrts.command.claim\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.claim\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.claim\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.claim\"));\n return false;\n }\n return true;\n }\n\n public static boolean canListStaff(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.list\")){\n sender.sendMessage(Message.errorPermission(\"reportrts.command.list\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.list\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.list\"));\n return false;\n }\n return true;\n }\n\n public static boolean canBroadcast(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.broadcast\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.broadcast\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.broadcast\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.broadcast\"));\n return false;\n }\n return true;\n }\n\n public static boolean canCheckStats(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.stats\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.stats\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.stats\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.stats\"));\n return false;\n }\n return true;\n }\n\n public static boolean canComment(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.comment\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.comment\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.comment\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.comment\"));\n return false;\n }\n return true;\n }\n\n public static boolean canBypassClaim(CommandSender sender) {\n\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.bypass.claim\");\n\n return sender.hasPermission(\"reportrts.bypass.claim\");\n\n }\n\n public static boolean canBypassLimit(CommandSender sender) {\n\n if(ReportRTS.permission != null) return ReportRTS.permission.has(sender, \"reportrts.bypass.limit\");\n\n return sender.hasPermission(\"reportrts.bypass.limit\");\n\n }\n\n public static boolean canSeeHelpPage(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.help\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.help\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.help\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.help\"));\n return false;\n }\n return true;\n }\n\n public static boolean canManageNotifications(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.notifications\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.notifications\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.notifications\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.notifications\"));\n return false;\n }\n return true;\n }\n\n public static boolean canAssignTickets(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.assign\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.assign\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.assign\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.assign\"));\n return false;\n }\n return true;\n }\n\n public static boolean canReopenTicket(CommandSender sender) {\n if(ReportRTS.permission != null) {\n if(!ReportRTS.permission.has(sender, \"reportrts.command.reopen\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reopen\"));\n return false;\n }\n return true;\n }\n if(!sender.hasPermission(\"reportrts.command.reopen\")) {\n sender.sendMessage(Message.errorPermission(\"reportrts.command.reopen\"));\n return false;\n }\n return true;\n }\n}", "public class ReportRTS extends JavaPlugin implements PluginMessageListener {\n\n private static ReportRTS plugin;\n private final Logger log = Logger.getLogger(\"Minecraft\");\n private static MessageHandler messageHandler = new MessageHandler();\n private VersionChecker versionChecker = new VersionChecker();\n private DataProvider provider;\n\n public Map<Integer, Ticket> tickets = new TreeMap<>();\n public Map<Integer, UUID> notifications = new HashMap<>();\n public Map<UUID, Integer> teleportMap = new HashMap<>();\n public Map<String, String> commandMap = new HashMap<>();\n public ArrayList<UUID> staff = new ArrayList<>();\n\n public boolean notifyStaffOnNewRequest;\n public boolean notificationSound;\n public boolean hideNotification;\n public boolean hideWhenOffline;\n public boolean debugMode;\n public boolean outdated;\n public boolean vanishSupport;\n public boolean bungeeCordSupport;\n public boolean setupDone = true;\n public boolean ticketNagHeld;\n public boolean ticketPreventDuplicate;\n public boolean apiEnabled;\n public boolean legacyCommands;\n public boolean fancify;\n\n public int maxTickets;\n public int ticketDelay;\n public int ticketMinimumWords;\n public int ticketsPerPage;\n public int storagePort;\n public long ticketNagging;\n public long storageRefreshTime;\n public long bungeeCordSync;\n public String storageType;\n public String storageHostname;\n public String storageDatabase;\n public String storageUsername;\n public String storagePassword;\n public String storagePrefix;\n public String versionString;\n public String bungeeCordServerPrefix;\n public String lineSeparator = System.lineSeparator();\n\n public static Permission permission = null;\n\n private ApiServer apiServer;\n private int apiPort;\n private String apiPassword;\n private List<String> apiAllowedIPs = new ArrayList<>();\n\n private String serverIP;\n\n public void onDisable() {\n if (provider != null) {\n provider.close();\n }\n if(apiEnabled) {\n try{\n apiServer.getListener().close();\n }catch(IOException e) {\n e.printStackTrace();\n }\n }\n messageHandler.saveMessageConfig();\n }\n\n public void onEnable() {\n plugin = this;\n reloadSettings();\n\n // Enable BungeeCord support if wanted.\n if(bungeeCordSupport) {\n if(getConfig().getString(\"bungeecord.serverName\") == null || getConfig().getString(\"bungeecord.serverName\").isEmpty()) {\n plugin.getLogger().warning(\"BungeeCord support enabled, but server name is not set yet. Scheduling a name-update task.\");\n new BungeeNameTask(plugin).runTaskTimer(plugin, 160L, 480L);\n } else {\n BungeeCord.setServer(getConfig().getString(\"bungeecord.serverName\"));\n }\n }\n final PluginManager pm = getServer().getPluginManager();\n\n // Register events that ReportRTS listens to.\n pm.registerEvents(new RTSListener(plugin), plugin);\n\n // Ensure that storage information is not default as that may not work.\n if(assertConfigIsDefault(\"STORAGE\")) {\n setupDone = false;\n } else {\n if(!storageType.equalsIgnoreCase(\"MYSQL\")) {\n log.severe(\"Unsupported STORAGE type specified. Allowed types are: MySQL\");\n pm.disablePlugin(this);\n }\n setDataProvider(new MySQLDataProvider(plugin));\n if(!provider.load()) {\n log.severe(\"Encountered an error while attempting to connect to the data-provider. Disabling...\");\n pm.disablePlugin(this);\n return;\n }\n reloadSettings();\n RTSFunctions.populateStaffMap();\n }\n\n // Check if plugin is up to date. TODO: This has to be updated for Spigot's website.\n outdated = !versionChecker.upToDate();\n\n // Enable fancier tickets if enabled and if ProtocolLib is enabled on the server.\n if(fancify && pm.getPlugin(\"ProtocolLib\") == null) {\n log.warning(\"Fancy messages are enabled, but ProtocolLib was not found.\");\n fancify = false;\n }\n\n // Register commands.\n if(legacyCommands) {\n pm.registerEvents(new LegacyCommandListener(commandMap.get(\"readTicket\"), commandMap.get(\"openTicket\"), commandMap.get(\"closeTicket\"), commandMap.get(\"reopenTicket\"),\n commandMap.get(\"claimTicket\"), commandMap.get(\"unclaimTicket\"), commandMap.get(\"holdTicket\"), commandMap.get(\"teleportToTicket\"), commandMap.get(\"broadcastToStaff\"),\n commandMap.get(\"listStaff\"), commandMap.get(\"commentTicket\")), plugin);\n }\n\n getCommand(\"reportrts\").setExecutor(new ReportRTSCommand(plugin));\n getCommand(\"ticket\").setExecutor(new TicketCommand(plugin));\n getCommand(\"ticket\").setTabCompleter(new TabCompleteHelper(plugin));\n\n // Set up Vault if it exists on the server.\n if(pm.getPlugin(\"Vault\") != null) setupPermissions();\n\n // Attempt to set up Metrics.\n try {\n MetricsLite metrics = new MetricsLite(this);\n metrics.start();\n } catch(IOException e) {\n log.info(\"Unable to submit stats!\");\n }\n\n // Enable API. (Not recommended since it is very incomplete!)\n apiEnabled = false; // TODO: Remove hard-coded false when this works!\n if(apiEnabled) {\n try {\n Properties props = new Properties();\n props.load(new FileReader(\"server.properties\"));\n serverIP = props.getProperty(\"server-ip\", \"ANY\");\n if(serverIP.isEmpty()) serverIP = \"ANY\";\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n apiPassword = apiPassword + \"ReportRTS\";\n md.update(apiPassword.getBytes(\"UTF-8\"));\n byte[] hash = md.digest();\n StringBuffer sb = new StringBuffer();\n for(byte b : hash) {\n sb.append(String.format(\"%02x\", b));\n }\n apiPassword = sb.toString();\n } catch(NoSuchAlgorithmException e) {\n log.warning(\"[ReportRTS] Unable to hash password, consider disabling the API!\");\n e.printStackTrace();\n }\n apiServer = new ApiServer(plugin, serverIP, apiPort, apiAllowedIPs, apiPassword);\n } catch(IOException e) {\n log.warning(\"[ReportRTS] Unable to start API server!\");\n e.printStackTrace();\n }\n apiServer.start();\n }\n\n // Enable nagging, staff will be reminded of unresolved tickets.\n if(ticketNagging > 0){\n getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable(){\n public void run(){\n int openTickets = tickets.size();\n if(ticketNagHeld) {\n int heldTickets = getDataProvider().countTickets(2);\n if(heldTickets > 0) {\n if(openTickets > 0) RTSFunctions.messageStaff(Message.ticketUnresolvedHeld(openTickets, heldTickets, (plugin.legacyCommands ? plugin.commandMap.get(\"readTicket\") : \"ticket \" + plugin.commandMap.get(\"readTicket\"))), false);\n } else {\n if(openTickets > 0) RTSFunctions.messageStaff(Message.ticketUnresolved(openTickets, (plugin.legacyCommands ? plugin.commandMap.get(\"readTicket\") : \"ticket \" + plugin.commandMap.get(\"readTicket\"))), false);\n }\n } else {\n if(openTickets > 0) RTSFunctions.messageStaff(Message.ticketUnresolved(openTickets, (plugin.legacyCommands ? plugin.commandMap.get(\"readTicket\") : \"ticket \" + plugin.commandMap.get(\"readTicket\"))), false);\n }\n }\n }, 120L, (ticketNagging * 60) * 20);\n }\n\n if(bungeeCordSupport) {\n // Register BungeeCord channels.\n getServer().getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\n getServer().getMessenger().registerIncomingPluginChannel(this, \"BungeeCord\", this);\n\n // Schedule a offline-sync in case no players are online.\n getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {\n public void run() {\n if(BungeeCord.isServerEmpty()) {\n RTSFunctions.sync();\n }\n }\n }, plugin.bungeeCordSync * 20, plugin.bungeeCordSync * 20);\n }\n }\n\n public void reloadPlugin() {\n reloadSettings();\n RTSFunctions.sync();\n }\n\n public void reloadSettings() {\n reloadConfig();\n getConfig().options().copyDefaults(true);\n assertConfigUpToDate();\n messageHandler.reloadMessageConfig();\n messageHandler.saveMessageConfig();\n messageHandler.reloadMessageMap();\n notifyStaffOnNewRequest = getConfig().getBoolean(\"notifyStaff\");\n notificationSound = getConfig().getBoolean(\"notifySound\");\n hideNotification = getConfig().getBoolean(\"hideMessageIfEmpty\");\n hideWhenOffline = getConfig().getBoolean(\"ticket.hideOffline\");\n maxTickets = getConfig().getInt(\"ticket.max\");\n ticketDelay = getConfig().getInt(\"ticket.delay\");\n ticketMinimumWords = getConfig().getInt(\"ticket.minimumWords\");\n ticketsPerPage = getConfig().getInt(\"ticket.perPage\");\n ticketPreventDuplicate = getConfig().getBoolean(\"ticket.preventDuplicates\", true);\n ticketNagging = getConfig().getLong(\"ticket.nag\");\n ticketNagHeld = getConfig().getBoolean(\"ticket.nagHeld\", false);\n storageRefreshTime = getConfig().getLong(\"storage.refreshTime\");\n storageType = getConfig().getString(\"storage.type\", \"mysql\");\n storagePort = getConfig().getInt(\"storage.port\");\n storageHostname = getConfig().getString(\"storage.hostname\");\n storageDatabase = getConfig().getString(\"storage.database\");\n storageUsername = getConfig().getString(\"storage.username\");\n storagePassword = getConfig().getString(\"storage.password\");\n storagePrefix = getConfig().getString(\"storage.prefix\");\n debugMode = getConfig().getBoolean(\"debug\");\n vanishSupport = getConfig().getBoolean(\"VanishSupport\", false);\n bungeeCordSupport = getConfig().getBoolean(\"bungeecord.enable\", false);\n bungeeCordSync = getConfig().getLong(\"bungeecord.sync\", 300L);\n bungeeCordServerPrefix = getConfig().getString(\"bungeecord.serverPrefix\");\n apiEnabled = false; // TODO: Change to this when it's ready: getConfig().getBoolean(\"api.enable\", false);\n apiPort = getConfig().getInt(\"api.port\", 25567);\n apiPassword = getConfig().getString(\"api.password\");\n apiAllowedIPs = getConfig().getStringList(\"api.whitelist\");\n legacyCommands = getConfig().getBoolean(\"command.legacy\", false);\n fancify = getConfig().getBoolean(\"ticket.fancify\", true);\n commandMap.clear();\n // Register all commands/subcommands.\n commandMap.put(\"readTicket\",getConfig().getString(\"command.readTicket\"));\n commandMap.put(\"openTicket\",getConfig().getString(\"command.openTicket\"));\n commandMap.put(\"closeTicket\",getConfig().getString(\"command.closeTicket\"));\n commandMap.put(\"reopenTicket\",getConfig().getString(\"command.reopenTicket\"));\n commandMap.put(\"claimTicket\",getConfig().getString(\"command.claimTicket\"));\n commandMap.put(\"unclaimTicket\",getConfig().getString(\"command.unclaimTicket\"));\n commandMap.put(\"holdTicket\",getConfig().getString(\"command.holdTicket\"));\n commandMap.put(\"teleportToTicket\",getConfig().getString(\"command.teleportToTicket\"));\n commandMap.put(\"broadcastToStaff\",getConfig().getString(\"command.broadcastToStaff\"));\n commandMap.put(\"listStaff\",getConfig().getString(\"command.listStaff\"));\n commandMap.put(\"assignTicket\",getConfig().getString(\"command.assignTicket\"));\n commandMap.put(\"commentTicket\",getConfig().getString(\"command.commentTicket\"));\n // Commands registered!\n }\n\n public static ReportRTS getPlugin() {\n return plugin;\n }\n\n public static MessageHandler getMessageHandler() {\n return messageHandler;\n }\n\n public DataProvider getDataProvider() {\n return provider;\n }\n\n public void setDataProvider(DataProvider provider) {\n if(this.provider != null) this.provider.close();\n this.provider = provider;\n }\n\n private Boolean setupPermissions() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n if(permissionProvider != null) {\n permission = permissionProvider.getProvider();\n }\n return (permission != null);\n }\n\n public void onPluginMessageReceived(String pluginChannel, Player player, byte[] bytes) {\n if(!pluginChannel.equals(\"BungeeCord\")) return;\n\n BungeeCord.handleNotify(bytes);\n }\n\n private void assertConfigUpToDate() {\n /**\n * What it does:\n * - - - - -\n * Checks if the mapping \"requests\" is located in the config\n * and replaces it with \"ticket\".\n * - - - - -\n * Since version:\n * 1.2.3\n */\n if(getConfig().getConfigurationSection(\"request\") != null) {\n getConfig().createSection(\"ticket\", getConfig().getConfigurationSection(\"request\").getValues(false));\n getConfig().set(\"request\", null);\n log.info(\"Updated configuration. 'request' => 'ticket'.\");\n }\n\n // Save changes.\n saveConfig();\n }\n\n private boolean assertConfigIsDefault(String path) {\n /**\n * What it does:\n * - - - - -\n * Checks if the specified configuration section is default,\n * returns a boolean depending on the result.\n */\n\n switch(path.toUpperCase()) {\n\n case \"STORAGE\":\n\n return (storageHostname.equalsIgnoreCase(\"localhost\") && storagePort == 3306 && storageDatabase.equalsIgnoreCase(\"minecraft\")\n && storageUsername.equalsIgnoreCase(\"username\") && storagePassword.equalsIgnoreCase(\"password\")\n && storagePrefix.equalsIgnoreCase(\"\") && storageRefreshTime == 600);\n }\n return false;\n }\n}", "public enum NotificationType {\n NEW(0), MODIFICATION(1), COMPLETE(2), NOTIFYONLY(3), HOLD(5), DELETE(6);\n\n private int code;\n\n NotificationType(int code){\n this.code = code;\n }\n\n public int getCode(){\n return code;\n }\n\n public static NotificationType getTypeByCode(int code){\n for(NotificationType g : values()){\n if(g.code == code) return g;\n }\n return NotificationType.values()[0];\n }\n}", "public class TicketBroadcastEvent extends Event {\n\n private static final HandlerList handlers = new HandlerList();\n\n String message;\n CommandSender sender;\n\n public TicketBroadcastEvent(CommandSender sender, String message) {\n this.sender = sender;\n this.message = message;\n }\n\n /**\n * Get the broadcast message.\n *\n * @return a String with the broadcast message.\n */\n public String getMessage() {\n return message;\n }\n\n /**\n * Get the sender of the broadcast message.\n *\n * @return a CommandSender object of the user that sent the broadcast.\n */\n public CommandSender getSender() {\n return sender;\n }\n\n /**\n *\n * @return\n */\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n /**\n *\n * @return\n */\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n}", "public class BungeeCord {\n\n private static List<byte[]> pendingRequests = new CopyOnWriteArrayList<>();\n\n private static boolean noPlayersOnline;\n\n private static String serverName;\n\n public static void processPendingRequests(){\n if(!pendingRequests.isEmpty()){\n for(byte[] toSend : pendingRequests){\n Player player = Bukkit.getOnlinePlayers().iterator().next();\n if(player != null){\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", toSend);\n pendingRequests.remove(toSend);\n }else{\n break;\n }\n }\n }\n }\n\n public static void triggerAutoSync(){\n noPlayersOnline = Bukkit.getOnlinePlayers().isEmpty();\n }\n\n public static boolean isServerEmpty(){\n return noPlayersOnline;\n }\n\n public static String getServerName() {\n return serverName;\n }\n\n public static String getServer() {\n if(!ReportRTS.getPlugin().bungeeCordSupport) { return \"\"; }\n if(serverName != null) {\n return serverName;\n } else {\n Player player = Bukkit.getOnlinePlayers().iterator().next(); // This will error if no player is online.\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(b);\n try {\n out.writeUTF(\"GetServer\");\n } catch(IOException e) {\n e.printStackTrace();\n }\n if(player != null) {\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", b.toByteArray());\n } else {\n pendingRequests.add(b.toByteArray());\n }\n }\n return \"\";\n }\n\n public static void setServer(String server){\n if(!ReportRTS.getPlugin().bungeeCordSupport || server == null) return;\n if(serverName == null){\n serverName = server;\n ReportRTS.getPlugin().getConfig().set(\"bungeecord.serverName\", server);\n ReportRTS.getPlugin().saveConfig();\n }\n }\n\n public static void teleportUser(Player player, String targetServer, int ticketId) throws IOException{\n if(!ReportRTS.getPlugin().bungeeCordSupport || player == null || serverName == null) return;\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(b);\n out.writeUTF(\"Forward\");\n out.writeUTF(targetServer);\n out.writeUTF(\"ReportRTS\");\n\n ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();\n DataOutputStream msgout = new DataOutputStream(msgbytes);\n msgout.writeUTF(\"TeleportNotify\");\n msgout.writeInt(ticketId);\n msgout.writeUTF(player.getUniqueId().toString());\n out.writeShort(msgbytes.toByteArray().length);\n out.write(msgbytes.toByteArray());\n\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", b.toByteArray());\n\n // Teleport\n ByteArrayOutputStream b1 = new ByteArrayOutputStream();\n DataOutputStream out1 = new DataOutputStream(b1);\n out1.writeUTF(\"Connect\");\n out1.writeUTF(targetServer);\n\n out1.writeShort(msgbytes.toByteArray().length);\n out1.write(msgbytes.toByteArray());\n\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", b1.toByteArray());\n }\n\n public static void globalNotify(String message, int ticketId, NotificationType notifyType) throws IOException{\n if(!ReportRTS.getPlugin().bungeeCordSupport || serverName == null) return;\n\n String serverPrefix = (ReportRTS.getPlugin().bungeeCordServerPrefix == null || ReportRTS.getPlugin().bungeeCordServerPrefix.equals(\"\") ? \"[\" + serverName + \"]\" : Message.parseColors(ReportRTS.getPlugin().bungeeCordServerPrefix));\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(b);\n out.writeUTF(\"Forward\");\n out.writeUTF(\"ALL\");\n out.writeUTF(\"ReportRTS\");\n\n ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();\n DataOutputStream msgout = new DataOutputStream(msgbytes);\n msgout.writeUTF(\"NotifyAndSync\");\n msgout.writeInt(ticketId);\n msgout.writeInt(notifyType.getCode());\n msgout.writeUTF(serverPrefix + \" \" + message);\n\n out.writeShort(msgbytes.toByteArray().length);\n out.write(msgbytes.toByteArray());\n\n Player player = (Bukkit.getOnlinePlayers().isEmpty() ? null : Bukkit.getOnlinePlayers().iterator().next());\n if(player != null){\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", b.toByteArray());\n }else{\n pendingRequests.add(b.toByteArray());\n }\n }\n\n public static void notifyUser(UUID uuid, String message, int ticketId) throws IOException{\n if(!ReportRTS.getPlugin().bungeeCordSupport || serverName == null) return;\n\n String serverPrefix = (ReportRTS.getPlugin().bungeeCordServerPrefix == null || ReportRTS.getPlugin().bungeeCordServerPrefix.equals(\"\") ? \"[\" + serverName + \"]\" : Message.parseColors(ReportRTS.getPlugin().bungeeCordServerPrefix));\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(b);\n out.writeUTF(\"Forward\");\n out.writeUTF(\"ALL\");\n out.writeUTF(\"ReportRTS\");\n\n ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();\n DataOutputStream msgout = new DataOutputStream(msgbytes);\n msgout.writeUTF(\"NotifyUserAndSync\");\n msgout.writeInt(ticketId);\n msgout.writeUTF(uuid.toString());\n msgout.writeUTF(serverPrefix + \" \" + message);\n\n out.writeShort(msgbytes.toByteArray().length);\n out.write(msgbytes.toByteArray());\n\n Player player = (Bukkit.getOnlinePlayers().isEmpty() ? null : Bukkit.getOnlinePlayers().iterator().next());\n if(player != null){\n player.sendPluginMessage(ReportRTS.getPlugin(), \"BungeeCord\", b.toByteArray());\n }else{\n pendingRequests.add(b.toByteArray());\n }\n }\n\n public static void handleNotify(byte[] bytes){\n try{\n DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));\n String subChannel = in.readUTF();\n if(subChannel.equals(\"ReportRTS\")) {\n short len = in.readShort();\n byte[] msgbytes = new byte[len];\n in.readFully(msgbytes);\n DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes));\n String function = msgin.readUTF();\n if(function.equals(\"NotifyAndSync\")) {\n int ticketId = msgin.readInt();\n NotificationType notifType = NotificationType.getTypeByCode(msgin.readInt());\n String msg = msgin.readUTF();\n if(notifType.getCode() == 0 || notifType.getCode() == 1) {\n if(RTSFunctions.syncTicket(ticketId)){\n RTSFunctions.messageStaff(msg, (notifType.getCode() == 0));\n }\n } else if(notifType.getCode() == 3 || notifType.getCode() == 4) {\n RTSFunctions.messageStaff(msg, false);\n } else if(notifType.getCode() == 2 || notifType.getCode() == 5) {\n if(RTSFunctions.syncTicket(ticketId)) {\n if(notifType.getCode() == 2) ReportRTS.getPlugin().notifications.put(ticketId, ReportRTS.getPlugin().tickets.get(ticketId).getUUID());\n ReportRTS.getPlugin().tickets.remove(ticketId);\n RTSFunctions.messageStaff(msg, (notifType.getCode() == 0));\n }\n } else if(notifType.getCode() == 6) {\n ReportRTS.getPlugin().tickets.remove(ticketId);\n RTSFunctions.messageStaff(msg, (notifType.getCode() == 0));\n }\n } else if(function.equals(\"NotifyUserAndSync\")) {\n int ticketId = msgin.readInt();\n UUID uuid = UUID.fromString(msgin.readUTF());\n String msg = msgin.readUTF();\n if(RTSFunctions.syncTicket(ticketId)){\n Player player = Bukkit.getPlayer(uuid);\n if(player != null) {\n player.sendMessage(msg);\n if(ReportRTS.getPlugin().getDataProvider().setNotificationStatus(ticketId, true) < 1) ReportRTS.getPlugin().getLogger().warning(\"Unable to set notification status to 1.\");\n }\n }\n }else if(function.equals(\"TeleportNotify\")) {\n int ticketId = msgin.readInt();\n UUID uuid = UUID.fromString(msgin.readUTF());\n if(RTSFunctions.isUserOnline(uuid)) {\n Player player = Bukkit.getPlayer(uuid);\n if(player != null) {\n player.sendMessage(Message.teleportXServer((ReportRTS.getPlugin().legacyCommands ? \"/\" + ReportRTS.getPlugin().commandMap.get(\"teleportToTicket\") : \"/ticket \" + ReportRTS.getPlugin().commandMap.get(\"teleportToTicket\") + \" \" + Integer.toString(ticketId))));\n Bukkit.dispatchCommand(player, \"ticket \" + ReportRTS.getPlugin().commandMap.get(\"teleportToTicket\") + \" \" + Integer.toString(ticketId));\n } else {\n ReportRTS.getPlugin().teleportMap.put(uuid, ticketId);\n }\n } else {\n ReportRTS.getPlugin().teleportMap.put(uuid, ticketId);\n }\n }\n } else if(subChannel.equals(\"GetServer\")) {\n String serverName = in.readUTF();\n setServer(serverName);\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}", "public class Message {\n\n private static String parse(String key, Object ... params ){\n Object prop = ReportRTS.getMessageHandler().messageMap.get(key);\n if(prop == null) {\n if(!ReportRTS.getMessageHandler().getMessageConfig().getDefaults().contains(key))\n return \"Missing message <\" + key + \"> in ReportRTS/messages.yml, no default found.\";\n ReportRTS.getMessageHandler().messageMap.put(key, ReportRTS.getMessageHandler().getMessageConfig().getDefaults().getString(key));\n ReportRTS.getMessageHandler().getMessageConfig().set(key, ReportRTS.getMessageHandler().getMessageConfig().getDefaults().getString(key));\n prop = ReportRTS.getMessageHandler().getMessageConfig().getDefaults().getString(key);\n ReportRTS.getMessageHandler().saveMessageConfig();\n }\n return MessageFormat.format(parseColors((String) prop), params);\n }\n\n public static String parseColors(String msg){\n String message = msg;\n for(ChatColor color : ChatColor.values()){\n String colorKey = \"%\" + color.name().toLowerCase() + \"%\";\n if(message.contains(colorKey)){\n message = message.replaceAll(colorKey, color.toString());\n }\n }\n return message;\n }\n\n public static void debug(String name, String className, double start, String cmd, String[] args){\n String arguments = String.join(\" \", args);\n ReportRTS.getPlugin().getLogger().info(name + \" \" + className + \" took \" + RTSFunctions.getTimeSpent(start) + \"ms: \" + cmd + \" \" + arguments);\n }\n\n /** Easy access messages below. **/\n\n public static String broadcast(Object ... params) {\n return parse(\"broadcast\", params);\n }\n\n public static String banUser(String sender, String player) {\n return parse(\"ban-user\", sender, player);\n }\n\n public static String banRemove(String sender, String player) {\n return parse(\"ban-remove\", sender, player);\n }\n\n public static String error(Object ... params) {\n return parse(\"error\", params);\n }\n\n public static String errorBanned() {\n return parse(\"error-banned\");\n }\n\n public static String errorBanUser(String player) {\n return parse(\"error-ban-user\", player);\n }\n\n public static String errorUnbanUser(String player) {\n return parse(\"error-unban-user\", player);\n }\n\n public static String errorPermission(String ... params) {\n return parse(\"error-permission\", params);\n }\n\n public static String errorTicketStatus() {\n return parse(\"error-ticket-status\");\n }\n\n public static String errorTicketNotClosed(String ticketId) {\n return parse(\"error-ticket-not-closed\",ticketId);\n }\n\n public static String errorTicketNaN(String param) {\n return parse(\"error-ticket-nan\", param);\n }\n\n public static String errorTicketClaim(int ticketId, String player) {\n return parse(\"error-ticket-claim\", ticketId, player);\n }\n\n public static String errorTicketOwner() {\n return parse(\"error-ticket-owner\");\n }\n\n public static String errorUserNotExists(String player) {\n return parse(\"error-user-not-exists\", player);\n }\n\n public static String errorUserNotSpecified() {\n return parse(\"error-user-not-specified\");\n }\n\n public static String teleport(String ticketId) {\n return parse(\"teleport\", ticketId);\n }\n\n public static String teleportXServer(String cmd) {\n return parse(\"teleport-x-server\", cmd);\n }\n\n public static String ticketAssign(String player, int ticketId) {\n return parse(\"ticket-assign\", player, ticketId);\n }\n\n public static String ticketAssignUser(String player) {\n return parse(\"ticket-assign-user\", player);\n }\n\n public static String ticketUnresolved(Object ... params) {\n return parse(\"ticket-unresolved\", params);\n }\n\n public static String ticketUnresolvedHeld(Object ... params) {\n return parse(\"ticket-unresolved-held\", params);\n }\n\n public static String ticketUnclaim(String player, String ticketId) {\n return parse(\"ticket-unclaim\", player, ticketId);\n }\n\n public static String ticketUnclaimUser(String player, int ticketId) {\n return parse(\"ticket-unclaim-user\", player, ticketId);\n }\n\n public static String ticketComment(String ticketId, String player) {\n return parse(\"ticket-comment\", ticketId, player);\n }\n\n public static String ticketCommentText(String player, String comment) {\n return parse(\"ticket-comment-text\", player, comment);\n }\n\n public static String ticketCommentUser(String ticketId) {\n return parse(\"ticket-comment-user\", ticketId);\n }\n\n public static String ticketClaim(String player, String ticketId) {\n return parse(\"ticket-claim\", player, ticketId);\n }\n\n public static String ticketClaimUser(String player) {\n return parse(\"ticket-claim-user\", player);\n }\n\n public static String ticketHold(String ticketId, String player) {\n return parse(\"ticket-hold\", ticketId, player);\n }\n\n public static String ticketHoldText(String ... params) {\n return parse(\"ticket-hold-text\", params);\n }\n\n public static String ticketHoldUser(String player, int ticketId) {\n return parse(\"ticket-hold-user\", player, ticketId);\n }\n\n public static String ticketClose(String ticketId, String player) {\n return parse(\"ticket-close\", ticketId, player);\n }\n\n public static String ticketCloseUser(String ticketId, String player) {\n return parse(\"ticket-close-user\", ticketId, player);\n }\n\n public static String ticketCloseOffline() {\n return parse(\"ticket-close-offline\");\n }\n\n public static String ticketCloseOfflineMulti(int amount, String cmd) {\n return parse(\"ticket-close-offline-multi\", amount, cmd);\n }\n\n public static String ticketCloseText(String ... params) {\n return parse(\"ticket-close-text\", params);\n }\n\n public static String ticketDuplicate() {\n return parse(\"ticket-duplicate\");\n }\n\n public static String ticketNotExists(int ticketId) {\n return parse(\"ticket-not-exists\", ticketId);\n }\n\n public static String ticketNotClaimed(int ticketId) {\n return parse(\"ticket-not-claimed\", ticketId);\n }\n\n public static String ticketNotOpen(int ticketId) {\n return parse(\"ticket-not-open\", ticketId);\n }\n\n public static String ticketText(String message) {\n return parse(\"ticket-text\", message);\n }\n\n public static String ticketOpen(String player, String ticketId) {\n return parse(\"ticket-open\", player, ticketId);\n }\n\n public static String ticketOpenUser(String ticketId) {\n return parse(\"ticket-open-user\", ticketId);\n }\n\n public static String ticketReopen(String player, String ticketId) {\n return parse(\"ticket-reopen\", player, ticketId);\n }\n\n public static String ticketReadNone() {\n return parse(\"ticket-read-none\");\n }\n\n public static String ticketReadNoneSelf() {\n return parse(\"ticket-read-none-self\");\n }\n\n public static String ticketReadNoneHeld() {\n return parse(\"ticket-read-none-held\");\n }\n\n public static String ticketReadNoneClosed() {\n return parse(\"ticket-read-none-closed\");\n }\n\n public static String ticketTooShort(int words) {\n return parse(\"ticket-too-short\", words);\n }\n\n public static String ticketTooMany() {\n return parse(\"ticket-too-many\");\n }\n\n public static String ticketTooFast(long ticketId) {\n return parse(\"ticket-too-fast\", ticketId);\n }\n\n public static String staffListSeparator(String ... params) {\n return parse(\"staff-list-separator\", params);\n }\n\n public static String staffListEmpty(String ... params) {\n return parse(\"staff-list-empty\", params);\n }\n\n public static String staffListOnline(String ... params) {\n return parse(\"staff-list-online\", params);\n }\n\n public static String outdated(String version) {\n return parse(\"plugin-outdated\", version);\n }\n\n public static String setup() {\n return parse(\"plugin-not-setup\");\n }\n}" ]
import com.nyancraft.reportrts.RTSFunctions; import com.nyancraft.reportrts.RTSPermissions; import com.nyancraft.reportrts.ReportRTS; import com.nyancraft.reportrts.data.NotificationType; import com.nyancraft.reportrts.event.TicketBroadcastEvent; import com.nyancraft.reportrts.util.BungeeCord; import com.nyancraft.reportrts.util.Message; import org.bukkit.command.CommandSender; import java.io.IOException;
package com.nyancraft.reportrts.command.sub; public class BroadcastMessage { private static ReportRTS plugin = ReportRTS.getPlugin(); /** * Initial handling of the Broadcast sub-command. * @param sender player that sent the command * @param args arguments * @return true if command handled correctly */ public static boolean handleCommand(CommandSender sender, String[] args) { if(!RTSPermissions.canBroadcast(sender)) return true; if(args.length < 2) return false; args[0] = null; String message = String.join(" ", args); try {
BungeeCord.globalNotify(Message.broadcast(sender.getName(), message), -1, NotificationType.NOTIFYONLY);
3
cytomine/Cytomine-java-client
src/main/java/be/cytomine/client/collections/AttachedFileCollection.java
[ "public class Cytomine {\n\n private static final Logger log = LogManager.getLogger(Cytomine.class);\n static Cytomine CYTOMINE;\n\n CytomineConnection defaultCytomineConnection;\n private String host;\n private String login;\n private String pass;\n private String publicKey;\n private String privateKey;\n private String charEncoding = \"UTF-8\";\n\n private int max = 0;\n private int offset = 0;\n\n public enum Filter {ALL, PROJECT, ANNOTATION, IMAGE, ABSTRACTIMAGE} //TODO=> RENAME IMAGE TO IMAGEINSTANCE\n\n public enum Operator {OR, AND}\n\n /**\n * Init a Cytomine object\n *\n * @param host Full url of the Cytomine instance (e.g. 'http://...')\n * @param publicKey Your cytomine public key\n * @param privateKey Your cytomine private key\n */\n public static synchronized CytomineConnection connection(String host, String publicKey, String privateKey) {\n return connection(host, publicKey, privateKey, true);\n }\n\n public static synchronized CytomineConnection connection(String host, String publicKey, String privateKey, boolean setAsDefault) {\n if (CYTOMINE == null) CYTOMINE = new Cytomine(host, publicKey, privateKey);\n else {\n CYTOMINE.host = host;\n CYTOMINE.publicKey = publicKey;\n CYTOMINE.privateKey = privateKey;\n }\n CytomineConnection connection = new CytomineConnection(host, publicKey, privateKey);\n if (setAsDefault) {\n CYTOMINE.defaultCytomineConnection = connection;\n }\n return connection;\n }\n\n public CytomineConnection getDefaultCytomineConnection() {\n return defaultCytomineConnection;\n }\n\n /**\n * Get Cytomine singleton\n */\n public static Cytomine getInstance() throws CytomineException {\n if (CYTOMINE == null) throw new CytomineException(400, \"Connection parameters not set\");\n return CYTOMINE;\n }\n\n private Cytomine(String host, String publicKey, String privateKey) {\n this.host = host;\n this.publicKey = publicKey;\n this.privateKey = privateKey;\n this.login = publicKey;\n this.pass = privateKey;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public String getCharEncoding() {\n return charEncoding;\n }\n\n public void setCharEncoding(String charEncoding) {\n this.charEncoding = charEncoding;\n }\n\n public void setMax(int max) {\n this.max = max;\n }\n\n public void setOffset(int offset) {\n this.offset = offset;\n }\n\n /**\n * Get the public key of this connection.\n *\n * @return\n * @author Philipp Kainz\n * @since\n */\n public String getPublicKey() {\n return this.publicKey;\n }\n\n /**\n * Get the private key of this connection.\n *\n * @return\n * @author Philipp Kainz\n * @since\n */\n public String getPrivateKey() {\n return this.privateKey;\n }\n\n /**\n * Test the connection to the Cytomine host instance.\n * This test can be run by external applications to check for the\n * availability of the Cytomine-Core.\n *\n * @return true, if HTTP response code (200, 201, 304), i.e. the host is available\n * @throws Exception if the host is not available\n */\n boolean testHostConnection() throws Exception {\n HttpClient client = new HttpClient();\n client.connect(getHost() + \"/server/ping\", login, pass);\n int code = 0;\n try {\n code = client.get();\n } catch (Exception e) {\n log.error(e.toString());\n }\n client.disconnect();\n return code == 200 || code == 201 || code == 304;\n }\n\n /**\n * Check if Cytomine accept connection\n */\n public boolean isAlive() throws CytomineException {\n try {\n return testHostConnection();\n } catch (Exception e) {\n return false;\n }\n }\n\n /**\n * Wait for Cytomine to be ready. Retry every second until timeoutInSeconds\n * @param timeoutInSeconds Timeout until last retry (seconds)\n */\n public void waitToAcceptConnection(int timeoutInSeconds) throws CytomineException {\n waitToAcceptConnection(timeoutInSeconds, 1);\n }\n\n /**\n * Wait for Cytomine to be ready. Retry every delayBetweenRetryInSeconds until timeoutInSeconds\n * @param timeoutInSeconds Timeout until last retry (seconds)\n * @param delayBetweenRetryInSeconds Delay between a retry (seconds)\n */\n public void waitToAcceptConnection(int timeoutInSeconds, int delayBetweenRetryInSeconds) throws CytomineException {\n Instant timeAtStart = Instant.now();\n while(Duration.between(timeAtStart, Instant.now()).toMillis() < (timeoutInSeconds * 1000L)) {\n if (isAlive()) {\n return;\n }\n try { Thread.sleep(delayBetweenRetryInSeconds* 1000L);} catch (InterruptedException ignored) {};\n }\n throw new CytomineException(0, \"Cytomine cannot be reach on \" + host);\n }\n\n /**\n * Go to the next page of a collection\n *\n * @param collection Collection\n * @return False if end of collection (previous was last page)\n * @throws Exception\n */\n public boolean nextPage(Collection collection) throws CytomineException {\n collection.fetchNextPage();\n return !collection.isEmpty();\n }\n\n private String buildEncode(String keywords) throws CytomineException {\n try {\n return URLEncoder.encode(keywords, getCharEncoding());\n } catch (UnsupportedEncodingException e) {\n throw new CytomineException(e);\n }\n }\n\n private void analyzeCode(int code, JSONObject json) throws CytomineException {\n\n //if 200,201,...no exception\n if (code >= 400 && code < 600) {\n throw new CytomineException(code, json);\n } else if (code == 302) {\n throw new CytomineException(code, json);\n }\n }\n\n private JSONObject createJSONResponse(int code, String response) throws CytomineException {\n try {\n Object obj = JSONValue.parse(response);\n return (JSONObject) obj;\n } catch (Exception e) {\n log.error(e);\n throw new CytomineException(code, response);\n } catch (Error e) {\n log.error(e);\n throw new CytomineException(code, response);\n }\n }\n\n private JSONArray createJSONArrayResponse(int code, String response) throws CytomineException {\n Object obj = JSONValue.parse(response);\n return (JSONArray) obj;\n }\n\n\n\n public String clearAbstractImageProperties(Long idImage) throws CytomineException {\n AbstractImage abs = new AbstractImage();\n abs.set(\"id\", idImage);\n return abs.clearProperties();\n }\n\n public String populateAbstractImageProperties(Long idImage) throws CytomineException {\n AbstractImage abs = new AbstractImage();\n abs.set(\"id\", idImage);\n return abs.populateProperties();\n }\n\n public String extractUsefulAbstractImageProperties(Long idImage) throws CytomineException {\n AbstractImage abs = new AbstractImage();\n abs.set(\"id\", idImage);\n return abs.extractUsefulProperties();\n }\n\n public void downloadAbstractImage(long ID, int maxSize, String dest) throws CytomineException {\n String url = getHost() + \"/api/abstractimage/\" + ID + \"/thumb.png?maxSize=\" + maxSize;\n getDefaultCytomineConnection().downloadPicture(url, dest, \"png\");\n }\n\n public void downloadImageInstance(long ID, String dest) throws CytomineException {\n getDefaultCytomineConnection().downloadFile(\"/api/imageinstance/\" + ID + \"/download\", dest);\n }\n\n public BufferedImage getAbstractImageThumb(long ID, int maxSize) throws CytomineException {\n String url = getHost() + \"/api/abstractimage/\" + ID + \"/thumb.png?maxSize=\" + maxSize;\n return getDefaultCytomineConnection().getPictureAsBufferedImage(url, \"png\");\n }\n\n public AttachedFile uploadAttachedFile(String file, String domainClassName, Long domainIdent) throws CytomineException {\n String url = \"/api/attachedfile.json?domainClassName=\" + domainClassName + \"&domainIdent=\" + domainIdent;\n JSONObject json = getDefaultCytomineConnection().uploadFile(url, file);\n AttachedFile attachedFile = new AttachedFile();\n attachedFile.setAttr(json);\n return attachedFile;\n }\n\n public void uploadJobData(Long idJobData, byte[] data) throws CytomineException {\n JobData jobData = new JobData();\n jobData.set(\"id\",idJobData);\n jobData.uploadJobData(data);\n }\n\n public void downloadJobData(Long idJobData, String file) throws CytomineException {\n JobData jobData = new JobData();\n jobData.set(\"id\",idJobData);\n jobData.downloadJobData(file);\n }\n\n public void downloadAnnotation(Annotation annotation, String path) throws CytomineException {\n String url = annotation.getStr(\"url\");\n getDefaultCytomineConnection().downloadPicture(url, path);\n }\n\n\n public void uploadImage(String uploadURL, String file, String cytomineHost) throws CytomineException {\n uploadImage(uploadURL, file, null, null, cytomineHost);\n }\n\n /**\n * Upload and create an abstract image on the plateform (use async upload)\n *\n * @param file The image file path\n * @param idProject If not null, add the image in this project\n * @param idStorage The storage where the image will be copied\n * @param cytomineHost The URL of the Core\n * @return A response with the status, the uploadedFile and the AbstractImage list\n * @throws Exception Error during upload\n */\n public JSONArray uploadImage(String uploadURL, String file, Long idProject, Long idStorage, String cytomineHost) throws CytomineException {\n return uploadImage(uploadURL, file, idProject, idStorage, cytomineHost, null, false);\n }\n\n /**\n * Upload and create an abstract image on the plateform (use async or sync upload depending on synchrone parameter)\n *\n * @param file The image file path\n * @param idProject If not null, add the image in this project\n * @param idStorage The storage where the image will be copied\n * @param cytomineHost The URL of the Core\n * @param properties These key-value will be add to the AbstractImage as Property domain instance\n * @param synchrone If true, the response will be send from server when the image will be converted, transfered, created,...(May take a long time)\n * Otherwise the server response directly after getting the image and the parameters\n * @return A response with the status, the uploadedFile and the AbstractImage list (only if synchrone!=true)\n * @throws Exception Error during upload\n */\n public JSONArray uploadImage(String uploadURL, String file, Long idProject, Long idStorage, String cytomineHost, Map<String, String> properties, boolean synchrone) throws CytomineException {\n\n CytomineConnection uploadConnection = Cytomine.connection(\n uploadURL,\n Cytomine.getInstance().getDefaultCytomineConnection().getPublicKey(),\n Cytomine.getInstance().getDefaultCytomineConnection().getPrivateKey(),\n false);\n\n Map<String, String> entityParts = new HashMap<>();\n if (idProject != null) {\n entityParts.put(\"idProject\", idProject + \"\");\n }\n if (idStorage != null) {\n entityParts.put(\"idStorage\", idStorage + \"\");\n }\n\n String projectParam = \"\";\n if (idProject != null && idProject != 0l) {\n projectParam = \"&idProject=\" + idProject;\n }\n\n String url = \"/upload?idStorage=\" + idStorage + \"&cytomine=\" + cytomineHost + projectParam;\n if (properties != null && properties.size() > 0) {\n List<String> keys = new ArrayList<String>();\n List<String> values = new ArrayList<String>();\n for (Map.Entry<String, String> entry : properties.entrySet()) {\n keys.add(entry.getKey());\n values.add(entry.getValue());\n }\n url = url + \"&keys=\" + StringUtils.join(keys, \",\") + \"&values=\" + StringUtils.join(values, \",\");\n }\n if (synchrone) {\n url = url + \"&sync=\" + true;\n }\n\n return uploadConnection.uploadImage(file, url, entityParts );\n }\n\n\n\n\n public void simplifyAnnotation(Long idAnnotation, Long minPoint, Long maxPoint) throws CytomineException {\n String url = \"/api/annotation/\" + idAnnotation + \"/simplify.json?minPoint=\" + minPoint + \"&maxPoint=\" + maxPoint;\n defaultCytomineConnection.doPut(url, \"\");\n }\n\n /**\n * Deletes all existing terms assigned by the calling user\n * from an annotation and sets a unique term.\n * <p>\n * This is basically the client implementation of the web-service endpoint\n * <code>/api/annotation/:idAnnotation/term/:idTerm/clearBefore.json</code>.\n * </p>\n *\n * @param idAnnotation\n * @param idTerm\n * @return the AnnotationTerm instance\n * @throws CytomineException if the term cannot be set\n * @author Philipp Kainz\n * @since 2015-01-06\n */\n public AnnotationTerm setAnnotationTerm(Long idAnnotation, Long idTerm) throws CytomineException {\n try {\n AnnotationTerm annotationTerm = new AnnotationTerm();\n annotationTerm.set(\"userannotation\", idAnnotation);\n annotationTerm.set(\"annotationIdent\", idAnnotation);\n annotationTerm.set(\"term\", idTerm);\n\n // bypass the default saveModel(Model model) method and use the\n // clearBefore url for setting the term to the annotation\n Model model = annotationTerm;\n\n String clearBeforeURL = \"/api/annotation/\" + idAnnotation + \"/term/\"\n + idTerm + \"/clearBefore.json\";\n\n HttpClient client = null;\n client = new HttpClient(publicKey, privateKey, getHost());\n client.authorize(\"POST\", clearBeforeURL, \"\", \"application/json,*/*\");\n client.connect(getHost() + clearBeforeURL);\n int code = client.post(model.toJSON());\n String response = client.getResponseData();\n client.disconnect();\n JSONObject json = createJSONResponse(code, response);\n analyzeCode(code, json);\n model.setAttr((JSONObject) json.get(model.getDomainName()));\n return (AnnotationTerm) model;\n } catch (IOException e) {\n throw new CytomineException(e);\n }\n }\n\n public AnnotationCollection getAnnotationsByTermAndProject(Long idTerm, Long idProject) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"term\", idTerm + \"\");\n annotations.addFilter(\"project\", idProject + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n public AnnotationCollection getAnnotations(Map<String, String> filters) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n //http://beta.cytomine.be/api/annotation.json?user=14794107&image=14391346&term=8171841\n for (Map.Entry<String, String> entry : filters.entrySet()) {\n annotations.addFilter(entry.getKey(), entry.getValue());\n }\n return (AnnotationCollection) annotations.fetch();\n }\n\n public AnnotationCollection getAnnotationsByTermAndImage(Long idTerm, Long idImage) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"term\", idTerm + \"\");\n annotations.addFilter(\"imageinstance\", idImage + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n public AnnotationTerm getAnnotationTerm(Long idAnnotation, Long idTerm) throws CytomineException {\n AnnotationTerm annotationTerm = new AnnotationTerm(idAnnotation,idTerm);\n return annotationTerm.fetch(idAnnotation.toString(),idTerm.toString());\n }\n\n public void deleteAnnotationTerm(Long idAnnotation, Long idTerm) throws CytomineException {\n AnnotationTerm annotationTerm = new AnnotationTerm();\n annotationTerm.set(\"annotation\", idAnnotation);\n annotationTerm.set(\"userannotation\", idAnnotation);\n annotationTerm.set(\"term\", idTerm);\n annotationTerm.delete();\n }\n\n public void addUserFromLDAP(String username) throws CytomineException {\n defaultCytomineConnection.doPost(\"/api/ldap/user.json?username=\" + username, \"\");\n }\n\n public User getCurrentUser() throws CytomineException {\n return defaultCytomineConnection.getCurrentUser();\n }\n\n /*public User getUserByUsername(String username) throws CytomineException {\n User user = new User();\n user.set(\"username get\", username);\n return defaultCytomineConnection.fetchModel(user);\n }*/\n\n public void addACL(String domainClassName, Long domainIdent, Long idUser, String auth) throws CytomineException {\n defaultCytomineConnection.doPost(\"/api/domain/\" + domainClassName + \"/\" + domainIdent + \"/user/\" + idUser + \".json?auth=\" + auth, \"\");\n }\n\n public void addUserProject(Long idUser, Long idProject) throws CytomineException {\n addUserProject(idUser, idProject, false);\n }\n\n public void addUserProject(Long idUser, Long idProject, boolean admin) throws CytomineException {\n defaultCytomineConnection.doPost(\"/api/project/\" + idProject + \"/user/\" + idUser + (admin ? \"/admin\" : \"\") + \".json\", \"\");\n }\n\n public void deleteUserProject(Long idUser, Long idProject) throws CytomineException {\n deleteUserProject(idUser, idProject, false);\n }\n\n public void deleteUserProject(Long idUser, Long idProject, boolean admin) throws CytomineException {\n defaultCytomineConnection.doDelete(\"/api/project/\" + idProject + \"/user/\" + idUser + (admin ? \"/admin\" : \"\") + \".json\");\n }\n\n public UserCollection getProjectUsers(Long idProject) throws CytomineException {\n UserCollection users = new UserCollection(offset, max);\n users.addFilter(\"project\", idProject + \"\");\n return (UserCollection) users.fetch();\n }\n\n public UserCollection getProjectAdmins(Long idProject) throws CytomineException {\n UserCollection users = new UserCollection(offset, max);\n users.addFilter(\"project\", idProject + \"\");\n users.addFilter(\"admin\", \"true\");\n return (UserCollection) users.fetch();\n }\n\n\n public void doUserPosition(Long idImage, Long x, Long y, Long zoom) throws CytomineException {\n //image, coord.x, coord.y, coord.zoom\n String data = \"{image : \" + idImage + \", lat : \" + x + \", lon : \" + y + \", zoom : \" + zoom + \"}\";\n defaultCytomineConnection.doPost(\"/api/imageinstance/\" + idImage + \"/position.json\", data);\n }\n\n public void doUserPosition(\n Long idImage,\n Long zoom,\n Long bottomLeftX,\n Long bottomLeftY,\n Long bottomRightX,\n Long bottomRightY,\n Long topLeftX,\n Long topLeftY,\n Long topRightX,\n Long topRightY) throws CytomineException {\n //image, coord.x, coord.y, coord.zoom\n String data = \"{image : \" + idImage + \", zoom : \" + zoom\n + \", bottomLeftX : \" + bottomLeftX + \", bottomLeftY : \" + bottomLeftY\n + \", bottomRightX : \" + bottomRightX + \", bottomRightY : \" + bottomRightY\n + \", topLeftX : \" + topLeftX + \", topLeftY : \" + topLeftY\n + \", topRightX : \" + topRightX + \", topRightY : \" + topRightY + \"}\";\n defaultCytomineConnection.doPost(\"/api/imageinstance/\" + idImage + \"/position.json\", data);\n }\n\n public User getUser(String publicKey) throws CytomineException {\n User user = new User();\n user.addParams(\"publicKey\", publicKey);\n return user.fetch(null);\n }\n\n /**\n * Forge an authentication token for the user with the related username and for a given validity\n *\n * @param username username of the targeted user\n * @param validity Number of minutes for the validity of the token\n * @return The token key that will allow temporary authentication\n */\n public String buildAuthenticationToken(String username, Long validity) throws CytomineException {\n String data = \"{username : \" + username + \", validity : \" + validity + \"}\";\n JSONObject json = defaultCytomineConnection.doPost(\"/api/token.json\", data);\n\n if(Boolean.parseBoolean(json.get(\"success\").toString())) {\n JSONObject token = (JSONObject) json.get(\"token\");\n return token.get(\"tokenKey\").toString();\n }\n return null;\n }\n\n\tpublic String getImageServersOfAbstractImage(Long abstractImageID) {\n\n\t\tString subUrl = \"/api/abstractimage/\"+abstractImageID+\"/imageservers.json\";\n\n\t\t HttpClient client = null;\n client = new HttpClient(publicKey, privateKey, getHost());\n\n\n\t\t\ttry {\n\t client.authorize(\"GET\", subUrl, \"\", \"application/json,*/*\");\n\t client.connect(getHost() + subUrl);\n\t int code = client.get();\n\n\t String response = client.getResponseData();\n\t client.disconnect();\n\t JSONObject json = createJSONResponse(code, response);\n \tanalyzeCode(code, json);\n\n \tJSONArray servers = (JSONArray) json.get(\"imageServersURLs\");\n\n \treturn (String) servers.get(0);\n\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CytomineException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\treturn null;\n\t}\n\n public Collection<ImageServer> getAbstractImageServers(AbstractImage abstractImage) throws CytomineException {\n Collection<ImageServer> imageServers = new Collection<>(ImageServer.class,0,0);\n imageServers.addFilter(\"abstractimage\", \"\" + abstractImage.getId());\n return imageServers.fetch();\n }\n\tpublic Collection<ImageServer> getImageInstanceServers(ImageInstance image) throws CytomineException {\n\t\tAbstractImage abstractImage = new AbstractImage();\n\t\tabstractImage.set(\"id\", image.get(\"baseImage\"));\n\t\treturn getAbstractImageServers(abstractImage);\n\t}\n\n public User getKeys(String publicKey) throws CytomineException {\n User user = new User();\n user.addFilter(\"publicKeyFilter\", publicKey);\n return user.fetch(null);\n }\n\n public User getKeys(Long id) throws CytomineException {\n User user = new User();\n user.addFilter(\"id\", id + \"\");\n user.addFilter(\"keys\", \"keys\");\n return user.fetch(id);\n }\n\n /*public User getKeysByUsername(String username) throws CytomineException {\n User user = new User();\n user.addFilter(\"id\", username + \"\");\n user.addFilter(\"keys\", \"keys\");\n return user.fetch();\n }*/\n\n public Job changeStatus(Long id, Job.JobStatus status, int progress) throws CytomineException {\n return this.changeStatus(id, status.getValue(), progress);\n }\n\n public Job changeStatus(Long id, Job.JobStatus status, int progress, String comment) throws CytomineException {\n return this.changeStatus(id, status.getValue(), progress, comment);\n }\n\n public Job changeStatus(Long id, int status, int progress) throws CytomineException {\n return this.changeStatus(id, status, progress, null);\n }\n\n public Job changeStatus(Long id, int status, int progress, String comment) throws CytomineException {\n Job job = new Job().fetch(id);\n return job.changeStatus(status, progress, comment);\n }\n\n public User addUserJob(Long idSoftware, Long idProject, Long idUserParent) throws CytomineException {\n return addUserJob(idSoftware, idUserParent, idProject, new Date(), null);\n }\n\n public User addUserJob(Long idSoftware, Long idUserParent, Long idProject, Date created, Long idJob) throws CytomineException {\n UserJob user = new UserJob();\n user.set(\"parent\", idUserParent);\n user.set(\"software\", idSoftware);\n user.set(\"project\", idProject);\n user.set(\"job\", idJob);\n user.set(\"created\", created.getTime());\n user = user.save();\n User userFinal = new User();\n userFinal.setAttr(user.getAttr());\n return userFinal;\n }\n\n public void unionAnnotation(Long idImage, Long idUser, Integer minIntersectionLength) throws CytomineException {\n AnnotationUnion annotation = new AnnotationUnion();\n annotation.addParams(\"idImage\", idImage + \"\");\n annotation.addParams(\"idUser\", idUser + \"\");\n annotation.addParams(\"minIntersectionLength\", minIntersectionLength + \"\");\n annotation.update();\n }\n\n public ReviewedAnnotationCollection getReviewedAnnotationsByTermAndImage(Long idTerm, Long idImage) throws CytomineException {\n ReviewedAnnotationCollection reviewed = new ReviewedAnnotationCollection(offset, max);\n reviewed.addFilter(\"term\", idTerm + \"\");\n reviewed.addFilter(\"imageinstance\", idImage + \"\");\n return (ReviewedAnnotationCollection)reviewed.fetch();\n }\n\n\n //PROPERTY\n public Property getDomainProperty(Long id, Long domainIdent, String domain) throws CytomineException {\n Property property = new Property(domain,domainIdent);\n return property.fetch(id);\n }\n\n public PropertyCollection getDomainProperties(String domain, Long domainIdent) throws CytomineException {\n PropertyCollection properties = new PropertyCollection(offset, max);\n properties.addFilter(domain, domainIdent + \"\");\n properties.addFilter(\"domainClassName\", domain + \"\");\n properties.addFilter(\"domainIdent\", domainIdent + \"\");\n return (PropertyCollection)properties.fetch();\n }\n\n public Property getPropertyByDomainAndKey(String domain, Long domainIdent, String key) throws CytomineException {\n Property property = new Property(domain,domainIdent);\n property.set(\"key\", key);\n return property.fetch(key);\n }\n\n public Property addDomainProperties(String domain, Long domainIdent, String key, String value) throws CytomineException {\n Property property = new Property(domain,domainIdent);\n property.set(\"key\", key);\n property.set(\"value\", value);\n return property.save();\n }\n\n public Property editDomainProperty(String domain, Long id, Long domainIdent, String key, String value) throws CytomineException {\n Property property = getDomainProperty(id, domainIdent, domain);\n property.set(\"domain\", domain);\n property.set(\"domainIdent\", domainIdent);\n property.set(\"key\", key);\n property.set(\"value\", value);\n return property.update();\n }\n\n public void deleteDomainProperty(String domain, Long id, Long domainIdent) throws CytomineException {\n Property property = getDomainProperty(id, domainIdent, domain);\n property.set(\"id\", id);\n property.set(\"domain\", domain);\n property.set(\"domainIdent\", domainIdent);\n property.delete();\n }\n\n //For ImageInstance ==> idDomain = id of Project\n //and Annotation ==> idDomain = id of Project or Image\n public PropertyCollection getKeysForDomain(String domain, String nameIdDomain, Long idDomain) throws CytomineException {\n PropertyCollection properties = new PropertyCollection(offset, max);\n properties.addFilter(domain, \"\");\n properties.addFilter(\"idDomain\", idDomain + \"\");\n properties.addFilter(\"nameIdDomain\", nameIdDomain);\n return (PropertyCollection)properties.fetch();\n }\n\n //SEARCH\n\n public SearchCollection getSearch(String keywords, Operator operator, Filter filter) throws CytomineException {\n return getSearch(keywords, operator, filter, null);\n }\n\n public SearchCollection getSearch(String keywords, Operator operator, Filter filter, List<Long> idProjects) throws CytomineException {\n SearchCollection search = new SearchCollection(offset, max);\n if (operator == null) {\n operator = Operator.OR;\n }\n if (filter == null) {\n filter = Filter.ALL;\n }\n search.addFilter(\"keywords\", buildEncode(keywords));\n search.addFilter(\"operator\", buildEncode(operator + \"\"));\n search.addFilter(\"filter\", buildEncode(filter + \"\"));\n if (idProjects != null) {\n ArrayList<String> list = new ArrayList<String>();\n for (int i = 0; i < idProjects.size(); i++) {\n list.add(idProjects.get(i) + \"\");\n }\n search.addFilter(\"projects\", Cytomine.join(list, \", \"));\n }\n\n return (SearchCollection) search.fetch();\n }\n\n\n //:to do move this method into Utils package\n public static String join(ArrayList s, String delimiter) {\n if (s.size() == 0) return \"\";\n StringBuffer buffer = new StringBuffer();\n Iterator iterator = s.iterator();\n while (iterator.hasNext()) {\n buffer.append(iterator.next());\n if (iterator.hasNext()) {\n buffer.append(delimiter);\n }\n }\n return buffer.toString();\n }\n\n public String resetPassword(Long idUser, String newPassword) throws CytomineException {\n\t\treturn getDefaultCytomineConnection().doPut(\"/api/user/\" + idUser + \"/password.json\", \"{password: \"+newPassword+\"}\").toString();\n }\n\n public Description getDescription(Long domainIdent, String domainClassName) throws CytomineException {\n Description description = new Description();\n return description.fetch(domainClassName, domainIdent.toString());\n }\n\n\n public Description addDescription(Long domainIdent, String domainClassName, String text) throws CytomineException {\n Description description = new Description();\n description.set(\"domainIdent\", domainIdent);\n description.set(\"domainClassName\", domainClassName);\n description.set(\"data\", text);\n return description.save();\n }\n\n public Description editDescription(Long domainIdent, String domainClassName, String text) throws CytomineException {\n Description description = getDescription(domainIdent, domainClassName);\n description.set(\"domainIdent\", domainIdent);\n description.set(\"domainClassName\", domainClassName);\n description.set(\"data\", text);\n return description.update();\n }\n\n public void deleteDescription(Long domainIdent, String domainClassName) throws CytomineException {\n Description description = getDescription(domainIdent, domainClassName);\n description.set(\"domainIdent\", domainIdent);\n description.set(\"domainClassName\", domainClassName);\n description.delete();\n }\n\n public Map<String, Long> getRoleMap() throws CytomineException {\n Map<String, Long> map = new TreeMap<String, Long>();\n Collection<Role> roles = Collection.fetch(Role.class);\n for (int i = 0; i < roles.size(); i++) {\n map.put(roles.get(i).getStr(\"authority\"), roles.get(i).getLong(\"id\"));\n }\n return map;\n }\n\n public Role addRole(Long idUser, Long idRole) throws CytomineException {\n Role role = new Role();\n role.set(\"user\", idUser + \"\");\n role.set(\"role\", idRole + \"\");\n role.addFilter(\"user\", idUser + \"\");\n return role.save();\n }\n\n\n public void deleteRole(Long idUser, Long idRole) throws CytomineException {\n Role role = new Role();\n role.set(\"user\", idUser + \"\");\n role.set(\"role\", idRole + \"\");\n role.addFilter(\"user\", idUser + \"\");\n role.addFilter(\"role\", idRole + \"\");\n role.delete();\n }\n\n public AbstractImage addNewImage(Long idUploadedFile, String path, String filename, String mimeType) throws CytomineException {\n return addNewImage(idUploadedFile, path, filename, null, mimeType);\n }\n\n public AbstractImage addNewImage(Long idUploadedFile, String path, String filename, String originalFilename, String mimeType) throws CytomineException {\n AbstractImage image = new AbstractImage();\n image.set(\"path\",path);\n image.set(\"filename\",filename);\n if(originalFilename != null) image.set(\"originalFilename\",originalFilename);\n image.set(\"mimeType\",mimeType);\n image.addFilter(\"uploadedFile\", idUploadedFile + \"\");\n return image.save();\n }\n\n public UploadedFileCollection getUploadedFiles(boolean deleted) throws CytomineException {\n UploadedFileCollection files = new UploadedFileCollection(offset, max);\n files.addParams(\"deleted\", \"true\");\n return (UploadedFileCollection)files.fetch();\n }\n\n\n public String getSimplified(String wkt, Long min, Long max) throws CytomineException {\n Annotation annotation = new Annotation();\n annotation.set(\"wkt\", wkt);\n return getDefaultCytomineConnection().doPost(\"/api/simplify.json?minPoint=\" + min + \"&maxPoint=\" + max, annotation.toJSON()).toString();\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n // Still here for backward compatibility\n\n @Deprecated\n public Project editProject(Long idProject, String name, Long idOntology) throws CytomineException {\n Project project = new Project().fetch(idProject);\n project.set(\"name\", name);\n project.set(\"ontology\", idOntology);\n return project.update();\n }\n\n @Deprecated\n public Ontology editOntology(Long idOntology, String name) throws CytomineException {\n Ontology ontology = new Ontology().fetch(idOntology);\n ontology.set(\"name\", name);\n return ontology.update();\n }\n\n @Deprecated\n public Annotation editAnnotation(Long idAnnotation, String locationWKT) throws CytomineException {\n Annotation annotation = new Annotation().fetch(idAnnotation);\n annotation.set(\"location\", locationWKT);\n return annotation.update();\n }\n\n @Deprecated\n public Term editTerm(Long idTerm, String name, String color, Long idOntology) throws CytomineException {\n Term term = new Term().fetch(idTerm);\n term.set(\"name\", name);\n term.set(\"color\", color);\n term.set(\"ontology\", idOntology);\n return term.update();\n }\n\n @Deprecated\n public JobData editJobData(Long idJobData, String key, Long idJob, String filename) throws CytomineException {\n JobData jobData = new JobData().fetch(idJobData);\n jobData.set(\"key\", key);\n jobData.set(\"job\", idJob);\n jobData.set(\"filename\", filename);\n return jobData.update();\n }\n\n @Deprecated\n public UploadedFile editUploadedFile(Long id, int status, boolean converted, Long idParent) throws CytomineException {\n UploadedFile uploadedFile = new UploadedFile().fetch(id);\n uploadedFile.set(\"status\", status);\n uploadedFile.set(\"converted\", converted);\n uploadedFile.set(\"parent\", idParent);\n return uploadedFile.update();\n }\n\n @Deprecated\n public UploadedFile editUploadedFile(Long id, int status, boolean converted) throws CytomineException {\n UploadedFile uploadedFile = new UploadedFile().fetch(id);\n uploadedFile.set(\"status\", status);\n uploadedFile.set(\"converted\", converted);\n return uploadedFile.update();\n }\n\n @Deprecated\n public UploadedFile editUploadedFile(Long id, int status) throws CytomineException {\n UploadedFile uploadedFile = new UploadedFile().fetch(id);\n uploadedFile.set(\"status\", status);\n return uploadedFile.update();\n }\n\n // Still here for backward compatibility\n // one line functions\n\n @Deprecated\n public Project getProject(Long id) throws CytomineException {\n return new Project().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(Project.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ProjectCollection getProjects() throws CytomineException {\n ProjectCollection projects = new ProjectCollection(offset, max);\n return (ProjectCollection) projects.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Project.class,Ontology.class,idOntology,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ProjectCollection getProjectsByOntology(Long idOntology) throws CytomineException {\n ProjectCollection projects = new ProjectCollection(offset, max);\n projects.addFilter(\"ontology\", idOntology + \"\");\n return (ProjectCollection)projects.fetch();\n }\n /**\n * Deprecated. Use Collection.fetchWithFilter(Project.class,User.class,idUser,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ProjectCollection getProjectsByUser(Long idUser) throws CytomineException {\n ProjectCollection projects = new ProjectCollection(offset, max);\n projects.addFilter(\"user\", idUser + \"\");\n return (ProjectCollection)projects.fetch();\n }\n\n @Deprecated\n public Project addProject(String name, Long idOntology) throws CytomineException {\n return new Project(name,idOntology).save();\n }\n\n @Deprecated\n public void deleteProject(Long idProject) throws CytomineException {\n new Project().delete(idProject);\n }\n\n @Deprecated\n public Ontology getOntology(Long id) throws CytomineException {\n return new Ontology().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(Ontology.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public OntologyCollection getOntologies() throws CytomineException {\n OntologyCollection ontologys = new OntologyCollection(offset, max);\n return (OntologyCollection)ontologys.fetch();\n }\n\n @Deprecated\n public Ontology addOntology(String name) throws CytomineException {\n return new Ontology(name).save();\n }\n\n @Deprecated\n public void deleteOntology(Long idOntology) throws CytomineException {\n new Ontology().delete(idOntology);\n }\n\n @Deprecated\n public AbstractImage addAbstractImage(String filename, String mime) throws CytomineException {\n return new AbstractImage(filename,mime).save();\n }\n\n @Deprecated\n public AbstractImage getAbstractImage(Long id) throws CytomineException {\n return new AbstractImage().fetch(id);\n }\n\n @Deprecated\n public ImageInstance getImageInstance(Long id) throws CytomineException {\n return new ImageInstance().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(ImageInstance.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ImageInstanceCollection getImageInstances(Long idProject) throws CytomineException {\n ImageInstanceCollection image = new ImageInstanceCollection(offset, max);\n image.addFilter(\"project\", idProject + \"\");\n return (ImageInstanceCollection) image.fetch();\n }\n /**\n * Deprecated. Use Collection.fetchWithFilter(ImageInstance.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ImageInstanceCollection getImageInstancesByOffsetWithMax(Long idProject, int offset, int max) throws CytomineException {\n ImageInstanceCollection image = new ImageInstanceCollection(offset, max);\n image.addFilter(\"project\", idProject + \"\");\n image.addFilter(\"offset\", offset + \"\");\n image.addFilter(\"max\", max + \"\");\n return (ImageInstanceCollection) image.fetch();\n }\n\n @Deprecated\n public ImageInstance addImageInstance(Long idAbstractImage, Long idProject) throws CytomineException {\n return new ImageInstance(idAbstractImage, idProject).save();\n }\n\n @Deprecated\n public void deleteImageInstance(Long idImageInstance) throws CytomineException {\n new ImageInstance().delete(idImageInstance);\n }\n\n @Deprecated\n public Annotation getAnnotation(Long id) throws CytomineException {\n return new Annotation().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(Annotation.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotations() throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n return (AnnotationCollection) annotations.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Annotation.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotationsByProject(Long idProject) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"project\", idProject + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Annotation.class,Term.class,idTerm,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotationsByTerm(Long idTerm) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"term\", idTerm + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Annotation.class,User.class,idUser,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotationsByUser(Long idUser) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"user\", idUser + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Annotation.class,Ontology.class,idOntology,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotationsByOntology(Long idOntology) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"ontology\", idOntology + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Annotation.class,ImageInstance.class,idImage,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AnnotationCollection getAnnotationsByImage(Long idImage) throws CytomineException {\n AnnotationCollection annotations = new AnnotationCollection(offset, max);\n annotations.addFilter(\"image\", idImage + \"\");\n return (AnnotationCollection) annotations.fetch();\n }\n\n @Deprecated\n public Annotation addAnnotation(String locationWKT, Long image) throws CytomineException {\n return new Annotation(locationWKT,image).save();\n }\n\n @Deprecated\n public Annotation addAnnotationWithTerms(String locationWKT, Long image, List<Long> terms) throws CytomineException {\n return new Annotation(locationWKT,image,terms).save();\n }\n\n @Deprecated\n public Annotation addAnnotation(String locationWKT, Long image, Long project) throws CytomineException {\n return new Annotation(locationWKT,image,project).save();\n }\n\n @Deprecated\n public void deleteAnnotation(Long idAnnotation) throws CytomineException {\n new Annotation().delete(idAnnotation);\n }\n\n @Deprecated\n public Term getTerm(Long id) throws CytomineException {\n return new Term().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(Term.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public TermCollection getTerms() throws CytomineException {\n TermCollection terms = new TermCollection(offset, max);\n return (TermCollection) terms.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Term.class,Ontology.class,idOntology,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public TermCollection getTermsByOntology(Long idOntology) throws CytomineException {\n TermCollection terms = new TermCollection(offset, max);\n terms.addFilter(\"ontology\", idOntology + \"\");\n return (TermCollection) terms.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Term.class,Annotation.class,idAnnotation,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public TermCollection getTermsByAnnotation(Long idAnnotation) throws CytomineException {\n TermCollection terms = new TermCollection(offset, max);\n terms.addFilter(\"annotation\", idAnnotation + \"\");\n return (TermCollection) terms.fetch();\n }\n\n @Deprecated\n public Term addTerm(String name, String color, Long idOntology) throws CytomineException {\n return new Term(name,color,idOntology).save();\n }\n\n @Deprecated\n public void deleteTerm(Long idTerm) throws CytomineException {\n new Term().delete(idTerm);\n }\n\n @Deprecated\n public AnnotationTerm addAnnotationTerm(Long idAnnotation, Long idTerm) throws CytomineException {\n return new AnnotationTerm(idAnnotation,idTerm).save();\n }\n\n @Deprecated\n public AnnotationTerm addAnnotationTerm(Long idAnnotation, Long idTerm, Long idExpectedTerm, Long idUser, double rate) throws CytomineException {\n return new AnnotationTerm(idAnnotation,idTerm,idExpectedTerm,idUser,rate).save();\n }\n\n @Deprecated\n public User addUser(String username, String firstname, String lastname, String email, String password) throws CytomineException {\n return new User(username,firstname,lastname,email,password).save();\n }\n\n @Deprecated\n public User getUser(Long id) throws CytomineException {\n return new User().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(User.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public UserCollection getUsers() throws CytomineException {\n UserCollection users = new UserCollection(offset, max);\n return (UserCollection) users.fetch();\n }\n\n @Deprecated\n public UserJob getUserJob(Long id) throws CytomineException {\n return new UserJob().fetch(id);\n }\n\n @Deprecated\n public Job getJob(Long id) throws CytomineException {\n return new Job().fetch(id);\n }\n\n @Deprecated\n public Software addSoftware(String name, Long idSoftwareUserRepository, Long idDefaultProcessingServer, String resultType, String executeCommand) throws CytomineException {\n return new Software(name, resultType, executeCommand, \"\", idSoftwareUserRepository, idDefaultProcessingServer).save();\n }\n\n @Deprecated\n public void deleteSoftware(Long idSoftware) throws CytomineException {\n new Software().delete(idSoftware);\n }\n\n @Deprecated\n public SoftwareParameter addSoftwareParameter(String name, String type, Long idSoftware, String defaultValue, boolean required, int index, String uri, String uriSortAttribut, String uriPrintAttribut, boolean setByServer) throws CytomineException {\n return new SoftwareParameter(name,type,idSoftware,defaultValue,required,index,uri,uriSortAttribut,uriPrintAttribut,setByServer).save();\n }\n\n @Deprecated\n public SoftwareParameter addSoftwareParameter(String name, String type, Long idSoftware, String defaultValue, boolean required, int index, String uri, String uriSortAttribut, String uriPrintAttribut) throws CytomineException {\n return addSoftwareParameter(name, type, idSoftware, defaultValue, required, index, uri, uriSortAttribut, uriPrintAttribut, false);\n }\n\n @Deprecated\n public SoftwareParameter addSoftwareParameter(String name, String type, Long idSoftware, String defaultValue, boolean required, int index) throws CytomineException {\n return addSoftwareParameter(name, type, idSoftware, defaultValue, required, index, null, null, null, false);\n }\n\n @Deprecated\n public SoftwareParameter addSoftwareParameter(String name, String type, Long idSoftware, String defaultValue, boolean required, int index, boolean setByServer) throws CytomineException {\n return addSoftwareParameter(name, type, idSoftware, defaultValue, required, index, null, null, null, setByServer);\n }\n\n @Deprecated\n public SoftwareProject addSoftwareProject(Long idSoftware, Long idProject) throws CytomineException {\n return new SoftwareProject(idSoftware,idProject).save();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Software.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public SoftwareCollection getSoftwaresByProject(Long idProject) throws CytomineException {\n SoftwareCollection softwares = new SoftwareCollection(offset, max);\n softwares.addFilter(\"project\", idProject + \"\");\n return (SoftwareCollection) softwares.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetch(Software.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public SoftwareCollection getSoftwares() throws CytomineException {\n SoftwareCollection softwares = new SoftwareCollection(offset, max);\n return (SoftwareCollection) softwares.fetch();\n }\n\n /*@Deprecated\n public ProcessingServer addProcessingServer(String url) throws CytomineException {\n return new ProcessingServer(url).save();\n }*/\n\n @Deprecated\n public ImageFilter addImageFilter(String name, String baseUrl, String processingServer) throws CytomineException {\n return new ImageFilter(name,baseUrl,processingServer).save();\n }\n\n public JobData getJobData(Long id) throws CytomineException {\n return new JobData().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(JobData.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public JobDataCollection getJobDatas() throws CytomineException {\n JobDataCollection jobDatas = new JobDataCollection(offset, max);\n return (JobDataCollection) jobDatas.fetch();\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(Software.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public JobDataCollection getJobDataByJob(Long idJob) throws CytomineException {\n JobDataCollection jobDatas = new JobDataCollection(offset, max);\n jobDatas.addFilter(\"job\", idJob + \"\");\n return (JobDataCollection) jobDatas.fetch();\n }\n\n @Deprecated\n public JobData addJobData(String key, Long idJob, String filename) throws CytomineException {\n return new JobData(idJob,key,filename).save();\n }\n\n public void deleteJobData(Long idJobData) throws CytomineException {\n new JobData().delete(idJobData);\n }\n\n /**\n * Deprecated. Use Collection.fetchWithFilter(ReviewedAnnotation.class,Project.class,idProject,offset,max) instead\n * @throws CytomineException\n */\n @Deprecated\n public ReviewedAnnotationCollection getReviewedAnnotationsByProject(Long idProject) throws CytomineException {\n ReviewedAnnotationCollection reviewed = new ReviewedAnnotationCollection(offset, max);\n reviewed.addFilter(\"project\", idProject + \"\");\n return (ReviewedAnnotationCollection) reviewed.fetch();\n }\n\n @Deprecated\n public Storage getStorage(Long id) throws CytomineException {\n return new Storage().fetch(id);\n }\n\n /**\n * Deprecated. Use Collection.fetch(Storage.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public StorageCollection getStorages() throws CytomineException {\n StorageCollection storages = new StorageCollection(offset, max);\n return (StorageCollection) storages.fetch();\n }\n\n @Deprecated\n public StorageAbstractImage addStorageAbstractImage(Long idStorage, Long idAbstractImage) throws CytomineException {\n return new StorageAbstractImage(idStorage,idAbstractImage);\n }\n\n @Deprecated\n public AbstractImage editAbstractImage(Long idAbstractImage, String originalFilename) throws CytomineException {\n AbstractImage image = new AbstractImage().fetch(idAbstractImage);\n image.set(\"originalFilename\", originalFilename);\n return image.update();\n }\n\n @Deprecated\n public ImageGroup addImageGroup(Long idProject) throws CytomineException {\n return new ImageGroup(idProject).save();\n }\n\n @Deprecated\n public ImageSequence addImageSequence(Long idImageGroup, Long idImage, Integer zStack, Integer slice, Integer time, Integer channel) throws CytomineException {\n return new ImageSequence(idImageGroup,idImage,zStack,slice,time,channel).save();\n }\n\n /**\n * Deprecated. Use Collection.fetch(Role.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public RoleCollection getRoles() throws CytomineException {\n RoleCollection roles = new RoleCollection(offset, max);\n return (RoleCollection) roles.fetch();\n }\n\n @Deprecated\n public JobTemplate addJobTemplate(String name, Long iProject, Long idSoftware) throws CytomineException {\n return new JobTemplate(name,iProject,idSoftware).save();\n }\n\n @Deprecated\n public JobParameter addJobParameter(Long job, Long softwareParameter, String value) throws CytomineException {\n return new JobParameter(job,softwareParameter,value).save();\n }\n\n @Deprecated\n public UploadedFile addUploadedFile(String originalFilename, String realFilename, String path, Long size, String ext, String contentType, List idProjects, List idStorages, Long idUser, Long idParent) throws CytomineException {\n return addUploadedFile(originalFilename, realFilename, path, size, ext, contentType, idProjects, idStorages, idUser, -1l, idParent);\n }\n\n @Deprecated\n public UploadedFile addUploadedFile(String originalFilename, String realFilename, String path, Long size, String ext, String contentType, List idProjects, List idStorages, Long idUser, Long status, Long idParent) throws CytomineException {\n UploadedFile.Status state = Arrays.stream(UploadedFile.Status.values())\n .filter(c -> c.getCode() == status)\n .findFirst().get();\n return new UploadedFile(originalFilename,realFilename,path,size,ext,contentType,idProjects,idStorages,idUser,state,idParent).save();\n }\n\n @Deprecated\n public UploadedFile getUploadedFile(Long id) throws CytomineException {\n return new UploadedFile().fetch(id);\n }\n\n @Deprecated\n public void deleteUploadedFile(Long idUploadedFile) throws CytomineException {\n UploadedFile uploadedFile = new UploadedFile();\n uploadedFile.set(\"id\", idUploadedFile);\n uploadedFile.delete();\n }\n\n public UploadedFile getUploadedFileByAbstractImage(Long idAbstractImage) throws CytomineException {\n return UploadedFile.getByAbstractImage(idAbstractImage);\n }\n\n /**\n * Deprecated. Use Collection.fetch(AmqpQueue.class,offset, max) instead\n * @throws CytomineException\n */\n @Deprecated\n public AmqpQueueCollection getAmqpQueue() throws CytomineException {\n AmqpQueueCollection queues = new AmqpQueueCollection(offset, max);\n return (AmqpQueueCollection) queues.fetch();\n }\n\n // TODO : remove this line when rest url of core are normalized\n public static String convertDomainName(String input){\n switch (input.toLowerCase()) {\n case \"project\" :\n return \"be.cytomine.project.Project\";\n case \"imageinstance\" :\n return \"be.cytomine.image.ImageInstance\";\n case \"annotation\" :\n return \"be.cytomine.AnnotationDomain\";\n case \"software\" :\n return \"be.cytomine.processing.Software\";\n case \"softwareparameter\" :\n return \"be.cytomine.processing.SoftwareParameter\";\n case \"software_parameter\" :\n return \"be.cytomine.processing.SoftwareParameter\";\n case \"storage\" :\n return \"be.cytomine.image.server.Storage\";\n default:\n try {\n throw new CytomineException(400,\"Client doesn't support other domain for now. Domain was \"+input);\n } catch (CytomineException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n }\n\n\tpublic DeleteCommandCollection getDeleteCommandByDomainAndAfterDate(String domain, Long timestamp) throws CytomineException {\n\t\tDeleteCommandCollection commands = new DeleteCommandCollection(offset, max);\n\t\tcommands.addParams(\"domain\",\"uploadedFile\");\n\t\tcommands.addParams(\"after\",timestamp.toString());\n\t\treturn (DeleteCommandCollection)commands.fetch();\n\t}\n\n}", "public class CytomineConnection {\n\n private static final Logger log = LogManager.getLogger(Cytomine.class);\n\n private String host;\n private String login;\n private String pass;\n private String publicKey;\n private String privateKey;\n\n private User currentUser;\n //private String charEncoding = \"UTF-8\";\n\n /*\n private int max = 0;\n private int offset = 0;\n*/\n\n private enum Method {GET, PUT, POST, DELETE}\n\n CytomineConnection(String host, String publicKey, String privateKey) {\n this.host = host;\n this.publicKey = publicKey;\n this.privateKey = privateKey;\n this.login = publicKey;\n this.pass = privateKey;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n/*\n public void setMax(int max) {\n this.max = max;\n }\n\n public void setOffset(int offset) {\n this.offset = offset;\n }\n*/\n /**\n * Get the public key of this connection.\n * @author Philipp Kainz\n * @since\n * @return\n */\n public String getPublicKey() { return this.publicKey; }\n\n /**\n * Get the private key of this connection.\n * @author Philipp Kainz\n * @since\n * @return\n */\n public String getPrivateKey() { return this.privateKey; }\n\n\n public User getCurrentUser() throws CytomineException {\n return getCurrentUser(false);\n }\n\n public User getCurrentUser(boolean forceRefresh) throws CytomineException {\n if (forceRefresh || this.currentUser == null) {\n User user = new User();\n user.set(\"current\", \"current\");\n currentUser = user.fetch(null);\n }\n\n return currentUser;\n }\n\n private void analyzeCode(int code, JSONObject json) throws CytomineException {\n\n //if 200,201,...no exception\n if (code >= 400 && code < 600) {\n throw new CytomineException(code, json);\n } else if (code == 301) {\n throw new CytomineException(code, json);\n } else if (code == 302) {\n throw new CytomineException(code, json);\n }\n }\n\n private JSONObject createJSONResponse(int code, String response) throws CytomineException {\n try {\n Object obj = JSONValue.parse(response);\n return (JSONObject) obj;\n } catch (Exception e) {\n log.error(e);\n throw new CytomineException(code, response);\n } catch (Error e) {\n log.error(e);\n throw new CytomineException(code, response);\n }\n }\n\n /*private JSONArray createJSONArrayResponse(int code, String response) throws CytomineException {\n Object obj = JSONValue.parse(response);\n return (JSONArray) obj;\n }*/\n\n public JSONObject doRequest(Method method, String URL, String data) throws CytomineException {\n HttpClient client = new HttpClient(publicKey, privateKey, getHost());\n try {\n client.authorize(method.toString(), URL, \"\", \"application/json,*/*\");\n client.connect(getHost() + URL);\n int code = 400;\n switch (method) {\n case GET:\n code = client.get();\n break;\n case POST:\n code = client.post(data);\n break;\n case DELETE:\n code = client.delete();\n break;\n case PUT:\n code = client.put(data);\n break;\n }\n String response = client.getResponseData();\n client.disconnect();\n JSONObject json = createJSONResponse(code, response);\n analyzeCode(code, json);\n return json;\n } catch(IOException e) {\n throw new CytomineException(e);\n }\n }\n\n public JSONObject doGet(String URL) throws CytomineException {\n return doRequest(Method.GET, URL, null);\n }\n public JSONObject doPost(String URL, String data) throws CytomineException {\n return doRequest(Method.POST, URL, data);\n }\n public JSONObject doDelete(String URL) throws CytomineException {\n return doRequest(Method.DELETE, URL, null);\n }\n public JSONObject doPut(String URL, String data) throws CytomineException {\n return doRequest(Method.PUT, URL, data);\n }\n\n //############### UPLOAD ###############\n public JSONObject uploadFile(String url, byte[] data, Map<String, String> entityParts) throws CytomineException {\n\n try {\n HttpClient client = null;\n MultipartEntity entity = new MultipartEntity();\n\n entity.addPart(\"files[]\", new ByteArrayBody(data, new Date().getTime() + \"file\"));\n\n if(entityParts != null) {\n for (Map.Entry<String, String> entry : entityParts.entrySet()) {\n entity.addPart(entry.getKey(), new StringBody(entry.getValue()));\n }\n }\n\n client = new HttpClient(publicKey, privateKey, getHost());\n client.authorize(\"POST\", url, entity.getContentType().getValue(), \"application/json,*/*\");\n client.connect(getHost() + url);\n\n int code = client.post(entity);\n String response = client.getResponseData();\n log.debug(\"response=\" + response);\n client.disconnect();\n JSONObject json = createJSONResponse(code, response);\n analyzeCode(code, json);\n return json;\n } catch (IOException e) {\n throw new CytomineException(e);\n }\n }\n public JSONObject uploadFile(String url, byte[] data) throws CytomineException {\n return this.uploadFile(url, data, null);\n }\n public JSONObject uploadFile(String url, File file, Map<String, String> entityParts) throws CytomineException {\n try {\n if(!entityParts.containsKey(\"filename\")) entityParts.put(\"filename\", file.getName());\n return uploadFile(url, Files.readAllBytes(file.toPath()), entityParts);\n } catch (IOException e) {\n throw new CytomineException(e);\n }\n }\n public JSONObject uploadFile(String url, File file) throws CytomineException {\n Map<String, String> entity = new HashMap<>();\n entity.put(\"filename\", file.getName());\n return this.uploadFile(url, file, entity);\n }\n public JSONObject uploadFile(String url, String file) throws CytomineException {\n return this.uploadFile(url, new File(file));\n }\n\n public JSONArray uploadImage(String file, String url, Map<String, String> entityParts) throws CytomineException {\n try {\n HttpClient client = null;\n\n MultipartEntity entity = new MultipartEntity();\n\n for (Map.Entry<String, String> entry : entityParts.entrySet()) {\n entity.addPart(entry.getKey(), new StringBody(entry.getValue()));\n }\n\n entity.addPart(\"files[]\", new FileBody(new File(file)));\n\n client = new HttpClient(publicKey, privateKey, getHost());\n client.authorize(\"POST\", url, entity.getContentType().getValue(), \"application/json,*/*\");\n client.connect(getHost() + url);\n int code = client.post(entity);\n String response = client.getResponseData();\n log.debug(\"response=\" + response);\n client.disconnect();\n Object obj = JSONValue.parse(response);\n return (JSONArray) obj;\n } catch (IOException e) {\n throw new CytomineException(e);\n }\n }\n\n //############### DOWNLOAD FILES AND PICTURES ###############\n public void downloadPicture(String url, String dest) throws CytomineException {\n downloadPicture(url, dest, \"jpg\");\n }\n\n public void downloadPicture(String url, String dest, String format) throws CytomineException {\n HttpClient client = null;\n try {\n client = new HttpClient(publicKey, privateKey, getHost());\n BufferedImage img = client.readBufferedImageFromURL(url);\n ImageIO.write(img, format, new File(dest));\n\n } catch (Exception e) {\n throw new CytomineException(0, e.toString());\n }\n }\n\n public void downloadPictureWithRedirect(String url, String dest, String format) throws CytomineException {\n HttpClient client = null;\n try {\n client = new HttpClient(publicKey, privateKey, getHost());\n BufferedImage img = client.readBufferedImageFromRETRIEVAL(url, login, pass, getHost());\n ImageIO.write(img, format, new File(dest));\n } catch (Exception e) {\n throw new CytomineException(0, e.toString());\n }\n }\n\n public BufferedImage getPictureAsBufferedImage(String url, String format) throws CytomineException {\n HttpClient client = null;\n try {\n client = new HttpClient(publicKey, privateKey, getHost());\n return client.readBufferedImageFromURL(url);\n\n } catch (Exception e) {\n throw new CytomineException(0, e.toString());\n }\n }\n\n public void downloadFile(String url, String dest) throws CytomineException {\n\n try {\n HttpClient client = new HttpClient(publicKey, privateKey, getHost());\n int code = client.get(getHost() + url, dest);\n analyzeCode(code, (JSONObject) JSONValue.parse(\"{}\"));\n } catch (Exception e) {\n throw new CytomineException(0, e.toString());\n }\n }\n\n\n}", "public class CytomineException extends Exception {\n\n private static final Logger log = LogManager.getLogger(CytomineException.class);\n\n int httpCode;\n String message = \"\";\n\n public CytomineException(Exception e) {\n super(e);\n this.message = e.getMessage();\n }\n\n public CytomineException(int httpCode, String message) {\n this.httpCode = httpCode;\n this.message = message;\n }\n\n public CytomineException(int httpCode, JSONObject json) {\n this.httpCode = httpCode;\n getMessage(json);\n }\n\n public int getHttpCode() {\n return this.httpCode;\n }\n\n public String getMsg() {\n return this.message;\n }\n\n private String getMessage(JSONObject json) {\n try {\n String msg = \"\";\n if (json != null) {\n Iterator iter = json.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n msg = msg + entry.getValue();\n }\n }\n message = msg;\n } catch (Exception e) {\n log.error(e);\n }\n return message;\n }\n\n public String toString() {\n return httpCode + \" \" + message;\n }\n}", "public class AttachedFile extends Model<AttachedFile> {\n\n public AttachedFile() {}\n public AttachedFile(Model model, File file) {\n this(model, file.getAbsolutePath());\n }\n public AttachedFile(Model model, String file) {\n this(Cytomine.convertDomainName(model.getClass().getSimpleName().toLowerCase()), model.getId(), file);\n }\n\n public AttachedFile(String domainClassName, Long idDomain, String file) {\n set(\"domainIdent\", idDomain.toString());\n set(\"domainClassName\", domainClassName);\n set(\"file\", file);\n }\n\n @Override\n public AttachedFile save() throws CytomineException {\n return this.save(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n @Override\n public AttachedFile save(CytomineConnection connection) throws CytomineException {\n if(getStr(\"file\") == null || getStr(\"domainIdent\") == null || getStr(\"domainClassName\") == null) {\n throw new CytomineException(400, \"domainClassName, domainIdent and file attribute must be set\");\n }\n\n Map<String, String> entities = new HashMap<>();\n entities.put(\"domainIdent\",getStr(\"domainIdent\"));\n entities.put(\"domainClassName\",getStr(\"domainClassName\"));\n if(getStr(\"filename\")!=null) entities.put(\"filename\",getStr(\"filename\"));\n\n JSONObject json = connection.uploadFile(this.toURL(), new File(getStr(\"file\")), entities);\n this.setAttr(json);\n\n // TODO reactive this when normalization into core\n //this.setAttr((JSONObject) json.get(this.getDomainName()));\n return this;\n }\n\n public void downloadFile(String dest) throws CytomineException {\n if(getStr(\"url\") == null) {\n throw new CytomineException(400, \"Download URL not known\");\n }\n Cytomine.getInstance().getDefaultCytomineConnection().downloadFile(this.get(\"url\").toString(), dest);\n }\n}", "public abstract class Model<T extends Model> {\n /**\n * Attribute for the current model\n */\n JSONObject attr = new JSONObject();\n\n /**\n * Params map (url params: ?param1=value&...\n */\n HashMap<String, String> params = new HashMap<>();\n\n /**\n * Filter maps (url params: /api/param1/value/model.json\n */\n LinkedHashMap<String, String> filters = new LinkedHashMap<>();\n\n\n /**\n * Generate JSON from Model\n *\n * @return JSON\n */\n public String toJSON() {\n return attr.toString();\n }\n\n // ####################### CREATE URL #######################\n /**\n * Build model REST url\n *\n * @return\n */\n public String toURL() {\n return getJSONResourceURL();\n }\n\n /**\n * Get Model URL\n *\n * @return URL\n */\n public String getJSONResourceURL() {\n Long id = getId();\n String base = \"/api/\";\n base += getFilterPrefix();\n base += getDomainName();\n if(id!= null) {\n base += \"/\" + id + \".json?\";\n } else {\n base += \".json?\";\n }\n\n for (Map.Entry<String, String> param : params.entrySet()) {\n base = base + param.getKey() + \"=\" + param.getValue() + \"&\";\n }\n base = base.substring(0, base.length() - 1);\n return base;\n }\n\n /**\n * Get the name of the domain for the domain\n *\n * @return Domain name\n */\n public String getDomainName(){\n return getClass().getSimpleName().toLowerCase();\n }\n\n protected String getFilterPrefix() {\n final StringBuilder prefix = new StringBuilder(\"\");\n filters.forEach((k,v) -> prefix.append(k+\"/\"+v+\"/\"));\n return prefix.toString();//throw new RuntimeException(\"Error of the java client. \"+getClass().getName()+\" does not support filters\");\n }\n\n // ####################### REST METHODS #######################\n\n public T fetch(Long id) throws CytomineException {\n return this.fetch(Cytomine.getInstance().getDefaultCytomineConnection(),id);\n }\n public T fetch(CytomineConnection connection, Long id) throws CytomineException {\n this.set(\"id\", id);\n JSONObject json = connection.doGet(this.toURL());\n this.setAttr(json);\n return (T)this;\n }\n\n public T save() throws CytomineException {\n return this.save(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n public T save(CytomineConnection connection) throws CytomineException {\n JSONObject json = connection.doPost(this.toURL(),this.toJSON());\n //TODO remove this if when the URL are normalized\n if(json.get(this.getDomainName()) == null){\n this.setAttr((JSONObject) json.get(getClass().getSimpleName().toLowerCase()));\n } else {\n this.setAttr((JSONObject) json.get(this.getDomainName()));\n }\n return (T)this;\n }\n\n public void delete() throws CytomineException {\n this.delete(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n public void delete(CytomineConnection connection) throws CytomineException {\n this.delete(connection, (T) this);\n }\n public void delete(Long id) throws CytomineException {\n this.delete(Cytomine.getInstance().getDefaultCytomineConnection(),id);\n }\n public void delete(CytomineConnection connection,Long id) throws CytomineException {\n this.set(\"id\", id);\n this.delete(connection, (T) this);\n }\n private void delete(T model) throws CytomineException {\n this.delete(Cytomine.getInstance().getDefaultCytomineConnection(), model);\n }\n private void delete(CytomineConnection connection,T model) throws CytomineException {\n connection.doDelete(model.toURL());\n }\n\n public T update() throws CytomineException {\n return this.update(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n public T update(CytomineConnection connection) throws CytomineException {\n JSONObject json = connection.doPut(this.toURL(),this.toJSON());\n //TODO remove this if when the URL are normalized\n if(json.get(this.getDomainName()) == null){\n this.setAttr((JSONObject) json.get(getClass().getSimpleName().toLowerCase()));\n } else {\n this.setAttr((JSONObject) json.get(this.getDomainName()));\n }\n return (T) this;\n }\n\n public T update(HashMap<String, Object> attributes) throws CytomineException {\n return this.update(Cytomine.getInstance().getDefaultCytomineConnection(), attributes);\n }\n\n public T update(CytomineConnection connection, HashMap<String, Object> attributes) throws CytomineException {\n attributes.forEach((k, v) -> {\n this.set(k,v);\n });\n return this.update(connection);\n }\n\n // ####################### Getters/Setters #######################\n\n public Long getId() {\n return getLong(\"id\");\n }\n\n public JSONObject getAttr() {\n return attr;\n }\n\n public Object get(String name) {\n try {\n return attr.get(name);\n } catch (Exception e) {\n return null;\n }\n }\n\n public String getStr(String name) {\n if (get(name) == null) {\n return null;\n }\n else {\n return get(name) + \"\";\n }\n }\n\n public Integer getInt(String name) {\n String str = getStr(name);\n if (str == null) {\n return null;\n }\n else {\n return Integer.parseInt(str);\n }\n }\n\n public Long getLong(String name) {\n String str = getStr(name);\n if (str == null) {\n return null;\n }\n else {\n return Long.parseLong(str);\n }\n }\n\n public Double getDbl(String name) {\n if(get(name) == null) return null;\n if (get(name).getClass().getName().equals(\"java.lang.Long\")) {\n return ((Long) get(name)).doubleValue();\n } else {\n return (Double) get(name);\n }\n }\n\n public Boolean getBool(String name) {\n return (Boolean) get(name);\n }\n\n public List getList(String name) {\n return (List) get(name);\n }\n\n public String getFilter(String name) {\n return filters.get(name);\n }\n\n boolean isFilterBy(String name) {\n return filters.containsKey(name);\n }\n\n public void addParams(String name, String value) {\n params.put(name, value);\n }\n\n public void setAttr(JSONObject attr) {\n this.attr = attr;\n }\n\n /**\n * Add value for attribute 'name'\n *\n * @param name attribute name\n * @param value value for this attribute\n */\n public void set(String name, Object value) {\n attr.put(name, value);\n }\n\n /**\n * Get value for attribute 'name'\n *\n * @param name attribute name\n * @return value value for this attribute\n */\n public /*protected */void addFilter(String name, String value) {\n if(value != null) filters.put(name, value);\n }\n\n\n // ####################### Object override #######################\n\n @Override\n public String toString() {\n return getDomainName() + getId();\n }\n\n @Override\n public int hashCode() {\n if(getId()!=null) {\n return getId().intValue() ;\n } else {\n return 0;\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n } else if (!(o instanceof Model)) {\n return false;\n } else {\n return ((Model) o).getId().equals(this.getId());\n }\n }\n}" ]
import be.cytomine.client.Cytomine; import be.cytomine.client.CytomineConnection; import be.cytomine.client.CytomineException; import be.cytomine.client.models.AttachedFile; import be.cytomine.client.models.Model;
package be.cytomine.client.collections; /* * Copyright (c) 2009-2020. Authors: see NOTICE file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class AttachedFileCollection extends Collection { public AttachedFileCollection() { this(0,0); } public AttachedFileCollection(int offset, int max) { super(AttachedFile.class, max, offset); }
public AttachedFileCollection(Model model) {
4
axxepta/project-argon
src/main/java/de/axxepta/oxygen/actions/SaveFileToArgonAction.java
[ "public enum BaseXSource {\r\n\r\n /**\r\n * Database.\r\n */\r\n DATABASE(\"argon\"),\r\n// /**\r\n// * RESTXQ.\r\n// */\r\n// RESTXQ(\"argonquery\"),\r\n /**\r\n * Repository.\r\n */\r\n REPO(\"argonrepo\");\r\n\r\n private final String protocol;\r\n\r\n BaseXSource(String protocol) {\r\n\r\n this.protocol = protocol;\r\n }\r\n\r\n public String getProtocol() {\r\n return protocol;\r\n }\r\n\r\n /**\r\n * Returns a source.\r\n *\r\n * @param string string representation\r\n * @return enumeration\r\n */\r\n public static BaseXSource get(final String string) {\r\n return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return name().toLowerCase(Locale.ENGLISH);\r\n }\r\n}", "public class ArgonChooserDialog extends JDialog implements MouseListener, ObserverInterface<MsgTopic>, DocumentListener {\n\n private static final Logger logger = LogManager.getLogger(ArgonChooserDialog.class);\n\n private boolean singleClick = true;\n private Timer timer;\n\n private final Type type;\n private int depth = 0;\n private final List<ArgonChooserListModel.Element> path = new ArrayList<>();\n private String pathString;\n private final SelectionAction selectionAction;\n\n private boolean canceled = true;\n\n private JButton newDirButton;\n private JTextField pathTextField;\n private boolean userChangedPathTextField = false;\n private JList resourceList;\n private ArgonChooserListModel model;\n private JTextField selectedFileTextField;\n\n public ArgonChooserDialog(Frame parent, String title, Type type) {\n super(parent);\n setModal(true);\n setTitle(title);\n this.type = type;\n setLayout(new BorderLayout());\n selectionAction = new SelectionAction();\n final JPanel topPanel = createTopPanel();\n final JScrollPane listPane = new JScrollPane(createSelectionTable());\n final JPanel bottomPanel = createBottomPanel();\n add(topPanel, BorderLayout.PAGE_START);\n add(listPane, BorderLayout.CENTER);\n add(bottomPanel, BorderLayout.PAGE_END);\n pack();\n TopicHolder.newDir.register(this);\n setLocationRelativeTo(null);\n timer = new javax.swing.Timer(300, e -> {\n timer.stop();\n if (!singleClick)\n selectionAction.actionPerformed(null);\n });\n timer.setRepeats(false);\n }\n\n private JPanel createTopPanel() {\n final JPanel panel = new JPanel(new BorderLayout(5, 5));\n pathTextField = new JTextField();\n pathTextField.setText(\"\");\n pathTextField.getDocument().addDocumentListener(this);\n newDirButton = new JButton(new NewDirectoryAction(Lang.get(Lang.Keys.cm_newdir), path));\n newDirButton.setEnabled(false);\n\n panel.add(pathTextField, BorderLayout.CENTER);\n panel.add(newDirButton, BorderLayout.EAST);\n return panel;\n }\n\n private JScrollPane createSelectionTable() {\n final List<ArgonChooserListModel.Element> baseList = getProtocolList();\n model = new ArgonChooserListModel(baseList);\n resourceList = new JList(model);\n resourceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n resourceList.setCellRenderer(ClassFactory.getInstance().getChooserListCellRenderer());\n resourceList.addListSelectionListener(e -> {\n if (!resourceList.isSelectionEmpty() &&\n (model.getTypeAt(resourceList.getMinSelectionIndex()).equals(ArgonEntity.FILE))) {\n selectedFileTextField.setText(model.getNameAt(resourceList.getMinSelectionIndex()));\n } else {\n selectedFileTextField.setText(\"\");\n }\n });\n resourceList.addMouseListener(this);\n resourceList.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), \"confirm\");\n resourceList.getActionMap().put(\"confirm\", selectionAction);\n return new JScrollPane(resourceList);\n }\n\n private JPanel createBottomPanel() {\n final JPanel panel = new JPanel(new FlowLayout());\n final JLabel fileNameLabel = new JLabel(Lang.get(Lang.Keys.lbl_filename) + \":\");\n selectedFileTextField = new JTextField();\n selectedFileTextField.setEditable(false);\n selectedFileTextField.setColumns(25);\n selectedFileTextField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), \"confirm\");\n selectedFileTextField.getActionMap().put(\"confirm\", selectionAction);\n final JButton[] buttons;\n switch (type) {\n case OPEN: {\n final String[] buttonNames = new String[]{Lang.get(Lang.Keys.cm_open), Lang.get(Lang.Keys.cm_checkout), Lang.get(Lang.Keys.cm_cancel)};\n buttons = createButtons(buttonNames);\n buttons[0].addActionListener(selectionAction);\n buttons[1].addActionListener(e -> {\n if (!StringUtils.isEmpty(selectedFileTextField.getText())) {\n lock();\n selectionAction.actionPerformed(null);\n }\n });\n buttons[2].addActionListener(e -> this.dispose());\n break;\n }\n default: {\n final String[] buttonNames = new String[]{Lang.get(Lang.Keys.cm_save), Lang.get(Lang.Keys.cm_cancel)};\n buttons = createButtons(buttonNames);\n buttons[0].addActionListener(selectionAction);\n buttons[1].addActionListener(e -> this.dispose());\n }\n }\n panel.add(fileNameLabel);\n panel.add(selectedFileTextField);\n for (JButton button : buttons) {\n panel.add(button);\n }\n return panel;\n }\n\n private JButton[] createButtons(String[] labels) {\n return Arrays.stream(labels).map(JButton::new).toArray(JButton[]::new);\n }\n\n /*\n * expects \"level-up\" element in the list to be of type ROOT\n */\n private void updateList(ArgonChooserListModel.Element element) {\n if (element.getType().equals(ArgonEntity.FILE)) {\n return;\n }\n final List<ArgonChooserListModel.Element> newList;\n if (element.getType().equals(ArgonEntity.ROOT)) {\n depth--;\n path.remove(path.size() - 1);\n if (depth == 0) {\n newList = getProtocolList();\n } else {\n newList = getNewList(element);\n }\n } else {\n depth++;\n path.add(element);\n newList = getNewList(element);\n }\n if ((depth == 0) || ((depth == 1) && (path.get(0).getType().equals(ArgonEntity.DB_BASE)))) {\n selectedFileTextField.setEditable(false);\n } else {\n selectedFileTextField.setEditable(true);\n }\n model.setData(newList);\n selectedFileTextField.setText(\"\");\n buildSelectionString();\n pathTextField.setText(pathString);\n userChangedPathTextField = false;\n if ((depth > 1) || ((depth == 1) && !(path.get(0).getType().equals(ArgonEntity.DB_BASE)))) {\n newDirButton.setEnabled(true);\n } else {\n newDirButton.setEnabled(false);\n }\n }\n\n private List<ArgonChooserListModel.Element> getNewList(ArgonChooserListModel.Element element) {\n final String resourcePath = getResourceString(path);\n final BaseXSource source = getSourceFromElement(element);\n return obtainNewList(source, resourcePath);\n }\n\n private BaseXSource getSourceFromElement(ArgonChooserListModel.Element element) {\n final ArgonEntity rootEntity;\n if (element.getType().equals(ArgonEntity.DIR)) {\n rootEntity = path.get(0).getType();\n } else {\n rootEntity = element.getType();\n }\n switch (rootEntity) {\n// case XQ: {\n// break BaseXSource.RESTXQ;\n// }\n case REPO: {\n return BaseXSource.REPO;\n }\n default:\n return BaseXSource.DATABASE;\n }\n }\n\n public static String getResourceString(List<ArgonChooserListModel.Element> path) {\n if (path.size() < 2) {\n return \"\";\n }\n return path.subList(1, path.size()).stream().map(ArgonChooserListModel.Element::getName)\n .collect(Collectors.joining(\"/\"));\n }\n\n private void buildSelectionString() {\n if (depth == 0) {\n pathString = \"\";\n } else {\n pathString = getSourceFromElement(path.get(0)).getProtocol() +\n \":\" + getResourceString(path) + \"/\" + selectedFileTextField.getText();\n }\n pathString = pathString.replace(\":/\", \":\");\n }\n\n private List<ArgonChooserListModel.Element> obtainNewList(BaseXSource source, String path) {\n final List<ArgonChooserListModel.Element> newList = new ArrayList<>();\n newList.add(new ArgonChooserListModel.Element(ArgonEntity.ROOT, \"..\"));\n try {\n final List<BaseXResource> resourceList = ConnectionWrapper.list(source, path);\n for (BaseXResource resource : resourceList) {\n if (depth == 1 && this.path.get(0).getType() == ArgonEntity.DB_BASE) {\n newList.add(new ArgonChooserListModel.Element(ArgonEntity.DB, resource.name));\n } else if (resource.type == BaseXType.DIRECTORY) {\n newList.add(new ArgonChooserListModel.Element(ArgonEntity.DIR, resource.name));\n } else\n newList.add(new ArgonChooserListModel.Element(ArgonEntity.FILE, resource.name));\n }\n } catch (IOException ioe) {\n PluginWorkspaceProvider.getPluginWorkspace().showErrorMessage(\"YYY \" + Lang.get(Lang.Keys.warn_failedlist) + \" \" +\n ioe.getMessage());\n }\n return newList;\n }\n\n private List<ArgonChooserListModel.Element> getProtocolList() {\n final List<ArgonChooserListModel.Element> list = new ArrayList<>();\n list.add(new ArgonChooserListModel.Element(ArgonEntity.DB_BASE, Lang.get(Lang.Keys.tree_DB)));\n// list.add(new ArgonChooserListModel.Element(ArgonEntity.XQ, Lang.get(Lang.Keys.tree_restxq)));\n list.add(new ArgonChooserListModel.Element(ArgonEntity.REPO, Lang.get(Lang.Keys.tree_repo)));\n return list;\n }\n\n private void lock() {\n final BaseXSource source = getSourceFromElement(path.get(0));\n final String fullPath = getResourceString(path) + \"/\" + selectedFileTextField.getText();\n ConnectionWrapper.lock(source, fullPath);\n }\n\n public URL[] selectURLs() {\n canceled = true;\n setVisible(true);\n if (canceled) {\n return null;\n } else {\n try {\n return new URL[] {new URL(pathString)};\n } catch (MalformedURLException mue) {\n logger.error(\"Selected path \" + pathString + \" cannot be converted to URL.\");\n }\n }\n return null;\n\n }\n\n /*\n * methods for interface DocumentListener\n */\n @Override\n public void insertUpdate(DocumentEvent e) {\n userChangedPathTextField = true;\n }\n\n @Override\n public void removeUpdate(DocumentEvent e) {\n userChangedPathTextField = true;\n }\n\n @Override\n public void changedUpdate(DocumentEvent e) {\n userChangedPathTextField = true;\n\n }\n\n\n /*\n * method for interface ObserverInterface\n */\n @Override\n public void update(MsgTopic type, Object... message) {\n }\n\n\n /*\n * methods for interface MouseListener\n */\n @Override\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() == 1) {\n singleClick = true;\n timer.start();\n } else {\n singleClick = false;\n }\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n }\n\n\n private class SelectionAction extends AbstractAction {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n if (!(StringUtils.isEmpty(selectedFileTextField.getText()) && resourceList.isSelectionEmpty())) {\n if ((resourceList.isSelectionEmpty()) ||\n (model.getTypeAt(resourceList.getSelectedIndices()[0]).equals(ArgonEntity.FILE))) {\n canceled = false;\n buildSelectionString();\n setVisible(false);\n dispose();\n } else {\n updateList((ArgonChooserListModel.Element) model.getElementAt(resourceList.getSelectedIndices()[0]));\n }\n }\n }\n }\n\n public enum Type {\n OPEN,\n SAVE\n }\n\n}", "public class CustomProtocolURLUtils {\n\n private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);\n\n public static String pathFromURL(URL url) {\n String urlString = \"\";\n try {\n urlString = java.net.URLDecoder.decode(url.toString(), \"UTF-8\");\n } catch (UnsupportedEncodingException | IllegalArgumentException ex) {\n logger.error(\"URLDecoder error decoding \" + url.toString(), ex.getMessage());\n }\n return pathFromURLString(urlString);\n }\n\n public static String pathFromURLString(String urlString) {\n String[] urlComponents = urlString.split(\":/*\");\n if (urlComponents.length < 2) {\n return \"\";\n // ToDo: exception handling\n } else {\n return urlComponents[1];\n }\n }\n\n public static BaseXSource sourceFromURL(URL url) {\n return sourceFromURLString(url.toString());\n }\n\n public static BaseXSource sourceFromURLString(String urlString) {\n final URI uri = URI.create(urlString);\n if (uri.getScheme() == null) {\n return null;\n }\n switch (uri.getScheme()) {\n// case ArgonConst.ARGON_XQ:\n// return BaseXSource.RESTXQ;\n case ArgonConst.ARGON_REPO:\n return BaseXSource.REPO;\n case ArgonConst.ARGON:\n return BaseXSource.DATABASE;\n default:\n return null;\n }\n }\n}", "public final class ConnectionWrapper {\n\n private static final Logger logger = LogManager.getLogger(ConnectionWrapper.class);\n\n private ConnectionWrapper() {\n }\n\n public static void init() {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.init();\n } catch (IOException | NullPointerException ex) {\n logger.debug(\"Argon initialization failed!\");\n }\n }\n\n public static void create(String db) throws IOException {\n String chop = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_CHOP, false).toLowerCase();\n String ftindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_FTINDEX, false).toLowerCase();\n String textindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_TEXTINDEX, false).toLowerCase();\n String attrindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_ATTRINDEX, false).toLowerCase();\n String tokenindex = ArgonOptionPage.getOption(ArgonOptionPage.KEY_BASEX_DB_CREATE_TOKENINDEX, false).toLowerCase();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.create(db, chop, ftindex, textindex, attrindex, tokenindex);\n TopicHolder.newDir.postMessage(ArgonConst.ARGON + \":\" + db);\n } catch (NullPointerException ex) {\n String error = ex.getMessage();\n if ((error == null) || error.equals(\"null\"))\n throw new IOException(\"Database connection could not be established.\");\n }\n }\n\n public static void save(URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, \"UTF-8\")) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(URL url, byte[] bytes, String encoding, boolean versionUp) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, encoding, versionUp)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(URL url, byte[] bytes, String encoding) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(url, encoding)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(String owner, URL url, byte[] bytes, String encoding) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(owner, url, encoding)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(String owner, boolean binary, URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(owner, binary, url)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(boolean binary, URL url, byte[] bytes) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(binary, url)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static void save(boolean binary, URL url, byte[] bytes, boolean versionUp) throws IOException {\n try (ByteArrayOutputStream os = new BaseXByteArrayOutputStream(binary, url, versionUp)) {\n os.write(bytes);\n } catch (NullPointerException npe) {\n logger.info(\"Error saving to \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException ioe) {\n logger.error(\"IO error saving to \" + url.toString() + \": \", ioe.getMessage());\n throw new IOException(ioe);\n }\n }\n\n public static InputStream getInputStream(URL url) throws IOException {\n ByteArrayInputStream inputStream;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n logger.info(\"Requested new InputStream: \" + url.toString());\n inputStream = new ByteArrayInputStream(connection.get(CustomProtocolURLUtils.sourceFromURL(url),\n CustomProtocolURLUtils.pathFromURL(url), false));\n } catch (NullPointerException npe) {\n logger.info(\"Error obtaining input stream from \" + url.toString() + \": no database connection\");\n throw new NoDatabaseConnectionException();\n } catch (IOException io) {\n logger.debug(\"Failed to obtain InputStream: \", io.getMessage());\n throw new IOException(io);\n }\n return inputStream;\n }\n\n public static List<BaseXResource> list(BaseXSource source, String path) throws IOException {\n logger.info(\"list \" + source + \" \"+ path);\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.list(source, path);\n } catch (NullPointerException npe) {\n final PrintWriter buf = new PrintWriter(new StringWriter());\n npe.printStackTrace(buf);\n logger.info(\"Error listing path \" + path + \": no database connection : \" + buf.toString());\n throw new NoDatabaseConnectionException();\n }\n }\n\n /**\n * lists all resources in the path, including directories\n *\n * @param source source in which path resides\n * @param path path to list\n * @return list of all resources in path, entries contain full path as name, for databases without the database name\n * @throws IOException throws exception if connection returns an exception/error code\n */\n public static List<BaseXResource> listAll(BaseXSource source, String path) throws IOException {\n logger.info(\"listAll\" + source + \" \"+ path);\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.listAll(source, path);\n } catch (NullPointerException npe) {\n logger.info(\"Error listing path \" + path + \": no database connection\");\n throw new NoDatabaseConnectionException();\n }\n }\n\n public static boolean directoryExists(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n List<BaseXResource> resourceList = connection.list(source, path);\n return (resourceList.size() != 0);\n } catch (NullPointerException npe) {\n logger.info(\"Error checking for directory \" + path + \": no database connection\");\n return true;\n } catch (IOException ioe) {\n return false;\n }\n }\n\n public static boolean isLocked(BaseXSource source, String path) {\n boolean isLocked = false;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n if (connection.locked(source, path))\n isLocked = true;\n } catch (Throwable ie) {\n isLocked = true;\n logger.debug(\"Querying LOCKED returned: \", ie.getMessage());\n }\n return isLocked;\n }\n\n public static boolean isLockedByUser(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.lockedByUser(source, path);\n } catch (Throwable ioe) {\n logger.debug(ioe);\n }\n return false;\n }\n\n public static void lock(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.lock(source, path);\n } catch (Throwable ioe) {\n logger.error(\"Failed to lock resource \" + path + \" in \" + source.toString() + \": \" + ioe.getMessage());\n }\n }\n\n public static void unlock(BaseXSource source, String path) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.unlock(source, path);\n } catch (Throwable ioe) {\n logger.error(\"Failed to unlock resource \" + path + \" in \" + source.toString() + \": \" + ioe.getMessage());\n }\n }\n\n public static List<String> findFiles(BaseXSource source, String path, String filter, boolean caseSensitive) throws IOException {\n List<String> result;\n StringBuilder regEx = new StringBuilder(caseSensitive ? \"\" : \"(?i)\");\n for (int i = 0; i < filter.length(); i++) {\n char c = filter.charAt(i);\n switch (c) {\n case '*':\n regEx.append(\".*\");\n break;\n case '?':\n regEx.append('.');\n break;\n case '.':\n regEx.append(\"\\\\.\");\n break;\n default:\n regEx.append(c);\n }\n }\n String regExString = regEx.toString();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n result = connection.search(source, path, regExString);\n for (int i = result.size() - 1; i > -1; i--) {\n String foundPath = result.get(i);\n String foundFile = TreeUtils.fileStringFromPathString(foundPath);\n Matcher matcher = Pattern.compile(regExString).matcher(foundFile);\n if (!matcher.find())\n result.remove(foundPath);\n }\n } catch (NullPointerException npe) {\n logger.error(\"Error searching for files: no database connection\");\n throw new NoDatabaseConnectionException();\n }\n return result;\n }\n\n public static List<String> parse(String path) throws IOException {\n List<String> result = new ArrayList<>();\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.parse(path);\n } catch (BaseXQueryException ex) {\n result.add(Integer.toString(ex.getLine()));\n result.add(Integer.toString(ex.getColumn()));\n result.add(ex.getInfo());\n }\n return result;\n }\n\n public static String query(String query, String[] parameter) throws IOException {\n return \"<response>\\n\" + sendQuery(query, parameter) + \"\\n</response>\";\n }\n\n private static String sendQuery(String query, String[] parameter) throws IOException {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.xquery(query, parameter);\n } catch (NullPointerException npe) {\n logger.info(\"Error sending query: no database connection\");\n throw new NoDatabaseConnectionException();\n }\n }\n\n private static List<String> searchInFiles(String query, String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n String[] parameter = {\"PATH\", path, \"FILTER\", filter, \"WHOLE\", Boolean.toString(wholeMatch),\n \"EXACTCASE\", Boolean.toString(exactCase)};\n String result = sendQuery(query, parameter);\n String db_name = (path.split(\"/\"))[0];\n final ArrayList<String> list = new ArrayList<>();\n if (!result.isEmpty()) {\n final String[] results = result.split(\"\\r?\\n\");\n for (String res : results) {\n list.add(\"argon:\" + db_name + \"/\" + res);\n }\n }\n return list;\n }\n\n public static List<String> searchAttributes(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-attributes\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchAttributeValues(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-attrvalues\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchElements(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-elements\"), path, filter, wholeMatch, exactCase);\n }\n\n public static List<String> searchText(String path, String filter, boolean wholeMatch, boolean exactCase)\n throws IOException {\n return searchInFiles(ConnectionUtils.getQuery(\"search-text\"), path, filter, wholeMatch, exactCase);\n }\n\n public static boolean resourceExists(BaseXSource source, String resource) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n return connection.exists(source, resource);\n } catch (Throwable ioe) {\n logger.error(\"Failed to ask BaseX for existence of resource \" + resource + \": \" + ioe.getMessage());\n return false;\n }\n }\n\n public static boolean pathContainsLockedResource(BaseXSource source, String path) {\n byte[] lockFile;\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n lockFile = connection.get(BaseXSource.DATABASE, ArgonConst.ARGON_DB + \"/\" + ArgonConst.LOCK_FILE, false);\n Document dom = XMLUtils.docFromByteArray(lockFile);\n XPathExpression expression = XMLUtils.getXPathExpression(\"*//\" + source.toString());\n NodeList lockedResources = (NodeList) expression.evaluate(dom, XPathConstants.NODESET);\n String[] pathComponents = path.split(\"/\");\n for (int i = 0; i < lockedResources.getLength(); i++) {\n String[] resourceComponents = lockedResources.item(i).getTextContent().split(\"/\");\n if (resourceComponents.length >= pathComponents.length) {\n boolean isEqual = true;\n for (int k = 0; k < pathComponents.length; k++) {\n if (!pathComponents[k].equals(resourceComponents[k]))\n isEqual = false;\n }\n if (isEqual)\n return true;\n }\n }\n } catch (IOException ioe) {\n logger.error(\"Failed to obtain lock list: \" + ioe.getMessage());\n return true;\n } catch (ParserConfigurationException | SAXException | XPathExpressionException xe) {\n logger.error(\"Failed to parse lock file XML: \" + xe.getMessage());\n return true;\n } catch (Throwable t) {\n return true;\n }\n return false;\n }\n\n /**\n * Adds new directory. Side effect: for databases an empty file .empty.xml will be added in the new directory to make\n * the new directory persistent in the database.\n *\n * @param source BaseXSource in which new directory shall be added\n * @param path path of new directory\n */\n public static void newDir(BaseXSource source, String path) {\n if (source.equals(BaseXSource.DATABASE)) {\n String resource = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<empty/>\";\n String urlString = source.getProtocol() + \":\" +\n path + \"/\" + ArgonConst.EMPTY_FILE;\n try {\n URL url = new URL(urlString);\n ConnectionWrapper.save(url, resource.getBytes(), \"UTF-8\");\n } catch (IOException e1) {\n logger.error(e1);\n }\n } else {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.newDir(source, path);\n } catch (Throwable io) {\n logger.error(\"Failed to create new directory: \" + io.getMessage());\n }\n }\n }\n\n}", "public class Lang {\r\n\r\n private static final Logger logger = LogManager.getLogger(Lang.class);\r\n\r\n private static final String PATH = \"/Argon\";\r\n private static final String MISSING_KEY = \"missing_key:\";\r\n private static final String MISSING_RESOURCE = \"missing_resource:\";\r\n private static PluginResourceBundle bundle = null;\r\n\r\n private static final Map<Locale, Bundle> availableResourceBundles = new HashMap<>();\r\n static {\r\n loadBundle(Locale.GERMANY);\r\n loadBundle(Locale.UK);\r\n }\r\n private static Bundle currentBundle = availableResourceBundles.get(Locale.UK);\r\n\r\n public static void init() {\r\n init(Locale.UK);\r\n }\r\n\r\n public static void init(Locale locale) {\r\n setLocale(locale);\r\n }\r\n\r\n private static void loadBundle(final Locale locale) {\r\n try {\r\n final Bundle bundle = new Bundle(PATH, locale);\r\n availableResourceBundles.put(locale, bundle);\r\n } catch (final IOException ex) {\r\n logger.warn(\"Failed to read resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n } catch (final NullPointerException ex) {\r\n logger.warn(\"Missing resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n }\r\n }\r\n\r\n public static void setLocale(Locale locale) {\r\n if (locale.equals(Locale.GERMANY) || locale.equals(Locale.GERMAN)) {\r\n currentBundle = availableResourceBundles.get(Locale.GERMANY);\r\n } else {\r\n currentBundle = availableResourceBundles.get(Locale.UK);\r\n }\r\n }\r\n \r\n public static void init(StandalonePluginWorkspace wsa) {\r\n bundle = wsa.getResourceBundle();\r\n }\r\n\r\n public static String get(Keys key) {\r\n if (bundle != null) {\r\n return bundle.getMessage(key.name());\r\n }\r\n if (currentBundle != null) {\r\n String val = currentBundle.getString(key.name());\r\n if (val != null) {\r\n return val;\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing key\", e);\r\n }\r\n return MISSING_KEY + key;\r\n }\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing bundle\", e);\r\n }\r\n return MISSING_RESOURCE + key;\r\n }\r\n }\r\n\r\n public enum Keys {\r\n tree_root, tree_DB,\r\n tree_repo,\r\n// tree_restxq,\r\n cm_open, cm_checkout, cm_checkin, cm_adddb, cm_add, cm_addsimple,\r\n cm_addfile, cm_delete, cm_rename, cm_newversion, cm_showversion, cm_refresh, cm_search, cm_searchsimple, cm_find,\r\n cm_newdir, cm_save, cm_ok, cm_cancel, cm_tofile, cm_todb, cm_export, cm_checkinselected, cm_exit, cm_saveas,\r\n cm_replycomment,\r\n cm_runquery,\r\n cm_yes, cm_no, cm_all, cm_always, cm_never, cm_compare, cm_reset, cm_overwrite,\r\n cm_nosave,\r\n lbl_filename, lbl_filetype, lbl_filestocheck, lbl_delete, lbl_dir, lbl_searchpath, lbl_elements, lbl_text,\r\n lbl_attributes, lbl_attrbvalues, lbl_scope, lbl_options, lbl_whole, lbl_casesens, lbl_snippet,\r\n lbl_search1, lbl_search2, lbl_search3, lbl_search4, lbl_overwrite, lbl_version, lbl_revision, lbl_date, lbl_closed,\r\n lbl_connection, lbl_host, lbl_user, lbl_pwd, lbl_vcs, lbl_fe, lbl_dboptions, lbl_chop, lbl_ftindex, lbl_textindex,\r\n lbl_attributeindex, lbl_tokenindex, lbl_fixdefault, tt_fe,\r\n title_connection, title_connection2, title_history,\r\n warn_failednewdb, warn_failednewfile, warn_faileddeletedb, warn_faileddelete,\r\n warn_failedexport, warn_failednewversion, warn_norename, warn_resource, warn_storing, warn_locked, warn_nosnippet,\r\n warn_nofile, warn_failedsearch, warn_failedlist, warn_notransfer, warn_transfernoread,\r\n warn_transfernowrite1, warn_transfernowrite2, warn_connectionsettings1, warn_connectionsettings2, warn_settingspath1,\r\n warn_settingspath2, warn_settingspath3,\r\n msg_dbexists1, msg_dbexists2, msg_fileexists1, msg_fileexists2, msg_noquery, msg_noeditor, msg_checkpriordelete,\r\n msg_noupdate1, msg_noupdate2, msg_norename1, msg_norename2, msg_norename3, msg_transferlocked, msg_nameexists,\r\n msg_settingsexists, msg_noscopeselected,\r\n dlg_addfileinto, dlg_externalquery, dlg_checkedout, dlg_delete, dlg_newdir, dlg_replycomment, dlg_saveas, dlg_open,\r\n dlg_snippet, dlg_foundresources, dlg_overwrite, dlg_closed, dlg_overwritesetting, dlg_newsetting\r\n }\r\n\r\n}\r", "public class WorkspaceUtils {\n\n public static final Logger logger = LogManager.getLogger(WorkspaceUtils.class);\n\n private static final PluginWorkspace workspaceAccess = PluginWorkspaceProvider.getPluginWorkspace();\n\n private static final int OVERWRITE_ALL = 2;\n private static final int OVERWRITE_YES = 1;\n private static final int OVERWRITE_ASK = 0;\n private static final int OVERWRITE_NO = -1;\n private static final int OVERWRITE_NONE = -2;\n\n private static JPanel treePanel;\n\n public static final Cursor WAIT_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);\n public static final Cursor DEFAULT_CURSOR = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);\n\n private WorkspaceUtils() {\n }\n\n public static byte[] getEditorByteContent(WSEditor editorAccess) {\n Document doc = getDocumentFromEditor(editorAccess);\n return doc.toString().getBytes(StandardCharsets.UTF_8);\n }\n\n private static byte[] getEditorContent(WSEditor editorAccess) throws IOException {\n byte[] content;\n try (InputStream contentStream = editorAccess.createContentInputStream()) {\n content = IOUtils.getBytesFromInputStream(contentStream);\n } catch (IOException ie) {\n logger.error(ie);\n content = new byte[0];\n }\n return content;\n }\n\n public static void setTreePanel(JPanel panel) {\n treePanel = panel;\n }\n\n /**\n * Extracts encoding from XML prologue in editor string content and the String content as second element,\n * returns empty string as first element if no prologue is found.\n *\n * @param editorAccess editor handle\n * @return encoding encoding and editor content as String array, empty if no encoding could be extracted\n */\n private static String[] editorStringEncoding(WSEditor editorAccess) {\n String encodingString[] = new String[2];\n String pageID = editorAccess.getCurrentPageID();\n if (!pageID.equals(EditorPageConstants.PAGE_TEXT))\n editorAccess.changePage(EditorPageConstants.PAGE_TEXT);\n WSTextEditorPage textPage = (WSTextEditorPage) editorAccess.getCurrentPage();\n Document doc = textPage.getDocument();\n if (!pageID.equals(EditorPageConstants.PAGE_TEXT))\n editorAccess.changePage(pageID);\n try {\n encodingString[1] = doc.getText(0, doc.getLength());\n encodingString[0] = XMLUtils.encodingFromPrologue(encodingString[1]);\n } catch (BadLocationException ex) {\n logger.error(ex);\n encodingString[0] = \"\";\n }\n return encodingString;\n }\n\n public static Document getDocumentFromEditor(WSEditor editorAccess) {\n boolean editorInAuthorMode = false;\n if (editorAccess.getCurrentPageID().equals(EditorPageConstants.PAGE_AUTHOR)) {\n editorInAuthorMode = true;\n editorAccess.changePage(EditorPageConstants.PAGE_TEXT);\n }\n WSTextEditorPage textPage = (WSTextEditorPage) editorAccess.getCurrentPage();\n Document doc = textPage.getDocument();\n if (editorInAuthorMode) {\n editorAccess.changePage(EditorPageConstants.PAGE_AUTHOR);\n }\n return doc;\n }\n\n public static void openURLString(String urlString) {\n try {\n URL argonURL = new URL(urlString);\n setCursor(WAIT_CURSOR);\n PluginWorkspaceProvider.getPluginWorkspace().open(argonURL);\n setCursor(DEFAULT_CURSOR);\n } catch (MalformedURLException e1) {\n logger.error(e1);\n }\n }\n\n public static void setCursor(Cursor cursor) {\n Component oxygenFrame = (Frame) workspaceAccess.getParentFrame();\n oxygenFrame.setCursor(cursor);\n if (treePanel != null)\n treePanel.setCursor(cursor);\n }\n\n public static int booleanDialog(PluginWorkspace pluginWorkspace,\n String title,\n String msg,\n String trueButton, int trueValue, String falseButton,\n int falseValue,\n int initial) {\n return pluginWorkspace.showConfirmDialog(\n title,\n msg,\n new String[]{trueButton, falseButton},\n new int[]{trueValue, falseValue},\n initial);\n }\n\n private static boolean checkOverwrite() {\n int save = booleanDialog(workspaceAccess,\n Lang.get(Lang.Keys.dlg_overwrite),\n Lang.get(Lang.Keys.lbl_overwrite),\n Lang.get(Lang.Keys.cm_yes), OVERWRITE_YES,\n Lang.get(Lang.Keys.cm_no), OVERWRITE_NO,\n 0);\n return (save == OVERWRITE_YES);\n }\n\n private static int checkOverwriteAll() {\n return workspaceAccess.showConfirmDialog(Lang.get(Lang.Keys.dlg_overwrite), Lang.get(Lang.Keys.lbl_overwrite),\n new String[]{Lang.get(Lang.Keys.cm_yes), Lang.get(Lang.Keys.cm_always), Lang.get(Lang.Keys.cm_no), Lang.get(Lang.Keys.cm_never)},\n new int[]{OVERWRITE_YES, OVERWRITE_ALL, OVERWRITE_NO, OVERWRITE_NONE}, 2);\n }\n\n /**\n * Check for existence of a BaseX resource and show overwrite dialog if necessary\n *\n * @param source source of storage target\n * @param path resource path of storage target\n * @return true if resource does not yet exist or user agreed to overwrite\n * @see OverwriteChecker\n */\n public static boolean newResourceOrOverwrite(BaseXSource source, String path) {\n boolean freeToSave = true;\n if (ConnectionWrapper.resourceExists(source, path)) {\n freeToSave = WorkspaceUtils.checkOverwrite();\n }\n return freeToSave;\n }\n\n /**\n * Store the content of an editor editorAccess to a BaseX resource url. Checks for encoding in prologue and byte code,\n * if none can be obtained assumes UTF-8 encoding.\n *\n * @param editorAccess editor handle\n * @param url BaseX target url\n * @throws IOException BaseX connection can return exception\n */\n public static void saveEditorToBaseXURL(WSEditor editorAccess, URL url) throws IOException {\n byte[] content = WorkspaceUtils.getEditorContent(editorAccess);\n String[] encodingString = WorkspaceUtils.editorStringEncoding(editorAccess);\n if (encodingString[0].equals(\"\"))\n encodingString[0] = XMLUtils.encodingFromBytes(content);\n if (!URLUtils.isXML(url) && (URLUtils.isBinary(url) || !IOUtils.isXML(content))) {\n ConnectionWrapper.save(true, url, content);\n } else {\n switch (encodingString[0]) {\n case \"\": {\n ConnectionWrapper.save(url, IOUtils.returnUTF8Array(encodingString[1]), \"UTF-8\");\n break;\n }\n case \"UTF-8\": {\n ConnectionWrapper.save(url, content, \"UTF-8\");\n break;\n }\n default:\n ConnectionWrapper.save(url, IOUtils.convertToUTF8(content, encodingString[0]), encodingString[0]);\n }\n }\n }\n\n /**\n * The OverwriteChecker implements a way to check for multiple files to store for their existence and ask the user\n * whether existing files should be overwritten with \"Always\" and \"Never\" options.\n * <p>\n * For storing single files use the static method\n * {@link WorkspaceUtils#newResourceOrOverwrite(BaseXSource, String) newResourceOrOverwrite}\n */\n public static class OverwriteChecker {\n\n private int checkFlag;\n\n public OverwriteChecker() {\n checkFlag = OVERWRITE_ASK;\n }\n\n public boolean newResourceOrOverwrite(BaseXSource source, String path) {\n if (checkFlag == OVERWRITE_ALL)\n return true;\n if (ConnectionWrapper.resourceExists(source, path)) {\n if (checkFlag == OVERWRITE_NONE)\n return false;\n int check;\n check = WorkspaceUtils.checkOverwriteAll();\n if ((check == OVERWRITE_ALL) || (check == OVERWRITE_NONE))\n checkFlag = check;\n return ((check == OVERWRITE_YES) || (check == OVERWRITE_ALL));\n } else {\n return true;\n }\n\n }\n }\n\n}" ]
import de.axxepta.oxygen.api.BaseXSource; import de.axxepta.oxygen.customprotocol.ArgonChooserDialog; import de.axxepta.oxygen.customprotocol.CustomProtocolURLUtils; import de.axxepta.oxygen.utils.ConnectionWrapper; import de.axxepta.oxygen.utils.Lang; import de.axxepta.oxygen.utils.WorkspaceUtils; import ro.sync.exml.workspace.api.PluginWorkspace; import ro.sync.exml.workspace.api.PluginWorkspaceProvider; import ro.sync.exml.workspace.api.editor.WSEditor; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URL;
package de.axxepta.oxygen.actions; /** * Store the current editor's content to BaseX. The URL can be chosen from a dialog. If no encoding can be obtained from * the editor content, the default UTF-8 will be used. */ public class SaveFileToArgonAction extends AbstractAction { private static final PluginWorkspace workspace = PluginWorkspaceProvider.getPluginWorkspace(); public SaveFileToArgonAction(String name, Icon icon) { super(name, icon); } @Override public void actionPerformed(ActionEvent e) { ArgonChooserDialog urlChooser = new ArgonChooserDialog((Frame) workspace.getParentFrame(), Lang.get(Lang.Keys.dlg_saveas), ArgonChooserDialog.Type.SAVE); URL[] url = urlChooser.selectURLs(); WSEditor editorAccess = workspace.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA); if (url != null) {
BaseXSource source = CustomProtocolURLUtils.sourceFromURL(url[0]);
0
Stay/PullRecycler
app/src/main/java/com/stay4it/sample/SampleSectionListFragment.java
[ "public abstract class BaseSectionListFragment<T> extends BaseListFragment<SectionData<T>> {\n protected static final int VIEW_TYPE_SECTION_HEADER = 1;\n protected static final int VIEW_TYPE_SECTION_CONTENT = 2;\n\n @Override\n protected BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_SECTION_HEADER) {\n return onCreateSectionHeaderViewHolder(parent);\n }\n return onCreateSectionViewHolder(parent, viewType);\n }\n\n protected abstract BaseViewHolder onCreateSectionViewHolder(ViewGroup parent, int viewType);\n\n private BaseViewHolder onCreateSectionHeaderViewHolder(ViewGroup parent) {\n View view = LayoutInflater.from(getContext()).inflate(R.layout.widget_pull_to_refresh_section_header, parent, false);\n return new SectionHeaderViewHolder(view);\n }\n\n @Override\n protected int getItemType(int position) {\n return mDataList.get(position).isHeader ? VIEW_TYPE_SECTION_HEADER : VIEW_TYPE_SECTION_CONTENT;\n }\n\n @Override\n protected boolean isSectionHeader(int position) {\n return mDataList.get(position).isHeader;\n }\n\n private class SectionHeaderViewHolder extends BaseViewHolder {\n private final TextView header;\n\n public SectionHeaderViewHolder(View view) {\n super(view);\n header = (TextView) view.findViewById(R.id.header);\n }\n\n @Override\n public void onBindViewHolder(int position) {\n header.setText(mDataList.get(position).header);\n }\n\n @Override\n public void onItemClick(View view, int position) {\n\n }\n }\n\n}", "public class ConstantValues {\n// fetch from http://gank.io/api\n public static String[] images = {\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f2h04lir85j20fa0mx784.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f2fuecji0lj20f009oab3.jpg\",\n\n \"http://ww1.sinaimg.cn/large/610dc034jw1f2ewruruvij20d70miadg.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f2cfxa9joaj20f00fzwg2.jpg\",\n\n \"http://ww1.sinaimg.cn/large/610dc034gw1f2cf4ulmpzj20dw0kugn0.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f27uhoko12j20ez0miq4p.jpg\",\n\n \"http://ww2.sinaimg.cn/large/610dc034jw1f27tuwswd3j20hs0qoq6q.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f26lox908uj20u018waov.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1f25gtggxqjj20f00b9tb5.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f249fugof8j20hn0qogo4.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f20ruz456sj20go0p0wi3.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1yjc38i9oj20hs0qoq6k.jpg\",\n\n \"http://ww3.sinaimg.cn/large/610dc034gw1f1yj0vc3ntj20e60jc0ua.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1xad7meu2j20dw0ku0vj.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f1w5m7c9knj20go0p0ae4.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1so7l2u60j20zk1cy7g9.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1rmqzruylj20hs0qon14.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1f1qed6rs61j20ss0zkgrt.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f1p77v97xpj20k00zkgpw.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f1o75j517xj20u018iqnf.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1klhuc8w5j20d30h9gn8.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1jionqvz6j20hs0qoq7p.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f1ia8qj5qbj20nd0zkmzp.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f1h4f51wbcj20f00lddih.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f1g2xpx9ehj20ez0mi0vc.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f1cl3c7rfgj20dw0ku76t.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1bdal8i3nj20f00lf77g.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f1a47fpjacj20f00imtam.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f19241kkpwj20f00hfabt.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f17x6wmh09j20f00m1mzh.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f14fbwrfptj20zk0npgtu.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f138l9egrmj20f00mbdij.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f1052bhjauj20f00l6q4o.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bgw1f0orab74l4j20go0p0jw5.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bgw1f0k67zz05jj20ku0rs0y1.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bgw1f0k67eluxej20fr0m8whw.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bgw1f0k6706308j20vg18gqfl.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bgw1f0k66sk2qbj20rs130wqf.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bgw1f0ixu5rmtcj20hs0qojv5.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f0f9fkzu78j20f00qo0xl.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1f0e4suv1tgj20hs0qo0w5.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1f0cw7swd9tj20hy0qogoo.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1f0buzmnacoj20f00liwi2.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f0bifjrh39j20v018gwtj.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1f082c0b6zyj20f00f0gnr.jpg\",\n\n \"http://ww3.sinaimg.cn/large/610dc034jw1f070hyadzkj20p90gwq6v.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f05pbp0p0yj20go0mu77b.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f04m5ngwwaj20dw0kmwgn.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1f03emebr4jj20ez0qoadk.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ezzaw04857j20p00gp40w.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ezysj9ytj5j20f00m8wh0.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezxog636o8j20du0kujsg.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezwgshzjpmj21ao1y0tf0.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezvbmuqz9cj20hs0qoq6o.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ezrtpmdv45j20u00spahy.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ezqon28qrzj20h80pamze.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1ezplg7s8mdj20xc0m8jwf.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezodh37eadj20n90qotfr.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ezn79ievhzj20p00odwhr.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezil3n0cqdj20p00ou776.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1ezhh5rh1r9j20hs0qoadi.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ezgal5vpjfj20go0p0adq.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ezf3wrxcx2j20p011i7b2.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1ezbriom623j20hs0qoadv.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ezak8074s3j20qo0k0adz.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ez9bkpuvipj20dw0kutb9.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ez5zq5g685j20hj0qo0w1.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bgw1eyz0s7ro75j20qo0hsgny.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bgw1eyz0rg13v9j20hs0qon28.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bgw1eyz0qixq0wj20hr0qoaek.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bgw1eyz0pe9m1nj20ol0gwdka.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bgw1eyz0ni2r15j21kw2dcq8x.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bgw1eyvkh5wnbsj20qo0hsn0e.jpg\",\n\n \"http://ww1.sinaimg.cn/large/610dc034gw1eyvgnb0nm5j20zk1dvtmy.jpg\",\n\n \"http://ww1.sinaimg.cn/large/610dc034gw1eyu8kqv2p6j20m80rsjuy.jpg\",\n\n \"http://ww2.sinaimg.cn/large/610dc034gw1eyt23vp9mdj20ex0miq65.jpg\",\n\n \"http://ww2.sinaimg.cn/large/610dc034gw1eyrfnh1fcuj20ey0mi3zz.jpg\",\n\n \"http://ww2.sinaimg.cn/large/610dc034gw1eyrfi5kot7j20f00f0q5o.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1eynh92kg6jj20dc0gqwho.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1eymacvzrz6j20e00k0gnm.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1eyl43vfbndj20dw0ijmye.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1eyk28taztqj20hs0qotb8.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1eyirmivmh6j20f80m7abx.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1eyfe319rvfj20hs0qo41p.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1eye51p41xlj20go0m8mz0.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bjw1eyd07uugyvj20qo0hqgom.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1eybuo04j6dj20hq0qon0s.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1eyaov0c9z4j20iz0sg40t.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ey77s2wab8j20zk0nmdm2.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1ey6238m03pj20gy0op77l.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1ey4w5cdjbej20hs0qoq7q.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ey3ptkta45j20hs0qomzy.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1ey2lc2h2ckj20o20gxacp.jpg\",\n\n \"http://ww3.sinaimg.cn/large/7a8aed7bgw1exz7lm0ow0j20qo0hrjud.jpg\",\n\n \"http://ww2.sinaimg.cn/large/7a8aed7bjw1exy13si92lj20v218g10h.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1exwto3cm5xj20nm0kq7a3.jpg\",\n\n \"http://ww1.sinaimg.cn/large/7a8aed7bjw1exvmxmy36wj20ru114gqq.jpg\",\n\n \"http://ww3.sinaimg.cn/large/a3bcec5fjw1exukiyu2zoj20hs0qo0w9.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1exr0p4r0h3j20oy15445o.jpg\",\n\n \"http://ww4.sinaimg.cn/large/7a8aed7bjw1exp4h479xfj20hs0qoq6t.jpg\",\n };\n}", "public abstract class BaseViewHolder extends RecyclerView.ViewHolder {\n public BaseViewHolder(View itemView) {\n super(itemView);\n itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClick(v, getAdapterPosition());\n }\n });\n }\n\n public abstract void onBindViewHolder(int position);\n public abstract void onItemClick(View view, int position);\n}", "public class PullRecycler extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener {\n private SwipeRefreshLayout mSwipeRefreshLayout;\n private RecyclerView mRecyclerView;\n public static final int ACTION_PULL_TO_REFRESH = 1;\n public static final int ACTION_LOAD_MORE_REFRESH = 2;\n public static final int ACTION_IDLE = 0;\n private OnRecyclerRefreshListener listener;\n private int mCurrentState = ACTION_IDLE;\n private boolean isLoadMoreEnabled = false;\n private boolean isPullToRefreshEnabled = true;\n private ILayoutManager mLayoutManager;\n private BaseListAdapter adapter;\n\n public PullRecycler(Context context) {\n super(context);\n setUpView();\n }\n\n public PullRecycler(Context context, AttributeSet attrs) {\n super(context, attrs);\n setUpView();\n }\n\n public PullRecycler(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n setUpView();\n }\n\n private void setUpView() {\n LayoutInflater.from(getContext()).inflate(R.layout.widget_pull_to_refresh, this, true);\n mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);\n mSwipeRefreshLayout.setOnRefreshListener(this);\n mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);\n mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n super.onScrollStateChanged(recyclerView, newState);\n }\n\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n if (mCurrentState == ACTION_IDLE && isLoadMoreEnabled && checkIfNeedLoadMore()) {\n mCurrentState = ACTION_LOAD_MORE_REFRESH;\n adapter.onLoadMoreStateChanged(true);\n mSwipeRefreshLayout.setEnabled(false);\n listener.onRefresh(ACTION_LOAD_MORE_REFRESH);\n }\n }\n });\n }\n\n private boolean checkIfNeedLoadMore() {\n int lastVisibleItemPosition = mLayoutManager.findLastVisiblePosition();\n int totalCount = mLayoutManager.getLayoutManager().getItemCount();\n return totalCount - lastVisibleItemPosition < 5;\n }\n\n public void enableLoadMore(boolean enable) {\n isLoadMoreEnabled = enable;\n }\n\n public void enablePullToRefresh(boolean enable) {\n isPullToRefreshEnabled = enable;\n mSwipeRefreshLayout.setEnabled(enable);\n }\n\n public void setLayoutManager(ILayoutManager manager) {\n this.mLayoutManager = manager;\n mRecyclerView.setLayoutManager(manager.getLayoutManager());\n }\n\n public void addItemDecoration(RecyclerView.ItemDecoration decoration) {\n if (decoration != null) {\n mRecyclerView.addItemDecoration(decoration);\n }\n }\n\n public void setAdapter(BaseListAdapter adapter) {\n this.adapter = adapter;\n mRecyclerView.setAdapter(adapter);\n mLayoutManager.setUpAdapter(adapter);\n }\n\n public void setRefreshing() {\n mSwipeRefreshLayout.post(new Runnable() {\n @Override\n public void run() {\n mSwipeRefreshLayout.setRefreshing(true);\n onRefresh();\n }\n });\n }\n\n public void setOnRefreshListener(OnRecyclerRefreshListener listener) {\n this.listener = listener;\n }\n\n @Override\n public void onRefresh() {\n mCurrentState = ACTION_PULL_TO_REFRESH;\n listener.onRefresh(ACTION_PULL_TO_REFRESH);\n }\n\n public void onRefreshCompleted() {\n switch (mCurrentState) {\n case ACTION_PULL_TO_REFRESH:\n mSwipeRefreshLayout.setRefreshing(false);\n break;\n case ACTION_LOAD_MORE_REFRESH:\n adapter.onLoadMoreStateChanged(false);\n if (isPullToRefreshEnabled) {\n mSwipeRefreshLayout.setEnabled(true);\n }\n break;\n }\n mCurrentState = ACTION_IDLE;\n }\n\n public void setSelection(int position) {\n mRecyclerView.scrollToPosition(position);\n }\n\n\n public interface OnRecyclerRefreshListener {\n void onRefresh(int action);\n }\n}", "public interface ILayoutManager {\n RecyclerView.LayoutManager getLayoutManager();\n int findLastVisiblePosition();\n void setUpAdapter(BaseListAdapter adapter);\n}", "public class MyGridLayoutManager extends GridLayoutManager implements ILayoutManager {\n\n public MyGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n }\n\n public MyGridLayoutManager(Context context, int spanCount) {\n super(context, spanCount);\n }\n\n public MyGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {\n super(context, spanCount, orientation, reverseLayout);\n }\n\n\n @Override\n public RecyclerView.LayoutManager getLayoutManager() {\n return this;\n }\n\n @Override\n public int findLastVisiblePosition() {\n return findLastVisibleItemPosition();\n }\n\n @Override\n public void setUpAdapter(BaseListAdapter adapter) {\n FooterSpanSizeLookup lookup = new FooterSpanSizeLookup(adapter, getSpanCount());\n setSpanSizeLookup(lookup);\n }\n}", "public class MyLinearLayoutManager extends LinearLayoutManager implements ILayoutManager {\n public MyLinearLayoutManager(Context context) {\n super(context);\n }\n\n public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {\n super(context, orientation, reverseLayout);\n }\n\n public MyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n }\n\n\n @Override\n public RecyclerView.LayoutManager getLayoutManager() {\n return this;\n }\n\n @Override\n public int findLastVisiblePosition() {\n return findLastVisibleItemPosition();\n }\n\n @Override\n public void setUpAdapter(BaseListAdapter adapter) {\n\n }\n}", "public class MyStaggeredGridLayoutManager extends StaggeredGridLayoutManager implements ILayoutManager {\n\n public MyStaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n }\n\n public MyStaggeredGridLayoutManager(int spanCount, int orientation) {\n super(spanCount, orientation);\n }\n\n @Override\n public RecyclerView.LayoutManager getLayoutManager() {\n return this;\n }\n\n @Override\n public int findLastVisiblePosition() {\n int[] positions = null;\n positions = findLastVisibleItemPositions(positions);\n return positions[0];\n }\n\n @Override\n public void setUpAdapter(BaseListAdapter adapter) {\n\n }\n}", "public class SectionData<T> {\n public boolean isHeader;\n public int headerIndex;//用于索引ABC...的index定位\n public T t;\n public String header;\n\n public SectionData(boolean isHeader, int headerIndex, String header) {\n this.isHeader = isHeader;\n this.header = header;\n this.headerIndex = headerIndex;\n this.t = null;\n }\n\n public SectionData(T t) {\n this.isHeader = false;\n this.header = null;\n this.t = t;\n }\n}" ]
import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.stay4it.R; import com.stay4it.core.BaseSectionListFragment; import com.stay4it.model.ConstantValues; import com.stay4it.widgets.pull.BaseViewHolder; import com.stay4it.widgets.pull.PullRecycler; import com.stay4it.widgets.pull.layoutmanager.ILayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyGridLayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyLinearLayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyStaggeredGridLayoutManager; import com.stay4it.widgets.pull.section.SectionData; import java.util.ArrayList; import java.util.Random;
package com.stay4it.sample; /** * Created by Stay on 8/3/16. * Powered by www.stay4it.com */ public class SampleSectionListFragment extends BaseSectionListFragment<String> { private int random; @Override protected BaseViewHolder onCreateSectionViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_sample_list_item, parent, false); return new SampleViewHolder(view); } @Override protected ILayoutManager getLayoutManager() { random = new Random().nextInt(3); switch (random) { case 0: return new MyLinearLayoutManager(getContext()); case 1: return new MyGridLayoutManager(getContext(), 3); case 2: return new MyStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); } return super.getLayoutManager(); } @Override protected RecyclerView.ItemDecoration getItemDecoration() { if (random == 0) { return super.getItemDecoration(); } else { return null; } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recycler.setRefreshing(); } @Override public void onRefresh(final int action) { if (mDataList == null) { mDataList = new ArrayList<>(); } recycler.postDelayed(new Runnable() { @Override public void run() {
if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
3
lakeinchina/librestreaming
librestreaming/src/main/java/me/lake/librestreaming/client/RESAudioClient.java
[ "public class RESSoftAudioCore {\n RESCoreParameters resCoreParameters;\n private final Object syncOp = new Object();\n private MediaCodec dstAudioEncoder;\n private MediaFormat dstAudioFormat;\n //filter\n private Lock lockAudioFilter = null;\n private BaseSoftAudioFilter audioFilter;\n //AudioBuffs\n //buffers to handle buff from queueAudio\n private RESAudioBuff[] orignAudioBuffs;\n private int lastAudioQueueBuffIndex;\n //buffer to handle buff from orignAudioBuffs\n private RESAudioBuff orignAudioBuff;\n private RESAudioBuff filteredAudioBuff;\n private AudioFilterHandler audioFilterHandler;\n private HandlerThread audioFilterHandlerThread;\n private AudioSenderThread audioSenderThread;\n\n public RESSoftAudioCore(RESCoreParameters parameters) {\n resCoreParameters = parameters;\n lockAudioFilter = new ReentrantLock(false);\n }\n\n public void queueAudio(byte[] rawAudioFrame) {\n int targetIndex = (lastAudioQueueBuffIndex + 1) % orignAudioBuffs.length;\n if (orignAudioBuffs[targetIndex].isReadyToFill) {\n LogTools.d(\"queueAudio,accept ,targetIndex\" + targetIndex);\n System.arraycopy(rawAudioFrame, 0, orignAudioBuffs[targetIndex].buff, 0, resCoreParameters.audioRecoderBufferSize);\n orignAudioBuffs[targetIndex].isReadyToFill = false;\n lastAudioQueueBuffIndex = targetIndex;\n audioFilterHandler.sendMessage(audioFilterHandler.obtainMessage(AudioFilterHandler.WHAT_INCOMING_BUFF, targetIndex, 0));\n } else {\n LogTools.d(\"queueAudio,abandon,targetIndex\" + targetIndex);\n }\n }\n\n public boolean prepare(RESConfig resConfig) {\n synchronized (syncOp) {\n resCoreParameters.mediacodecAACProfile = MediaCodecInfo.CodecProfileLevel.AACObjectLC;\n resCoreParameters.mediacodecAACSampleRate = 44100;\n resCoreParameters.mediacodecAACChannelCount = 1;\n resCoreParameters.mediacodecAACBitRate = 32 * 1024;\n resCoreParameters.mediacodecAACMaxInputSize = 8820;\n\n dstAudioFormat = new MediaFormat();\n dstAudioEncoder = MediaCodecHelper.createAudioMediaCodec(resCoreParameters, dstAudioFormat);\n if (dstAudioEncoder == null) {\n LogTools.e(\"create Audio MediaCodec failed\");\n return false;\n }\n //audio\n //44100/10=4410,4410*2 = 8820\n int audioQueueNum = resCoreParameters.audioBufferQueueNum;\n int orignAudioBuffSize = resCoreParameters.mediacodecAACSampleRate / 5;\n orignAudioBuffs = new RESAudioBuff[audioQueueNum];\n for (int i = 0; i < audioQueueNum; i++) {\n orignAudioBuffs[i] = new RESAudioBuff(AudioFormat.ENCODING_PCM_16BIT, orignAudioBuffSize);\n }\n orignAudioBuff = new RESAudioBuff(AudioFormat.ENCODING_PCM_16BIT, orignAudioBuffSize);\n filteredAudioBuff = new RESAudioBuff(AudioFormat.ENCODING_PCM_16BIT, orignAudioBuffSize);\n return true;\n }\n }\n\n public void start(RESFlvDataCollecter flvDataCollecter) {\n synchronized (syncOp) {\n try {\n for (RESAudioBuff buff : orignAudioBuffs) {\n buff.isReadyToFill = true;\n }\n if (dstAudioEncoder == null) {\n dstAudioEncoder = MediaCodec.createEncoderByType(dstAudioFormat.getString(MediaFormat.KEY_MIME));\n }\n dstAudioEncoder.configure(dstAudioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);\n dstAudioEncoder.start();\n lastAudioQueueBuffIndex = 0;\n audioFilterHandlerThread = new HandlerThread(\"audioFilterHandlerThread\");\n audioSenderThread = new AudioSenderThread(\"AudioSenderThread\", dstAudioEncoder, flvDataCollecter);\n audioFilterHandlerThread.start();\n audioSenderThread.start();\n audioFilterHandler = new AudioFilterHandler(audioFilterHandlerThread.getLooper());\n } catch (Exception e) {\n LogTools.trace(\"RESSoftAudioCore\", e);\n }\n }\n }\n\n public void stop() {\n synchronized (syncOp) {\n audioFilterHandler.removeCallbacksAndMessages(null);\n audioFilterHandlerThread.quit();\n try {\n audioFilterHandlerThread.join();\n audioSenderThread.quit();\n audioSenderThread.join();\n } catch (InterruptedException e) {\n LogTools.trace(\"RESSoftAudioCore\", e);\n }\n dstAudioEncoder.stop();\n dstAudioEncoder.release();\n dstAudioEncoder = null;\n }\n }\n\n public BaseSoftAudioFilter acquireAudioFilter() {\n lockAudioFilter.lock();\n return audioFilter;\n }\n\n public void releaseAudioFilter() {\n lockAudioFilter.unlock();\n }\n\n public void setAudioFilter(BaseSoftAudioFilter baseSoftAudioFilter) {\n lockAudioFilter.lock();\n if (audioFilter != null) {\n audioFilter.onDestroy();\n }\n audioFilter = baseSoftAudioFilter;\n if (audioFilter != null) {\n audioFilter.onInit(resCoreParameters.mediacodecAACSampleRate / 5);\n }\n lockAudioFilter.unlock();\n }\n\n public void destroy() {\n synchronized (syncOp) {\n lockAudioFilter.lock();\n if (audioFilter != null) {\n audioFilter.onDestroy();\n }\n lockAudioFilter.unlock();\n }\n }\n\n private class AudioFilterHandler extends Handler {\n public static final int FILTER_LOCK_TOLERATION = 3;//3ms\n public static final int WHAT_INCOMING_BUFF = 1;\n private int sequenceNum;\n\n AudioFilterHandler(Looper looper) {\n super(looper);\n sequenceNum = 0;\n }\n\n @Override\n public void handleMessage(Message msg) {\n if (msg.what != WHAT_INCOMING_BUFF) {\n return;\n }\n sequenceNum++;\n int targetIndex = msg.arg1;\n long nowTimeMs = SystemClock.uptimeMillis();\n System.arraycopy(orignAudioBuffs[targetIndex].buff, 0,\n orignAudioBuff.buff, 0, orignAudioBuff.buff.length);\n orignAudioBuffs[targetIndex].isReadyToFill = true;\n boolean isFilterLocked = lockAudioFilter();\n boolean filtered = false;\n if (isFilterLocked) {\n filtered = audioFilter.onFrame(orignAudioBuff.buff, filteredAudioBuff.buff, nowTimeMs, sequenceNum);\n unlockAudioFilter();\n } else {\n System.arraycopy(orignAudioBuffs[targetIndex].buff, 0,\n orignAudioBuff.buff, 0, orignAudioBuff.buff.length);\n orignAudioBuffs[targetIndex].isReadyToFill = true;\n }\n //orignAudioBuff is ready\n int eibIndex = dstAudioEncoder.dequeueInputBuffer(-1);\n if (eibIndex >= 0) {\n ByteBuffer dstAudioEncoderIBuffer = dstAudioEncoder.getInputBuffers()[eibIndex];\n dstAudioEncoderIBuffer.position(0);\n dstAudioEncoderIBuffer.put(filtered?filteredAudioBuff.buff:orignAudioBuff.buff, 0, orignAudioBuff.buff.length);\n dstAudioEncoder.queueInputBuffer(eibIndex, 0, orignAudioBuff.buff.length, nowTimeMs * 1000, 0);\n } else {\n LogTools.d(\"dstAudioEncoder.dequeueInputBuffer(-1)<0\");\n }\n LogTools.d(\"AudioFilterHandler,ProcessTime:\" + (System.currentTimeMillis() - nowTimeMs));\n }\n\n /**\n * @return ture if filter locked & filter!=null\n */\n\n private boolean lockAudioFilter() {\n try {\n boolean locked = lockAudioFilter.tryLock(FILTER_LOCK_TOLERATION, TimeUnit.MILLISECONDS);\n if (locked) {\n if (audioFilter != null) {\n return true;\n } else {\n lockAudioFilter.unlock();\n return false;\n }\n } else {\n return false;\n }\n } catch (InterruptedException e) {\n }\n return false;\n }\n\n private void unlockAudioFilter() {\n lockAudioFilter.unlock();\n }\n }\n}", "public class BaseSoftAudioFilter {\n protected int SIZE;\n protected int SIZE_HALF;\n\n public void onInit(int size) {\n SIZE = size;\n SIZE_HALF = size/2;\n }\n\n /**\n *\n * @param orignBuff\n * @param targetBuff\n * @param presentationTimeMs\n * @param sequenceNum\n * @return false to use orignBuff,true to use targetBuff\n */\n public boolean onFrame(byte[] orignBuff, byte[] targetBuff, long presentationTimeMs, int sequenceNum) {\n return false;\n }\n\n public void onDestroy() {\n\n }\n}", "public class RESConfig {\n public static class FilterMode {\n public static final int HARD = RESCoreParameters.FILTER_MODE_HARD;\n public static final int SOFT = RESCoreParameters.FILTER_MODE_SOFT;\n }\n\n public static class RenderingMode {\n public static final int NativeWindow = RESCoreParameters.RENDERING_MODE_NATIVE_WINDOW;\n public static final int OpenGLES = RESCoreParameters.RENDERING_MODE_OPENGLES;\n }\n\n public static class DirectionMode {\n public static final int FLAG_DIRECTION_FLIP_HORIZONTAL = RESCoreParameters.FLAG_DIRECTION_FLIP_HORIZONTAL;\n public static final int FLAG_DIRECTION_FLIP_VERTICAL = RESCoreParameters.FLAG_DIRECTION_FLIP_VERTICAL;\n public static final int FLAG_DIRECTION_ROATATION_0 = RESCoreParameters.FLAG_DIRECTION_ROATATION_0;\n public static final int FLAG_DIRECTION_ROATATION_90 = RESCoreParameters.FLAG_DIRECTION_ROATATION_90;\n public static final int FLAG_DIRECTION_ROATATION_180 = RESCoreParameters.FLAG_DIRECTION_ROATATION_180;\n public static final int FLAG_DIRECTION_ROATATION_270 = RESCoreParameters.FLAG_DIRECTION_ROATATION_270;\n }\n\n private int filterMode;\n private Size targetVideoSize;\n private int videoBufferQueueNum;\n private int bitRate;\n private String rtmpAddr;\n private int renderingMode;\n private int defaultCamera;\n private int frontCameraDirectionMode;\n private int backCameraDirectionMode;\n private int videoFPS;\n private int videoGOP;\n private boolean printDetailMsg;\n\n private RESConfig() {\n }\n\n public static RESConfig obtain() {\n RESConfig res = new RESConfig();\n res.setFilterMode(FilterMode.SOFT);\n res.setRenderingMode(RenderingMode.NativeWindow);\n res.setTargetVideoSize(new Size(1280, 720));\n res.setVideoFPS(15);\n res.setVideoGOP(1);\n res.setVideoBufferQueueNum(5);\n res.setBitRate(2000000);\n res.setPrintDetailMsg(false);\n res.setDefaultCamera(Camera.CameraInfo.CAMERA_FACING_BACK);\n res.setBackCameraDirectionMode(DirectionMode.FLAG_DIRECTION_ROATATION_0);\n res.setFrontCameraDirectionMode(DirectionMode.FLAG_DIRECTION_ROATATION_0);\n return res;\n }\n\n /**\n * set the filter mode.\n *\n * @param filterMode {@link FilterMode}\n */\n public void setFilterMode(int filterMode) {\n this.filterMode = filterMode;\n }\n\n /**\n * set the default camera to start stream\n */\n public void setDefaultCamera(int defaultCamera) {\n this.defaultCamera = defaultCamera;\n }\n\n /**\n * set front camera rotation & flip\n * @param frontCameraDirectionMode {@link DirectionMode}\n */\n public void setFrontCameraDirectionMode(int frontCameraDirectionMode) {\n this.frontCameraDirectionMode = frontCameraDirectionMode;\n }\n /**\n * set front camera rotation & flip\n * @param backCameraDirectionMode {@link DirectionMode}\n */\n public void setBackCameraDirectionMode(int backCameraDirectionMode) {\n this.backCameraDirectionMode = backCameraDirectionMode;\n }\n\n /**\n * set renderingMode when using soft mode<br/>\n * no use for hard mode\n * @param renderingMode {@link RenderingMode}\n */\n public void setRenderingMode(int renderingMode) {\n this.renderingMode = renderingMode;\n }\n\n /**\n * no use for now\n * @param printDetailMsg\n */\n public void setPrintDetailMsg(boolean printDetailMsg) {\n this.printDetailMsg = printDetailMsg;\n }\n\n /**\n * set the target video size.<br/>\n * real video size may different from it.Depend on device.\n * @param videoSize\n */\n public void setTargetVideoSize(Size videoSize) {\n targetVideoSize = videoSize;\n }\n\n /**\n * set video buffer number for soft mode.<br/>\n * num larger:video Smoother,more memory.\n * @param num\n */\n public void setVideoBufferQueueNum(int num) {\n videoBufferQueueNum = num;\n }\n\n /**\n * set video bitrate\n * @param bitRate\n */\n public void setBitRate(int bitRate) {\n this.bitRate = bitRate;\n }\n\n public int getVideoFPS() {\n return videoFPS;\n }\n\n public void setVideoFPS(int videoFPS) {\n this.videoFPS = videoFPS;\n }\n\n public int getVideoGOP(){\n return videoGOP;\n }\n\n public void setVideoGOP(int videoGOP){\n this.videoGOP = videoGOP;\n }\n\n public int getVideoBufferQueueNum() {\n return videoBufferQueueNum;\n }\n\n public int getBitRate() {\n return bitRate;\n }\n\n public Size getTargetVideoSize() {\n return targetVideoSize;\n }\n\n public int getFilterMode() {\n return filterMode;\n }\n\n public int getDefaultCamera() {\n return defaultCamera;\n }\n\n public int getBackCameraDirectionMode() {\n return backCameraDirectionMode;\n }\n\n public int getFrontCameraDirectionMode() {\n return frontCameraDirectionMode;\n }\n\n public int getRenderingMode() {\n return renderingMode;\n }\n\n public String getRtmpAddr() {\n return rtmpAddr;\n }\n\n public void setRtmpAddr(String rtmpAddr) {\n this.rtmpAddr = rtmpAddr;\n }\n\n public boolean isPrintDetailMsg() {\n return printDetailMsg;\n }\n}", "public class RESCoreParameters {\n public static final int FILTER_MODE_HARD = 1;\n public static final int FILTER_MODE_SOFT = 2;\n\n public static final int RENDERING_MODE_NATIVE_WINDOW = 1;\n public static final int RENDERING_MODE_OPENGLES = 2;\n /**\n * same with jni\n */\n public static final int FLAG_DIRECTION_FLIP_HORIZONTAL = 0x01;\n public static final int FLAG_DIRECTION_FLIP_VERTICAL = 0x02;\n public static final int FLAG_DIRECTION_ROATATION_0 = 0x10;\n public static final int FLAG_DIRECTION_ROATATION_90 = 0x20;\n public static final int FLAG_DIRECTION_ROATATION_180 = 0x40;\n public static final int FLAG_DIRECTION_ROATATION_270 = 0x80;\n\n public boolean done;\n public boolean printDetailMsg;\n public int filterMode;\n public int renderingMode;\n public String rtmpAddr;\n public int frontCameraDirectionMode;\n public int backCameraDirectionMode;\n public boolean isPortrait;\n public int previewVideoWidth;\n public int previewVideoHeight;\n public int videoWidth;\n public int videoHeight;\n public int videoFPS;\n public int videoGOP;\n public float cropRatio;\n public int previewColorFormat;\n public int previewBufferSize;\n public int mediacodecAVCColorFormat;\n public int mediacdoecAVCBitRate;\n public int videoBufferQueueNum;\n public int audioBufferQueueNum;\n public int audioRecoderFormat;\n public int audioRecoderSampleRate;\n public int audioRecoderChannelConfig;\n public int audioRecoderSliceSize;\n public int audioRecoderSource;\n public int audioRecoderBufferSize;\n public int previewMaxFps;\n public int previewMinFps;\n public int mediacodecAVCFrameRate;\n public int mediacodecAVCIFrameInterval;\n public int mediacodecAVCProfile;\n public int mediacodecAVClevel;\n\n public int mediacodecAACProfile;\n public int mediacodecAACSampleRate;\n public int mediacodecAACChannelCount;\n public int mediacodecAACBitRate;\n public int mediacodecAACMaxInputSize;\n\n //sender\n public int senderQueueLength;\n\n public RESCoreParameters() {\n done = false;\n printDetailMsg = false;\n filterMode=-1;\n videoWidth = -1;\n videoHeight = -1;\n videoFPS=-1;\n videoGOP=1;\n previewColorFormat = -1;\n mediacodecAVCColorFormat = -1;\n mediacdoecAVCBitRate = -1;\n videoBufferQueueNum = -1;\n audioBufferQueueNum = -1;\n mediacodecAVCFrameRate = -1;\n mediacodecAVCIFrameInterval = -1;\n mediacodecAVCProfile = -1;\n mediacodecAVClevel = -1;\n mediacodecAACProfile = -1;\n mediacodecAACSampleRate = -1;\n mediacodecAACChannelCount = -1;\n mediacodecAACBitRate = -1;\n mediacodecAACMaxInputSize = -1;\n }\n\n public void dump() {\n LogTools.e(this.toString());\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"ResParameter:\");\n Field[] fields = this.getClass().getDeclaredFields();\n for (Field field : fields) {\n if (Modifier.isStatic(field.getModifiers())) {\n continue;\n }\n field.setAccessible(true);\n try {\n sb.append(field.getName());\n sb.append('=');\n sb.append(field.get(this));\n sb.append(';');\n } catch (IllegalAccessException e) {\n }\n }\n return sb.toString();\n }\n}", "public interface RESFlvDataCollecter {\n void collect(RESFlvData flvData, int type);\n}", "public class LogTools {\n protected static final String TAG = \"RESLog\";\n private static boolean enableLog = true;\n\n public static boolean isEnableLog() {\n return enableLog;\n }\n\n public static void setEnableLog(boolean enableLog) {\n LogTools.enableLog = enableLog;\n }\n\n public static void e(String content) {\n if (!enableLog) {\n return;\n }\n Log.e(TAG, content);\n }\n\n public static void d(String content) {\n if (!enableLog) {\n return;\n }\n Log.d(TAG, content);\n }\n\n public static void trace(String msg) {\n if (!enableLog) {\n return;\n }\n trace(msg, new Throwable());\n }\n\n public static void trace(Throwable e) {\n if (!enableLog) {\n return;\n }\n trace(null, e);\n }\n\n public static void trace(String msg, Throwable e) {\n if (!enableLog) {\n return;\n }\n if (null == e || e instanceof UnknownHostException) {\n return;\n }\n\n final Writer writer = new StringWriter();\n final PrintWriter pWriter = new PrintWriter(writer);\n e.printStackTrace(pWriter);\n String stackTrace = writer.toString();\n if (null == msg || msg.equals(\"\")) {\n msg = \"================error!==================\";\n }\n Log.e(TAG, \"==================================\");\n Log.e(TAG, msg);\n Log.e(TAG, stackTrace);\n Log.e(TAG, \"-----------------------------------\");\n }\n}" ]
import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import me.lake.librestreaming.core.RESSoftAudioCore; import me.lake.librestreaming.filter.softaudiofilter.BaseSoftAudioFilter; import me.lake.librestreaming.model.RESConfig; import me.lake.librestreaming.model.RESCoreParameters; import me.lake.librestreaming.rtmp.RESFlvDataCollecter; import me.lake.librestreaming.tools.LogTools;
package me.lake.librestreaming.client; /** * Created by lake on 16-5-24. */ public class RESAudioClient { RESCoreParameters resCoreParameters; private final Object syncOp = new Object(); private AudioRecordThread audioRecordThread; private AudioRecord audioRecord; private byte[] audioBuffer; private RESSoftAudioCore softAudioCore; public RESAudioClient(RESCoreParameters parameters) { resCoreParameters = parameters; }
public boolean prepare(RESConfig resConfig) {
2
fabian7593/MagicalCamera
magicalcamera/src/main/java/com/frosquivel/magicalcamera/MagicalCamera.java
[ "public class ActionPictureObject {\n\n //the max of quality photo\n public static final int BEST_QUALITY_PHOTO = 4000;\n\n //The photo name for uxiliar save picture\n public static final String photoNameAuxiliar = \"MagicalCamera\";\n\n //properties\n //my intent curret fragment (only use for fragments)\n private Intent intentFragment;\n\n //Your own resize picture\n private int resizePhoto;\n\n //my activity variable\n private Activity activity;\n\n //bitmap to set and get\n private Bitmap myPhoto;\n\n\n //getters and setters\n public Intent getIntentFragment() {\n return intentFragment;\n }\n\n public void setIntentFragment(Intent intentFragment) {\n this.intentFragment = intentFragment;\n }\n\n public Bitmap getMyPhoto() {\n return myPhoto;\n }\n\n public void setMyPhoto(Bitmap myPhoto) {\n this.myPhoto = myPhoto;\n }\n\n public int getResizePhoto() {\n return resizePhoto;\n }\n\n public void setResizePhoto(int resizePhoto) {\n resizePhoto = resizePhoto * 40;\n if (resizePhoto <= BEST_QUALITY_PHOTO && resizePhoto > 0)\n this.resizePhoto = resizePhoto;\n else{\n this.resizePhoto = BEST_QUALITY_PHOTO;\n }\n }\n\n public Activity getActivity() {\n return activity;\n }\n\n public void setActivity(Activity activity) {\n this.activity = activity;\n }\n}", "public class FaceRecognitionObject {\n //Getters and Setters method\n public List<Landmark> listLandMarkPhoto;\n\n public List<Landmark> getListLandMarkPhoto() {\n return listLandMarkPhoto;\n }\n\n public void setListLandMarkPhoto(List<Landmark> listLandMarkPhoto) {\n this.listLandMarkPhoto = listLandMarkPhoto;\n }\n}", "public class MagicalCameraObject {\n //================================================================================\n // Properties\n //================================================================================\n\n //my activity variable\n private Activity activity;\n\n //the face recognition class for instance\n private FaceRecognition faceRecognition;\n\n //the private information class for instance\n private PrivateInformation privateInformation;\n\n //the private variable of saveEasyPhoto\n private SaveEasyPhoto saveEasyPhoto;\n\n //the actions to take pictures or selected\n private ActionPicture actionPicture;\n\n //the uri of paths class\n private URIPaths uriPaths;\n //endregion\n\n\n //Constructor\n public MagicalCameraObject(Activity activity, int qualityPhoto){\n this.activity = activity;\n this.faceRecognition = new FaceRecognition();\n this.privateInformation = new PrivateInformation();\n this.uriPaths = new URIPaths(this.privateInformation, activity);\n this.saveEasyPhoto = new SaveEasyPhoto();\n this.actionPicture = new ActionPicture(activity, qualityPhoto, this.uriPaths);\n }\n\n\n //================================================================================\n // Accessors\n //================================================================================\n\n public Activity getActivity() {\n return activity;\n }\n\n public void setActivity(Activity activity) {\n this.activity = activity;\n }\n\n public FaceRecognition getFaceRecognition() {\n return faceRecognition;\n }\n\n public void setFaceRecognition(FaceRecognition faceRecognition) {\n this.faceRecognition = faceRecognition;\n }\n\n public PrivateInformation getPrivateInformation() {\n return privateInformation;\n }\n\n public void setPrivateInformation(PrivateInformation privateInformation) {\n this.privateInformation = privateInformation;\n }\n\n public SaveEasyPhoto getSaveEasyPhoto() {\n return saveEasyPhoto;\n }\n\n public void setSaveEasyPhoto(SaveEasyPhoto saveEasyPhoto) {\n this.saveEasyPhoto = saveEasyPhoto;\n }\n\n public ActionPicture getActionPicture() {\n return actionPicture;\n }\n\n public void setActionPicture(ActionPicture actionPicture) {\n this.actionPicture = actionPicture;\n }\n public URIPaths getUriPaths() {\n return uriPaths;\n }\n //endregion\n}", "public class PrivateInformationObject {\n //Properties of face recognition\n float latitude;\n String latitudeReference;\n float longitude;\n String longitudeReference;\n String dateTimeTakePhoto;\n String imageLength;\n String imageWidth;\n String modelDevice;\n String makeCompany;\n String orientation;\n String iso;\n String dateStamp;\n\n public void setLongitudeReference(String longitudeReference) {\n this.longitudeReference = longitudeReference;\n }\n\n public void setDateStamp(String dateStamp) {\n this.dateStamp = dateStamp;\n }\n\n public void setDateTimeTakePhoto(String dateTimeTakePhoto) {\n this.dateTimeTakePhoto = dateTimeTakePhoto;\n }\n\n public void setImageLength(String imageLength) {\n this.imageLength = imageLength;\n }\n\n public void setImageWidth(String imageWidth) {\n this.imageWidth = imageWidth;\n }\n\n public void setIso(String iso) {\n this.iso = iso;\n }\n\n public void setLatitude(float latitude) {\n this.latitude = latitude;\n }\n\n public void setLatitudeReference(String latitudeReference) {\n this.latitudeReference = latitudeReference;\n }\n\n public void setLongitude(float longitude) {\n this.longitude = longitude;\n }\n\n public void setMakeCompany(String makeCompany) {\n this.makeCompany = makeCompany;\n }\n\n public void setModelDevice(String modelDevice) {\n this.modelDevice = modelDevice;\n }\n\n public void setOrientation(String orientation) {\n this.orientation = orientation;\n }\n\n public float getLatitude() {\n return latitude;\n }\n\n public String getLatitudeReference() {\n return latitudeReference;\n }\n\n public float getLongitude() {\n return longitude;\n }\n\n public String getLongitudeReference() {\n return longitudeReference;\n }\n\n public String getMakeCompany() {\n return makeCompany;\n }\n\n public String getModelDevice() {\n return modelDevice;\n }\n\n public String getDateTimeTakePhoto() {\n return dateTimeTakePhoto;\n }\n\n public String getImageLength() {\n return imageLength;\n }\n\n public String getImageWidth() {\n return imageWidth;\n }\n\n public String getOrientation() {\n return orientation;\n }\n\n public String getIso() {\n return iso;\n }\n\n public String getDateStamp() {\n return dateStamp;\n }\n}", "public class PictureUtils {\n //===============================================================================\n // Utils methods, resize and get Photo Uri and others\n //================================================================================\n\n /**\n * Rotate the bitmap if the image is in landscape camera\n * @param source\n * @param angle\n * @return\n */\n public static Bitmap rotateImage(Bitmap source, float angle) {\n Bitmap retVal;\n Matrix matrix = new Matrix();\n matrix.postRotate(angle);\n retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);\n return retVal;\n }\n\n /**\n * This method resize the photo\n *\n * @param realImage the bitmap of image\n * @param maxImageSize the max image size percentage\n * @param filter the filter\n * @return a bitmap of the photo rezise\n */\n public static Bitmap resizePhoto(Bitmap realImage, float maxImageSize,\n boolean filter) {\n float ratio = Math.min(\n (float) maxImageSize / realImage.getWidth(),\n (float) maxImageSize / realImage.getHeight());\n int width = Math.round((float) ratio * realImage.getWidth());\n int height = Math.round((float) ratio * realImage.getHeight());\n\n Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,\n height, filter);\n return newBitmap;\n }\n}" ]
import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import com.frosquivel.magicalcamera.Objects.ActionPictureObject; import com.frosquivel.magicalcamera.Objects.FaceRecognitionObject; import com.frosquivel.magicalcamera.Objects.MagicalCameraObject; import com.frosquivel.magicalcamera.Objects.PrivateInformationObject; import com.frosquivel.magicalcamera.Utilities.PictureUtils; import static android.graphics.Color.RED;
} } public void takeFragmentPhoto(final android.support.v4.app.Fragment fragment) { if (magicalCameraObject.getActionPicture().takeFragmentPhoto()) { Runnable runnable = new Runnable() { @Override public void run() { fragment.startActivityForResult(getIntentFragment(), MagicalCamera.TAKE_PHOTO); } }; askPermissions(runnable, CAMERA); } } public void selectFragmentPicture(final android.support.v4.app.Fragment fragment, final String header) { if (magicalCameraObject.getActionPicture().selectedFragmentPicture()) { Runnable runnable = new Runnable() { @Override public void run() { fragment.startActivityForResult( Intent.createChooser(getIntentFragment(), header), MagicalCamera.SELECT_PHOTO); } }; askPermissions(runnable, EXTERNAL_STORAGE); } } private void askPermissions(final Runnable runnable){ magicalPermissions.askPermissions(runnable); } private void askPermissions(final Runnable runnable, final String operationType){ magicalPermissions.askPermissions(runnable, operationType); } //Face detector methods public Bitmap faceDetector(int stroke, int color){ return magicalCameraObject.getFaceRecognition().faceDetector(stroke, color, magicalCameraObject.getActivity(), magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto()); } public Bitmap faceDetector(){ return magicalCameraObject.getFaceRecognition().faceDetector(5, RED, magicalCameraObject.getActivity(), magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto()); } public FaceRecognitionObject getFaceRecognitionInformation(){ return magicalCameraObject.getFaceRecognition().getFaceRecognitionInformation(); } //Image information methods public boolean initImageInformation() { return magicalCameraObject.getPrivateInformation().getImageInformation(magicalCameraObject.getUriPaths().getUriPathsObject().getRealPath()); } public PrivateInformationObject getPrivateInformation() { return magicalCameraObject.getPrivateInformation().getPrivateInformationObject(); } /** * *********************************************** * This methods save the photo in memory device * with diferents params * ********************************************** */ public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, "MAGICAL CAMERA", PNG, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, Bitmap.CompressFormat format, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, "MAGICAL CAMERA", format, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, String directoryName, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, directoryName, PNG, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, String directoryName, Bitmap.CompressFormat format, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, directoryName, format, autoIncrementNameByDate, magicalCameraObject.getActivity()); } //get variables public String getRealPath(){ return magicalCameraObject.getUriPaths().getUriPathsObject().getRealPath(); } public Bitmap getPhoto(){ return magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto(); } public void setPhoto(Bitmap bitmap){ magicalCameraObject.getActionPicture().getActionPictureObject().setMyPhoto(bitmap); } public void resultPhoto(int requestCode, int resultCode, Intent data){ magicalCameraObject.getActionPicture().resultPhoto(requestCode, resultCode, data); } public void resultPhoto(int requestCode, int resultCode, Intent data, int rotateType){ magicalCameraObject.getActionPicture().resultPhoto(requestCode, resultCode, data, rotateType); } public Intent getIntentFragment(){ return magicalCameraObject.getActionPicture().getActionPictureObject().getIntentFragment(); } public void setResizePhoto(int resize){ magicalCameraObject.getActionPicture().getActionPictureObject().setResizePhoto(resize); } //methods to rotate picture public Bitmap rotatePicture(int rotateType){ if(getPhoto() != null)
return PictureUtils.rotateImage(getPhoto(), rotateType);
4
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresUpdateDocument.java
[ "@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = \"@class\")\npublic interface JresBulkable {\n\n /**\n * @return bulk command\n */\n Object getAction();\n\n /**\n * @return (optional) payload of action, e.g. index operation is followed by the document to be indexed\n */\n Object getPayload();\n\n /**\n * @return target ElasticSearch index\n */\n String getIndex();\n\n /**\n * @return target ElasticSearch type\n */\n String getType();\n\n /*\n * @return target document id\n */\n String getId();\n\n /**\n * In jackson serialization, the darned @JsonTypeInfo annotation is not dynamically looked up based on runtime type,\n * but declared type. In the case where JresBulkables are type-erased (such as in collections) the declared type\n * becomes effectively Object which means no @JsonTypeInfo. The serialization includes no type information.\n * Jackson could have <strong>easily</strong> examined the runtime types for @JsonTypeInfo annotations, but they\n * just didn't. So subclasses must implement this 'special' property to be picked up on the other end for\n * proper polymorphic deserialization.\n * <p/>\n * Realize that this means Jackson deserialization has NO issues with finding the @JsonTypeInfo annotation on a\n * type-erased generic type. This is only a workaround for the shortcoming of the serialization side.\n *\n * @return the fully-qualified name of the sub-class\n */\n @JsonProperty(\"@class\")\n String getJsonTypeInfo();\n}", "public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> {\n\n private final Class<REPLY> responseClass;\n\n protected JresJsonRequest(Class<REPLY> responseClass) {\n this.responseClass = responseClass;\n }\n\n @Override\n public final Class<REPLY> getResponseClass() {\n return responseClass;\n }\n}", "public class JresBulk extends JresJsonRequest<JresBulkReply> {\n\n private final @Nullable String index;\n private final @Nullable String type;\n private final Iterable<JresBulkable> actions;\n\n /**\n * `index` or `type` are nullable if given JresBulkables specify them. For those that don't, ElasticSearch behavior\n * is to default to the index or type given here.\n */\n public JresBulk(@Nullable String index, @Nullable String type, Iterable<JresBulkable> actions) {\n super(JresBulkReply.class);\n this.index = index;\n this.type = type;\n this.actions = actions;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPost.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + \"_bulk\";\n }\n\n @Override\n public Object getPayload() {\n // Note that while _bulk requests are made up of JSON, the body as a whole isn't actually valid JSON.\n final InputStream input;\n try {\n input = ByteSource.concat(Iterables.transform(actions, new PayloadFn())).openStream();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return input;\n }\n\n private static final ByteSource NEW_LINE = ByteSource.wrap(\"\\n\".getBytes());\n\n private static class PayloadFn implements Function<JresBulkable, ByteSource> {\n @Override\n public ByteSource apply(JresBulkable action) {\n try {\n\n ByteSource lines = ByteSource.concat(\n ByteSource.wrap(ObjectMappers.NORMAL.writeValueAsBytes(action.getAction())),\n NEW_LINE\n );\n\n Object payload = action.getPayload();\n if (payload != null) {\n lines = ByteSource.concat(\n lines,\n ByteSource.wrap(ObjectMappers.NORMAL.writeValueAsBytes(payload)),\n NEW_LINE\n );\n }\n\n return lines;\n\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n}", "public class JresIndexDocumentReply extends JresJsonReply {\n\n @JsonProperty(\"_index\")\n private String index;\n\n @JsonProperty(\"_type\")\n private String type;\n\n @JsonProperty(\"_id\")\n private String id;\n\n @JsonProperty(\"_version\")\n private String version;\n\n private Boolean created;\n\n public String getIndex() {\n return index;\n }\n\n public String getType() {\n return type;\n }\n\n public String getId() {\n return id;\n }\n\n public String getVersion() {\n return version;\n }\n\n public Boolean getCreated() {\n return created;\n }\n\n}", "public class NoNullsMap<K, V> extends HashMap<K, V> {\n\n public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {\n NoNullsMap<K, V> map = new NoNullsMap<K, V>(1);\n map.put(k1, v1);\n return ImmutableMap.copyOf(map);\n\n }\n\n public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {\n NoNullsMap<K, V> map = new NoNullsMap<K, V>(3);\n map.put(k1, v1);\n map.put(k2, v2);\n map.put(k3, v3);\n return ImmutableMap.copyOf(map);\n }\n\n public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {\n NoNullsMap<K, V> map = new NoNullsMap<K, V>(3);\n map.put(k1, v1);\n map.put(k2, v2);\n map.put(k3, v3);\n map.put(k4, v4);\n return ImmutableMap.copyOf(map);\n }\n\n public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {\n NoNullsMap<K, V> map = new NoNullsMap<K, V>(3);\n map.put(k1, v1);\n map.put(k2, v2);\n map.put(k3, v3);\n map.put(k4, v4);\n map.put(k5, v5);\n return ImmutableMap.copyOf(map);\n }\n\n private NoNullsMap(int initialCapacity) {\n super(initialCapacity);\n }\n\n /**\n * Ignores null keys or values. The key won't be added at all if it is null or its value is null.\n */\n @Override\n public V put(K key, V value) {\n return key != null && value != null ? super.put(key, value) : null;\n }\n}", "public static String slashedPath(String... fragments) {\n String slashed = slashed(fragments);\n try {\n // Encode (anything that needs to be) in the path. Surprisingly this works.\n String encodedPath = new URI(null, null, slashed, null).getRawPath();\n // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed.\n return encodedPath.startsWith(\"/\") ? encodedPath.substring(1) : encodedPath;\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n}" ]
import com.blacklocus.jres.request.JresBulkable; import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.bulk.JresBulk; import com.blacklocus.jres.response.index.JresIndexDocumentReply; import com.blacklocus.misc.NoNullsMap; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpPost; import javax.annotation.Nullable; import static com.blacklocus.jres.strings.JresPaths.slashedPath;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-update.html">Update Document API</a> */ @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) public class JresUpdateDocument extends JresJsonRequest<JresIndexDocumentReply> implements JresBulkable { private @Nullable String index; private @Nullable String type; private String id; private Object document; private Boolean docAsUpsert; private Integer retryOnConflict; // for JSON deserialization JresUpdateDocument() { super(JresIndexDocumentReply.class); } /** * Update a document. If it does not exist will create one (<code>doc_as_upsert:true</code>). Note in ElasticSearch * "update" means to modify an existing document (e.g. merge or overwrite particular fields). To overwrite an * existing document with some id is not an ElasticSearch "update" operation, but rather an "index" * ({@link JresIndexDocument}) operation. * <p/> * `index` or `type` are nullable if this operation is to be included in a {@link JresBulk} request which specifies * a default index or type, respectively. */ public JresUpdateDocument(@Nullable String index, @Nullable String type, String id, Object document) { this(index, type, id, document, true, 0); } /** * Update a document. If it does not exist will create one. Note in ElasticSearch "update" means to modify an * existing document (e.g. merge or overwrite particular fields). To overwrite an existing document with some id is * not an ElasticSearch "update" operation, but rather an "index" ({@link JresIndexDocument}) operation. * <p/> * `index` or `type` are nullable if this operation is to be included in a {@link JresBulk} request which specifies * a default index or type, respectively. * * @param docAsUpsert If false, prevents ElasticSearch from automatically creating a new document. */ public JresUpdateDocument(@Nullable String index, @Nullable String type, String id, Object document, Boolean docAsUpsert, Integer retryOnConflict) { super(JresIndexDocumentReply.class); this.index = index; this.type = type; this.id = id; this.document = document; this.docAsUpsert = docAsUpsert; this.retryOnConflict = retryOnConflict; } @Nullable @JsonProperty public String getIndex() { return index; } public void setIndex(@Nullable String index) { this.index = index; } @Nullable @JsonProperty public String getType() { return type; } public void setType(@Nullable String type) { this.type = type; } @JsonProperty public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonProperty public Object getDocument() { return document; } public void setDocument(Object document) { this.document = document; } @JsonProperty public Boolean getDocAsUpsert() { return docAsUpsert; } public void setDocAsUpsert(Boolean docAsUpsert) { this.docAsUpsert = docAsUpsert; } @JsonProperty public Integer getRetryOnConflict() { return retryOnConflict; } public void setRetryOnConflict(Integer retryOnConflict) { this.retryOnConflict = retryOnConflict; } @Override public String getJsonTypeInfo() { return JresUpdateDocument.class.getName(); } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() { String path = slashedPath(index, type, id) + "_update"; if (retryOnConflict != null) { path += "?retry_on_conflict=" + retryOnConflict; } return path; } @Override public Object getPayload() { return ImmutableMap.builder() .put("doc", document) .put("doc_as_upsert", docAsUpsert) .build(); } @Override public Object getAction() {
return ImmutableMap.of("update", NoNullsMap.of(
4
GlitchCog/ChatGameFontificator
src/main/java/com/glitchcog/fontificator/gui/controls/panel/ControlPanelDebug.java
[ "public class FontificatorProperties extends Properties\n{\n private static final Logger logger = Logger.getLogger(FontificatorProperties.class);\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Copy of properties to compare with when checking if there have been changes\n */\n private FontificatorProperties lastSavedCopy;\n\n private final static String ENC_PASSWORD = \"Eastmost penninsula is the secret.\";\n\n /**\n * The name of the file that holds the location of the last file saved or loaded by a user, to be used when the\n * program starts to automatically load the previously used configuration\n */\n private static final String CONFIG_FILE_LAST_LOCATION = \".fontificator.conf\";\n\n public static final String KEY_IRC_USER = \"ircUser\";\n public static final String KEY_IRC_HOST = \"ircHost\";\n public static final String KEY_IRC_PORT = \"ircPort\";\n public static final String KEY_IRC_AUTH = \"ircAuth\";\n public static final String KEY_IRC_ANON = \"ircAnon\";\n public static final String KEY_IRC_CHAN = \"ircChannel\";\n public static final String KEY_IRC_AUTO_RECONNECT = \"ircAutoReconnect\";\n\n public static final String[] IRC_KEYS = new String[] { KEY_IRC_USER, KEY_IRC_HOST, KEY_IRC_PORT, KEY_IRC_AUTH, KEY_IRC_ANON, KEY_IRC_CHAN, KEY_IRC_AUTO_RECONNECT };\n\n public static final String KEY_FONT_FILE_BORDER = \"fontBorderFile\";\n public static final String KEY_FONT_FILE_FONT = \"fontFile\";\n public static final String KEY_FONT_TYPE = \"fontType\";\n public static final String KEY_FONT_GRID_WIDTH = \"fontGridWidth\";\n public static final String KEY_FONT_GRID_HEIGHT = \"fontGridHeight\";\n public static final String KEY_FONT_SCALE = \"fontScale\";\n public static final String KEY_FONT_BORDER_SCALE = \"fontBorderScale\";\n public static final String KEY_FONT_BORDER_INSET_X = \"fontBorderInsetX\";\n public static final String KEY_FONT_BORDER_INSET_Y = \"fontBorderInsetY\";\n public static final String KEY_FONT_SPACE_WIDTH = \"fontSpaceWidth\";\n public static final String KEY_FONT_BASELINE_OFFSET = \"fontBaselineOffset\";\n public static final String KEY_FONT_UNKNOWN_CHAR = \"fontUnknownChar\";\n public static final String KEY_FONT_EXTENDED_CHAR = \"fontExtendedChar\";\n public static final String KEY_FONT_CHARACTERS = \"fontCharacters\";\n public static final String KEY_FONT_SPACING_LINE = \"fontLineSpacing\";\n public static final String KEY_FONT_SPACING_CHAR = \"fontCharSpacing\";\n public static final String KEY_FONT_SPACING_MESSAGE = \"fontMessageSpacing\";\n\n public static final String[] FONT_KEYS = new String[] { KEY_FONT_FILE_BORDER, KEY_FONT_FILE_FONT, KEY_FONT_TYPE, KEY_FONT_GRID_WIDTH, KEY_FONT_GRID_HEIGHT, KEY_FONT_SCALE, KEY_FONT_BORDER_SCALE, KEY_FONT_BORDER_INSET_X, KEY_FONT_BORDER_INSET_Y, KEY_FONT_SPACE_WIDTH, KEY_FONT_BASELINE_OFFSET, KEY_FONT_UNKNOWN_CHAR, KEY_FONT_EXTENDED_CHAR, KEY_FONT_CHARACTERS, KEY_FONT_SPACING_LINE, KEY_FONT_SPACING_CHAR, KEY_FONT_SPACING_MESSAGE };\n\n public static final String KEY_CHAT_SCROLL = \"chatScrollEnabled\";\n public static final String KEY_CHAT_RESIZABLE = \"chatResizable\";\n public static final String KEY_CHAT_POSITION = \"chatPosition\";\n public static final String KEY_CHAT_POSITION_X = \"chatPositionX\";\n public static final String KEY_CHAT_POSITION_Y = \"chatPositionY\";\n public static final String KEY_CHAT_FROM_BOTTOM = \"chatFromBottom\";\n public static final String KEY_CHAT_WINDOW_WIDTH = \"chatWidth\"; // Legacy, no longer saved, used for chat window, not chat window content pane\n public static final String KEY_CHAT_WINDOW_HEIGHT = \"chatHeight\"; // Legacy, no longer saved, used for chat window, not chat window content pane\n public static final String KEY_CHAT_WIDTH = \"chatPixelWidth\";\n public static final String KEY_CHAT_HEIGHT = \"chatPixelHeight\";\n public static final String KEY_CHAT_CHROMA_ENABLED = \"chromaEnabled\";\n public static final String KEY_CHAT_INVERT_CHROMA = \"invertChroma\";\n public static final String KEY_CHAT_REVERSE_SCROLLING = \"reverseScrolling\";\n public static final String KEY_CHAT_CHROMA_LEFT = \"chromaLeft\";\n public static final String KEY_CHAT_CHROMA_TOP = \"chromaTop\";\n public static final String KEY_CHAT_CHROMA_RIGHT = \"chromaRight\";\n public static final String KEY_CHAT_CHROMA_BOTTOM = \"chromaBottom\";\n public static final String KEY_CHAT_CHROMA_CORNER = \"chromaCornerRadius\";\n public static final String KEY_CHAT_ALWAYS_ON_TOP = \"chatAlwaysOnTop\";\n public static final String KEY_CHAT_ANTIALIAS = \"chatAntialias\";\n\n public static final String[] CHAT_KEYS = new String[] { KEY_CHAT_SCROLL, KEY_CHAT_RESIZABLE, KEY_CHAT_POSITION, KEY_CHAT_POSITION_X, KEY_CHAT_POSITION_Y, KEY_CHAT_FROM_BOTTOM, KEY_CHAT_WIDTH, KEY_CHAT_HEIGHT, KEY_CHAT_CHROMA_ENABLED, KEY_CHAT_INVERT_CHROMA, KEY_CHAT_REVERSE_SCROLLING, KEY_CHAT_CHROMA_LEFT, KEY_CHAT_CHROMA_TOP, KEY_CHAT_CHROMA_RIGHT, KEY_CHAT_CHROMA_BOTTOM, KEY_CHAT_CHROMA_CORNER, KEY_CHAT_ALWAYS_ON_TOP, KEY_CHAT_ANTIALIAS };\n\n public static final String[] CHAT_KEYS_EXCEPT_WINDOW_POSITION = new String[] { KEY_CHAT_SCROLL, KEY_CHAT_RESIZABLE, KEY_CHAT_POSITION, KEY_CHAT_FROM_BOTTOM, KEY_CHAT_WIDTH, KEY_CHAT_HEIGHT, KEY_CHAT_CHROMA_ENABLED, KEY_CHAT_INVERT_CHROMA, KEY_CHAT_REVERSE_SCROLLING, KEY_CHAT_CHROMA_LEFT, KEY_CHAT_CHROMA_TOP, KEY_CHAT_CHROMA_RIGHT, KEY_CHAT_CHROMA_BOTTOM, KEY_CHAT_CHROMA_CORNER, KEY_CHAT_ALWAYS_ON_TOP, KEY_CHAT_ANTIALIAS };\n\n public static final String KEY_COLOR_BG = \"colorBackground\";\n public static final String KEY_COLOR_FG = \"colorForeground\";\n public static final String KEY_COLOR_BORDER = \"colorBorder\";\n public static final String KEY_COLOR_HIGHLIGHT = \"colorHighlight\";\n public static final String KEY_COLOR_CHROMA_KEY = \"chromaKey\";\n public static final String KEY_COLOR_PALETTE = \"colorPalette\";\n public static final String KEY_COLOR_USERNAME = \"colorUsername\";\n public static final String KEY_COLOR_TIMESTAMP = \"colorTimestamp\";\n public static final String KEY_COLOR_MESSAGE = \"colorMessage\";\n public static final String KEY_COLOR_JOIN = \"colorJoin\";\n public static final String KEY_COLOR_TWITCH = \"colorUseTwitch\";\n\n public static final String[] COLOR_KEYS = new String[] { KEY_COLOR_BG, KEY_COLOR_FG, KEY_COLOR_BORDER, KEY_COLOR_HIGHLIGHT, KEY_COLOR_CHROMA_KEY, KEY_COLOR_PALETTE, KEY_COLOR_USERNAME, KEY_COLOR_TIMESTAMP, KEY_COLOR_MESSAGE, KEY_COLOR_JOIN, KEY_COLOR_TWITCH };\n\n public static final String[] COLOR_KEYS_WITHOUT_PALETTE = new String[] { KEY_COLOR_BG, KEY_COLOR_FG, KEY_COLOR_BORDER, KEY_COLOR_HIGHLIGHT, KEY_COLOR_CHROMA_KEY, KEY_COLOR_USERNAME, KEY_COLOR_TIMESTAMP, KEY_COLOR_MESSAGE, KEY_COLOR_JOIN, KEY_COLOR_TWITCH };\n\n public static final String KEY_MESSAGE_JOIN = \"messageShowJoin\";\n public static final String KEY_MESSAGE_USERNAME = \"messageShowUsername\";\n public static final String KEY_MESSAGE_TIMESTAMP = \"messageShowTimestamp\";\n public static final String KEY_MESSAGE_USERFORMAT = \"messageUsernameFormat\";\n public static final String KEY_MESSAGE_TIMEFORMAT = \"messageTimestampFormat\";\n public static final String KEY_MESSAGE_CONTENT_BREAK = \"messageContentBreak\";\n public static final String KEY_MESSAGE_QUEUE_SIZE = \"messageQueueSize\";\n public static final String KEY_MESSAGE_SPEED = \"messageSpeed\";\n public static final String KEY_MESSAGE_EXPIRATION_TIME = \"messageExpirationTime\";\n public static final String KEY_MESSAGE_HIDE_EMPTY_BORDER = \"messageHideEmptyBorder\";\n public static final String KEY_MESSAGE_HIDE_EMPTY_BACKGROUND = \"messageHideEmptyBackground\";\n public static final String KEY_MESSAGE_CASE_TYPE = \"messageUserCase\";\n public static final String KEY_MESSAGE_CASE_SPECIFY = \"messageUserCaseSpecify\";\n public static final String KEY_MESSAGE_CASING = \"messageCasing\";\n\n public static final String[] MESSAGE_KEYS = new String[] { KEY_MESSAGE_JOIN, KEY_MESSAGE_USERNAME, KEY_MESSAGE_TIMESTAMP, KEY_MESSAGE_USERFORMAT, KEY_MESSAGE_TIMEFORMAT, KEY_MESSAGE_CONTENT_BREAK, KEY_MESSAGE_QUEUE_SIZE, KEY_MESSAGE_SPEED, KEY_MESSAGE_EXPIRATION_TIME, KEY_MESSAGE_HIDE_EMPTY_BORDER, KEY_MESSAGE_HIDE_EMPTY_BACKGROUND, KEY_MESSAGE_CASE_TYPE, KEY_MESSAGE_CASE_SPECIFY, KEY_MESSAGE_CASING };\n\n public static final String KEY_EMOJI_ENABLED = \"emojiEnabled\";\n public static final String KEY_EMOJI_ANIMATION = \"emojiAnimationEnabled\";\n public static final String KEY_EMOJI_TWITCH_BADGES = \"badgesEnabled\";\n public static final String KEY_EMOJI_FFZ_BADGES = \"badgesFfzEnabled\";\n public static final String KEY_EMOJI_SCALE_TO_LINE = \"emojiScaleToLine\";\n public static final String KEY_EMOJI_BADGE_SCALE_TO_LINE = \"badgeScaleToLine\";\n public static final String KEY_EMOJI_BADGE_HEIGHT_OFFSET = \"badgeHeightOffset\";\n public static final String KEY_EMOJI_SCALE = \"emojiScale\";\n public static final String KEY_EMOJI_BADGE_SCALE = \"badgeScale\";\n public static final String KEY_EMOJI_DISPLAY_STRAT = \"emojiDisplayStrat\";\n public static final String KEY_EMOJI_TWITCH_ENABLE = \"emojiTwitchEnabled\";\n public static final String KEY_EMOJI_TWITCH_CACHE = \"emojiTwitchCached\";\n public static final String KEY_EMOJI_FFZ_ENABLE = \"emojiFfzEnabled\";\n public static final String KEY_EMOJI_FFZ_CACHE = \"emojiFfzCached\";\n public static final String KEY_EMOJI_BTTV_ENABLE = \"emojiBttvEnabled\";\n public static final String KEY_EMOJI_BTTV_CACHE = \"emojiBttvCached\";\n public static final String KEY_EMOJI_TWITTER_ENABLE = \"emojiTwitterEnabled\";\n\n public static final String[] EMOJI_KEYS = new String[] { KEY_EMOJI_ENABLED, KEY_EMOJI_ANIMATION, KEY_EMOJI_TWITCH_BADGES, KEY_EMOJI_FFZ_BADGES, KEY_EMOJI_SCALE_TO_LINE, KEY_EMOJI_BADGE_SCALE_TO_LINE, KEY_EMOJI_BADGE_HEIGHT_OFFSET, KEY_EMOJI_SCALE, KEY_EMOJI_BADGE_SCALE, KEY_EMOJI_DISPLAY_STRAT, KEY_EMOJI_TWITCH_ENABLE, KEY_EMOJI_TWITCH_CACHE, KEY_EMOJI_FFZ_ENABLE, KEY_EMOJI_FFZ_CACHE, KEY_EMOJI_BTTV_ENABLE, KEY_EMOJI_BTTV_CACHE, KEY_EMOJI_TWITTER_ENABLE };\n\n public static final String KEY_CENSOR_ENABLED = \"censorEnabled\";\n public static final String KEY_CENSOR_PURGE_ON_TWITCH_BAN = \"censorPurgeOnTwitchBan\";\n public static final String KEY_CENSOR_URL = \"censorUrl\";\n public static final String KEY_CENSOR_FIRST_URL = \"censorFirstUrl\";\n public static final String KEY_CENSOR_UNKNOWN_CHARS = \"censorUnknownChars\";\n public static final String KEY_CENSOR_UNKNOWN_CHARS_PERCENT = \"censorUnknownCharsPercent\";\n public static final String KEY_CENSOR_WHITE = \"censorWhitelist\";\n public static final String KEY_CENSOR_BLACK = \"censorBlacklist\";\n public static final String KEY_CENSOR_BANNED = \"censorBannedWords\";\n\n public static final String[] CENSOR_KEYS = new String[] { KEY_CENSOR_ENABLED, KEY_CENSOR_PURGE_ON_TWITCH_BAN, KEY_CENSOR_URL, KEY_CENSOR_FIRST_URL, KEY_CENSOR_UNKNOWN_CHARS, KEY_CENSOR_UNKNOWN_CHARS_PERCENT, KEY_CENSOR_WHITE, KEY_CENSOR_BLACK, KEY_CENSOR_BANNED };\n\n public static final String[][] ALL_KEYS_EXCEPT_CHAT_WINDOW_POSITION = new String[][] { IRC_KEYS, FONT_KEYS, CHAT_KEYS_EXCEPT_WINDOW_POSITION, COLOR_KEYS, MESSAGE_KEYS, EMOJI_KEYS, CENSOR_KEYS };\n\n public static final String[][] ALL_KEYS = new String[][] { IRC_KEYS, FONT_KEYS, CHAT_KEYS, COLOR_KEYS, MESSAGE_KEYS, EMOJI_KEYS, CENSOR_KEYS };\n\n /**\n * Get all the property keys to be tested to determine if two fProps are equal. The parameter FontificatorProperties\n * is to be used as a collection of configuration that is used to select which properties matter. For example, if\n * chat window position should be remembered or not, so if remember position is unchecked, it doesn't ask you to\n * save changes just because you moved the window.\n * \n * @param fProps\n * contains configuration to be used to determine which keys are needed\n * @return all keys to be tested for equals\n */\n private static String[][] getKeysForEqualsTest(FontificatorProperties fProps)\n {\n if (fProps != null && fProps.getChatConfig() != null && fProps.getChatConfig().isRememberPosition())\n {\n return ALL_KEYS_EXCEPT_CHAT_WINDOW_POSITION;\n }\n\n return ALL_KEYS;\n }\n\n private ConfigIrc ircConfig = new ConfigIrc();\n\n private ConfigFont fontConfig = new ConfigFont();\n\n private ConfigChat chatConfig = new ConfigChat();\n\n private ConfigColor colorConfig = new ConfigColor();\n\n private ConfigMessage messageConfig = new ConfigMessage();\n\n private ConfigEmoji emojiConfig = new ConfigEmoji();\n\n private ConfigCensor censorConfig = new ConfigCensor();\n\n public FontificatorProperties()\n {\n }\n\n @Override\n public void clear()\n {\n ircConfig.reset();\n fontConfig.reset();\n chatConfig.reset();\n colorConfig.reset();\n messageConfig.reset();\n emojiConfig.reset();\n censorConfig.reset();\n super.clear();\n }\n\n public ConfigIrc getIrcConfig()\n {\n return ircConfig;\n }\n\n public ConfigFont getFontConfig()\n {\n return fontConfig;\n }\n\n public ConfigChat getChatConfig()\n {\n return chatConfig;\n }\n\n public ConfigColor getColorConfig()\n {\n return colorConfig;\n }\n\n public ConfigMessage getMessageConfig()\n {\n return messageConfig;\n }\n\n public ConfigEmoji getEmojiConfig()\n {\n return emojiConfig;\n }\n\n public ConfigCensor getCensorConfig()\n {\n return censorConfig;\n }\n\n /**\n * Called whenever unsaved changes might be lost to let the user have the option to save them\n * \n * @param ctrlWindow\n * @return okayToContinue\n */\n public boolean checkForUnsavedProps(ControlWindow ctrlWindow, Component parent)\n {\n if (hasUnsavedChanges())\n {\n int response = JOptionPane.showConfirmDialog(parent, \"Save configuration changes?\", \"Unsaved Changes\", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);\n if (response == JOptionPane.YES_OPTION)\n {\n if (ctrlWindow.saveConfig())\n {\n return true;\n }\n }\n else if (response == JOptionPane.NO_OPTION)\n {\n return true;\n }\n\n return false;\n }\n else\n {\n return true;\n }\n }\n\n /**\n * Load configuration from the file indicated by the specified filename, or a preset file contained in the classpath\n * resource directory\n * \n * @param filename\n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadFile(String filename) throws Exception\n {\n if (filename.startsWith(ConfigFont.INTERNAL_FILE_PREFIX))\n {\n final String plainFilename = filename.substring(ConfigFont.INTERNAL_FILE_PREFIX.length());\n\n if (getClass().getClassLoader().getResource(plainFilename) == null)\n {\n LoadConfigReport report = new LoadConfigReport();\n final String errorMsg = \"Preset theme \" + plainFilename + \" not found\";\n ChatWindow.popup.handleProblem(errorMsg);\n report.addError(errorMsg, LoadConfigErrorType.FILE_NOT_FOUND);\n return report;\n }\n\n InputStream is = getClass().getClassLoader().getResourceAsStream(plainFilename);\n LoadConfigReport report = loadFile(is, filename, true);\n\n if (report.isErrorFree())\n {\n // This is a temporary copy, not to be saved to the last saved file for loading next time, but to avoid\n // having to not save when switching between presets\n this.lastSavedCopy = getCopy();\n }\n\n is.close();\n return report;\n }\n else\n {\n return loadFile(new File(filename));\n }\n }\n\n /**\n * Load configuration from the specified file\n * \n * @param file\n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadFile(File file) throws Exception\n {\n logger.trace(\"Loading file \" + file.getAbsolutePath());\n InputStream is = new FileInputStream(file);\n LoadConfigReport report = loadFile(is, file.getAbsolutePath(), false);\n is.close();\n return report;\n }\n\n /**\n * Load file from InputStream. Does not close InputStream\n * \n * @param is\n * @param filename\n * @param isPreset\n * @return report\n * @throws Exception\n */\n private LoadConfigReport loadFile(InputStream is, String filename, boolean isPreset) throws Exception\n {\n final String prevAuth = getProperty(KEY_IRC_AUTH);\n super.load(is);\n final String currAuth = getProperty(KEY_IRC_AUTH);\n\n // Only decrypt the auth token here if there wasn't a previously loaded one that was already decrypted. This is\n // determined by whether the previous authorization wasn't loaded (null) or if there has been a change. If the\n // inputstream data didn't have an auth token, then the previous and current ones will match, meaning a new one\n // wasn't loaded and there's no need to decrypt.\n if (prevAuth == null || !prevAuth.equals(currAuth))\n {\n decryptProperty(KEY_IRC_AUTH);\n }\n\n LoadConfigReport report = loadConfigs(!isPreset);\n\n if (report.isErrorFree() && !isPreset)\n {\n rememberLastConfigFile(filename);\n }\n\n return report;\n }\n\n /**\n * Store the specified path to a configuration file in the last config file location conf file\n * \n * @param path\n * The path of the configuration file to remember\n */\n public void rememberLastConfigFile(String path)\n {\n logger.trace(\"Remembering last loaded file \" + path);\n\n // Keep track of the last saved or loaded copy to compare with to see if a save prompt is required when exiting\n this.lastSavedCopy = getCopy();\n\n BufferedWriter writer = null;\n try\n {\n writer = new BufferedWriter(new FileWriter(CONFIG_FILE_LAST_LOCATION, false));\n writer.write(path);\n }\n catch (Exception e)\n {\n // Don't alert the user, just log behind the scenes, not important enough to warrant a popup\n logger.error(\"Unable to save last file loaded\", e);\n }\n finally\n {\n if (writer != null)\n {\n try\n {\n writer.close();\n }\n catch (Exception e)\n {\n logger.error(e.toString(), e);\n }\n }\n }\n }\n\n /**\n * Delete the last config file location conf file that stored the path to a configuration file. To be used to remove\n * a file that is not found or has errors.\n */\n public void forgetLastConfigFile()\n {\n logger.trace(\"Forgetting last loaded\");\n\n File f = new File(CONFIG_FILE_LAST_LOCATION);\n f.delete();\n }\n\n /**\n * Save the configuration to the specified file\n * \n * @param file\n * @throws Exception\n */\n public void saveFile(File file) throws Exception\n {\n OutputStream os = new FileOutputStream(file);\n encryptProperty(KEY_IRC_AUTH);\n super.store(os, null);\n decryptProperty(KEY_IRC_AUTH);\n rememberLastConfigFile(file.getAbsolutePath());\n }\n\n public void encryptProperty(String key)\n {\n BasicTextEncryptor textEncryptor = new BasicTextEncryptor();\n textEncryptor.setPassword(ENC_PASSWORD);\n\n final String decryptedValue = getProperty(key);\n if (decryptedValue != null && !decryptedValue.isEmpty())\n {\n try\n {\n final String encryptedValue = textEncryptor.encrypt(decryptedValue);\n setProperty(key, encryptedValue);\n }\n catch (Exception e)\n {\n final String errorMessage = \"Error encrypting value for \" + key + \" property\";\n logger.error(errorMessage, e);\n ChatWindow.popup.handleProblem(errorMessage);\n setProperty(key, \"\");\n }\n }\n }\n\n public void decryptProperty(String key)\n {\n BasicTextEncryptor textEncryptor = new BasicTextEncryptor();\n textEncryptor.setPassword(ENC_PASSWORD);\n final String encryptedValue = getProperty(key);\n if (encryptedValue != null && !encryptedValue.isEmpty())\n {\n try\n {\n final String decryptedValue = textEncryptor.decrypt(encryptedValue);\n setProperty(key, decryptedValue);\n }\n catch (Exception e)\n {\n final String errorMessage = \"Error decrypting value for \" + key + \" property\";\n logger.error(errorMessage, e);\n ChatWindow.popup.handleProblem(errorMessage);\n setProperty(key, \"\");\n }\n }\n }\n\n /**\n * Try to load the configuration file stored i the last config file location conf file.\n * \n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadLast() throws Exception\n {\n logger.trace(\"Load last\");\n\n final String previousConfigNotFound = \"Previous configuration not found.\";\n final String previousConfigError = \"Error loading previous configuration.\";\n\n BufferedReader reader = null;\n try\n {\n File lastFile = new File(CONFIG_FILE_LAST_LOCATION);\n if (!lastFile.exists())\n {\n LoadConfigReport errorReport = new LoadConfigReport();\n errorReport.addError(previousConfigNotFound, LoadConfigErrorType.FILE_NOT_FOUND);\n return errorReport;\n }\n reader = new BufferedReader(new FileReader(lastFile));\n final String lastConfigFilename = reader.readLine();\n reader.close();\n LoadConfigReport report = loadFile(lastConfigFilename);\n if (report.isProblem())\n {\n report.setMainMessage(previousConfigError);\n }\n return report;\n }\n finally\n {\n if (reader != null)\n {\n try\n {\n reader.close();\n }\n catch (Exception e)\n {\n logger.error(e.toString(), e);\n }\n }\n }\n }\n\n /**\n * Set a value only if it isn't already set, optionally overriding if specified\n * \n * @param key\n * @param value\n * @param override\n */\n private void setPropertyOverride(final String key, final String value, final boolean override)\n {\n final boolean valueExists = getProperty(key) != null && !getProperty(key).isEmpty();\n if (override || !valueExists)\n {\n setProperty(key, value);\n }\n }\n\n /**\n * Load a default configuration, for if something goes wrong, or if no previously used configuration file is stored\n * \n * @param override\n * Whether to override values should they already exist\n */\n public void loadDefaultValues(boolean override)\n {\n logger.trace(\"Loading default values\");\n\n final String trueString = Boolean.toString(true);\n final String falseString = Boolean.toString(false);\n\n setPropertyOverride(KEY_IRC_HOST, \"irc.twitch.tv\", override);\n setPropertyOverride(KEY_IRC_PORT, Integer.toString(6667), override);\n setPropertyOverride(KEY_IRC_ANON, trueString, override);\n setPropertyOverride(KEY_IRC_AUTO_RECONNECT, trueString, override);\n\n setPropertyOverride(KEY_FONT_FILE_BORDER, ConfigFont.INTERNAL_FILE_PREFIX + \"borders/dw3_border.png\", override);\n setPropertyOverride(KEY_FONT_FILE_FONT, ConfigFont.INTERNAL_FILE_PREFIX + \"fonts/dw3_font.png\", override);\n setPropertyOverride(KEY_FONT_TYPE, FontType.FIXED_WIDTH.name(), override);\n setPropertyOverride(KEY_FONT_GRID_WIDTH, Integer.toString(8), override);\n setPropertyOverride(KEY_FONT_GRID_HEIGHT, Integer.toString(12), override);\n setPropertyOverride(KEY_FONT_SCALE, Integer.toString(2), override);\n setPropertyOverride(KEY_FONT_BORDER_SCALE, Integer.toString(3), override);\n setPropertyOverride(KEY_FONT_BORDER_INSET_X, Integer.toString(1), override);\n setPropertyOverride(KEY_FONT_BORDER_INSET_Y, Integer.toString(1), override);\n setPropertyOverride(KEY_FONT_SPACE_WIDTH, Integer.toString(25), override);\n setPropertyOverride(KEY_FONT_BASELINE_OFFSET, Integer.toString(0), override);\n setPropertyOverride(KEY_FONT_CHARACTERS, SpriteFont.NORMAL_ASCII_KEY, override);\n setPropertyOverride(KEY_FONT_UNKNOWN_CHAR, Character.toString((char) 127), override);\n setPropertyOverride(KEY_FONT_EXTENDED_CHAR, trueString, override);\n setPropertyOverride(KEY_FONT_SPACING_LINE, Integer.toString(2), override);\n setPropertyOverride(KEY_FONT_SPACING_CHAR, Integer.toString(0), override);\n setPropertyOverride(KEY_FONT_SPACING_MESSAGE, Integer.toString(0), override);\n\n setPropertyOverride(KEY_CHAT_SCROLL, falseString, override);\n setPropertyOverride(KEY_CHAT_RESIZABLE, trueString, override);\n setPropertyOverride(KEY_CHAT_POSITION, falseString, override);\n setPropertyOverride(KEY_CHAT_POSITION_X, Integer.toString(0), override);\n setPropertyOverride(KEY_CHAT_POSITION_Y, Integer.toString(0), override);\n setPropertyOverride(KEY_CHAT_FROM_BOTTOM, falseString, override);\n setPropertyOverride(KEY_CHAT_WIDTH, Integer.toString(550), override);\n setPropertyOverride(KEY_CHAT_HEIGHT, Integer.toString(450), override);\n setPropertyOverride(KEY_CHAT_CHROMA_ENABLED, falseString, override);\n setPropertyOverride(KEY_CHAT_INVERT_CHROMA, falseString, override);\n setPropertyOverride(KEY_CHAT_REVERSE_SCROLLING, falseString, override);\n setPropertyOverride(KEY_CHAT_CHROMA_LEFT, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_TOP, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_RIGHT, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_BOTTOM, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_CORNER, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_ALWAYS_ON_TOP, falseString, override);\n setPropertyOverride(KEY_CHAT_ANTIALIAS, falseString, override);\n\n setPropertyOverride(KEY_COLOR_BG, \"000000\", override);\n setPropertyOverride(KEY_COLOR_FG, \"FFFFFF\", override);\n setPropertyOverride(KEY_COLOR_BORDER, \"FFFFFF\", override);\n setPropertyOverride(KEY_COLOR_HIGHLIGHT, \"6699FF\", override);\n setPropertyOverride(KEY_COLOR_PALETTE, \"F7977A,FDC68A,FFF79A,A2D39C,6ECFF6,A187BE,F6989D\", override);\n setPropertyOverride(KEY_COLOR_CHROMA_KEY, \"00FF00\", override);\n setPropertyOverride(KEY_COLOR_USERNAME, trueString, override);\n setPropertyOverride(KEY_COLOR_TIMESTAMP, falseString, override);\n setPropertyOverride(KEY_COLOR_MESSAGE, falseString, override);\n setPropertyOverride(KEY_COLOR_JOIN, falseString, override);\n setPropertyOverride(KEY_COLOR_TWITCH, falseString, override);\n\n setPropertyOverride(KEY_MESSAGE_JOIN, falseString, override);\n setPropertyOverride(KEY_MESSAGE_USERNAME, trueString, override);\n setPropertyOverride(KEY_MESSAGE_TIMESTAMP, falseString, override);\n setPropertyOverride(KEY_MESSAGE_USERFORMAT, ConfigMessage.USERNAME_REPLACE, override);\n setPropertyOverride(KEY_MESSAGE_TIMEFORMAT, \"[HH:mm:ss]\", override);\n setPropertyOverride(KEY_MESSAGE_CONTENT_BREAK, ConfigMessage.DEFAULT_CONTENT_BREAKER, override);\n setPropertyOverride(KEY_MESSAGE_QUEUE_SIZE, Integer.toString(64), override);\n setPropertyOverride(KEY_MESSAGE_SPEED, Integer.toString((int) (ConfigMessage.MAX_MESSAGE_SPEED * 0.25f)), override);\n setPropertyOverride(KEY_MESSAGE_EXPIRATION_TIME, Integer.toString(0), override);\n setPropertyOverride(KEY_MESSAGE_HIDE_EMPTY_BORDER, falseString, override);\n setPropertyOverride(KEY_MESSAGE_HIDE_EMPTY_BACKGROUND, falseString, override);\n setPropertyOverride(KEY_MESSAGE_CASE_TYPE, UsernameCaseResolutionType.NONE.name(), override);\n setPropertyOverride(KEY_MESSAGE_CASE_SPECIFY, falseString, override);\n setPropertyOverride(KEY_MESSAGE_CASING, MessageCasing.MIXED_CASE.name(), override);\n\n setPropertyOverride(KEY_EMOJI_ENABLED, trueString, override);\n setPropertyOverride(KEY_EMOJI_ANIMATION, falseString, override);\n setPropertyOverride(KEY_EMOJI_TWITCH_BADGES, trueString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_BADGES, falseString, override);\n setPropertyOverride(KEY_EMOJI_SCALE_TO_LINE, trueString, override);\n setPropertyOverride(KEY_EMOJI_BADGE_SCALE_TO_LINE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BADGE_HEIGHT_OFFSET, Integer.toString(0), override);\n setPropertyOverride(KEY_EMOJI_SCALE, Integer.toString(100), override);\n setPropertyOverride(KEY_EMOJI_BADGE_SCALE, Integer.toString(100), override);\n setPropertyOverride(KEY_EMOJI_DISPLAY_STRAT, EmojiLoadingDisplayStragegy.SPACE.name(), override);\n setPropertyOverride(KEY_EMOJI_TWITCH_ENABLE, trueString, override);\n setPropertyOverride(KEY_EMOJI_TWITCH_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_ENABLE, falseString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BTTV_ENABLE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BTTV_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_TWITTER_ENABLE, trueString, override);\n\n setPropertyOverride(KEY_CENSOR_ENABLED, trueString, override);\n setPropertyOverride(KEY_CENSOR_PURGE_ON_TWITCH_BAN, trueString, override);\n setPropertyOverride(KEY_CENSOR_URL, falseString, override);\n setPropertyOverride(KEY_CENSOR_FIRST_URL, falseString, override);\n setPropertyOverride(KEY_CENSOR_UNKNOWN_CHARS, falseString, override);\n setPropertyOverride(KEY_CENSOR_UNKNOWN_CHARS_PERCENT, Integer.toString(20), override);\n setPropertyOverride(KEY_CENSOR_WHITE, \"\", override);\n setPropertyOverride(KEY_CENSOR_BLACK, \"\", override);\n setPropertyOverride(KEY_CENSOR_BANNED, \"\", override);\n\n loadConfigs(true);\n }\n\n private FontificatorProperties getCopy()\n {\n FontificatorProperties copy = new FontificatorProperties();\n for (String key : stringPropertyNames())\n {\n copy.setProperty(key, getProperty(key));\n }\n return copy;\n }\n\n /**\n * Load properties into specialized config objects. This method returns its own report.\n * \n * @return success\n */\n private LoadConfigReport loadConfigs(boolean loadNonFontConfig)\n {\n LoadConfigReport report = new LoadConfigReport();\n if (loadNonFontConfig)\n {\n ircConfig.load(this, report);\n chatConfig.load(this, report);\n messageConfig.load(this, report);\n emojiConfig.load(this, report);\n censorConfig.load(this, report);\n }\n fontConfig.load(this, report);\n colorConfig.load(this, report);\n\n if (!report.isErrorFree())\n {\n if (report.isOnlyMissingKeys())\n {\n report.setMainMessage(\"<center>Please resave the configuration file<br />to fix these issues:</center>\");\n }\n ChatWindow.popup.handleProblem(report);\n }\n\n return report;\n }\n\n private boolean hasUnsavedChanges()\n {\n return !equals(lastSavedCopy);\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + ((chatConfig == null) ? 0 : chatConfig.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (getClass() != obj.getClass())\n return false;\n\n FontificatorProperties otherFp = (FontificatorProperties) obj;\n\n return FontificatorProperties.propertyBatchMatch(getKeysForEqualsTest(this), this, otherFp);\n }\n\n private static boolean propertyBatchMatch(String[][] keys, FontificatorProperties a, FontificatorProperties b)\n {\n for (int i = 0; i < keys.length; i++)\n {\n for (int j = 0; j < keys[i].length; j++)\n {\n if (!propertyEquals(a.getProperty(keys[i][j]), b.getProperty(keys[i][j])))\n {\n return false;\n }\n }\n }\n return true;\n }\n\n private static boolean propertyEquals(String one, String two)\n {\n if (one == null)\n {\n return two == null;\n }\n else\n {\n return one.equals(two);\n }\n }\n\n}", "public class LoadConfigReport\n{\n private static final int MAX_NUMBER_OF_NON_PROBLEMS = 15;\n\n private String mainMessage;\n\n /**\n * A set of types of errors that have been collected in this report\n */\n private Set<LoadConfigErrorType> types;\n\n /**\n * Human-readable messages describing the errors collected so far\n */\n private List<String> messages;\n\n /**\n * Instantiates an empty report\n */\n public LoadConfigReport()\n {\n types = new HashSet<LoadConfigErrorType>();\n messages = new ArrayList<String>();\n }\n\n /**\n * Instantiate this report with only a type, when there is no need for human-readable explanations\n * \n * @param type\n */\n public LoadConfigReport(LoadConfigErrorType type)\n {\n this();\n types.add(type);\n }\n\n /**\n * Add an error to this report\n * \n * @param message\n * @param type\n */\n public void addError(String message, LoadConfigErrorType type)\n {\n messages.add(message);\n types.add(type);\n }\n\n /**\n * Whether no errors have been reported, whether they are problems or not. This check identifies the load as being capable of handling any subsequent work, no need to supplement the results with defaults.\n * \n * @return error free\n */\n public boolean isErrorFree()\n {\n return messages.isEmpty();\n }\n\n /**\n * Get the opposite of whether there is a problem\n * \n * @return success\n */\n public boolean isSuccess()\n {\n return !isProblem();\n }\n\n /**\n * Get whether there is a problem. A problem is whenever at least one of the types of errors is marked as a problem-type error.\n * \n * @return problem\n */\n public boolean isProblem()\n {\n for (LoadConfigErrorType result : types)\n {\n if (result.isProblem())\n {\n return true;\n }\n }\n // No real problems exist, but if there are more than the max number allowed, consider it a problem. For\n // example, someone might be loading a random text file as a config file that has nothing to do with this\n // program. That should be a problem, even though it will register as merely having a bunch of missing values\n return messages.size() > MAX_NUMBER_OF_NON_PROBLEMS;\n }\n\n /**\n * Get whether all the load problems are just missing keys\n * \n * @return whether all errors are missing keys\n */\n public boolean isOnlyMissingKeys()\n {\n for (LoadConfigErrorType result : types)\n {\n if (result != LoadConfigErrorType.MISSING_KEY)\n {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get the messages\n * \n * @return messages\n */\n public List<String> getMessages()\n {\n return messages;\n }\n\n /**\n * Get the types\n * \n * @return types\n */\n public Set<LoadConfigErrorType> getTypes()\n {\n return types;\n }\n\n /**\n * Adds all the contents of the specified other report to this report\n * \n * @param otherReport\n */\n public void addFromReport(LoadConfigReport otherReport)\n {\n for (String msg : otherReport.getMessages())\n {\n messages.add(msg);\n }\n for (LoadConfigErrorType rslt : otherReport.getTypes())\n {\n types.add(rslt);\n }\n }\n\n public String getMainMessage()\n {\n return mainMessage;\n }\n\n public void setMainMessage(String mainMessage)\n {\n this.mainMessage = mainMessage;\n }\n}", "public class DebugAppender extends WriterAppender implements UncaughtExceptionHandler\n{\n private LogBox debugLogBox;\n\n public DebugAppender(LogBox debugLogBox)\n {\n super(FontificatorMain.LOG_PATTERN_LAYOUT, System.out);\n this.debugLogBox = debugLogBox;\n setName(\"Debug Logging\");\n setThreshold(Level.DEBUG);\n }\n\n @Override\n public void append(LoggingEvent event)\n {\n debugLogBox.log(this.layout.format(event));\n ThrowableInformation info = event.getThrowableInformation();\n if (info != null && info.getThrowable() != null)\n {\n Throwable t = info.getThrowable();\n debugLogBox.log(throwableToString(t));\n }\n }\n\n @Override\n public void uncaughtException(Thread t, Throwable e)\n {\n try\n {\n System.err.println(\"Exception in thread \\\"\" + t.getName() + \"\\\" \");\n e.printStackTrace(System.err);\n debugLogBox.log(\"Exception in thread \\\"\" + t.getName() + \"\\\" \");\n debugLogBox.log(throwableToString(e));\n }\n catch (Exception debugException)\n {\n debugException.printStackTrace();\n }\n }\n\n private static String throwableToString(Throwable e)\n {\n StringWriter stackTraceWriter = new StringWriter();\n e.printStackTrace(new PrintWriter(stackTraceWriter));\n return stackTraceWriter.toString();\n }\n}", "public class ChatWindow extends JFrame\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * A stored reference to the chat panel, used whenever some part of the system has a reference to this ChatWindow,\n * but needs to modify something on the panel. This is in lieu of putting a bunch of accessor methods here to do\n * pass through the function to the panel in an encapsulated way.\n */\n private ChatPanel chatPanel;\n\n /**\n * A static copy of this ChatWindow for accessing it globally\n */\n public static ChatWindow me;\n\n /**\n * The popup for submitting errors that the user needs to see\n */\n public static FontificatorError popup;\n\n /**\n * Mouse listeners for dragging the Chat Window around when dragging the mouse inside the chat\n */\n private ChatMouseListeners mouseListeners;\n\n /**\n * Escape stroke to close popups\n */\n private static final KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);\n\n /**\n * Construct the Chat Window\n */\n public ChatWindow()\n {\n me = this;\n setTitle(\"Fontificator Chat\");\n popup = new FontificatorError(null);\n }\n\n /**\n * Sets the properties to get hooks into the properties' configuration models; Sets the ControlWindow to get hooks\n * back into the controls; Sets the loaded member Boolean to indicate it has everything it needs to begin rendering\n * the visualization\n * \n * @param fProps\n * @param ctrlWindow\n * @throws IOException\n */\n public void initChat(final FontificatorProperties fProps, final ControlWindow ctrlWindow) throws IOException\n {\n chatPanel = new ChatPanel();\n add(chatPanel);\n\n mouseListeners = new ChatMouseListeners(this, ctrlWindow);\n addMouseListener(mouseListeners);\n addMouseMotionListener(mouseListeners);\n addMouseWheelListener(chatPanel);\n setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n\n setChatSize(fProps.getChatConfig());\n\n setResizable(fProps.getChatConfig().isResizable());\n setAlwaysOnTop(fProps.getChatConfig().isAlwaysOnTop());\n\n chatPanel.setConfig(fProps);\n chatPanel.initExpirationTimer();\n\n addWindowListener(new WindowListener()\n {\n @Override\n public void windowOpened(WindowEvent e)\n {\n }\n\n @Override\n public void windowClosing(WindowEvent e)\n {\n callExit(e.getComponent());\n }\n\n @Override\n public void windowClosed(WindowEvent e)\n {\n }\n\n @Override\n public void windowIconified(WindowEvent e)\n {\n }\n\n @Override\n public void windowDeiconified(WindowEvent e)\n {\n }\n\n @Override\n public void windowActivated(WindowEvent e)\n {\n }\n\n @Override\n public void windowDeactivated(WindowEvent e)\n {\n }\n\n /**\n * Calls exit from the control window\n */\n private void callExit(Component caller)\n {\n ctrlWindow.attemptToExit(caller);\n }\n });\n\n }\n\n /**\n * Handles sizing the Chat Window, clearing out old JFrame-based config values in the ConfigChat model if they were\n * the only ones available\n * \n * @param chatConfig\n */\n public void setChatSize(ConfigChat chatConfig)\n {\n if (chatConfig.getWindowWidth() != null && chatConfig.getWindowHeight() != null)\n {\n setSize(chatConfig.getWindowWidth(), chatConfig.getWindowHeight());\n chatConfig.setWidth(getContentPane().getWidth());\n chatConfig.setHeight(getContentPane().getHeight());\n chatConfig.clearLegacyWindowSize();\n }\n else if (chatConfig.getWidth() > 0 && chatConfig.getHeight() > 0)\n {\n getContentPane().setPreferredSize(new Dimension(chatConfig.getWidth(), chatConfig.getHeight()));\n getContentPane().setSize(chatConfig.getWidth(), chatConfig.getHeight());\n pack();\n }\n }\n\n /**\n * Does the work required to make the parameter JDialog be hidden when pressing escape\n * \n * @param popup\n */\n public static void setupHideOnEscape(final JDialog popup)\n {\n Action aa = new AbstractAction()\n {\n private static final long serialVersionUID = 1L;\n\n public void actionPerformed(ActionEvent event)\n {\n popup.setVisible(false);\n }\n };\n final String mapKey = \"escapePressed\";\n JRootPane root = popup.getRootPane();\n root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, mapKey);\n root.getActionMap().put(mapKey, aa);\n }\n\n /**\n * Access to the chat panel through this window, for any places there is a reference to just the ChatWindow, but\n * that needs to affect the ChatPanel, which has all the actual chat options\n * \n * @return chatPanel\n */\n public ChatPanel getChatPanel()\n {\n return chatPanel;\n }\n\n /**\n * This is a small hack to expose the ctrl window to the message control panel so its username case map can be\n * cleared out if the user changes the type of username case resolution\n */\n public void clearUsernameCases()\n {\n mouseListeners.clearUsernameCases();\n }\n\n}", "public class ColorButton extends JPanel\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * The text label for identifying the color button component\n */\n private JLabel label;\n\n /**\n * The button that displays the color\n */\n private JButton button;\n\n /**\n * A reference to the control panel this button sits on, so its update method to use the newly selected colors can\n * be called\n */\n private final ControlPanelBase control;\n\n public ColorButton(final String label, Color value, final String explanation, ControlPanelBase controlPanel)\n {\n super();\n this.control = controlPanel;\n this.button = new JButton();\n this.button.setToolTipText(\"\");\n this.label = new JLabel(label);\n setColor(value == null ? Color.BLACK : value);\n button.setBackground(value);\n\n // So the button color shows up on Mac OS\n button.setOpaque(true);\n\n add(this.label);\n add(this.button);\n\n this.button.addActionListener(new ActionListener()\n {\n public void actionPerformed(ActionEvent e)\n {\n Color color = JColorChooser.showDialog(ControlWindow.me, \"Select Color\" + (label == null ? \"\" : \" for \" + label), getColor());\n if (color != null)\n {\n setColor(color);\n control.update();\n }\n }\n });\n }\n\n /**\n * Get the selected color\n * \n * @return color\n */\n public Color getColor()\n {\n return button.getBackground();\n }\n\n /**\n * Set the selected color\n * \n * @param value\n */\n public void setColor(Color value)\n {\n button.setBackground(value);\n }\n\n /**\n * Get the label text\n * \n * @return labelText\n */\n public String getLabel()\n {\n return label.getText();\n }\n\n}", "public class LabeledSlider extends JPanel\n{\n private static final long serialVersionUID = 1L;\n\n private static final float NO_SCALE = 1.0f;\n\n protected JSlider slider;\n\n private JLabel label;\n\n private String unitLabelStr;\n\n private JLabel unitLabel;\n\n private int maxValueDigits;\n\n private float scale;\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max)\n {\n this(labelStr, unitLabelStr, min, max, Math.max(Integer.toString(min).length(), Integer.toString(max).length()));\n }\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max, float scale)\n {\n this(labelStr, unitLabelStr, min, max, Math.max(Integer.toString(min).length(), Integer.toString(max).length()), scale);\n }\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max, int maxValueDigits)\n {\n this(labelStr, unitLabelStr, min, max, min, maxValueDigits);\n }\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max, int maxValueDigits, float scale)\n {\n this(labelStr, unitLabelStr, min, max, min, maxValueDigits, scale);\n }\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max, int value, int maxValueDigits)\n {\n this(labelStr, unitLabelStr, min, max, value, maxValueDigits, NO_SCALE);\n }\n\n public LabeledSlider(String labelStr, String unitLabelStr, int min, int max, int value, int maxValueDigits, float scale)\n {\n this.scale = scale;\n this.unitLabelStr = unitLabelStr;\n this.slider = new JSlider(JSlider.HORIZONTAL, min, max, value);\n this.label = new JLabel(labelStr);\n this.unitLabel = new JLabel(slider.getValue() + \" \" + unitLabelStr);\n this.maxValueDigits = maxValueDigits;\n setUnitLabel();\n slider.addChangeListener(new ChangeListener()\n {\n public void stateChanged(ChangeEvent e)\n {\n setUnitLabel();\n }\n });\n addComponents();\n }\n\n protected void addComponents()\n {\n setLayout(new GridBagLayout());\n GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);\n\n gbc.weightx = 0.0;\n gbc.weighty = 0.0;\n gbc.anchor = GridBagConstraints.EAST;\n gbc.gridx = 0;\n gbc.gridy = 0;\n\n add(label, gbc);\n\n gbc.weightx = 1.0;\n gbc.anchor = GridBagConstraints.CENTER;\n gbc.gridx++;\n\n gbc.fill = GridBagConstraints.HORIZONTAL;\n add(slider, gbc);\n gbc.fill = GridBagConstraints.NONE;\n\n gbc.weightx = 0.0;\n gbc.anchor = GridBagConstraints.WEST;\n gbc.gridx++;\n\n add(unitLabel, gbc);\n }\n\n public void setEnabled(boolean enabled)\n {\n slider.setEnabled(enabled);\n label.setEnabled(enabled);\n unitLabel.setEnabled(enabled);\n }\n\n public int getValue()\n {\n return slider.getValue();\n }\n\n public float getScaledValue()\n {\n return getValue() * scale;\n }\n\n public String getValueString()\n {\n if (scale == NO_SCALE)\n {\n return Integer.toString(getValue());\n }\n else\n {\n return String.format(\"%.2f\", getScaledValue());\n }\n }\n\n protected void setUnitLabel()\n {\n unitLabel.setText(\"<html><nobr><tt><b>\" + padValue(getValueString()) + \" \" + getUnitLabelStr() + \"</b></tt></nobr></html>\");\n }\n\n private String padValue(String valStr)\n {\n return padValue(valStr, maxValueDigits);\n }\n\n protected String padValue(String valStr, int length)\n {\n while (valStr.length() < length)\n {\n valStr = \" \" + valStr;\n }\n valStr = valStr.replaceAll(\" \", \"&nbsp;\");\n return valStr;\n }\n\n public void addChangeListener(ChangeListener cl)\n {\n slider.addChangeListener(cl);\n }\n\n public void setValue(int value)\n {\n slider.setValue(value);\n }\n\n public void setScaledValue(float value)\n {\n setValue((int) (value / scale));\n }\n\n public JSlider getSlider()\n {\n return slider;\n }\n\n public void setValueTextColor(Color textColor)\n {\n unitLabel.setForeground(textColor);\n }\n\n protected String getUnitLabelStr()\n {\n return unitLabelStr;\n }\n}", "public class ControlWindow extends JDialog\n{\n private static final Logger logger = Logger.getLogger(ControlWindow.class);\n\n private static final long serialVersionUID = 1L;\n\n private final String DEFAULT_CONFIG_FILE_EXTENSION = \"cgf\";\n\n private final String DEFAULT_SCREENSHOT_FILE_EXTENSION = \"png\";\n\n private ControlTabs controlTabs;\n\n private ChatViewerBot bot;\n\n private ChatWindow chatWindow;\n\n private MessageDialog messageDialog;\n\n private FontificatorProperties fProps;\n\n private JEditorPane aboutPane;\n\n // @formatter:off\n private static String ABOUT_CONTENTS = \"<html><table bgcolor=#EEEEEE width=100% border=1><tr><td>\" + \n \"<center><font face=\\\"Arial, Helvetica\\\"><b>Chat Game Fontificator</b> is a Twitch chat display that makes<br />\" + \n \"the chat look like the text boxes from various video games.<br /><br />\" + \n \"It is free, open source, and in the public domain to the furthest<br />\" + \n \"extent I am permitted to forfeit my copyright over this software.<br /><br />\" + \n \"Please enjoy!<br /><br />\" + \n \"By Matt Yanos<br /><br />\" + \n \"<a href=\\\"www.github.com/GlitchCog/ChatGameFontificator\\\">www.github.com/GlitchCog/ChatGameFontificator</a>\" + \n \"</font></center>\" + \n \"</td></tr></table></html>\";\n // @formatter:on\n\n private String helpText;\n\n public static ControlWindow me;\n\n private JDialog help;\n\n private JFileChooser opener;\n\n private JFileChooser configSaver;\n\n private JFileChooser screenshotSaver;\n\n private ScreenshotOptions screenshotOptions;\n\n public ControlWindow(JFrame parent, FontificatorProperties fProps, LogBox logBox)\n {\n super(parent);\n\n BufferedReader br = null;\n try\n {\n\n InputStream is = getClass().getClassLoader().getResourceAsStream(\"help.html\");\n br = new BufferedReader(new InputStreamReader(is));\n String line;\n StringBuilder helpBuilder = new StringBuilder();\n while ((line = br.readLine()) != null)\n {\n helpBuilder.append(line);\n }\n helpText = helpBuilder.toString();\n }\n catch (Exception e)\n {\n helpText = \"Unable to load help file\";\n logger.error(helpText, e);\n ChatWindow.popup.handleProblem(helpText);\n }\n finally\n {\n if (br != null)\n {\n try\n {\n br.close();\n }\n catch (Exception e)\n {\n logger.error(e.toString(), e);\n }\n }\n }\n\n ControlWindow.me = this;\n\n setTitle(\"Fontificator Configuration\");\n setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n\n this.fProps = fProps;\n\n FileFilter cgfFileFilter = new FileNameExtensionFilter(\"Chat Game Fontificator Configuration (*.\" + DEFAULT_CONFIG_FILE_EXTENSION + \")\", DEFAULT_CONFIG_FILE_EXTENSION.toLowerCase());\n FileFilter pngFileFilter = new FileNameExtensionFilter(\"PNG Image (*.\" + DEFAULT_SCREENSHOT_FILE_EXTENSION + \")\", DEFAULT_SCREENSHOT_FILE_EXTENSION.toLowerCase());\n\n this.opener = new JFileChooser();\n this.opener.setFileFilter(cgfFileFilter);\n\n this.configSaver = new JFileChooser();\n this.configSaver.setFileFilter(cgfFileFilter);\n\n this.screenshotOptions = new ScreenshotOptions();\n\n this.screenshotSaver = new JFileChooser();\n this.screenshotSaver.setFileFilter(pngFileFilter);\n this.screenshotSaver.setAccessory(screenshotOptions);\n }\n\n public void loadLastData(ChatWindow chatWindow)\n {\n this.chatWindow = chatWindow;\n\n ChatWindow.setupHideOnEscape(this);\n\n LoadConfigReport report = new LoadConfigReport();\n\n fProps.clear();\n try\n {\n report = fProps.loadLast();\n }\n catch (Exception e)\n {\n final String errorMsg = \"Unknown error loading last config file\";\n logger.error(errorMsg, e);\n report.addError(errorMsg, LoadConfigErrorType.UNKNOWN_ERROR);\n }\n\n if (!report.isErrorFree())\n {\n final boolean overwriteExistingValues = report.isProblem();\n if (overwriteExistingValues)\n {\n fProps.forgetLastConfigFile();\n }\n fProps.loadDefaultValues(overwriteExistingValues);\n }\n }\n\n /**\n * Called separately from construction.\n * \n * @param logBox\n */\n public void build(LogBox logBox)\n {\n constructAboutPopup();\n\n this.messageDialog = new MessageDialog(fProps, chatWindow, this, logBox);\n\n this.bot = new ChatViewerBot();\n this.bot.setUsername(fProps.getIrcConfig().getUsername());\n\n this.controlTabs = new ControlTabs(fProps, bot, messageDialog.getCensorPanel(), logBox);\n this.controlTabs.build(chatWindow, this);\n\n this.bot.setChatPanel(chatWindow.getChatPanel());\n\n setLayout(new GridLayout(1, 1));\n add(controlTabs);\n\n initMenus();\n\n // This wasn't built before the config was loaded into the chat control\n // tab, so set it here\n setAlwaysOnTopMenu(fProps.getChatConfig().isAlwaysOnTop());\n setRememberPositionMenu(fProps.getChatConfig().isRememberPosition());\n setAntiAliasMenu(fProps.getChatConfig().isAntiAlias());\n\n setupHelp();\n\n pack();\n setMinimumSize(getSize());\n setResizable(false);\n }\n\n private void setupHelp()\n {\n final String helpTitle = \"Chat Game Fontificator Help\";\n\n help = new JDialog(this, true);\n help.setTitle(helpTitle);\n help.setSize(640, 480);\n help.setLayout(new GridBagLayout());\n\n JEditorPane helpPane = new JEditorPane();\n helpPane.setContentType(\"text/html\");\n helpPane.setText(helpText);\n helpPane.setEditable(false);\n JScrollPane scrollHelp = new JScrollPane(helpPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);\n\n JButton ok = new JButton(\"Close\");\n ok.addActionListener(new ActionListener()\n {\n public void actionPerformed(ActionEvent e)\n {\n help.setVisible(false);\n }\n });\n\n GridBagConstraints gbc = new GridBagConstraints();\n\n gbc.gridy = 0;\n gbc.weightx = 1.0;\n gbc.weighty = 0.0;\n gbc.fill = GridBagConstraints.NONE;\n gbc.anchor = GridBagConstraints.NORTH;\n help.add(new JLabel(\"The function of each option available in the Control Window tabs is explained below\"), gbc);\n\n gbc.fill = GridBagConstraints.BOTH;\n gbc.anchor = GridBagConstraints.CENTER;\n gbc.weightx = 1.0;\n gbc.weighty = 1.0;\n gbc.gridy = 1;\n help.add(scrollHelp, gbc);\n\n gbc.gridy++;\n gbc.fill = GridBagConstraints.NONE;\n gbc.anchor = GridBagConstraints.SOUTH;\n gbc.weighty = 0.0;\n help.add(ok, gbc);\n\n help.setResizable(false);\n }\n\n /**\n * Builds the menus from the static arrays\n */\n private void initMenus()\n {\n JMenuBar menuBar = new JMenuBar();\n\n final String[] mainMenuText = { \"File\", \"Presets\", \"View\", \"Message\", \"Help\" };\n final int[] mainMnomonics = { KeyEvent.VK_F, KeyEvent.VK_P, KeyEvent.VK_V, KeyEvent.VK_M, KeyEvent.VK_H };\n\n JMenu[] menus = new JMenu[mainMenuText.length];\n\n for (int i = 0; i < mainMenuText.length; i++)\n {\n menus[i] = new JMenu(mainMenuText[i]);\n menus[i].setMnemonic(mainMnomonics[i]);\n }\n\n /* File Menu Item Text */\n final String strFileOpen = \"Open Configuration\";\n final String strFileSave = \"Save Configuration\";\n final String strFileRestore = \"Restore Default Configuration\";\n final String strScreenshot = \"Screenshot\";\n final String strFileExit = \"Exit\";\n // @formatter:off\n final MenuComponent[] fileComponents = new MenuComponent[] { \n new MenuComponent(strFileOpen, KeyEvent.VK_O, KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK)), \n new MenuComponent(strFileSave, KeyEvent.VK_S, KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK)), \n new MenuComponent(strFileRestore, KeyEvent.VK_R, null), \n new MenuComponent(strScreenshot, KeyEvent.VK_C, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0)), \n new MenuComponent(strFileExit, KeyEvent.VK_X, KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK)) \n };\n // @formatter:on\n\n /* View Menu Item Text */\n final String strAntiAlias = \"Anti-Aliased\";\n final String strViewTop = \"Always On Top\";\n final String strRememberPos = \"Remember Chat Window Position\";\n final String strViewHide = \"Hide Control Window\";\n final MenuComponent[] viewComponents = new MenuComponent[] { new MenuComponent(strAntiAlias, KeyEvent.VK_A, null, true), null, new MenuComponent(strViewTop, KeyEvent.VK_T, null, true), new MenuComponent(strRememberPos, KeyEvent.VK_P, null, true), new MenuComponent(strViewHide, KeyEvent.VK_H, KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.CTRL_MASK)) };\n\n /* Message Menu Item Text */\n final String strMsgMsg = \"Message Management\";\n final MenuComponent[] messageComponents = new MenuComponent[] { new MenuComponent(strMsgMsg, KeyEvent.VK_M, KeyStroke.getKeyStroke(KeyEvent.VK_M, Event.CTRL_MASK)) };\n\n /* Help Menu Item Text */\n final String strHelpHelp = \"Help\";\n final String strHelpDebug = \"Debug Mode\";\n final String strHelpAbout = \"About\";\n final MenuComponent[] helpComponents = new MenuComponent[] { new MenuComponent(strHelpHelp, KeyEvent.VK_R, null), new MenuComponent(strHelpDebug, KeyEvent.VK_D, null, true), null, new MenuComponent(strHelpAbout, KeyEvent.VK_A, null) };\n\n /* All menu components, with a placeholder for the Presets menu */\n final MenuComponent[][] allMenuComponents = new MenuComponent[][] { fileComponents, new MenuComponent[] {}, viewComponents, messageComponents, helpComponents };\n\n ActionListener mal = new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n JMenuItem mi = (JMenuItem) e.getSource();\n if (strFileOpen.equals(mi.getText()))\n {\n open();\n }\n else if (strFileSave.equals(mi.getText()))\n {\n saveConfig();\n }\n else if (strFileRestore.equals(mi.getText()))\n {\n restoreDefaults(true);\n controlTabs.refreshUiFromConfig(fProps);\n }\n else if (strScreenshot.equals(mi.getText()))\n {\n saveScreenshot();\n }\n else if (strFileExit.equals(mi.getText()))\n {\n attemptToExit();\n }\n else if (strAntiAlias.equals(mi.getText()))\n {\n JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) e.getSource();\n controlTabs.setAntiAlias(checkBox.isSelected());\n chatWindow.getChatPanel().repaint();\n }\n else if (strViewTop.equals(mi.getText()))\n {\n JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) e.getSource();\n ((JFrame) getParent()).setAlwaysOnTop(checkBox.isSelected());\n controlTabs.setAlwaysOnTopConfig(checkBox.isSelected());\n }\n else if (strRememberPos.equals(mi.getText()))\n {\n JCheckBoxMenuItem checkBox = (JCheckBoxMenuItem) e.getSource();\n controlTabs.setRememberChatWindowPosition(checkBox.isSelected());\n if (checkBox.isSelected())\n {\n final int sx = (int) chatWindow.getLocationOnScreen().getX();\n final int sy = (int) chatWindow.getLocationOnScreen().getY();\n fProps.getChatConfig().setChatWindowPositionX(sx);\n fProps.getChatConfig().setChatWindowPositionY(sy);\n }\n }\n else if (strViewHide.equals(mi.getText()))\n {\n setVisible(false);\n }\n else if (strMsgMsg.equals(mi.getText()))\n {\n messageDialog.showDialog();\n }\n else if (strHelpHelp.equals(mi.getText()))\n {\n help.setVisible(true);\n }\n else if (strHelpDebug.equals(mi.getText()))\n {\n toggleDebugTab();\n }\n else if (strHelpAbout.equals(mi.getText()))\n {\n showAboutPane();\n }\n }\n };\n\n /* Set all menu items but presets */\n JMenuItem item = null;\n for (int i = 0; i < allMenuComponents.length; i++)\n {\n for (int j = 0; j < allMenuComponents[i].length; j++)\n {\n MenuComponent mc = allMenuComponents[i][j];\n if (mc == null)\n {\n menus[i].add(new JSeparator());\n }\n else\n {\n item = mc.checkbox ? new JCheckBoxMenuItem(mc.label) : new JMenuItem(mc.label);\n item.addActionListener(mal);\n item.setMnemonic(mc.mnemonic);\n if (mc.accelerator != null)\n {\n item.setAccelerator(mc.accelerator);\n }\n menus[i].add(item);\n }\n }\n menuBar.add(menus[i]);\n }\n\n Map<String, List<String[]>> presetMapSubmenuToItem = AssetIndexLoader.loadPresets();\n\n final List<String[]> allPresets = new ArrayList<String[]>();\n for (String key : presetMapSubmenuToItem.keySet())\n {\n for (String[] value : presetMapSubmenuToItem.get(key))\n {\n allPresets.add(value);\n }\n }\n\n ActionListener presetListener = new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n String sourceText = ((JMenuItem) e.getSource()).getText();\n for (String[] presets : allPresets)\n {\n if (presets[0].equals(sourceText))\n {\n loadPreset(presets[0], presets[1]);\n break;\n }\n }\n }\n };\n\n for (String submenuKey : presetMapSubmenuToItem.keySet())\n {\n List<String[]> submenuItems = presetMapSubmenuToItem.get(submenuKey);\n if (submenuKey != null)\n {\n JMenu submenu = new JMenu(submenuKey);\n for (String[] itemAndFilename : submenuItems)\n {\n JMenuItem submenuItem = new JMenuItem(itemAndFilename[0]);\n submenuItem.addActionListener(presetListener);\n submenu.add(submenuItem);\n }\n menus[1].add(submenu);\n }\n else\n {\n for (String[] submenuRootItemAndFilename : submenuItems)\n {\n JMenuItem submenuRootItem = new JMenuItem(submenuRootItemAndFilename[0]);\n submenuRootItem.addActionListener(presetListener);\n menus[1].add(submenuRootItem);\n }\n }\n }\n\n for (int i = 0; i < menus.length; i++)\n {\n menuBar.add(menus[i]);\n }\n\n setJMenuBar(menuBar); // add the whole menu bar\n }\n\n /**\n * Restore default values to the configuration\n * \n * @param overrideExistingValues\n */\n private void restoreDefaults(boolean overrideExistingValues)\n {\n boolean okayToProceed = fProps.checkForUnsavedProps(this, this);\n\n if (okayToProceed)\n {\n int result = JOptionPane.showConfirmDialog(this, \"Reset to default configuration?\", \"Confirm\", JOptionPane.YES_NO_OPTION);\n if (result == JOptionPane.YES_OPTION)\n {\n fProps.loadDefaultValues(overrideExistingValues);\n controlTabs.refreshUiFromConfig(fProps);\n chatWindow.getChatPanel().repaint();\n }\n }\n }\n\n private void open()\n {\n boolean okayToProceed = fProps.checkForUnsavedProps(this, this);\n\n if (okayToProceed)\n {\n int result = opener.showOpenDialog(me);\n if (result == JFileChooser.APPROVE_OPTION)\n {\n try\n {\n LoadConfigReport report = fProps.loadFile(opener.getSelectedFile());\n if (report.isProblem())\n {\n throw new Exception(\"Configuration file open error\");\n }\n controlTabs.refreshUiFromConfig(fProps);\n chatWindow.getChatPanel().repaint();\n }\n catch (Exception ex)\n {\n final String errorMsg = \"Unable to open file \" + (opener.getSelectedFile() == null ? \"null\" : opener.getSelectedFile().getName());\n logger.error(errorMsg, ex);\n ChatWindow.popup.handleProblem(errorMsg);\n }\n }\n }\n }\n\n private void loadPreset(String presetName, String presetFilename)\n {\n boolean okayToProceed = fProps.checkForUnsavedProps(this, this);\n if (okayToProceed)\n {\n try\n {\n LoadConfigReport report = fProps.loadFile(presetFilename);\n if (report.isProblem())\n {\n logger.error(\"Unsuccessful call to FontificatorProperties.loadFile(String)\");\n throw new Exception();\n }\n }\n catch (Exception ex)\n {\n logger.error(ex.toString(), ex);\n ChatWindow.popup.handleProblem(\"Unable to load preset \" + presetName + \" (\" + presetFilename + \")\");\n }\n controlTabs.refreshUiFromConfig(fProps);\n chatWindow.getChatPanel().repaint();\n }\n }\n\n /**\n * Gets a file to save to from the given file chooser, including options to overwrite\n * \n * @param chooser\n * the chooser to use to get the file\n * @param extension\n * the extension of the type of file being saved, or null if there is no default extension\n * @return file or null if selection is canceled\n */\n public static File getTargetSaveFile(JFileChooser chooser, String extension)\n {\n int overwrite = JOptionPane.YES_OPTION;\n // Do while overwrite is no, so it loops back around to try again if someone says they don't want to\n // overwrite an existing file, but if they select cancel it just breaks out of the loop\n do\n {\n int result = chooser.showSaveDialog(me);\n\n // Default to yes, so it writes even if there's no existing file\n overwrite = JOptionPane.YES_OPTION;\n\n if (result == JFileChooser.APPROVE_OPTION)\n {\n File saveFile = chooser.getSelectedFile();\n\n if (chooser.getFileFilter() instanceof FileNameExtensionFilter)\n {\n String[] exts = ((FileNameExtensionFilter) (chooser.getFileFilter())).getExtensions();\n boolean endsInExt = false;\n for (String ext : exts)\n {\n if (saveFile.getName().toLowerCase().endsWith(ext.toLowerCase()))\n {\n endsInExt = true;\n break;\n }\n }\n if (extension != null && !endsInExt)\n {\n saveFile = new File(saveFile.getPath() + \".\" + extension);\n }\n }\n\n if (saveFile.exists())\n {\n overwrite = JOptionPane.showConfirmDialog(me, \"File \" + saveFile.getName() + \" already exists. Overwrite?\", \"Overwrite?\", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);\n }\n\n if (overwrite == JOptionPane.YES_OPTION)\n {\n return saveFile;\n }\n }\n } while (overwrite == JOptionPane.NO_OPTION);\n return null;\n }\n\n /**\n * Save configuration to a file\n * \n * @return whether the file was saved\n */\n public boolean saveConfig()\n {\n final boolean configReadyToSave = controlTabs.refreshConfigFromUi();\n File saveFile = null;\n if (configReadyToSave)\n {\n saveFile = getTargetSaveFile(configSaver, DEFAULT_CONFIG_FILE_EXTENSION);\n }\n if (saveFile != null)\n {\n try\n {\n fProps.saveFile(saveFile);\n return true;\n }\n catch (Exception ex)\n {\n logger.error(\"Configuration file save error\", ex);\n return false;\n }\n }\n return false;\n }\n\n /**\n * Takes and saves a screenshot of the current chat window\n * \n * @return whether the screenshot was saved\n */\n private boolean saveScreenshot()\n {\n // Take the screenshot before the save file chooser is shown\n ChatPanel chat = chatWindow.getChatPanel();\n BufferedImage chatImage = new BufferedImage(chat.getWidth(), chat.getHeight(), screenshotOptions.isTransparencyEnabled() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);\n Graphics chatGraphics = chatImage.getGraphics();\n chat.paint(chatGraphics);\n\n final boolean chromaEnabled = Boolean.toString(true).equalsIgnoreCase(fProps.getProperty(FontificatorProperties.KEY_CHAT_CHROMA_ENABLED));\n if (screenshotOptions.isTransparencyEnabled() && chromaEnabled)\n {\n final int chromaKey = new Color(Integer.parseInt(fProps.getProperty(FontificatorProperties.KEY_COLOR_CHROMA_KEY), 16)).getRGB();\n final int transparentPixel = new Color(0, true).getRGB();\n\n for (int r = 0; r < chatImage.getHeight(); r++)\n {\n for (int c = 0; c < chatImage.getWidth(); c++)\n {\n if (chatImage.getRGB(c, r) == chromaKey)\n {\n chatImage.setRGB(c, r, transparentPixel);\n }\n }\n }\n }\n\n File saveFile = getTargetSaveFile(screenshotSaver, DEFAULT_SCREENSHOT_FILE_EXTENSION);\n if (saveFile != null)\n {\n try\n {\n if (screenshotOptions.isMetadataEnabled())\n {\n ImageWriter writer = ImageIO.getImageWritersByFormatName(\"PNG\").next();\n ImageOutputStream stream = ImageIO.createImageOutputStream(saveFile);\n writer.setOutput(stream);\n\n IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(chatImage), writer.getDefaultWriteParam());\n\n IIOMetadataNode title = generateMetadataNode(\"Title\", \"CGF Screenshot\");\n IIOMetadataNode software = generateMetadataNode(\"Software\", \"Chat Game Fontificator\");\n final String fontGameName = ControlPanelFont.getFontGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_FONT));\n final String borderGameName = ControlPanelFont.getBorderGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_BORDER));\n IIOMetadataNode description = generateMetadataNode(\"Description\", fontGameName + \" Font / \" + borderGameName + \" Border\");\n\n IIOMetadataNode text = new IIOMetadataNode(\"tEXt\");\n text.appendChild(title);\n text.appendChild(software);\n text.appendChild(description);\n\n final String metadataFormatStr = \"javax_imageio_png_1.0\";\n IIOMetadataNode root = new IIOMetadataNode(metadataFormatStr);\n root.appendChild(text);\n metadata.mergeTree(metadataFormatStr, root);\n\n writer.write(metadata, new IIOImage(chatImage, null, metadata), writer.getDefaultWriteParam());\n\n stream.close();\n }\n else\n {\n ImageIO.write(chatImage, \"png\", saveFile);\n }\n\n return true;\n }\n catch (Exception e)\n {\n logger.error(\"Unable to save screenshot\", e);\n return false;\n }\n }\n return false;\n }\n\n private IIOMetadataNode generateMetadataNode(String key, String value)\n {\n IIOMetadataNode node = new IIOMetadataNode(\"tEXtEntry\");\n node.setAttribute(\"keyword\", key);\n node.setAttribute(\"value\", value);\n return node;\n }\n\n public void setAlwaysOnTopMenu(boolean alwaysOnTop)\n {\n ((JCheckBoxMenuItem) (getJMenuBar().getMenu(2).getItem(2))).setSelected(alwaysOnTop);\n }\n\n public void setRememberPositionMenu(boolean rememberPosition)\n {\n ((JCheckBoxMenuItem) (getJMenuBar().getMenu(2).getItem(3))).setSelected(rememberPosition);\n }\n\n public void setAntiAliasMenu(boolean antiAlias)\n {\n ((JCheckBoxMenuItem) (getJMenuBar().getMenu(2).getItem(0))).setSelected(antiAlias);\n }\n\n public void clearUsernameCases()\n {\n bot.clearUsernameCases();\n }\n\n public void addManualMessage(String username, String message)\n {\n bot.sendMessageToChat(MessageType.MANUAL, message, new TwitchPrivmsg(username));\n }\n\n public void disconnect()\n {\n bot.disconnect();\n }\n\n public void attemptToExit()\n {\n attemptToExit(this);\n }\n\n /**\n * Any program exit should call this method to do so\n */\n public void attemptToExit(Component parent)\n {\n boolean okayToProceed = fProps.checkForUnsavedProps(this, parent);\n if (okayToProceed)\n {\n disconnect();\n System.exit(0);\n }\n }\n\n /**\n * Construct the popup dialog containing the About message\n */\n private void constructAboutPopup()\n {\n aboutPane = new JEditorPane(\"text/html\", ABOUT_CONTENTS);\n aboutPane.addHyperlinkListener(new HyperlinkListener()\n {\n public void hyperlinkUpdate(HyperlinkEvent e)\n {\n if (EventType.ACTIVATED.equals(e.getEventType()))\n {\n if (Desktop.isDesktopSupported())\n {\n try\n {\n Desktop.getDesktop().browse(URI.create(\"https://\" + e.getDescription()));\n }\n catch (IOException e1)\n {\n e1.printStackTrace();\n }\n }\n }\n }\n });\n aboutPane.setEditable(false);\n }\n\n private void toggleDebugTab()\n {\n controlTabs.toggleDebugTab();\n }\n\n private void showAboutPane()\n {\n JOptionPane.showMessageDialog(this, aboutPane, \"About\", JOptionPane.PLAIN_MESSAGE);\n }\n\n public MessageDialog getMessageDialog()\n {\n return messageDialog;\n }\n\n public void loadAfterInit()\n {\n controlTabs.setChatWindowPosition();\n }\n\n public ControlPanelDebug getDebugPanel()\n {\n return controlTabs.getDebugTab();\n }\n\n}", "public class SpriteFont\n{\n private static final Logger logger = Logger.getLogger(SpriteFont.class);\n\n public static final String NORMAL_ASCII_KEY = \" !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\" + (char) 127;\n\n /**\n * The number of pixels between each individual badge and between badges and the username;\n */\n public static final int BADGE_MINIMUM_SPACING_PIXELS = 3;\n\n protected SpriteCache sprites;\n\n protected Map<Integer, Rectangle> characterBounds;\n\n /**\n * Characters that can be line breaks for wrapping to the next line\n */\n protected static final String WORD_BREAKS = \" \\n\\r\\t\";\n\n /**\n * Characters that indicate a return to the start of the next line\n */\n protected static final String LINE_BREAKS = \"\\n\";\n\n /**\n * Shift the messages down this many lines\n */\n protected int lineScrollOffset;\n\n protected ConfigFont config;\n\n public SpriteFont(ConfigFont config)\n {\n logger.trace(\"Creating sprite font using config font filename \" + (config == null ? \"null\" : config.getFontFilename()));\n this.config = config;\n this.characterBounds = new HashMap<Integer, Rectangle>();\n this.sprites = new SpriteCache(config);\n }\n\n /**\n * Get the dimensions of an emoji image\n * \n * @param img\n * @param emojiConfig\n * @return\n */\n private int[] getEmojiDimensions(SpriteCharacterKey c, ConfigEmoji emojiConfig)\n {\n LazyLoadEmoji emoji = c.getEmoji();\n Image img = emoji.getImage(emojiConfig.isAnimationEnabled());\n\n int iw;\n int ih;\n\n if (img == null)\n {\n switch (emojiConfig.getDisplayStrategy())\n {\n case SPACE:\n case BOX_FILL:\n case BOX_FRAME:\n iw = emoji.getWidth();\n ih = emoji.getHeight();\n break;\n case UNKNOWN:\n // Do not use the emoji scaling below because it's a character, not an emoji\n // We can pass a null in for the FontMetrics, because we know the unknown character falls within the\n // non-extended range\n return new int[] { getCharacterWidth(null, new SpriteCharacterKey(config.getUnknownChar()), emojiConfig), 1 };\n case NOTHING:\n default:\n iw = 0;\n ih = 1;\n break;\n }\n }\n else\n {\n iw = emoji.getWidth();\n ih = emoji.getHeight();\n }\n\n float h;\n float w;\n\n float eScale = emoji.getType().isBadge() ? (emojiConfig.getBadgeScale() / 100.0f) : (emojiConfig.getEmojiScale() / 100.0f);\n if ((emoji.getType().isBadge() && emojiConfig.isBadgeScaleToLine()) || (!emoji.getType().isBadge() && emojiConfig.isEmojiScaleToLine()))\n {\n final float emojiScaleRatio = eScale * getLineHeightScaled() / (float) ih;\n h = ih * emojiScaleRatio;\n w = iw * h / ih;\n }\n else\n {\n w = eScale * iw;\n h = eScale * ih;\n }\n\n return new int[] { (int) w, (int) h };\n }\n\n /**\n * Return how wide a character is in pixels- must take scale into consideration scale\n * \n * @param c\n * @return character width\n */\n public int getCharacterWidth(FontMetrics fontMetrics, SpriteCharacterKey c, ConfigEmoji emojiConfig)\n {\n if (c.isChar())\n {\n int baseWidth;\n\n // Extended characters are enabled\n if (c.isExtended())\n {\n if (config.isExtendedCharEnabled())\n {\n // Return string width of extended char\n baseWidth = fontMetrics.charWidth(c.getCodepoint());\n // Don't include scale in this calculation, because it's already built into the font size\n return (int) (baseWidth + config.getCharSpacing() * config.getFontScale());\n }\n // The extended character should be replaced with the unknown character\n else\n {\n baseWidth = getCharacterBounds(config.getUnknownChar()).width;\n }\n }\n // It's a normal character\n else\n {\n // Character\n baseWidth = getCharacterBounds(c.getCodepoint()).width;\n }\n return (int) ((baseWidth + config.getCharSpacing()) * config.getFontScale());\n }\n else\n {\n // Emoji\n int[] eDim = getEmojiDimensions(c, emojiConfig);\n final int charSpacing = (int) (config.getCharSpacing() * config.getFontScale());\n final int extraSpacing = (c.getEmoji().getType().isBadge() ? Math.max(charSpacing, (int) (BADGE_MINIMUM_SPACING_PIXELS * config.getFontScale())) : charSpacing);\n return eDim[0] + extraSpacing;\n }\n\n }\n\n public void calculateCharacterDimensions()\n {\n // Start from scratch\n characterBounds.clear();\n\n // For fixed width, just put the same sized box for all characters. The\n // only difference is the location on the sprite grid\n switch (config.getFontType())\n {\n case FIXED_WIDTH:\n calculateFixedCharacterDimensions();\n break;\n case VARIABLE_WIDTH:\n calculateVariableCharacterDimensions();\n break;\n default:\n logger.error(\"Unknown font type: \" + config.getFontType());\n break;\n }\n }\n\n private void calculateFixedCharacterDimensions()\n {\n final int spriteWidth = sprites.getSprite(config).getSpriteWidth();\n final int spriteHeight = sprites.getSprite(config).getSpriteHeight();\n\n for (int i = 0; i < config.getCharacterKey().length(); i++)\n {\n final char c = config.getCharacterKey().charAt(i);\n final int index = config.getCharacterKey().indexOf(c);\n final int gridX = index % config.getGridWidth();\n final int gridY = index / config.getGridWidth();\n Rectangle bounds = new Rectangle();\n bounds.setLocation(gridX * spriteWidth, gridY * spriteHeight);\n bounds.setSize(spriteWidth, spriteHeight);\n characterBounds.put((int) c, bounds);\n }\n }\n\n /**\n * Go through each character and determine how wide it is based on the non transparent pixels\n */\n private void calculateVariableCharacterDimensions()\n {\n logger.trace(\"Calculating character dimensions\");\n characterBounds.clear();\n\n Sprite sprite = sprites.getSprite(config);\n\n final int charWidth = sprite.getSpriteWidth();\n final int charHeight = sprite.getSpriteHeight();\n final int wholeWidth = sprite.getImage().getWidth();\n final int wholeHeight = sprite.getImage().getHeight();\n\n final String key = config.getCharacterKey();\n\n int[] pixelData = new int[wholeWidth * wholeHeight];\n pixelData = sprite.getImage().getRGB(0, 0, wholeWidth, wholeHeight, pixelData, 0, wholeWidth);\n int letterIndex = 0;\n // For each grid row\n for (int y = 0; y < wholeHeight; y += charHeight)\n {\n // For each grid col\n for (int x = 0; x < wholeWidth; x += charWidth)\n {\n final char ckey = key.charAt(letterIndex);\n\n boolean leftEdgeFound = false;\n int leftEdge = 0;\n int rightEdge = 0;\n\n // Go through each column in the letter cell\n for (int localX = 0; localX < charWidth; localX++)\n {\n int absoluteX = localX + x;\n // Go down the whole column looking for opaque pixels\n boolean opaquePixelFound = false;\n for (int absoluteY = y; absoluteY < y + charHeight && !opaquePixelFound; absoluteY++)\n {\n // If the alpha component of the pixel RGB integer\n // is greater than zero, then the pixel counts\n // towards the width of the character\n opaquePixelFound = ((pixelData[absoluteX + absoluteY * wholeWidth] >> 24) & 0xff) > 0;\n }\n\n if (opaquePixelFound)\n {\n // Set left only the first time an opaque pixel is\n // found\n if (!leftEdgeFound)\n {\n leftEdge = localX;\n leftEdgeFound = true;\n }\n // Keep setting the right each time to expand the\n // width\n rightEdge = localX;\n }\n }\n\n // Add one pixel for the space between characters, and take\n // the\n // minimum of the calculated width and the max charWidth\n // just in case\n\n rightEdge++;\n\n final int letterWidth = Math.min(charWidth, rightEdge - leftEdge);\n\n Rectangle bounds = new Rectangle(x + leftEdge, y, letterWidth, charHeight);\n\n // If the character is a space and the bounds calculated to be nothing, meaning there were no\n // opaque pixels found, then make it a default quarter of the sprite width\n if (!leftEdgeFound)\n {\n // Then just use a quarter of the character width\n characterBounds.put((int) ckey, new Rectangle(x + charWidth / 4, y, charWidth / 2, charHeight));\n }\n // For all other characters, or for spaces that have some non transparent pixels, use the calculated\n // bounds\n else\n {\n characterBounds.put((int) ckey, bounds);\n }\n\n letterIndex++;\n }\n }\n }\n\n /**\n * Get the bounding box for the character in the sprite font image (does not use scale at all)\n * \n * @param c\n * @return bounding box\n */\n public Rectangle getCharacterBounds(int c)\n {\n if (!config.getCharacterKey().contains(new String(Character.toChars(c))))\n {\n c = config.getUnknownChar();\n }\n\n if (FontType.VARIABLE_WIDTH.equals(config.getFontType()) && c == ' ')\n {\n Rectangle spaceBounds = characterBounds.get(c);\n spaceBounds.width = (int) (sprites.getSprite(config).getSpriteWidth() * (config.getSpaceWidth() / 100.0f));\n }\n\n return characterBounds.get(c);\n }\n\n /**\n * Should be called if the ConfigFont object is updated\n */\n public void updateForConfigChange()\n {\n calculateCharacterDimensions();\n }\n\n /**\n * Get the distance in pixels from the top of one line of text to the top of the next line of text, scaled\n * \n * @return lineHeightScaled\n */\n public int getLineHeightScaled()\n {\n return (int) (getLineHeight() * config.getFontScale());\n }\n\n /**\n * Get the distance in pixels from the top of one line of text to the top of the next line of text, unscaled\n * \n * @return lineHeight\n */\n public int getLineHeight()\n {\n return getFontHeight() + config.getLineSpacing();\n }\n\n public int getFontHeight()\n {\n return sprites.getSprite(config).pixelHeight;\n }\n\n public int getLineScrollOffset()\n {\n return lineScrollOffset;\n }\n\n public void setLineScrollOffset(int lineScrollOffset)\n {\n this.lineScrollOffset = lineScrollOffset;\n }\n\n /**\n * Change the line scroll offset by the specified amount if it falls within or up/down to the specified min and max\n * values\n * \n * @param delta\n * The amount to try to change the line scroll offset\n * @param min\n * The smallest the line scroll offset should be\n * @param max\n * The largest the line scroll offset should be\n */\n public void incrementLineScrollOffset(int delta, int min, int max)\n {\n final int test = lineScrollOffset + delta;\n if (test >= min && test < max)\n {\n lineScrollOffset = test;\n }\n else\n {\n lineScrollOffset = Math.max(lineScrollOffset, min);\n lineScrollOffset = Math.min(lineScrollOffset, max);\n }\n }\n\n /**\n * Do a mock drawing of the string to determine the dimensions of the bounding box that would surround the drawn\n * message\n * \n * @param message\n * @param messageConfig\n * @param emojiConfig\n * @param emojiManager\n * @param lineWrapLength\n * @return The size of the bounding box of the drawn message\n */\n public Dimension getMessageDimensions(Message message, FontMetrics fontMetrics, ConfigMessage messageConfig, ConfigEmoji emojiConfig, EmojiManager emojiManager, int lineWrapLength, boolean lastMessage)\n {\n return drawMessage(null, fontMetrics, message, null, null, messageConfig, emojiConfig, emojiManager, 0, 0, 0, 0, lineWrapLength, false, null, null, lastMessage);\n }\n\n /**\n * @param g2d\n * The graphics object upon which to draw\n * @param fontMetrics\n * The actual font metrics of the JPanel drawing this SpriteFont, used to draw extended characters\n * @param msg\n * The message to draw\n * @param userColor\n * The color unique to the sender of the message being drawn\n * @param colorConfig\n * The configuration for how to color messages\n * @param messageConfig\n * The configuration for how to draw messages\n * @param emojiConfig\n * The configuration for how to handle emoji\n * @param emojiManager\n * The manager for accessing emoji images\n * @param x_init\n * The left edge x coordinate to start drawing from\n * @param y_init\n * The top edge y coordinate to start drawing from (probably up in negative space above the graphics\n * object)\n * @param topLimit\n * When to start drawing lines as y increases, because many will be off screen or under the top order\n * @param botLimit\n * Only draw up to this edge\n * @param lineWrapLength\n * How long to let the text go to the right before going to a new line\n * @param debug\n * Whether to draw debugging boxes\n * @param debugColor\n * The color to draw debugging boxes\n * @param emojiObserver\n * Used to update animated GIF BTTV emotes\n * @param lastMessage\n * Whether this message is the last message, used to determine whether to add message spacing distance\n * after the message is printed\n * @return The size of the bounding box of the drawn message\n */\n public Dimension drawMessage(Graphics2D g2d, FontMetrics fontMetrics, Message msg, Color userColor, ConfigColor colorConfig, ConfigMessage messageConfig, ConfigEmoji emojiConfig, EmojiManager emojiManager, int x_init, int y_init, int topLimit, int botLimit, int lineWrapLength, boolean debug, Color debugColor, ImageObserver emojiObserver, boolean lastMessage)\n {\n if (msg.isJoinType() && !messageConfig.showJoinMessages())\n {\n return new Dimension();\n }\n\n SpriteCharacterKey[] text = msg.getText(emojiManager, messageConfig, emojiConfig);\n\n int maxCharWidth = 0;\n for (int c = 0; c < text.length; c++)\n {\n maxCharWidth = Math.max(maxCharWidth, getCharacterWidth(fontMetrics, text[c], emojiConfig));\n }\n if (maxCharWidth > lineWrapLength)\n {\n return new Dimension();\n }\n\n // Because the letters are set back by this amount to divide up the\n // spacing between their left and right sides\n x_init -= config.getCharSpacing() / 2;\n\n int x = x_init;\n int y = y_init;\n\n int height = getLineHeightScaled();\n int maxWidth = 0;\n int width = 0;\n\n y += lineScrollOffset * height;\n\n boolean forcedBreak = false;\n\n Color color = Color.WHITE;\n\n // Go through each character in the text\n for (int ci = 0; ci < text.length; ci++)\n {\n if (colorConfig != null)\n {\n color = getFontColor(msg, ci, messageConfig, colorConfig, userColor);\n }\n\n // If the character is a line return, go to the next line\n if (LINE_BREAKS.contains(String.valueOf(text[ci].getChar())))\n {\n x = x_init;\n maxWidth = Math.max(maxWidth, width);\n width = 0;\n y += getLineHeightScaled();\n if (ci < msg.getDrawCursor())\n {\n height += getLineHeightScaled();\n }\n }\n // If it's not a line return, look forward into the text to find if\n // the next word fits\n else if (WORD_BREAKS.contains(String.valueOf(text[ci].getChar())))\n {\n int charWidth = getCharacterWidth(fontMetrics, text[ci], emojiConfig);\n x += charWidth;\n width += charWidth;\n forcedBreak = false;\n }\n else\n {\n int currentWordPixelWidth = 0;\n for (int nwc = 0; nwc < text.length - ci && !WORD_BREAKS.contains(String.valueOf(text[ci + nwc].getChar())); nwc++)\n {\n currentWordPixelWidth += getCharacterWidth(fontMetrics, text[ci + nwc], emojiConfig);\n }\n int distanceAlreadyFilled = x - x_init;\n\n // The next word fits\n if (distanceAlreadyFilled + currentWordPixelWidth < lineWrapLength)\n {\n if (g2d != null && y >= topLimit && y < botLimit && ci < msg.getDrawCursor())\n {\n drawCharacter(g2d, fontMetrics, text[ci], x, y, emojiConfig, color, debug, debugColor, emojiObserver);\n }\n int charWidth = getCharacterWidth(fontMetrics, text[ci], emojiConfig);\n x += charWidth;\n width += charWidth;\n }\n // The next word doesn't fit, but it doesn't exceed the length\n // of a full line, so hit return\n else if (!forcedBreak && currentWordPixelWidth < lineWrapLength)\n {\n x = x_init;\n maxWidth = Math.max(maxWidth, width);\n width = 0;\n y += getLineHeightScaled();\n if (ci < msg.getDrawCursor())\n {\n height += getLineHeightScaled();\n }\n if (g2d != null && y >= topLimit && y < botLimit && ci < msg.getDrawCursor())\n {\n drawCharacter(g2d, fontMetrics, text[ci], x, y, emojiConfig, color, debug, debugColor, emojiObserver);\n }\n int charWidth = getCharacterWidth(fontMetrics, text[ci], emojiConfig);\n x += charWidth;\n width += charWidth;\n }\n // The next word doesn't even fit on its own line, so it needs a\n // forced break at the end of the line\n else\n {\n forcedBreak = true;\n distanceAlreadyFilled = x - x_init;\n final int remainderOfTheLine = lineWrapLength - distanceAlreadyFilled;\n int charWidth = getCharacterWidth(fontMetrics, text[ci], emojiConfig);\n if (charWidth > remainderOfTheLine)\n {\n x = x_init;\n maxWidth = Math.max(maxWidth, width);\n width = 0;\n y += getLineHeightScaled();\n if (ci < msg.getDrawCursor())\n {\n height += getLineHeightScaled();\n }\n }\n\n if (g2d != null && y >= topLimit && y < botLimit && ci < msg.getDrawCursor())\n {\n drawCharacter(g2d, fontMetrics, text[ci], x, y, emojiConfig, color, debug, debugColor, emojiObserver);\n }\n x += charWidth;\n width += charWidth;\n }\n }\n }\n\n if (!lastMessage)\n {\n height += config.getMessageSpacing();\n }\n\n return new Dimension(maxWidth, height);\n }\n\n private void drawCharacter(Graphics2D g2d, FontMetrics fontMetrics, SpriteCharacterKey sck, int x, int y, ConfigEmoji emojiConfig, Color color, boolean debug, Color debugColor, ImageObserver emojiObserver)\n {\n final int drawX = x + config.getCharSpacing() / 2;\n int drawY = y;\n\n if (sck.isChar())\n {\n final boolean validNormalChar = !sck.isExtended() && characterBounds.containsKey(sck.getCodepoint());\n final boolean drawUnknownChar = !validNormalChar && !config.isExtendedCharEnabled();\n\n // If the option to draw the unknown character in place of anything out of range is enabled,\n // then switch out the SpriteCharacterKey with one given the selected unknown character\n if (drawUnknownChar)\n {\n sck = new SpriteCharacterKey(config.getUnknownChar());\n }\n\n // Draw either a valid normal ASCII character, or draw the selected unknown replacement character\n if (validNormalChar || drawUnknownChar)\n {\n Rectangle bounds = characterBounds.get(sck.getCodepoint());\n sprites.getSprite(config).draw(g2d, drawX, drawY, bounds.width, bounds.height, bounds, config.getFontScale(), color);\n if (debug)\n {\n g2d.setColor(debugColor);\n g2d.drawRect(drawX, drawY, (int) (bounds.width * config.getFontScale()), (int) (bounds.height * config.getFontScale()));\n }\n }\n // The character is invalid, and drawing the unknown char is not selected, so draw the extended characters\n else\n {\n g2d.setColor(color);\n g2d.drawString(sck.toString(), drawX, drawY + (fontMetrics.getHeight() - fontMetrics.getDescent()) - config.getBaselineOffset() * config.getFontScale());\n }\n }\n else\n {\n int[] eDim = getEmojiDimensions(sck, emojiConfig);\n // yOffset is to center the emoji on the line\n int yOffset = (int) (sprites.getSprite(config).getSpriteDrawHeight(config.getFontScale()) / 2 - config.getBaselineOffset() * config.getFontScale()) - (sck.isBadge() ? emojiConfig.getBadgeHeightOffset() : 0);\n drawY += yOffset - eDim[1] / 2;\n Image eImage = sck.getEmoji().getImage(emojiConfig.isAnimationEnabled());\n if (eImage == null)\n {\n // If the image is null, then it's not loaded, so do the backup display strategy\n g2d.setColor(color);\n switch (emojiConfig.getDisplayStrategy())\n {\n case BOX_FILL:\n g2d.fillRect(drawX, drawY, eDim[0] + 1, eDim[1] + 1);\n break;\n case BOX_FRAME:\n g2d.drawRect(drawX, drawY, eDim[0], eDim[1]);\n break;\n case UNKNOWN:\n drawCharacter(g2d, fontMetrics, new SpriteCharacterKey(config.getUnknownChar()), x, y, emojiConfig, color, debug, debugColor, emojiObserver);\n break;\n case SPACE:\n case NOTHING:\n default:\n break;\n }\n }\n else\n {\n // Draw a color square background for the emoji (for FrankerFaceZ badges)\n if (sck.getEmoji().isColoringRequired())\n {\n g2d.setColor(sck.getEmojiBgColor());\n g2d.fillRect(drawX, drawY, eDim[0] + 1, eDim[1] + 1);\n }\n // Draw the emoji image\n g2d.drawImage(eImage, drawX, drawY, eDim[0], eDim[1], emojiObserver);\n }\n }\n }\n\n /**\n * If the change to the next character requires a change to the color of the text, this method will set the\n * appropriate color\n * \n * @param msg\n * @param c\n * @param messageConfig\n * @param colorConfig\n * @param userColor\n */\n public Color getFontColor(Message msg, int c, ConfigMessage messageConfig, ConfigColor colorConfig, Color userColor)\n {\n boolean timestampIndexEncountered = messageConfig.showTimestamps() && c < msg.getIndexTimestamp(messageConfig);\n\n if (msg.isJoinType())\n {\n if (timestampIndexEncountered)\n {\n return colorConfig.isColorJoin() && colorConfig.isColorTimestamp() ? colorConfig.getHighlight() : colorConfig.getFgColor();\n }\n else\n {\n return colorConfig.isColorJoin() ? colorConfig.getHighlight() : colorConfig.getFgColor();\n }\n }\n else\n {\n if (timestampIndexEncountered)\n {\n return colorConfig.isColorTimestamp() ? userColor : colorConfig.getFgColor();\n }\n else if (messageConfig.showUsernames() && c >= msg.getIndexUsername(messageConfig)[0] && c < msg.getIndexUsername(messageConfig)[1])\n {\n return colorConfig.isColorUsername() ? userColor : colorConfig.getFgColor();\n }\n else if (colorConfig.isColorMessage() || MessageType.ACTION.equals(msg.getType()))\n {\n return userColor;\n }\n else\n {\n return colorConfig.getFgColor();\n }\n }\n }\n\n}" ]
import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JToggleButton; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.glitchcog.fontificator.config.FontificatorProperties; import com.glitchcog.fontificator.config.loadreport.LoadConfigReport; import com.glitchcog.fontificator.gui.DebugAppender; import com.glitchcog.fontificator.gui.chat.ChatWindow; import com.glitchcog.fontificator.gui.component.ColorButton; import com.glitchcog.fontificator.gui.component.LabeledSlider; import com.glitchcog.fontificator.gui.controls.ControlWindow; import com.glitchcog.fontificator.sprite.SpriteFont;
package com.glitchcog.fontificator.gui.controls.panel; /** * Control Panel containing debugging options and information * * @author Matt Yanos */ public class ControlPanelDebug extends ControlPanelBase { private static final long serialVersionUID = 1L; /** * Whether debugging is activated, which should correspond to when this panel is displayed */ private boolean debugging;
private ControlWindow ctrlWindow;
6
concentricsky/android-viewer-for-khan-academy
src/com/concentricsky/android/khanacademy/app/HomeActivity.java
[ "public class KADataService extends Service {\n \n\tpublic final String LOG_TAG = getClass().getSimpleName();\n\t\n\tpublic static final int RESULT_SUCCESS = 0;\n\tpublic static final int RESULT_ERROR = 1;\n\tpublic static final int RESULT_CANCELLED = 2;\n\t\n\tprivate KADataBinder mBinder = new KADataBinder(this);\n private DatabaseHelper helper;\n private KAAPIAdapter api;\n private CaptionManager captionManager;\n private OfflineVideoManager offlineVideoManager;\n private ThumbnailManager thumbnailManager;\n \n private Executor libraryUpdateExecutor = Executors.newSingleThreadExecutor();\n private NotificationManager notificationManager;\n \n /**\n * Passed as the IBinder parameter to ServiceConnection.onServiceConnected when a\n * consumer binds to this service.\n * \n * Must be static:\n * http://code.google.com/p/android/issues/detail?id=6426\n */\n public static class KADataBinder extends Binder {\n \tprivate KADataService dataService;\n \tpublic KADataBinder(KADataService dataService) {\n \t\tsetDataService(dataService);\n \t}\n public KADataService getService() {\n return dataService;\n }\n public void setDataService(KADataService dataService) {\n \t\tthis.dataService = dataService;\n }\n }\n\t\n /**\n * Thrown by Provider instances when the service is not (yet) available.\n */\n\tpublic static class ServiceUnavailableException extends Exception {\n\t\tprivate static final long serialVersionUID = 581386365380491650L;\n\t\tpublic final boolean expected;\n\t\tpublic ServiceUnavailableException(boolean expected) {\n\t\t\tsuper();\n\t\t\tthis.expected = expected;\n\t\t}\n\t}\n \n\t/**\n\t * Simplified accessor interface.\n\t */\n public interface Provider {\n \tpublic KADataService getDataService() throws ServiceUnavailableException;\n \tpublic boolean requestDataService(ObjectCallback<KADataService> callback);\n \tpublic boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);\n }\n\n @Override\n public void onCreate() {\n \tLog.d(LOG_TAG, \"onCreate\");\n \t\n \thelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);\n \t\n \tInputStream is = getResources().openRawResource(R.raw.oauth_credentials);\n \tbyte[] buffer;\n\t\ttry {\n\t\t\tbuffer = new byte[is.available()];\n\t \twhile (is.read(buffer) != -1);\n\t \tString jsontext = new String(buffer);\n\t \tJSONObject oauthCredentials = new JSONObject(jsontext);\n\t \tString key = oauthCredentials.getString(\"OAUTH_CONSUMER_KEY\");\n\t \tString secret = oauthCredentials.getString(\"OAUTH_CONSUMER_SECRET\");\n\t \tapi = new KAAPIAdapter(this, key, secret);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n \t\n \tcaptionManager = new CaptionManager(this);\n \tofflineVideoManager = new OfflineVideoManager(this);\n \tthumbnailManager = ThumbnailManager.getSharedInstance(this);\n \tnotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n \t\n \tsetupResponseCache();\n }\n \n /**\n * Used for long-running operations including library updates and video downloads.\n * \n */\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Log.i(\"KADataService\", \"Received start id \" + startId + \": \" + intent);\n \n PendingIntent pendingIntent = null;\n if (intent.hasExtra(Intent.EXTRA_INTENT)) {\n \t// TODO : use this intent. It needs to be called with the results of requestLibraryUpdate (so far)\n \tpendingIntent = intent.getParcelableExtra(Intent.EXTRA_INTENT);\n }\n \n if (ACTION_LIBRARY_UPDATE.equals(intent.getAction())) {\n \trequestLibraryUpdate(startId, pendingIntent, intent.getBooleanExtra(EXTRA_FORCE, false));\n \treturn START_REDELIVER_INTENT;\n }\n \n if (ACTION_UPDATE_DOWNLOAD_STATUS.equals(intent.getAction())) {\n \tLog.d(LOG_TAG, \"update download status\");\n \tupdateDownloadStatus(intent, pendingIntent, startId);\n \treturn START_REDELIVER_INTENT;\n }\n \n /*\n START_NOT_STICKY\n\t\tDo not recreate the service, unless there are pending intents to deliver. This is the \n\t\tsafest option to avoid running your service when not necessary and when your application \n\t\tcan simply restart any unfinished jobs.\n\t\tSTART_STICKY\n\t\tRecreate the service and call onStartCommand(), but do not redeliver the last intent. \n\t\tInstead, the system calls onStartCommand() with a null intent, unless there were pending \n\t\tintents to start the service, in which case, those intents are delivered. This is suitable \n\t\tfor media players (or similar services) that are not executing commands, but running \n\t\tindefinitely and waiting for a job.\n\t\tSTART_REDELIVER_INTENT\n\t\tRecreate the service and call onStartCommand() with the last intent that was delivered \n\t\tto the service. Any pending intents are delivered in turn. This is suitable for services \n\t\tthat are actively performing a job that should be immediately resumed, such as downloading a file.\n */\n \n // If we reach this point, the intent has some unknown action, so just ignore it and stop.\n this.stopSelfResult(startId);\n return START_NOT_STICKY;\n }\n\n @Override\n public void onDestroy() {\n \tLog.d(LOG_TAG, \"onDestroy\");\n \t\n \tapi = null;\n \tcaptionManager = null;\n \t\n \tofflineVideoManager.destroy();\n \tofflineVideoManager = null;\n \t\n \tthumbnailManager.destroy();\n \tthumbnailManager = null;\n \t\n \tOpenHelperManager.releaseHelper();\n \tflushResponseCache();\n \t\n \tmBinder.setDataService(null);\n \tmBinder = null;\n \tnotificationManager = null;\n \t\n \tsuper.onDestroy();\n }\n\n /**\n * Used for maintaining a connection to this service to use it as a data backend.\n */\n @Override\n public IBinder onBind(Intent intent) {\n \tLog.d(LOG_TAG, \"onBind\");\n return mBinder;\n }\n \n @Override\n public boolean onUnbind(Intent intent) {\n \tLog.d(LOG_TAG, \"onUnbind\");\n \treturn super.onUnbind(intent);\n }\n \n \n /*\n * Database Access\n */\n\n public DatabaseHelper getHelper() {\n \treturn helper;\n }\n \n private void setupResponseCache() {\n \t// directly from http://developer.android.com/reference/android/net/http/HttpResponseCache.html\n \ttry {\n \t\tFile httpCacheDir = new File(getCacheDir(), \"http\");\n \t\tlong httpCacheSize = 10 * 1024 * 1024; // 10 MiB\n \t\tClass.forName(\"android.net.http.HttpResponseCache\")\n\t \t\t.getMethod(\"install\", File.class, long.class)\n\t \t\t.invoke(null, httpCacheDir, httpCacheSize);\n \t} catch (Exception httpResponseCacheNotAvailable) {\n \t\t// TODO : set cache the old way\n httpResponseCacheNotAvailable.printStackTrace();\n \t}\n }\n \n private void flushResponseCache() {\n \t\n \t// TODO : check if cache was set the old way, and flush that one.\n \t\n \ttry {\n\t \tClass<?> cls = Class.forName(\"android.net.http.HttpResponseCache\");\n\t \t\n\t\t\tObject cache = cls\n\t \t\t.getMethod(\"getInstalled\")\n\t \t\t.invoke(null);\n\t\t\t\n\t if (cache != null) {\n\t \tcls.getMethod(\"flush\").invoke(cache);\n\t }\n \t} catch (Exception e) {\n \t\t// Swallow.\n e.printStackTrace();\n \t}\n }\n\n\tprivate void finish(int startId, PendingIntent pendingIntent, int result) {\n\t\tif (pendingIntent != null) {\n\t\t\ttry {\n\t\t\t\tpendingIntent.send(result);\n\t\t\t} catch (CanceledException e) {\n\t\t\t\t// Ignore this. If they don't want their result, they don't get it.\n\t\t\t}\n\t\t}\n\t\tthis.stopSelfResult(startId);\n\t}\n \n\tprivate void broadcastLibraryUpdateNotification() {\n\t\tIntent intent = new Intent();\n\t\tintent.setAction(ACTION_LIBRARY_UPDATE);\n\t\tLocalBroadcastManager.getInstance(this).sendBroadcast(intent);\n\t}\n\t\n\tprivate void broadcastOfflineVideoSetChanged() {\n\t\tLocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);\n\t\tIntent intent = new Intent(Constants.ACTION_OFFLINE_VIDEO_SET_CHANGED);\n\t\tbroadcastManager.sendBroadcast(intent);\n\t}\n\t\n\tprivate void showUpdateNotification() {\n\t\tNotification notification = new NotificationCompat.Builder(this)\n\t\t\t\t.setSmallIcon(R.drawable.icon_72)\n\t\t\t\t.setContentTitle(\"Khan Academy content update\")\n\t\t\t\t.setContentText(\"Updating content for Viewer for Khan Academy\")\n\t\t\t\t.setOngoing(true)\n\t\t\t\t.build();\n\t notificationManager.notify(1, notification);\n\t}\n\t\n\tprivate void updateDownloadStatus(Intent intent, final PendingIntent pendingIntent, final int startId) {\n \tfinal long id = intent.getLongExtra(EXTRA_ID, -1);\n\t\tfinal DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);\n\t\tfinal DownloadManager.Query q = new DownloadManager.Query();\n\t\tq.setFilterById(id);\n\n \tnew AsyncTask<Void, Void, Boolean>() {\n \t\t@Override\n \t\tprotected Boolean doInBackground(Void... arg) {\n\t\t\t\tCursor cursor = mgr.query(q);\n\t\t\t\tString youtubeId = null;\n\t\t\t\tint status = -1;\n\t\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\t\tString filename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));\n\t\t\t\t\tyoutubeId = OfflineVideoManager.youtubeIdFromFilename(filename);\n\t\t\t\t\tstatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));\n\t\t\t\t}\n\t\t\t\tcursor.close();\n\t\t\t\t\n\t\t\t\tif (status == DownloadManager.STATUS_SUCCESSFUL && youtubeId != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tDao<Video, String> videoDao = helper.getVideoDao();\n\t\t\t\t\t\tUpdateBuilder<Video, String> q = videoDao.updateBuilder();\n\t\t\t\t\t\tq.where().eq(\"youtube_id\", youtubeId);\n\t\t\t\t\t\tq.updateColumnValue(\"download_status\", Video.DL_STATUS_COMPLETE);\n\t\t\t\t\t\tq.update();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn false;\n \t\t}\n \t\t\n \t\t@Override\n \t\tprotected void onPostExecute(Boolean successful) {\n \t\t\tif (successful) {\n\t\t\t\t\tbroadcastOfflineVideoSetChanged();\n\t\t\t\t\tfinish(startId, pendingIntent, RESULT_SUCCESS);\n \t\t\t} else {\n \t\t\t\tfinish(startId, pendingIntent, RESULT_ERROR);\n \t\t\t}\n \t\t}\n \t}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\n\t\t\n\t}\n\t\n\tprivate void cancelUpdateNotification() {\n\t notificationManager.cancel(1);\n\t}\n\t\n private void requestLibraryUpdate(final int startId, final PendingIntent pendingIntent, boolean force) {\n \tLog.d(LOG_TAG, \"requestLibraryUpdate\");\n \t\n \tshowUpdateNotification();\n \tLibraryUpdaterTask task = new LibraryUpdaterTask(this) {\n \t\t@Override\n \t\tpublic void onPostExecute(Integer status) {\n \t\t\tif (status != RESULT_CODE_FAILURE) {\n \t\t\t\ttry {\n\t\t\t\t\t\thelper.getDao(Topic.class).clearObjectCache();\n\t \t\t\t\thelper.getDao(Video.class).clearObjectCache();\n\t\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n \t\t\t\t\n \t\t\t\tbroadcastLibraryUpdateNotification();\n \t\t\t} else {\n \t\t\t\tLog.w(LOG_TAG, \"library update failure code\");\n \t\t\t}\n \t\t\t\t\n\t\t\t\tfinish(startId, pendingIntent, RESULT_SUCCESS);\n\t\t\t\tcancelUpdateNotification();\n \t\t}\n \t};\n \ttask.force = force;\n \ttask.executeOnExecutor(libraryUpdateExecutor);\n \t\n \tLog.d(LOG_TAG, \"Returning from requestLibraryUpdate\");\n }\n \n public KAAPIAdapter getAPIAdapter() {\n \treturn api;\n }\n \n public CaptionManager getCaptionManager() {\n \treturn captionManager;\n }\n\n public OfflineVideoManager getOfflineVideoManager() {\n \treturn offlineVideoManager;\n }\n \n public ThumbnailManager getThumbnailManager() {\n \treturn thumbnailManager;\n }\n \n \n /*\n * Data access\n */\n \n public Topic getRootTopic() {\n \tTopic topic = null;\n\t\ttry {\n\t\t\tDao<Topic, String> topicDao = helper.getTopicDao();\n\t\t\tPreparedQuery<Topic> q = topicDao.queryBuilder().where().isNull(\"parentTopic_id\").prepare();\n\t\t\ttopic = topicDao.queryForFirst(q);\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn topic;\n }\n \n}", "@JsonIgnoreProperties(ignoreUnknown=true)\n@DatabaseTable\npublic class Topic extends EntityBase implements Comparable<Topic>, Serializable {\n\tpublic static final String LOG_TAG = Topic.class.getSimpleName();\n/*\n * Full Topic \n * \n \n // Always in both\n \"kind\": \"Topic\",\n \"title\": \"The Root of All Knowledge\",\n \n // Full version of both\n \"description\": \"All concepts fit into the root of all knowledge\",\n \"relative_url\": \"/#root\",\n \"ka_url\": \"http://www.khanacademy.org/#root\",\n \"backup_timestamp\": \"2012-10-16T22:05:27Z\",\n \n // Topic only\n \"community_questions_title\": null,\n \"community_questions_url\": null,\n \"tags\": [],\n \"init_custom_stack\": null,\n \"id\": \"root\",\n \"assessment_progress_key\": \"awOEn1j7Rz0sCb-JrZu5agXkun6N382jJwX5fWYEo\",\n \"topic_page_url\": \"/\",\n \"hide\": true,\n \"extended_slug\": \"\",\n \"standalone_title\": \"The Root of All Knowledge\",\n \"children\": [\n\n */\n\t\n\t/*\n\t * Topic as child\n\t * \n\t \n\t \"kind\": \"Topic\",\n \"hide\": false,\n \"title\": \"New and Noteworthy\",\n \"url\": \"http://www.khanacademy.org/#new-and-noteworthy\",\n \"key_id\": null,\n \"id\": \"new-and-noteworthy\"\n\n\t */\n\t\n\tprivate static final long serialVersionUID = -4876433391343270374L;\n\t\n\tpublic static final String CHILD_KIND_VIDEO = \"Video\";\n\tpublic static final String CHILD_KIND_TOPIC = \"Topic\";\n\tpublic static final String CHILD_KIND_NONE = \"CHILD_KIND_NONE\";\n\tpublic static final String CHILD_KIND_UNKNOWN = \"CHILD_KIND_???\";\n\n\t// columnName=\"_id\" for CursorAdapter use.\n\t@DatabaseField(id=true, columnName=\"_id\")\n\tString id;\n\t\n\t@DatabaseField\n\tString child_kind;\n\t\n\t@DatabaseField\n\tint video_count;\n\t\n\t@DatabaseField\n\tint downloaded_video_count;\n\t\n\t/** Youtube Id of the video whose thumbnail we will display with this topic. \n\t * This will be the first video descendant of this topic that has a thumbnail url). */\n\t@DatabaseField\n\tString thumb_id;\n\t\n\t@DatabaseField\n String standalone_title;\n\t\n Collection<EntityBase> children;\n \n @ForeignCollectionField(eager=false)\n Collection<Topic> childTopics;\n \n @ForeignCollectionField(eager=false)\n Collection<Video> childVideos;\n \n\t/**\n\t * @return the id\n\t */\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getChild_kind() {\n\t\treturn child_kind;\n\t}\n\tpublic void setChild_kind(String child_kind) {\n\t\tthis.child_kind = child_kind;\n\t}\n\t@Override\n\tpublic int getVideo_count() {\n\t\treturn video_count;\n\t}\n\tpublic void setVideo_count(int video_count) {\n\t\tthis.video_count = video_count;\n\t}\n\t/**\n\t * @return the downloaded_video_count\n\t */\n\t@Override\n\tpublic int getDownloaded_video_count() {\n\t\treturn downloaded_video_count;\n\t}\n\t/**\n\t * @param downloaded_video_count the downloaded_video_count to set\n\t */\n\tpublic void setDownloaded_video_count(int downloaded_video_count) {\n\t\tthis.downloaded_video_count = downloaded_video_count;\n\t}\n\tpublic String getThumb_id() {\n\t\treturn thumb_id;\n\t}\n\tpublic void setThumb_id(String thumb_id) {\n\t\tthis.thumb_id = thumb_id;\n\t}\n\t/**\n\t * @return the standalone_title\n\t */\n\tpublic String getStandalone_title() {\n\t\treturn standalone_title;\n\t}\n\t/**\n\t * @param standalone_title the standalone_title to set\n\t */\n\tpublic void setStandalone_title(String standalone_title) {\n\t\tthis.standalone_title = standalone_title;\n\t}\n\t\n\tpublic Collection<? extends EntityBase> getChildren() {\n\t\tLog.d(LOG_TAG, String.format(\"getChildren: %s\", getId()));\n\t\t\n\t\tif (children != null && children.size() > 0) {\n\t\t\t// This must have been set on this object by Jackson.\n\t\t\treturn children;\n\t\t}\n\t\t\n\t\tCollection<Video> childVideos = getChildVideos();\n\t\tLog.d(LOG_TAG, String.format(\" childVideos is %s\", childVideos == null ? \"null\" : String.valueOf(childVideos.size())));\n\t\tif (childVideos != null && childVideos.size() > 0) {\n\t\t\treturn childVideos;\n\t\t}\n\t\tCollection<Topic> childTopics = getChildTopics();\n\t\tLog.d(LOG_TAG, String.format(\" childTopics is %s\", childTopics == null ? \"null\" : String.valueOf(childTopics.size())));\n\t\tif (childTopics != null && childTopics.size() > 0) {\n\t\t\treturn childTopics;\n\t\t}\n\t\treturn new ArrayList<EntityBase>();\n\t}\n\tpublic void setChildren(Collection<EntityBase> children) {\n\t\tthis.children = children;\n\t\tfor (EntityBase child : children) {\n\t\t\tchild.setParentTopic(this);\n\t\t}\n\t}\n\t\n\t\n\t/**\n\t * Implements Comparable<Topic>\n\t */\n\t@Override\n\tpublic int compareTo(Topic other) {\n\t\treturn getId().compareTo(other.getId());\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\ttry {\n\t\t\treturn ((Topic) other).getId().equals(getId());\n\t\t} catch (ClassCastException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn (getClass().hashCode() + getId().hashCode()) % Integer.MAX_VALUE;\n\t}\n\t\n\t@Override\n\tpublic BaseEntityUpdateVisitor<Topic> buildUpdateVisitor() {\n\t\treturn new BaseEntityUpdateVisitor<Topic>(this) {\n\t\t\t@Override\n\t\t\tpublic void visit(Topic toUpdate) {\n\t\t\t\tsuper.visit(toUpdate);\n\t\t\t\t\n\t\t\t\tString value = getChild_kind();\n\t\t\t\tif (!isDefaultValue(value, String.class)) {\n\t\t\t\t\ttoUpdate.setChild_kind(value);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvalue = getStandalone_title();\n\t\t\t\tif (!isDefaultValue(value, String.class)) {\n\t\t\t\t\ttoUpdate.setStandalone_title(value);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic void accept(EntityVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\tpublic Collection<Topic> getChildTopics() {\n\t\treturn childTopics;\n\t}\n\tpublic Collection<Video> getChildVideos() {\n\t\treturn childVideos;\n\t}\n}", "@JsonIgnoreProperties(ignoreUnknown=true)\n@DatabaseTable(tableName = \"user\")\npublic class User extends ModelBase {\n\t\n\t/*\n{\n \"all_proficient_exercises\": [\n \"addition_1\", \n \"subtraction_1\", \n \"multiplication_0.5\"\n ], \n \"badge_counts\": {\n \"0\": 1, \n \"1\": 1, \n \"2\": 0, \n \"3\": 0, \n \"4\": 0, \n \"5\": 1\n }, \n \"coaches\": [\n \"[email protected]\"\n ], \n \"joined\": \"2011-02-04T06:01:47Z\", \n \"kind\": \"UserData\", \n \"last_activity\": \"2011-05-04T06:01:47Z\", \n \"nickname\": \"Gob Bluth\",\n \"points\": 9188, \n \"proficient_exercises\": [\n \"addition_1\", \n \"subtraction_1\", \n \"multiplication_0.5\"\n ], \n \"suggested_exercises\": [\n \"addition_2\", \n \"subtraction_2\"\n ], \n \"total_seconds_watched\": 105, \n \"user_id\": \"[email protected]\", \n \"prettified_user_email\": \"[email protected]\" \n} \n\t */\n\t\n\tpublic User() { }\n\t\n\tpublic User(String username) {\n\t\tthis.nickname = username;\n\t}\n\t\n\t@DatabaseField\n\tString token;\n\t\n\t@DatabaseField\n\tString secret;\n\t\n\t@DatabaseField\n\tboolean isSignedIn;\n\t\n\t@JsonIgnoreProperties(ignoreUnknown=true)\n\tstatic class BadgeCounts {\n\t\tint type0;\n\t\tint type1;\n\t\tint type2;\n\t\tint type3;\n\t\tint type4;\n\t\tint type5;\n\t}\n\t\n\tBadgeCounts badgeCounts;\n\t\n\t@DatabaseField\n\tString user_id;\n\t\n\t@DatabaseField\n\tString prettified_user_email;\n\t\n\t@DatabaseField\n\tint total_seconds_watched;\n\t\n\t@DatabaseField\n\tint points;\n\t\n\t@DatabaseField(id=true)\n\tString nickname;\n\t\n\t@DatabaseField\n\tDate joined;\n\n\t/**\n\t * @return the token\n\t */\n\tpublic String getToken() {\n\t\treturn token;\n\t}\n\n\t/**\n\t * @param token the token to set\n\t */\n\tpublic void setToken(String token) {\n\t\tthis.token = token;\n\t}\n\n\t/**\n\t * @return the secret\n\t */\n\tpublic String getSecret() {\n\t\treturn secret;\n\t}\n\n\t/**\n\t * @param secret the secret to set\n\t */\n\tpublic void setSecret(String secret) {\n\t\tthis.secret = secret;\n\t}\n\n\t/**\n\t * @return the isSignedIn\n\t */\n\tpublic boolean isSignedIn() {\n\t\treturn isSignedIn;\n\t}\n\n\t/**\n\t * @param isSignedIn the isSignedIn to set\n\t */\n\tpublic void setSignedIn(boolean isSignedIn) {\n\t\tthis.isSignedIn = isSignedIn;\n\t}\n\n\t/**\n\t * @return the badgeCounts\n\t */\n\tpublic BadgeCounts getBadgeCounts() {\n\t\treturn badgeCounts;\n\t}\n\n\t/**\n\t * @param badgeCounts the badgeCounts to set\n\t */\n\tpublic void setBadgeCounts(BadgeCounts badgeCounts) {\n\t\tthis.badgeCounts = badgeCounts;\n\t}\n\n\t/**\n\t * @return the user_id\n\t */\n\tpublic String getUser_id() {\n\t\treturn user_id;\n\t}\n\n\t/**\n\t * @param user_id the user_id to set\n\t */\n\tpublic void setUser_id(String user_id) {\n\t\tthis.user_id = user_id;\n\t}\n\n\t/**\n\t * @return the prettified_user_email\n\t */\n\tpublic String getPrettified_user_email() {\n\t\treturn prettified_user_email;\n\t}\n\n\t/**\n\t * @param prettified_user_email the prettified_user_email to set\n\t */\n\tpublic void setPrettified_user_email(String prettified_user_email) {\n\t\tthis.prettified_user_email = prettified_user_email;\n\t}\n\n\t/**\n\t * @return the total_seconds_watched\n\t */\n\tpublic int getTotal_seconds_watched() {\n\t\treturn total_seconds_watched;\n\t}\n\n\t/**\n\t * @param total_seconds_watched the total_seconds_watched to set\n\t */\n\tpublic void setTotal_seconds_watched(int total_seconds_watched) {\n\t\tthis.total_seconds_watched = total_seconds_watched;\n\t}\n\n\t/**\n\t * @return the points\n\t */\n\tpublic int getPoints() {\n\t\treturn points;\n\t}\n\n\t/**\n\t * @param points the points to set\n\t */\n\tpublic void setPoints(int points) {\n\t\tthis.points = points;\n\t}\n\n\t/**\n\t * @return the nickname\n\t */\n\tpublic String getNickname() {\n\t\treturn nickname;\n\t}\n\n\t/**\n\t * @param nickname the nickname to set\n\t */\n\tpublic void setNickname(String nickname) {\n\t\tthis.nickname = nickname;\n\t}\n\n\t/**\n\t * @return the joined\n\t */\n\tpublic Date getJoined() {\n\t\treturn joined;\n\t}\n\n\t/**\n\t * @param joined the joined to set\n\t */\n\tpublic void setJoined(Date joined) {\n\t\tthis.joined = joined;\n\t}\n}", "public class Log {\n\t\n\tpublic static final String LOG_TAG = \"KA\";\n\t\n\tpublic static final int VERBOSE = 0;\n\tpublic static final int DEBUG = 1;\n\tpublic static final int INFO = 2;\n\tpublic static final int WARN = 3;\n\tpublic static final int ERROR = 4;\n\tpublic static final int ASSERT = 5;\n\tpublic static final int SUPPRESS = 6;\n\t\n\tprivate static Map<String, Integer> enabledTags = new HashMap<String, Integer> ();\n\tprivate static int defaultLogLevel = SUPPRESS;\n\t\n\t/**\n\t * Set the default logging level. If no level has been set for a given tag, this\n\t * default level will determine whether the message is logged. \n\t * \n\t * @param defaultLevel The default log level.\n\t */\n\tpublic static void setDefaultLevel(int defaultLevel) {\n\t\tdefaultLogLevel = defaultLevel;\n\t}\n\t\n\t/**\n\t * Get the default log level, which is used to determine whether a message is logged\n\t * if no level has been explicitly set for its tag.\n\t * \n\t * @return The default log level.\n\t */\n\tpublic static int getDefaultLevel() {\n\t\treturn defaultLogLevel;\n\t}\n\t\n\t/**\n\t * Get the log level for a given tag.\n\t * \n\t * @param tag The tag for which to return a log level.\n\t * @return The minimum level at which logs will be posted for the given tag.\n\t */\n\tpublic static int getLevel(String tag) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif (level == null) return SUPPRESS;\n\t\treturn level;\n\t}\n\t\n\t/**\n\t * Enable a tag for future log messages.\n\t * \n\t * @param tag The tag to enable, or \"*\" to set the default.\n\t * @param level The minimum level to log.\n\t */\n\tpublic static void setLevel(String tag, int level) {\n\t\tenabledTags.put(tag, level);\n\t}\n\t\n\t/**\n\t * Disable a tag for future log messages.\n\t * \n\t * @param tag The tag to disable, or \"*\" to suppress logging by default.\n\t */\n\tpublic static void disable(String tag) { \n\t\tenabledTags.remove(tag);\n\t}\n\t\n\t/**\n\t * Forward a message to the android logger. \n\t * \n\t * The message will be forwarded only if its tag has previously been enabled at the \n\t * DEBUG or lower level, or if the default log level is DEBUG or lower. \n\t * \n\t * The tag is wrapped into the message, and sent to the android \n\t * logger with the application's tag. For a call like Log.d(\"a\", \"b\") this results in \n\t * the call android.util.Log.d(\"KA\", \"a: b\") if \"a\" is enabled at DEBUG or lower, and \n\t * no operation otherwise.\n\t * \n\t * @param tag The tag to check against the enabled list and prepend to the message.\n\t * @param msg The message to log.\n\t */\n\tpublic static void d(String tag, String msg) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif ( (level != null && level <= DEBUG) || (level == null && defaultLogLevel <= DEBUG) ) {\n\t\t\tandroid.util.Log.d(LOG_TAG, tag + \": \" + msg);\n\t\t}\n\t}\n\t\n\t/**\n\t * Forward a message to the android logger. \n\t * \n\t * The message will be forwarded only if its tag has previously been enabled at the \n\t * ERROR or lower level, or if the default log level is ERROR or lower. \n\t * \n\t * The tag is wrapped into the message, and sent to the android \n\t * logger with the application's tag. For a call like Log.e(\"a\", \"b\") this results in \n\t * the call android.util.Log.e(\"KA\", \"a: b\") if \"a\" is enabled at ERROR or lower, and \n\t * no operation otherwise.\n\t * \n\t * @param tag The tag to check against the enabled list and prepend to the message.\n\t * @param msg The message to log.\n\t */\n\tpublic static void e(String tag, String msg) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif ( (level != null && level <= ERROR) || (level == null && defaultLogLevel <= ERROR) ) {\n\t\t\tandroid.util.Log.e(LOG_TAG, tag + \": \" + msg);\n\t\t}\n\t}\n\t\n\t/**\n\t * Forward a message to the android logger. \n\t * \n\t * The message will be forwarded only if its tag has previously been enabled at the \n\t * WARN or lower level, or if the default log level is WARN or lower. \n\t * \n\t * The tag is wrapped into the message, and sent to the android \n\t * logger with the application's tag. For a call like Log.w(\"a\", \"b\") this results in \n\t * the call android.util.Log.w(\"KA\", \"a: b\") if \"a\" is enabled at WARN or lower, and \n\t * no operation otherwise.\n\t * \n\t * @param tag The tag to check against the enabled list and prepend to the message.\n\t * @param msg The message to log.\n\t */\n\tpublic static void w(String tag, String msg) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif ( (level != null && level <= WARN) || (level == null && defaultLogLevel <= WARN) ) {\n\t\t\tandroid.util.Log.w(LOG_TAG, tag + \": \" + msg);\n\t\t}\n\t}\n\t\n\t/**\n\t * Forward a message to the android logger. \n\t * \n\t * The message will be forwarded only if its tag has previously been enabled at the \n\t * INFO or lower level, or if the default log level is INFO or lower. \n\t * \n\t * The tag is wrapped into the message, and sent to the android \n\t * logger with the application's tag. For a call like Log.i(\"a\", \"b\") this results in \n\t * the call android.util.Log.i(\"KA\", \"a: b\") if \"a\" is enabled at INFO or lower, and \n\t * no operation otherwise.\n\t * \n\t * @param tag The tag to check against the enabled list and prepend to the message.\n\t * @param msg The message to log.\n\t */\n\tpublic static void i(String tag, String msg) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif ( (level != null && level <= INFO) || (level == null && defaultLogLevel <= INFO) ) {\n\t\t\tandroid.util.Log.i(LOG_TAG, tag + \": \" + msg);\n\t\t}\n\t}\n\t\n\t/**\n\t * Forward a message to the android logger. \n\t * \n\t * The message will be forwarded only if its tag has previously been enabled at the \n\t * VERBOSE level, or if the default log level is VERBOSE. \n\t * \n\t * The tag is wrapped into the message, and sent to the android \n\t * logger with the application's tag. For a call like Log.v(\"a\", \"b\") this results in \n\t * the call android.util.Log.v(\"KA\", \"a: b\") if \"a\" is enabled at VERBOSE, and \n\t * no operation otherwise.\n\t * \n\t * @param tag The tag to check against the enabled list and prepend to the message.\n\t * @param msg The message to log.\n\t */\n\tpublic static void v(String tag, String msg) {\n\t\tInteger level = enabledTags.get(tag);\n\t\tif ( (level != null && level <= VERBOSE) || (level == null && defaultLogLevel <= VERBOSE) ) {\n\t\t\tandroid.util.Log.v(LOG_TAG, tag + \": \" + msg);\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience function for passing in the level at runtime.\n\t */\n\tpublic static void log(int priority, String tag, String msg) {\n\t\tswitch (priority) {\n\t\tcase VERBOSE:\n\t\t\tv(tag, msg); break;\n\t\tcase INFO:\n\t\t\ti(tag, msg); break;\n\t\tcase DEBUG:\n\t\t\td(tag, msg); break;\n\t\tcase WARN:\n\t\t\tw(tag, msg); break;\n\t\tcase ERROR:\n\t\t\te(tag, msg); break;\n\t\tcase ASSERT:\n\t\tcase SUPPRESS:\n\t\tdefault:\n\t\t\t// nop\n\t\t}\n\t\n\t}\n\t\n}", "public interface ObjectCallback<T> {\n\tpublic void call(T obj);\n}" ]
import static com.concentricsky.android.khanacademy.Constants.ACTION_BADGE_EARNED; import static com.concentricsky.android.khanacademy.Constants.ACTION_LIBRARY_UPDATE; import static com.concentricsky.android.khanacademy.Constants.ACTION_TOAST; import static com.concentricsky.android.khanacademy.Constants.EXTRA_BADGE; import static com.concentricsky.android.khanacademy.Constants.EXTRA_MESSAGE; import static com.concentricsky.android.khanacademy.Constants.PARAM_TOPIC_ID; import static com.concentricsky.android.khanacademy.Constants.REQUEST_CODE_RECURRING_LIBRARY_UPDATE; import static com.concentricsky.android.khanacademy.Constants.TAG_LIST_FRAGMENT; import static com.concentricsky.android.khanacademy.Constants.UPDATE_DELAY_FROM_FIRST_RUN; import java.sql.SQLException; import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.concentricsky.android.khan.R; import com.concentricsky.android.khanacademy.Constants; import com.concentricsky.android.khanacademy.MainMenuDelegate; import com.concentricsky.android.khanacademy.data.KADataService; import com.concentricsky.android.khanacademy.data.db.Badge; import com.concentricsky.android.khanacademy.data.db.Topic; import com.concentricsky.android.khanacademy.data.db.User; import com.concentricsky.android.khanacademy.util.Log; import com.concentricsky.android.khanacademy.util.ObjectCallback;
private boolean userHasAcceptedTOS() { return getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) .getBoolean(Constants.SETTING_ACKNOWLEDGEMENT, false); } private void showTOSAcknowledgement() { View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_tos, null, false); // Use this LinkMovementMethod (as opposed to just the xml setting android:autoLink="web") to allow for named links. TextView mustAccept = (TextView) contentView.findViewById(R.id.dialog_tos_must_accept); TextView notEndorsed = (TextView) contentView.findViewById(R.id.dialog_tos_not_endorsed); mustAccept.setMovementMethod(LinkMovementMethod.getInstance()); notEndorsed.setMovementMethod(LinkMovementMethod.getInstance()); new AlertDialog.Builder(this) .setCancelable(false) .setView(contentView) .setPositiveButton(getString(R.string.button_i_accept), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Store the fact that the user has accepted. getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) .edit() .putBoolean(Constants.SETTING_ACKNOWLEDGEMENT, true) .apply(); } }) .setNegativeButton(getString(R.string.button_quit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } /* * API TOS * * We must display prominently: * * "This product uses the Khan Academy API but is not endorsed or certified by Khan Academy (www.khanacademy.org)." * and * "All Khan Academy content is available for free at www.khanacademy.org" * * * Among the "Trademark and Brand Usage Policy": * As another example, the use by an organization that is incorporating our content in a paid offering is NOT "non-commercial" * * WE WILL: * a. require all users of Your Application to affirmatively agree to be bound by the Khan Academy Terms of Service and the Khan Academy Privacy Policy ; b. notify Khan Academy if any users of Your Application are "repeat infringers" as that term is defined in the Khan Academy Terms of Service ; c. notify Khan Academy if you receive any complaint (including a copyright or other right holder) based on any content that is hosted by Khan Academy; d. in connection with your use of the Khan Academy API and the Khan Academy Platform, comply with all applicable local, state, national, and international laws and regulations, including, without limitation, copyright and other laws protecting proprietary rights (including the DMCA) and all applicable export control laws and regulations and country-specific economic sanctions implemented by the United States Office of Foreign Assets Control. For clarity, the foregoing does not limit your representations in Section 4, above; e. provide any information and/or other materials related to Your Applications reasonably requested by Khan Academy from time to time to verify your compliance with these API Terms. * and WILL NOT do a bunch of the usual things. * * * * (non-Javadoc) * @see com.concentricsky.android.khanacademy.app.LifecycleTraceActivity#onStart() */ @Override protected void onStart() { super.onStart(); if (!userHasAcceptedTOS()) { showTOSAcknowledgement(); } mainMenuDelegate = new MainMenuDelegate(this); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService dataService) { topic = dataService.getRootTopic(); if (topic != null) { // It is important to create the AbstractListFragment programmatically here as opposed to // specifying it in the xml layout. If it is specified in xml, we end up with an // error about "Content view not yet created" when clicking a list item after restoring // a fragment from the back stack. setListForTopic(topic, TopicListFragment.class, true); } } }); IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_LIBRARY_UPDATE); filter.addAction(ACTION_BADGE_EARNED); filter.addAction(ACTION_TOAST); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter); } @Override protected void onStop() { mainMenuDelegate = null; LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); super.onStop(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { Log.d(LOG_TAG, "onCreateOptionsMenu"); mainMenu = menu; // We use a different menu in this activity, so we skip the delegate's onCreateOptionsMenu. getMenuInflater().inflate(R.menu.home, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { Log.d(LOG_TAG, "onPrepareOptionsMenu"); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService dataService) {
User user = dataService.getAPIAdapter().getCurrentUser();
2
tomasbjerre/git-changelog-lib
src/test/java/se/bjurr/gitchangelog/api/TemplatesTest.java
[ "public static GitChangelogApi gitChangelogApiBuilder() {\n return new GitChangelogApi();\n}", "public static final String ZERO_COMMIT = \"0000000000000000000000000000000000000000\";", "public static void mock(final RestClient mock) {\n mockedRestClient = mock;\n}", "public class GitHubMockInterceptor implements Interceptor {\n\n private final Map<String, String> mockedResponses = new TreeMap<>();\n\n public GitHubMockInterceptor addMockedResponse(final String url, final String response) {\n this.mockedResponses.put(url, response);\n return this;\n }\n\n @Override\n public Response intercept(final Chain chain) throws IOException {\n final Request original = chain.request();\n\n // Get Request URI.\n final String url = chain.request().url().toString();\n\n if (this.mockedResponses.containsKey(url)) {\n return new Response.Builder()\n .code(200)\n .message(this.mockedResponses.get(url))\n .request(original)\n .protocol(Protocol.HTTP_1_0)\n .body(\n ResponseBody.create(\n MediaType.parse(\"application/json\"), this.mockedResponses.get(url).getBytes()))\n .addHeader(\"content-type\", \"application/json\")\n .build();\n }\n\n fail(\"No mocked response for: \" + url);\n return null;\n }\n}", "public class GitHubServiceFactory {\n static Interceptor interceptor;\n\n public static void setInterceptor(final Interceptor interceptor) {\n GitHubServiceFactory.interceptor = interceptor;\n }\n\n public static synchronized GitHubService getGitHubService(\n String api, final Optional<String> token) {\n if (!api.endsWith(\"/\")) {\n api += \"/\";\n }\n final File cacheDir = new File(\".okhttpcache\");\n cacheDir.mkdir();\n final Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);\n\n final OkHttpClient.Builder builder =\n new OkHttpClient.Builder().cache(cache).connectTimeout(10, SECONDS);\n\n if (token != null && token.isPresent() && !token.get().isEmpty()) {\n builder.addInterceptor(\n chain -> {\n final Request original = chain.request();\n\n final Request request =\n original\n .newBuilder() //\n .addHeader(\"Authorization\", \"token \" + token.get()) //\n .method(original.method(), original.body()) //\n .build();\n return chain.proceed(request);\n });\n }\n\n if (interceptor != null) {\n builder.addInterceptor(interceptor);\n }\n\n final Retrofit retrofit =\n new Retrofit.Builder() //\n .baseUrl(api) //\n .client(builder.build()) //\n .addConverterFactory(GsonConverterFactory.create()) //\n .build();\n\n return retrofit.create(GitHubService.class);\n }\n}", "public class JiraClientFactory {\n\n private static JiraClient jiraClient;\n\n public static void reset() {\n jiraClient = null;\n }\n\n /** The Bitbucket Server plugin uses this method to inject the Atlassian Client. */\n public static void setJiraClient(final JiraClient jiraClient) {\n JiraClientFactory.jiraClient = jiraClient;\n }\n\n public static JiraClient createJiraClient(final String apiUrl) {\n if (jiraClient != null) {\n return jiraClient;\n }\n return new DefaultJiraClient(apiUrl);\n }\n}", "public class RestClientMock extends RestClient {\n private final Map<String, String> mockedResponses = new TreeMap<>();\n\n public RestClientMock() {}\n\n public RestClientMock addMockedResponse(final String url, final String response) {\n this.mockedResponses.put(url, response);\n return this;\n }\n\n @Override\n public String getResponse(final HttpURLConnection conn) throws Exception {\n final String key = conn.getURL().getPath() + \"?\" + conn.getURL().getQuery();\n if (this.mockedResponses.containsKey(key)) {\n return this.mockedResponses.get(key);\n } else {\n throw new RuntimeException(\n \"Could not find mock for \\\"\"\n + key\n + \"\\\" available mocks are:\\n\"\n + this.mockedResponses.keySet().stream().collect(Collectors.joining(\"\\n\")));\n }\n }\n\n @Override\n public HttpURLConnection openConnection(final URL addr) throws Exception {\n return new HttpURLConnection(addr) {\n @Override\n public Map<String, List<String>> getHeaderFields() {\n final Map<String, List<String>> map = new TreeMap<>();\n map.put(\"Set-Cookie\", Arrays.asList(\"thesetcookie\"));\n return map;\n }\n\n @Override\n public void connect() throws IOException {}\n\n @Override\n public boolean usingProxy() {\n return false;\n }\n\n @Override\n public void disconnect() {}\n\n @Override\n public OutputStream getOutputStream() throws IOException {\n return new OutputStream() {\n @Override\n public void write(final int b) throws IOException {}\n };\n }\n };\n }\n}", "public class ApprovalsWrapper {\n private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();\n private static final String SEPARATOR = \"\\n\\n---------------------------------------------\\n\\n\";\n\n public static void verify(GitChangelogApi given) throws Exception {\n String changelogContext = GSON.toJson(given.getChangelog());\n String changelog = given.render();\n Object actual =\n new Object() {\n @Override\n public String toString() {\n return \"template:\\n\\n\"\n + given.getTemplateString()\n + SEPARATOR\n + \"settings:\\n\\n\"\n + GSON.toJson(given.getSettings())\n + SEPARATOR\n + \"changelog:\\n\\n\"\n + changelog\n + SEPARATOR\n + \"context:\\n\\n\"\n + changelogContext;\n }\n };\n Approvals.verify(actual, new Options().withReporter(new AutoApproveReporter()));\n }\n}" ]
import static java.nio.charset.StandardCharsets.UTF_8; import static se.bjurr.gitchangelog.api.GitChangelogApi.gitChangelogApiBuilder; import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.ZERO_COMMIT; import static se.bjurr.gitchangelog.internal.integrations.rest.RestClient.mock; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Test; import se.bjurr.gitchangelog.internal.integrations.github.GitHubMockInterceptor; import se.bjurr.gitchangelog.internal.integrations.github.GitHubServiceFactory; import se.bjurr.gitchangelog.internal.integrations.jira.JiraClientFactory; import se.bjurr.gitchangelog.internal.integrations.rest.RestClientMock; import se.bjurr.gitchangelog.test.ApprovalsWrapper;
package se.bjurr.gitchangelog.api; public class TemplatesTest { private GitChangelogApi baseBuilder; @Before public void before() throws Exception { JiraClientFactory.reset(); final RestClientMock mockedRestClient = new RestClientMock(); mockedRestClient // .addMockedResponse( "/repos/tomasbjerre/git-changelog-lib/issues?state=all", new String( Files.readAllBytes( Paths.get(TemplatesTest.class.getResource("/github-issues.json").toURI())), UTF_8)) // .addMockedResponse( "/jira/rest/api/2/issue/JIR-1234?fields=parent,summary,issuetype,labels,description,issuelinks", new String( Files.readAllBytes( Paths.get( TemplatesTest.class.getResource("/jira-issue-jir-1234.json").toURI())), UTF_8)) // .addMockedResponse( "/jira/rest/api/2/issue/JIR-5262?fields=parent,summary,issuetype,labels,description,issuelinks", new String( Files.readAllBytes( Paths.get( TemplatesTest.class.getResource("/jira-issue-jir-5262.json").toURI())), UTF_8)); mock(mockedRestClient);
final GitHubMockInterceptor gitHubMockInterceptor = new GitHubMockInterceptor();
3
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/model/DCE.java
[ "public class Configuration {\n\tpublic enum Sections {\n\t\tMACROSCOPY, MICROSCOPY, CYTOPATHOLOGY, LIQUID_CYTOPATHOLOGY, CONCLUSION, OTHERS;\n\t}\n\n\tpublic enum Criteria {\n\t\tONE_REPORT_ONE_REGISTRY, MANY_REPORT_ONE_REGISTRY, MANY_REPORT_MANY_REGISTRY;\n\t}\n\n\tpublic enum Classifiers {\n\t\tNAIVE, BAYES, BAYES_NET, BERNOULLI, SVM;\n\t}\n\n\tpublic enum WeightingSchemes {\n\t\tTF, IDF, TFIDF;\n\t}\n\n\tpublic enum SmoothingTechniques {\n\t\tADD_ONE, ADD_ALPHA, GOOD_TURING;\n\t}\n\n\tpublic enum Sources {\n\t\tDCE_REPORT, SIGH_REPORT, TOTLAUD_REPORT, ALL;\n\t}\n\n\tpublic enum Stemmers {\n\t\t// TODO test with PTStemmer V1 available at Maven repositories\n\t\tNONE, ORENGO, PORTER, SAVOY, COGROO;\n\t}\n\n\tpublic enum SentenceDetectors {\n\t\tNONE, OPENNLP, COGROO;\n\t}\n\n\tpublic enum Tokenizers {\n\t\tWORD, ALPHABETIC, OPENNLP, COGROO;\n\t}\n\n\tpublic enum Chunkers {\n\t\tNONE, COGROO;\n\t}\n\n\tpublic enum Targets {\n\t\tMORPHOLOGY, MORPHOLOGY_GROUP, TOPOGRAPHY, TOPOGRAPHY_CATEGORY, TOPOGRAPHY_GROUP;\n\t}\n\n\tpublic enum MetastasisStatus {\n\t\tALL, NONM1;\n\t}\n\n\tprivate Set<Sections> sections;\n\tprivate Criteria criteria;\n\tprivate int minReports = 1;\n\tprivate Classifiers classifier;\n\tprivate WeightingSchemes weightScheme;\n\tprivate SmoothingTechniques smoothing;\n\tprivate double svmCostParameter = 1;\n\tprivate Sources source;\n\tprivate boolean stoplist;\n\tprivate int ngrams = 1;\n\tprivate SentenceDetectors sentenceDetector;\n\tprivate Tokenizers tokenizer;\n\tprivate Stemmers stemmer;\n\tprivate Chunkers chunker;\n\tprivate Targets target;\n\tprivate MetastasisStatus meta;\n\tprivate int patientYear = -1;\n\n\tpublic Configuration(Set<Sections> sections, Criteria criteria, Classifiers classifier,\n\t\t\tWeightingSchemes weightScheme, SmoothingTechniques smoothing, double svmCParameter, Sources source,\n\t\t\tboolean stoplist, int ngrams, SentenceDetectors sentenceDetector, Tokenizers tokenizer, Stemmers stemmer,\n\t\t\tChunkers chunker, Targets target, int minReports, int year, MetastasisStatus meta) {\n\t\tsuper();\n\t\tthis.sections = sections;\n\t\tthis.criteria = criteria;\n\t\tif (criteria == Criteria.MANY_REPORT_ONE_REGISTRY)\n\t\t\tthis.minReports = minReports;\n\t\tthis.classifier = classifier;\n\t\tthis.weightScheme = weightScheme;\n\t\tthis.smoothing = smoothing;\n\t\tthis.svmCostParameter = svmCParameter;\n\t\tthis.source = source;\n\t\tthis.stoplist = stoplist;\n\t\tthis.ngrams = ngrams;\n\t\tthis.sentenceDetector = sentenceDetector;\n\t\tthis.tokenizer = tokenizer;\n\t\tthis.stemmer = stemmer;\n\t\tthis.chunker = chunker;\n\t\tthis.target = target;\n\t\tthis.patientYear = year;\n\t\tthis.meta = meta;\n\t}\n\n\tpublic Set<Sections> getSections() {\n\t\treturn sections;\n\t}\n\n\tpublic Criteria getCriteria() {\n\t\treturn criteria;\n\t}\n\n\tpublic int getMinReports() {\n\t\treturn minReports;\n\t}\n\n\tpublic Classifiers getClassifier() {\n\t\treturn classifier;\n\t}\n\n\tpublic WeightingSchemes getWeightScheme() {\n\t\treturn weightScheme;\n\t}\n\n\tpublic SmoothingTechniques getSmoothing() {\n\t\treturn smoothing;\n\t}\n\n\tpublic double getSvmCostParameter() {\n\t\treturn svmCostParameter;\n\t}\n\n\tpublic Sources getSource() {\n\t\treturn source;\n\t}\n\n\tpublic boolean getStoplist() {\n\t\treturn stoplist;\n\t}\n\t\n\tpublic int getNGrams() {\n\t\treturn ngrams;\n\t}\n\n\tpublic SentenceDetectors getSentenceDetector() {\n\t\treturn sentenceDetector;\n\t}\n\n\tpublic Tokenizers getTokenizer() {\n\t\treturn tokenizer;\n\t}\n\n\tpublic Stemmers getStemmer() {\n\t\treturn stemmer;\n\t}\n\n\tpublic Chunkers getChunker() {\n\t\treturn chunker;\n\t}\n\n\tpublic Targets getTarget() {\n\t\treturn target;\n\t}\n\n\tpublic MetastasisStatus getMetastasisStatus() {\n\t\treturn meta;\n\t}\n\n\tpublic int getPatientYear() {\n\t\treturn patientYear;\n\t}\n\n\tpublic String getInstanceDependentStringRepresentation() {\n\t\treturn (Arrays.toString(sections.toArray()) + \"-\" + criteria + \"-\" + minReports + \"-\" + source + \"-\"\n\t\t\t\t+ sentenceDetector + \"-\" + tokenizer + \"Tokenizer-\" + stemmer + \"Stemmer-\" + chunker + \"Chunker-\"\n\t\t\t\t+ target + \"-\" + meta + \"-\" + patientYear).toLowerCase();\n\t}\n\n\tpublic String getStringRepresentation() {\n\t\treturn (Arrays.toString(sections.toArray()) + \"-\" + criteria + \"-\" + minReports + \"-\" + classifier + \"-\"\n\t\t\t\t+ weightScheme + \"-\" + smoothing + \"-\" + svmCostParameter + \"-\" + Constants.ALPHA + \"-\" + source + \"-\"\n\t\t\t\t+ stoplist + \"-\" + ngrams + \"-\" + sentenceDetector + \"-\" + tokenizer + \"-\" + stemmer + \"-\" + chunker + \"-\" + target\n\t\t\t\t+ \"-\" + meta + \"-\" + patientYear).toLowerCase();\n\t}\n\n}", "public class Constants {\n\n\tpublic static final int THREADS = 1;\n\tpublic static final int CONNECTIONS = THREADS * 2;\n\n\t// TODO change to something better, maybe setting automatically on the main method.\n\tpublic static final boolean RECREATE_DB = true;\n\tpublic static final int BATCH_SIZE = 100;\n\n\t// TODO move to a config file\n\t/** Root directory where reference tables are located. */\n\tpublic static final String REF_DIR = \"src/ref/\";\n\n\t/** Directory containing large data files. */\n\tpublic static final String DATA_DIR = \"src/data/\";\n\n\t// TODO defined in models.xml for CoGrOO implementation. May not be necessary.\n\t/** Directory containing models (e.g. OpenNLP models). */\n\tpublic static final String MODEL_DIR = \"src/models/\";\n\n\t/** Defines if a cache of instances is used or not. */\n\tpublic static final boolean CACHE = false;\n\n\t/** Indicates wheter to generate stats or not. */\n\tpublic static final boolean STATS = false;\n\n\tpublic static final float TEST_RATIO = 0.1f;\n\t// public static final int THRESHOLD = 10;\n\n\t// TODO move to a class smoothing or something\n\tpublic static final double ALPHA = 0.5d;\n\n\tpublic static Configuration CONFIG;\n\n}", "public class DAOFactory {\r\n\t// TODO migrate to JPA Persistence:\r\n\t// http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/\r\n\tprivate static final int CONNECTIONS = Constants.CONNECTIONS;\r\n\r\n\tprivate static final DAOFactory instance = new DAOFactory();\r\n\r\n\tpublic static DAOFactory getDAOFactory() {\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tprivate SessionFactory sessionFactory;\r\n\tprivate Session[] session = new Session[CONNECTIONS];\r\n\r\n\tprivate TopographyDAO[] topographyDAO = new TopographyDAO[CONNECTIONS];\r\n\tprivate TopographyCategoryDAO[] topographyCategoryDAO = new TopographyCategoryDAO[CONNECTIONS];\r\n\tprivate TopographyGroupDAO[] topographyGroupDAO = new TopographyGroupDAO[CONNECTIONS];\r\n\r\n\tprivate MorphologyDAO[] morphologyDAO = new MorphologyDAO[CONNECTIONS];\r\n\tprivate MorphologyGroupDAO[] morphologyGroupDAO = new MorphologyGroupDAO[CONNECTIONS];\r\n\r\n\tprivate DceDAO[] dceDAO = new DceDAO[CONNECTIONS];\r\n\tprivate SighDAO[] sighDAO = new SighDAO[CONNECTIONS];\r\n\tprivate RhcDAO[] rhcDAO = new RhcDAO[CONNECTIONS];\r\n\tprivate PatientDAO[] patientDAO = new PatientDAO[CONNECTIONS];\r\n\r\n\tprivate DAOFactory() {\r\n\t\tAnnotationConfiguration cfg = new AnnotationConfiguration();\r\n\r\n\t\tcfg.addAnnotatedClass(Topography.class);\r\n\t\tcfg.addAnnotatedClass(TopographyCategory.class);\r\n\t\tcfg.addAnnotatedClass(TopographyGroup.class);\r\n\r\n\t\tcfg.addAnnotatedClass(Morphology.class);\r\n\t\tcfg.addAnnotatedClass(MorphologyGroup.class);\r\n\r\n\t\tcfg.addAnnotatedClass(RHC.class);\r\n\t\tcfg.addAnnotatedClass(DCE.class);\r\n\t\tcfg.addAnnotatedClass(SighReport.class);\r\n\t\tcfg.addAnnotatedClass(Patient.class);\r\n\t\tcfg.configure();\r\n\r\n\t\t// TODO set fetch size according to Constants.BATCH_SIZE\r\n\r\n\t\tif (Constants.RECREATE_DB) {\r\n\t\t\tSchemaExport se = new SchemaExport(cfg);\r\n\t\t\tse.create(true, true);\r\n\t\t}\r\n\r\n\t\tthis.sessionFactory = cfg.buildSessionFactory();\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tsession[i] = sessionFactory.openSession();\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyDAO[i] = new TopographyDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyCategoryDAO[i] = new TopographyCategoryDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\ttopographyGroupDAO[i] = new TopographyGroupDAO(session[i]);\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tmorphologyDAO[i] = new MorphologyDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tmorphologyGroupDAO[i] = new MorphologyGroupDAO(session[i]);\r\n\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tdceDAO[i] = new DceDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tsighDAO[i] = new SighDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\trhcDAO[i] = new RhcDAO(session[i]);\r\n\t\tfor (int i = 0; i < CONNECTIONS; i++)\r\n\t\t\tpatientDAO[i] = new PatientDAO(session[i]);\r\n\t}\r\n\r\n\tint sess = 0;\r\n\r\n\tprivate int getNextSession() {\r\n\t\tsess++;\r\n\t\tif (sess >= CONNECTIONS)\r\n\t\t\tsess = 0;\r\n\t\treturn sess;\r\n\t}\r\n\r\n\tpublic ClassifiableDAO getIcdClassDAO() {\r\n\t\tswitch (Constants.CONFIG.getTarget()) {\r\n\t\tcase MORPHOLOGY:\r\n\t\t\treturn (ClassifiableDAO) getMorphologyDAO();\r\n\t\tcase MORPHOLOGY_GROUP:\r\n\t\t\treturn (ClassifiableDAO) getMorphologyGroupDAO();\r\n\t\tcase TOPOGRAPHY:\r\n\t\t\treturn (ClassifiableDAO) getTopographyDAO();\r\n\t\tcase TOPOGRAPHY_CATEGORY:\r\n\t\t\treturn (ClassifiableDAO) getTopographyCategoryDAO();\r\n\t\tcase TOPOGRAPHY_GROUP:\r\n\t\t\treturn (ClassifiableDAO) getTopographyGroupDAO();\r\n\t\tdefault:\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic TopographyDAO getTopographyDAO() {\r\n\t\treturn topographyDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic TopographyCategoryDAO getTopographyCategoryDAO() {\r\n\t\treturn topographyCategoryDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic TopographyGroupDAO getTopographyGroupDAO() {\r\n\t\treturn topographyGroupDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic MorphologyDAO getMorphologyDAO() {\r\n\t\treturn morphologyDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic MorphologyGroupDAO getMorphologyGroupDAO() {\r\n\t\treturn morphologyGroupDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic DceDAO getDceDAO() {\r\n\t\treturn dceDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic SighDAO getSighDAO() {\r\n\t\treturn sighDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic RhcDAO getRhcDAO() {\r\n\t\treturn rhcDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic PatientDAO getPatientDAO() {\r\n\t\treturn patientDAO[getNextSession()];\r\n\t}\r\n\r\n\tpublic void close() {\r\n\t\tfor (Session s : session)\r\n\t\t\ts.close();\r\n\t\tsessionFactory.close();\r\n\t}\r\n\r\n}\r", "public class PatientDAO {\r\n\tprivate Session session;\r\n\r\n\t// public static final String USER_ENTITY = Patient.class.getName();\r\n\r\n\tpublic PatientDAO(Session session) {\r\n\t\tthis.session = session;\r\n\t}\r\n\r\n\tpublic void save(Patient p) {\r\n\t\tthis.session.save(p);\r\n\t}\r\n\r\n\tpublic void delete(Patient p) {\r\n\t\tthis.session.delete(p);\r\n\t}\r\n\r\n\tpublic Patient load(Long id) {\r\n\t\treturn (Patient) this.session.load(Patient.class, id);\r\n\t}\r\n\r\n\tpublic Patient locate(Integer rgh) {\r\n\t\treturn (Patient) this.session.createCriteria(Patient.class)\r\n\t\t\t\t.add(Restrictions.eq(\"rgh\", rgh)).uniqueResult();\r\n\t}\r\n\t\r\n\tpublic Integer count() {\r\n\t\treturn (Integer) this.session.createCriteria(Patient.class).setProjection(Projections.rowCount()).uniqueResult();\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Patient> list() {\r\n\t\treturn this.session.createCriteria(Patient.class).addOrder(Order.asc(\"rgh\")).list();\r\n\t}\r\n\r\n\tpublic void update(Patient p) {\r\n\t\tthis.session.update(p);\r\n\t}\r\n\t\r\n\tpublic void saveOrUpdate(Patient p) {\r\n\t\tthis.session.saveOrUpdate(p);\r\n\t}\r\n\t\r\n\tpublic void beginTransaction() {\r\n\t\tthis.session.beginTransaction();\r\n\t}\r\n\t\r\n\tpublic void commit() {\r\n\t\tthis.session.getTransaction().commit();\r\n\t}\r\n\t\r\n\tpublic void flushAndClear() {\r\n\t\tthis.session.flush();\r\n\t\tthis.session.clear();\r\n\t}\r\n\t\r\n\tpublic void merge(Patient p) {\r\n\t\tthis.session.merge(p);\r\n\t}\r\n}\r", "public class DCELoader extends Thread {\r\n\r\n\t// Longest known valid sequence of numbers has 15 characters.\r\n\tprivate static final Pattern HEXA = Pattern.compile(\"[a-f0-9]{20,}\");\r\n\r\n\tprivate static final String SECTION_DIVIDER = \"---------\";\r\n\r\n\t// Ordered by corpus frequency\r\n\tprivate static final Map<String, Configuration.Sections> sectionsTranslator = new HashMap<String, Configuration.Sections>();\r\n\tstatic {\r\n\t\tsectionsTranslator.put(\"MACROSCOPIA\", Configuration.Sections.MACROSCOPY);\r\n\t\tsectionsTranslator.put(\"MICROSCOPIA\", Configuration.Sections.MICROSCOPY);\r\n\t\tsectionsTranslator.put(\"EXAME CITOPATOLÓGICO CÉRVICO-VAGINAL\", Configuration.Sections.CYTOPATHOLOGY);\r\n//\t\tsections.add(\"LAUDO COMPLEMENTAR DE IMUNOISTOQUÍMICA\");\r\n//\t\tsections.add(\"IMUNOISTOQUÍMICA\");\r\n//\t\tsections.add(\"REVISÃO DE LMINAS\");\t// sic\r\n//\t\tsections.add(\"EXAME CITOLÓGICO\");\r\n//\t\tsections.add(\"PUNÇÃO ASPIRATIVA\");\r\n\t\tsectionsTranslator.put(\"EXAME CITOPATOLÓGICO CÉRVICO-VAGINAL EM MEIO LÍQUIDO\", Configuration.Sections.LIQUID_CYTOPATHOLOGY);\r\n\t}\r\n\r\n\t/**\r\n\t * reportId => patientId\r\n\t */\r\n\tprivate Map<Integer, Integer> map;\r\n\r\n\tprivate File dir;\r\n\r\n\tprivate DceDAO dceDao = DAOFactory.getDAOFactory().getDceDAO();\r\n\tprivate PatientDAO patientDao = DAOFactory.getDAOFactory().getPatientDAO();\r\n\r\n\tprivate static final Logger LOG = Logger.getLogger(DCELoader.class);\r\n\r\n\tpublic DCELoader(Map<Integer, Integer> map, File dir) {\r\n\t\tthis.map = map;\r\n\t\tthis.dir = dir;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tint total = map.keySet().size();\r\n\r\n\t\tdceDao.beginTransaction();\r\n\r\n\t\tStringBuilder sb = null;\r\n\t\tIterator<Map.Entry<Integer, Integer>> iter = map.entrySet().iterator();\r\n\r\n\t\tString line = null, oldText = null, newText = null;\r\n\t\tBufferedReader br = null;\r\n\r\n\t\t// zoneDescription => text\r\n\t\tMap<Configuration.Sections, String> sections = null;\r\n\t\tConfiguration.Sections currentSection = null;\r\n\r\n\t\tint i = -1;\r\n\t\tlong start = System.currentTimeMillis();\r\n\r\n\t\t// Runs for each file\r\n\t\twhile (iter.hasNext()) {\r\n\t\t\ti++;\r\n\t\t\tif (i % Constants.BATCH_SIZE == 0) {\r\n\t\t\t\tlong now = System.currentTimeMillis();\r\n\t\t\t\tdouble milisecondsPerEntry = (now - start) / (double) i;\r\n\t\t\t\tint remain = (int) ((milisecondsPerEntry * (total - i)) / 1000);\r\n\t\t\t\tLOG.debug(i + \"/\" + total + \" (\" + 100 * i / total + \"%) \" + remain + \" seconds remaining\");\r\n\t\t\t\tdceDao.flushAndClear();\r\n\t\t\t}\r\n\r\n\t\t\tMap.Entry<Integer, Integer> entry = iter.next();\r\n\t\t\tInteger laudoId = entry.getKey();\r\n\t\t\tInteger rgh = entry.getValue();\r\n\r\n\t\t\tFile f = new File(dir, laudoId + \".txt\");\r\n\t\t\tif (!f.exists() || !f.canRead()) {\r\n\t\t\t\tSystem.err.println(\"Cannot read file \" + f.getName());\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\ttry {\r\n\t\t\t\tbr = new BufferedReader(new InputStreamReader(new FileInputStream(f), \"UTF-8\"));\r\n\t\t\t\tsb = new StringBuilder();\r\n\t\t\t\tsections = new HashMap<Configuration.Sections, String>();\r\n\t\t\t\tcurrentSection = null;\r\n\r\n\t\t\t\t// The first section might not be prepended by the section\r\n\t\t\t\t// divider.\r\n\t\t\t\tline = br.readLine();\r\n\t\t\t\tif (!line.equals(\"\")) {\r\n\t\t\t\t\tcurrentSection = getNewSection(line);\r\n\t\t\t\t\tsb.append(line);\r\n\t\t\t\t\tsb.append(\"\\n\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Runs for each line\r\n\t\t\t\tfor (line = br.readLine(); line != null; line = br.readLine()) {\r\n\t\t\t\t\tline = HEXA.matcher(line).replaceAll(\"\");\r\n\r\n\t\t\t\t\t// After the section divider, we have the section header.\r\n\t\t\t\t\tif (line.equals(SECTION_DIVIDER)) {\r\n\t\t\t\t\t\t// currentSection == null iff the file starts with a section divider\r\n\t\t\t\t\t\tif (currentSection != null) {\r\n\t\t\t\t\t\t\tnewText = sb.toString();\r\n\t\t\t\t\t\t\toldText = \"\";\r\n\t\t\t\t\t\t\t// Updates the current section with the new value.\r\n\t\t\t\t\t\t\t// Should not happen that often, if ever.\r\n\t\t\t\t\t\t\tif (sections.containsKey(currentSection)) {\r\n\t\t\t\t\t\t\t\tLOG.debug(\"Found a document with at least two \" + currentSection + \" sections in file \" + f.getName());\r\n\t\t\t\t\t\t\t\toldText = sections.get(currentSection);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tsections.put(currentSection, oldText + newText);\r\n\t\t\t\t\t\t\tsb = new StringBuilder();\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tline = br.readLine();\r\n\t\t\t\t\t\tcurrentSection = getNewSection(line);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsb.append(line);\r\n\r\n\t\t\t\t\t// TODO change to OS dependent line separator (is Weka\r\n\t\t\t\t\t// compatible?)\r\n\t\t\t\t\tsb.append(\"\\n\");\r\n\t\t\t\t}\r\n\t\t\t\tbr.close();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tPatient p = patientDao.locate(rgh);\r\n\r\n\t\t\tDCE dce = new DCE(laudoId, sections);\r\n\t\t\tp.addDCE(dce);\r\n\t\t\tdceDao.save(dce);\r\n\t\t}\r\n\r\n\t\tdceDao.commit();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Check if the found section should be stratified\r\n\t * @param lineHeader\r\n\t * @return\r\n\t */\r\n\tprivate Configuration.Sections getNewSection(String lineHeader) {\r\n\t\tif (sectionsTranslator.containsKey(lineHeader)) {\r\n\t\t\treturn sectionsTranslator.get(lineHeader);\r\n\t\t} else {\r\n\t\t\tLOG.trace(\"Found non-default header: \" + lineHeader + \".\");\r\n\t\t\treturn Configuration.Sections.OTHERS;\r\n\t\t}\r\n\t}\r\n}\r" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.apache.log4j.Logger; import org.hibernate.annotations.Index; import br.usp.ime.icdc.Configuration; import br.usp.ime.icdc.Constants; import br.usp.ime.icdc.dao.DAOFactory; import br.usp.ime.icdc.dao.PatientDAO; import br.usp.ime.icdc.run.loader.DCELoader;
package br.usp.ime.icdc.model; @Entity public class DCE implements Report { @Id @GeneratedValue private Long id; @Column @Index(name = "internalid_ndx") private Integer hospitalId; // Longest known (939586) contains 21448 characters. @Column(length = 30000) @Deprecated private String text; // TODO change fields to aggregation, with classes that implements a well-defined interface. @Column(length = 100000) private String macroscopy; @Column(length = 100000) private String microscopy; @Column(length = 100000) private String cytopathology; @Column(length = 100000) private String liquidCytopathology; @Column(length = 100000) private String others; // bidirectional relationship @ManyToOne @JoinColumn(name = "patient_fk") private Patient rgh; public DCE() { } public void setRgh(Patient rgh) { this.rgh = rgh; } @Deprecated public DCE(Integer hospitalId, String text) { this.hospitalId = hospitalId; this.text = text; } public DCE(Integer hospitalId, String macroscopy, String microscopy, String cytopathology, String liquidCytopathology, String others) { this.hospitalId = hospitalId; this.macroscopy = macroscopy; this.microscopy = microscopy; this.cytopathology = cytopathology; this.liquidCytopathology = liquidCytopathology; this.others = others; }
public DCE(Integer hospitalId, Map<Configuration.Sections, String> sections) {
0
TheClimateCorporation/mirage
samples/src/main/java/com/climate/mirage/app/SettingsActivity.java
[ "public class Mirage {\n\n\t/**\n\t * Location of where the resource came from\n\t */\n\tpublic static enum Source {\n\t\tMEMORY,\n\t\tDISK,\n\t\tEXTERNAL\n\t}\n\n\tpublic static final Executor THREAD_POOL_EXECUTOR = new MirageExecutor();\n\n\tprivate static final String TAG = Mirage.class.getSimpleName();\n\tprivate static Mirage mirage;\n\tprivate Executor defaultExecutor;\n\tprivate MemoryCache<String, Bitmap> defaultMemoryCache;\n\tprivate DiskCache defaultDiskCache;\n\tprivate UrlFactory defaultUrlConnectionFactory;\n\tprivate Map<Object, MirageTask> runningRequests;\n\tprivate LoadErrorManager loadErrorManager;\n\tprivate ObjectPool<MirageRequest> requestObjectPool;\n\tprivate Context applicationContext;\n private ActivityLifecycleStub activityLifecycles;\n\n\tpublic Mirage(Context applicationContext) {\n\t\tthis.applicationContext = applicationContext.getApplicationContext();\n\t\trequestObjectPool = new ObjectPool<>(new MirageRequestFactory(), 50);\n\t\tloadErrorManager = new LoadErrorManager();\n\t\trunningRequests = Collections.synchronizedMap(new HashMap<Object, MirageTask>());\n\t\tdefaultUrlConnectionFactory = new SimpleUrlConnectionFactory();\n\t\t((Application)this.applicationContext).registerActivityLifecycleCallbacks(activityLifecycles = new ActivityLifecycleStub() {\n\t\t\t@Override\n\t\t\tpublic void onActivityDestroyed(Activity activity) {\n\t\t\t\tIterator<Map.Entry<Object, MirageTask>> it = runningRequests.entrySet().iterator();\n\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\tMap.Entry<Object, MirageTask> item = it.next();\n\t\t\t\t\tif (item.getKey() instanceof View) {\n\t\t\t\t\t\tContext context = ((View)item.getKey()).getContext();\n\t\t\t\t\t\tif (activity == context) {\n\t\t\t\t\t\t\tit.remove();\n\t\t\t\t\t\t\tMirageTask task = item.getValue();\n\t\t\t\t\t\t\tif (task != null) task.mirageCancel();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tsynchronized public static void set(Mirage mirage) {\n\t\tMirage.mirage = mirage;\n\t}\n\n\tsynchronized public static Mirage get(Context context) {\n\t\tif (mirage == null) {\n\t\t\tmirage = new Mirage(context.getApplicationContext());\n\t\t\tmirage.defaultMemoryCache = new BitmapLruCache(0.25f);\n\t\t\tmirage.defaultDiskCache = new DiskLruCacheWrapper(\n\t\t\t\t\tnew DiskLruCacheWrapper.SharedDiskLruCacheFactory(\n\t\t\t\t\t\t\tnew File(context.getCacheDir(), \"mirage\"),\n\t\t\t\t\t\t\t50 * 1024 * 1024));\n\t\t\tmirage.defaultExecutor = THREAD_POOL_EXECUTOR;\n\t\t}\n\t\treturn mirage;\n\t}\n\n /**\n * If you create a mirage instance directly, call this to cancel all pending tasks\n * and to release application resources.\n */\n public void dispose() {\n ((Application)applicationContext).unregisterActivityLifecycleCallbacks(activityLifecycles);\n Iterator<Map.Entry<Object, MirageTask>> it = runningRequests.entrySet().iterator();\n while (it.hasNext()) {\n Map.Entry<Object, MirageTask> item = it.next();\n it.remove();\n MirageTask task = item.getValue();\n if (task != null) task.mirageCancel();\n }\n }\n\n\tpublic MirageRequest load(String uri) {\n\t\tif (TextUtils.isEmpty(uri)) return load((Uri)null);\n\t\treturn load(Uri.parse(uri));\n\t}\n\n\tpublic MirageRequest load(File file) {\n\t\tif (file == null) return load((Uri)null);\n return load(Uri.fromFile(file));\n\t}\n\n\t/**\n\t * Method for loading from the drawables folders\n\t * @param resId\n\t * @return\n\t */\n\tpublic MirageRequest load(@AnyRes int resId) {\n\t\tResources res = applicationContext.getResources();\n\t\tUri uri = Uri.parse(SCHEME_ANDROID_RESOURCE +\n\t\t\t\t\"://\" + res.getResourcePackageName(resId)\n\t\t\t\t+ '/' + res.getResourceTypeName(resId)\n\t\t\t\t+ '/' + res.getResourceEntryName(resId));\n\t\treturn load(uri);\n\t}\n\n public MirageRequest load(BitmapProvider provider) {\n MirageRequest r = load((Uri)null);\n return r.provider(provider);\n }\n\n\t/**\n\t * The URI of the asset to load. Types of Uri's supported include\n\t * http, https, file, and content\n\t *\n\t * @see android.net.Uri#parse(String)\n\t * @see android.net.Uri#fromFile(java.io.File)\n\t *\n\t * @param uri the uri to load\n\t * @return an new (or recycled) {@link com.climate.mirage.requests.MirageRequest} instance to daisy chain\n\t */\n\tpublic MirageRequest load(Uri uri) {\n\t\tMirageRequest r = requestObjectPool.getObject();\n r.mirage(this);\n\t\tif (uri == null || TextUtils.isEmpty(uri.toString())) {\n\t\t return r;\n }\n\n\t\tString scheme = uri.getScheme();\n\n\t\t// if this is a file or content resource, no need to cache all.\n // default to just caching the result\n\t\tif (!TextUtils.isEmpty(scheme)) {\n\t\t\tif (scheme.startsWith(SCHEME_FILE) ||\n\t\t\t\t\tscheme.startsWith(SCHEME_ANDROID_RESOURCE) ||\n scheme.startsWith(SCHEME_CONTENT)) {\n\t\t\t\tr.diskCacheStrategy(DiskCacheStrategy.RESULT);\n\t\t\t}\n\t\t}\n\n BitmapProvider provider;\n if (scheme.startsWith(SCHEME_FILE)) {\n\t\t provider = new FileProvider(r);\n } else if (scheme.startsWith(SCHEME_CONTENT) ||\n scheme.startsWith(SCHEME_ANDROID_RESOURCE)) {\n provider = new ContentUriProvider(applicationContext, r);\n } else {\n provider = new UriProvider(r);\n }\n r.uri(uri);\n\t\tr.provider(provider);\n\t\treturn r;\n\t}\n\t\n\t/**\n\t * Fires off the loading asynchronous. Mostly likely you will not access this directly\n\t * but instead go through {@link com.climate.mirage.targets.ImageViewTarget#go()}\n\t * or {@link com.climate.mirage.requests.MirageRequest#go()}\n\t *\n\t * @param request the configured request for the resource to load\n\t * @return The AsyncTask responsible for running the request. It could be null if the resource is in the memory cache\n\t */\n @MainThread\n\tpublic MirageTask go(MirageRequest request) {\n\t\tMirageTask<Void, Void, Bitmap> task = createGoTask(request);\n return executeGoTask(task, request);\n\t}\n\n /**\n * Creates the go task that Mirage will run without actually running it yet.\n\n * @param request the configured request for the resource to load.\n * @return\n */\n public MirageTask<Void, Void, Bitmap> createGoTask(MirageRequest request) {\n cancelRequest(request.target());\n\n // if the url is blank, fault out immediately\n if ((request.uri() == null || TextUtils.isEmpty(request.uri().toString()))\n && request.provider() == null) {\n if (request.target() != null) request.target().onError(\n new IllegalArgumentException(\"Uri is null\"), Source.MEMORY,\n request);\n return null;\n }\n\n MirageTask<Void, Void, Bitmap> task = new BitmapTask(this, request, loadErrorManager, bitmapGoTaskCallback);\n addRequestToList(request, task);\n return task;\n }\n\n /**\n * Runs the go task.\n *\n * @param task the mirage task\n * @param request the configured request for the resource to load\n * @return The AsyncTask responsible for running the request. It could be null if the resource is in the memory cache\n */\n\tpublic MirageTask<Void, Void, Bitmap> executeGoTask(MirageTask<Void, Void, Bitmap> task, MirageRequest request) {\n if (task == null || task.isCancelled()) {\n return null;\n }\n\n // exit early if the lifecycle is not active.\n Lifecycle lifecycle = request.lifecycle();\n if (lifecycle != null && lifecycle.getCurrentState() == Lifecycle.State.DESTROYED) {\n \treturn null;\n\t\t}\n\n // TODO: clean up this duplicate\n if (request.memoryCache() == null) request.memoryCache(defaultMemoryCache);\n if (request.diskCache() == null) request.diskCache(defaultDiskCache);\n if (request.executor() == null) request.executor(defaultExecutor);\n if (request.urlFactory() == null) request.urlFactory(defaultUrlConnectionFactory);\n\n // if the url is blank, fault out immediately\n // TODO: clean up this duplicate\n if ((request.uri() == null || TextUtils.isEmpty(request.uri().toString()))\n && request.provider() == null) {\n if (request.target() != null) request.target().onError(\n new IllegalArgumentException(\"Uri is null\"), Source.MEMORY,\n request);\n return null;\n }\n\n Bitmap resource;\n\n // Check immediately if the resource is in the memory cache\n MemoryCache<String, Bitmap> memCache = request.memoryCache();\n if (memCache != null) {\n resource = memCache.get(request.getResultKey());\n if (resource != null) {\n if (request.target() != null) request.target().onResult(resource,\n Source.MEMORY, request);\n return null;\n }\n }\n\n // Check immediately if the resource is in the error cache\n LoadError error = getLoadError(request.provider().id());\n if (error != null && error.isValid()) {\n if (request.target() != null) request.target().onError(error.getException(),\n Source.MEMORY, request);\n return null;\n }\n\n\t\tExecutor executor = request.executor();\n\t\tif (request.target() != null) request.target().onPreparingLoad();\n task.executeOnExecutor(executor);\n return task;\n\t}\n\n\n\t/**\n\t * Fires off the loading synchronous.\n\t *\n\t * @param request the configured request for the resource to load\n\t * @return the loaded resource\n\t */\n @WorkerThread\n\tpublic Bitmap goSync(MirageRequest request) throws MirageIOException, InterruptedIOException {\n\t\tif (isMainThread()) throw new NetworkOnMainThreadException();\n\t\tif (request.target() != null) throw new IllegalArgumentException(\"goSync does not allow for callbacks\");\n\n\t\tif (request.memoryCache() == null) request.memoryCache(defaultMemoryCache);\n\t\tif (request.diskCache() == null) request.diskCache(defaultDiskCache);\n\t\tif (request.executor() == null) request.executor(defaultExecutor);\n\t\tif (request.urlFactory() == null) request.urlFactory(defaultUrlConnectionFactory);\n\n cancelRequest(request.target());\n\n MirageTask<Void, Void, Bitmap> task = createGoTask(request);\n if (task == null) return null;\n Bitmap bitmap;\n try {\n \tbitmap = task.doTask();\n\t\t} finally {\n\t\t\trequestObjectPool.recycle(request);\n\t\t}\n\t\treturn bitmap;\n\t}\n\n\t/**\n\t * Fires off the loading asynchronous. The return returned to the target here will be a\n\t * File reference and not a bitmap.\n\t *\n\t * @param request the configured request for the resource to load\n\t * @return The AsyncTask responsible for running the request. It could be null if the resource is in the memory cache\n\t */\n\tpublic MirageTask downloadOnly(MirageRequest request) {\n\t\tif (request.memoryCache() == null) request.memoryCache(defaultMemoryCache);\n\t\tif (request.diskCache() == null) request.diskCache(defaultDiskCache);\n\t\tif (request.executor() == null) request.executor(defaultExecutor);\n\t\tif (request.urlFactory() == null) request.urlFactory(defaultUrlConnectionFactory);\n\t\tcancelRequest(request.target());\n\n\t\t// TODO: dont cache if the thread has been interrupted\n // FIXME: Can i modify the others tasks so I dont have to make a new task here?\n\t\tBitmapDownloadTask task = new BitmapDownloadTask(this, request, loadErrorManager, downloadTaskCallback);\n\t\taddRequestToList(request, task);\n\t\tif (request.target() != null) request.target().onPreparingLoad();\n\t\ttask.executeOnExecutor(request.executor());\n\t\treturn task;\n\t}\n\n\t/**\n\t * Fires off the loading synchronous. The return returned to the target here will be a\n\t * File reference and not a bitmap. This is good to use when in a sync adapter to where\n\t * the caching file never needs to go into memory just into a sync cache.\n\t *\n\t * @param request the configured request for the resource to load\n\t * @return The file location the image was loaded to. If the cache strategy is\n\t * \t\t{@link com.climate.mirage.cache.disk.DiskCacheStrategy#ALL} the return file\n\t * \t\tis from the result and not source.\n\t */\n\tpublic File downloadOnlySync(MirageRequest request) throws MirageIOException {\n\t\tif (isMainThread()) throw new NetworkOnMainThreadException();\n\t\tif (request.target() != null) throw new IllegalArgumentException(\"/downloadOnlySync does not allow for callbacks\");\n\n\t\tif (request.memoryCache() == null) request.memoryCache(defaultMemoryCache);\n\t\tif (request.diskCache() == null) request.diskCache(defaultDiskCache);\n\t\tif (request.executor() == null) request.executor(defaultExecutor);\n\t\tif (request.urlFactory() == null) request.urlFactory(new SimpleUrlConnectionFactory());\n\n\t\tBitmapDownloadTask task = new BitmapDownloadTask(this, request, loadErrorManager, null);\n\t\tFile file = task.doTask();\n\t\trequestObjectPool.recycle(request);\n\t\treturn file;\n\t}\n\n\t/**\n\t * Cancels a loading request or nothing if one doesn't exist.\n\t *\n\t * @param target The target as defined in the request\n\t */\n\tpublic void cancelRequest(Target target) {\n\t\tif (target instanceof ViewTarget) {\n\t\t\tView view = ((ViewTarget) target).getView();\n\t\t\tif (view != null) {\n\t\t\t\tcancelRequest(view);\n\t\t\t}\n\t\t} else {\n\t\t\tMirageTask t = runningRequests.remove(target);\n\t\t\tif (t != null) {\n\t\t\t\tt.mirageCancel();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Cancels a loading request or nothing if one doesn't exist.\n\t *\n\t * @param view The view the which the resource was going into.\n\t */\n\tpublic void cancelRequest(View view) {\n\t\tMirageTask t = runningRequests.remove(view);\n\t\tif (t != null) {\n t.mirageCancel();\n\t\t}\n\t}\n\n\t/**\n\t * Clear all caches. This is safe to run from the UI thread as it will background automatically if needed\n\t */\n\tpublic void clearCache() {\n\t\tclearMemoryCache();\n\t\tclearDiskCache();\n\t}\n\n\t/**\n\t * Removes a saved result or source resource from the memory and disk cache\n\t *\n\t * @param request The request which can hit the cache\n\t */\n\tpublic void removeFromCache(MirageRequest request) {\n\t\tfinal String sourceKey = request.getSourceKey();\n\t\tfinal String resultKey = request.getResultKey();\n\n\t\tif (defaultMemoryCache != null) {\n\t\t\tdefaultMemoryCache.remove(resultKey);\n\t\t}\n\n\t\tif (defaultDiskCache != null) {\n\t\t\tif (isMainThread()) {\n\t\t\t\tnew AsyncTask<Void, Void, Void>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected Void doInBackground(Void... params) {\n\t\t\t\t\t\tif (defaultDiskCache != null) {\n\t\t\t\t\t\t\tdefaultDiskCache.delete(resultKey);\n\t\t\t\t\t\t\tif (resultKey != null && !resultKey.equals(sourceKey)) {\n\t\t\t\t\t\t\t\tdefaultDiskCache.delete(sourceKey);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}.execute();\n\t\t\t}\n\n\t\t\t// if on a BG thread\n\t\t\telse {\n\t\t\t\tdefaultDiskCache.delete(resultKey);\n\t\t\t\tif (resultKey != null && !resultKey.equals(sourceKey)) {\n\t\t\t\t\tdefaultDiskCache.delete(sourceKey);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Clears the default memory cache.\n\t */\n\tpublic void clearMemoryCache() {\n\t\tif (defaultMemoryCache != null) defaultMemoryCache.clear();\n\t}\n\n\t/**\n\t * Clears the default disk cache\n\t */\n\tpublic void clearDiskCache() {\n\t\tif (defaultDiskCache != null) {\n\t\t\tif (isMainThread()) {\n\t\t\t\tnew AsyncTask<Void, Void, Void>() {\n\t\t\t\t\t@Override\n\t\t\t\t\tprotected Void doInBackground(Void... params) {\n\t\t\t\t\t\tif (defaultDiskCache != null) defaultDiskCache.clear();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}.execute();\n\t\t\t}\n\n\t\t\t// if on a BG thread\n\t\t\telse {\n\t\t\t\tdefaultDiskCache.clear();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setDefaultUrlConnectionFactory(UrlFactory defaultUrlConnectionFactory) {\n\t\tthis.defaultUrlConnectionFactory = defaultUrlConnectionFactory;\n\t}\n\n\tpublic Executor getDefaultExecutor() {\n\t\treturn defaultExecutor;\n\t}\n\n\tpublic Mirage setDefaultExecutor(Executor defaultExecutor) {\n\t\tthis.defaultExecutor = defaultExecutor;\n\t\treturn this;\n\t}\n\n\tpublic Mirage setDefaultMemoryCache(MemoryCache<String, Bitmap> defaultMemoryCache) {\n\t\tthis.defaultMemoryCache = defaultMemoryCache;\n\t\treturn this;\n\t}\n\n\tpublic MemoryCache<String, Bitmap> getDefaultMemoryCache() {\n\t\treturn defaultMemoryCache;\n\t}\n\n\tpublic Mirage setDefaultDiskCache(DiskCache defaultDiskCache) {\n\t\tthis.defaultDiskCache = defaultDiskCache;\n\t\treturn this;\n\t}\n\n\tpublic DiskCache getDefaultDiskCache() {\n\t\treturn defaultDiskCache;\n\t}\n\n\tprivate boolean isMainThread() {\n\t\treturn Looper.myLooper() == Looper.getMainLooper();\n\t}\n\n\tprivate LoadError getLoadError(String id) {\n\t\treturn loadErrorManager.getLoadError(id);\n\t}\n\n\tprivate void addRequestToList(MirageRequest request, MirageTask task) {\n\t\tif (request.target() != null) {\n\t\t\tif (request.target() instanceof ViewTarget) {\n\t\t\t\tView view = ((ViewTarget)request.target()).getView();\n\t\t\t\tif (view != null) {\n\t\t\t\t\trunningRequests.put(view, task);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trunningRequests.put(request.target(), task);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate BitmapTask.Callback<Bitmap> bitmapGoTaskCallback = new BitmapTask.Callback<Bitmap>() {\n\t\t@Override\n\t\tpublic void onCancel(MirageTask task, MirageRequest request) {\n\t\t\tremoveSavedTask(request, task);\n\t\t\trequestObjectPool.recycle(request);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPostExecute(MirageTask task, MirageRequest request, Bitmap bitmap) {\n\t\t\tremoveSavedTask(request, task);\n\t\t\trequestObjectPool.recycle(request);\n\t\t}\n\t};\n\n\tprivate BitmapDownloadTask.Callback<File> downloadTaskCallback = new BitmapDownloadTask.Callback<File>() {\n\t\t@Override\n\t\tpublic void onCancel(MirageTask task, MirageRequest request) {\n\t\t\tremoveSavedTask(request, task);\n\t\t\trequestObjectPool.recycle(request);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPostExecute(MirageTask task, MirageRequest request, File file) {\n\t\t\tremoveSavedTask(request, task);\n\t\t\trequestObjectPool.recycle(request);\n\t\t}\n\t};\n\n\tprivate void removeSavedTask(MirageRequest request, AsyncTask task) {\n\t\tif (request.target() != null) {\n\t\t\tif (request.target() instanceof ViewTarget) {\n\t\t\t\tView view = ((ViewTarget) request.target()).getView();\n\t\t\t\tif (view != null) {\n\t\t\t\t\tif (runningRequests.get(view) == task) {\n\t\t\t\t\t\tAsyncTask t = runningRequests.remove(view);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (runningRequests.get(request.target()) == task) {\n\t\t\t\t\tAsyncTask t = runningRequests.remove(request.target());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static class MirageRequestFactory implements ObjectFactory<MirageRequest> {\n\t\t@Override\n\t\tpublic MirageRequest create() {\n\t\t\treturn new MirageRequest();\n\t\t}\n\n\t\t@Override\n\t\tpublic void recycle(MirageRequest object) {\n\t\t\tobject.recycle();\n\t\t}\n\t}\n\n}", "public class CompositeDiskCache implements DiskCache {\n\n\tprivate List<DiskCache> leafs;\n\n\tpublic CompositeDiskCache(DiskCache... caches) {\n\t\tsynchronized (this) {\n\t\t\tleafs = new ArrayList<>();\n\t\t\tfor (int i=0; i<caches.length; i++) {\n\t\t\t\tleafs.add(caches[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic File get(String key) {\n\t\tsynchronized (this) {\n\t\t\tfor (int i=0; i<leafs.size(); i++) {\n\t\t\t\tDiskCache cache = leafs.get(i);\n\t\t\t\tFile file = cache.get(key);\n\t\t\t\tif (file != null) {\n\t\t\t\t\treturn file;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void put(String key, Writer writer) {\n\t\tsynchronized (this) {\n\t\t\tfor (int i=0; i<leafs.size(); i++) {\n\t\t\t\tDiskCache cache = leafs.get(i);\n\t\t\t\tcache.put(key, writer);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void delete(String key) {\n\t\tsynchronized (this) {\n\t\t\tfor (int i=0; i<leafs.size(); i++) {\n\t\t\t\tDiskCache cache = leafs.get(i);\n\t\t\t\tcache.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tsynchronized (this) {\n\t\t\tfor (int i=0; i<leafs.size(); i++) {\n\t\t\t\tDiskCache cache = leafs.get(i);\n\t\t\t\tcache.clear();\n\t\t\t}\n\t\t}\n\t}\n}", "public interface DiskCache {\n\n /**\n * An interface for lazily creating a disk cache.\n */\n interface Factory {\n /**\n * Returns a new disk cache, or {@code null} if no disk cache could be created.\n */\n DiskCache build();\n }\n\n /**\n * An interface to actually write data to a key in the disk cache.\n */\n interface Writer {\n /**\n * Writes data to the file and returns true if the write was successful and should be committed, and\n * false if the write should be aborted.\n *\n * @param file The File the Writer should write to.\n */\n boolean write(File file);\n }\n\n /**\n * Get the cache for the value at the given key.\n *\n * <p>\n * Note - This is potentially dangerous, someone may write a new value to the file at any point in timeand we\n * won't know about it.\n * </p>\n *\n * @param key The key in the cache.\n * @return An InputStream representing the data at key at the time get is called.\n */\n File get(String key);\n\n /**\n * Write to a key in the cache. {@link Writer} is used so that the cache implementation can perform actions after\n * the write finishes, like commit (via atomic file rename).\n *\n * @param key The key to write to.\n * @param writer An interface that will write data given an OutputStream for the key.\n */\n void put(String key, Writer writer);\n\n /**\n * Remove the key and value from the cache.\n *\n * @param key The key to remove.\n */\n void delete(String key);\n\n /**\n * Clear the cache.\n */\n void clear();\n}", "public class DiskLruCacheWrapper implements DiskCache {\n\n\tpublic static interface DiskLruCacheFactory {\n\t\tpublic DiskLruCache getDiskCache() throws IOException;\n\t\tpublic void resetDiskCache();\n\t}\n\n\tpublic static class SharedDiskLruCacheFactory implements DiskLruCacheFactory {\n\t\tprivate static Map<String, DiskLruCache> wrappers;\n\t\tprivate static final int APP_VERSION = 1;\n\t\tprivate static final int VALUE_COUNT = 1;\n\n\t\tstatic {\n\t\t\twrappers = Collections.synchronizedMap(new HashMap<String, DiskLruCache>());\n\t\t}\n\n\t\tprivate File directory;\n\t\tprivate int maxSize;\n\n\t\tpublic SharedDiskLruCacheFactory(File directory, int maxSize) {\n\t\t\tthis.directory = directory;\n\t\t\tthis.maxSize = maxSize;\n\t\t}\n\n\t\t@Override\n\t\tpublic DiskLruCache getDiskCache() throws IOException{\n\t\t\tif (wrappers.containsKey(directory.getAbsolutePath())) {\n\t\t\t\treturn wrappers.get(directory.getAbsolutePath());\n\t\t\t} else {\n\t\t\t\tif (!directory.exists()) {\n\t\t\t\t\tdirectory.mkdirs();\n\t\t\t\t\tboolean made = directory.isDirectory();\n\t\t\t\t}\n\t\t\t\tDiskLruCache diskLruCache = DiskLruCache.open(directory, APP_VERSION, VALUE_COUNT, maxSize);\n\t\t\t\twrappers.put(directory.getAbsolutePath(), diskLruCache);\n\t\t\t\treturn diskLruCache;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void resetDiskCache() {\n\t\t\tif (wrappers.containsKey(directory.getAbsolutePath())) {\n\t\t\t\twrappers.remove(directory.getAbsolutePath());\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static final String TAG = DiskLruCacheWrapper.class.getSimpleName();\n\tprivate DiskLruCacheFactory diskLruCacheFactory;\n\tvolatile private boolean isReadOnly = false;\n\n public DiskLruCacheWrapper(DiskLruCacheFactory diskLruCacheFactory) {\n this.diskLruCacheFactory = diskLruCacheFactory;\n }\n\n\t/**\n\t * Allows this cache to toggle between read &amp; write or just read-only mode. This is\n\t * useful for when data is being read from an offline sync cache, but we do not want to\n\t * add more data to the cache if it's read it from online.\n\t *\n\t * @param isReadOnly true if cache is read-only mode\n\t */\n\tsynchronized public void setReadOnly(boolean isReadOnly) {\n\t\tthis.isReadOnly = isReadOnly;\n\t}\n\n\t@Override\n public File get(String key) {\n String safeKey = key;\n File result = null;\n try {\n //It is possible that the there will be a put in between these two gets. If so that shouldn't be a problem\n //because we will always put the same value at the same key so our input streams will still represent\n //the same data\n final DiskLruCache.Value value = getDiskCache().get(safeKey);\n if (value != null) {\n result = value.getFile(0);\n }\n } catch (IOException e) {\n Log.w(TAG, \"Unable to get from disk cache\", e);\n }\n return result;\n }\n\n @Override\n public void put(String key, Writer writer) {\n\t\tif (isReadOnly) return;\n String safeKey = key;\n try {\n DiskLruCache.Editor editor = getDiskCache().edit(safeKey);\n // Editor will be null if there are two concurrent puts. In the worst case we will just silently fail.\n if (editor != null) {\n try {\n File file = editor.getFile(0);\n if (writer.write(file)) {\n editor.commit();\n }\n } finally {\n editor.abortUnlessCommitted();\n }\n }\n } catch (IOException e) {\n Log.w(TAG, \"Unable to put to disk cache\", e);\n }\n }\n\n @Override\n public void delete(String key) {\n String safeKey = key;\n try {\n getDiskCache().remove(safeKey);\n } catch (IOException e) {\n Log.w(TAG, \"Unable to delete from disk cache\", e);\n }\n }\n\n @Override\n public synchronized void clear() {\n try {\n getDiskCache().delete();\n resetDiskCache();\n } catch (IOException e) {\n Log.w(TAG, \"Unable to clear disk cache\", e);\n }\n }\n\n\tprivate synchronized DiskLruCache getDiskCache() throws IOException {\n\t\treturn diskLruCacheFactory.getDiskCache();\n\t}\n\n\tprivate synchronized void resetDiskCache() {\n\t\tdiskLruCacheFactory.resetDiskCache();\n\t}\n}", "public class BitmapLruCache extends LruCacheAdapter<String, Bitmap> {\n\n\tprivate LruCache<String, Bitmap> impl;\n\t\n\tpublic BitmapLruCache(float percentOfAvailableMemory) {\n\t\tsuper(new MyCache((int)(Runtime.getRuntime().maxMemory() * percentOfAvailableMemory)));\n\t\timpl = getLruCache();\n\t}\n\t\n\tpublic BitmapLruCache(int maxSize) {\n\t\tsuper(new MyCache(maxSize));\n\t\timpl = getLruCache();\n\t}\n\n\t@Override\n\tpublic boolean has(String key) {\n\t\tif (key == null) return false;\n\t\tBitmap value = get(key);\n\t\treturn (value != null && !value.isRecycled());\n\t}\n\t\n\tprivate static class MyCache extends LruCache<String, Bitmap> {\n\t\tpublic MyCache(int maxSize) {\n\t\t\tsuper(maxSize);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected int sizeOf(String key, Bitmap value) {\n\t\t\tif (value == null) return 0;\n\t\t\treturn getBitmapSize(value);\n\t\t}\n\t\t\n\t\t/**\n\t * Get the size in bytes of a bitmap.\n\t * @param bitmap\n\t * @return size in bytes\n\t */\n\t private int getBitmapSize(Bitmap bitmap) {\n\t\t\treturn bitmap.getByteCount();\n\t }\n\t}\n\t\n}" ]
import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.climate.mirage.Mirage; import com.climate.mirage.cache.disk.CompositeDiskCache; import com.climate.mirage.cache.disk.DiskCache; import com.climate.mirage.cache.disk.DiskLruCacheWrapper; import com.climate.mirage.cache.memory.BitmapLruCache; import java.io.File;
package com.climate.mirage.app; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); setContentView(ll); Button btn = new Button(this); ll.addView(btn); btn.setText("Clear Cache"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mirage.get(SettingsActivity.this).clearCache(); } }); btn = new Button(this); ll.addView(btn); btn.setText("Standard Cache Settings"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mirage.get(SettingsActivity.this)
.setDefaultMemoryCache(new BitmapLruCache(0.25f))
4
zhenglu1989/web-sso
ki4so-core/src/main/java/com/github/ebnew/ki4so/core/service/KnightServiceImpl.java
[ "public class KnightApp implements Serializable {\n\n private static final long serialVersionUID = -1850808070447330706L;\n\n\n /**\n * 应用id\n */\n private String appId;\n\n /**\n * 应用名称\n */\n\n private String appName;\n\n /***\n * 应用所在的主机地址\n */\n\n private String host;\n\n /**\n * 应用退出地址\n */\n\n private String logoutPath;\n\n\n /**\n * 是否是knight服务本身\n */\n private boolean knightService = false;\n\n public String getAppId() {\n return appId;\n }\n\n public void setAppId(String appId) {\n this.appId = appId;\n }\n\n public String getAppName() {\n return appName;\n }\n\n public void setAppName(String appName) {\n this.appName = appName;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public String getLogoutPath() {\n return logoutPath;\n }\n\n public void setLogoutPath(String logoutPath) {\n this.logoutPath = logoutPath;\n }\n\n public boolean isKnightService() {\n return knightService;\n }\n\n public void setKnightService(boolean knightService) {\n this.knightService = knightService;\n }\n}", "public interface KnightAppService {\n\n /**\n * 通过appid查找对应的应用信息\n * @param appId\n * @return\n */\n\n public KnightApp findAppById(String appId);\n\n /**\n * 查找系统中Ki4so服务对应的应用信息\n * @return\n */\n\n public KnightApp findKi4soServerApp();\n\n /**\n * 通过host查找对应的应用信息\n * @param host\n * @return\n */\n\n public KnightApp findAppByHost(String host);\n}", "public interface KnightAuthentication {\n\n public Map<String,Object> getAttrbutes();\n\n public Date getAuthenticateDate();\n\n public KnightUser getUser();\n\n\n}", "public interface KnightAuthenticationManager {\n\n /**\n * fixedby zhenglu 失败可以返回null,不必抛出异常。保证系统可用性\n * 对用户凭证进行认证,若失败则抛出异常,若成功则放回认证结果\n * @return\n */\n public KnightAuthentication authentication(KnightCredential credential);\n}", "public interface KnightCredential {\n\n\n /**\n * 是否是原始凭据,即未认证过的原始信息\n *\n * @return true :原始凭据,false:加密后的凭据\n */\n public boolean isOriginal();\n}", "public interface KnightUserLoggedStatusStore {\n\n\n /**\n * 增加新的用户登录状态\n * @param userLoginStatus\n */\n public void addUserLoggerStatus(KnightUserLoginStatus userLoginStatus);\n\n /**\n * 删除用户登录状态\n * @param userId\n * @param appId\n */\n public void deleteUserLoginStatus(String userId,String appId);\n\n\n /**\n * 清楚某个用户所有的登录状态\n * @param userId\n */\n public void clearUpUserLoginStatus(String userId);\n\n\n /**\n * 根据用户标识查询所有的登录状态\n * @param userId\n * @return\n */\n public List<KnightUserLoginStatus> findUserLoginStatus(String userId);\n\n\n}", "public class KnightUserLoginStatus implements Serializable{\n\n\n private static final long serialVersionUID = 8453108828607661563L;\n /**\n * 登录用户的标识\n */\n private String userId;\n\n /**\n * 用户登录的应用标识\n */\n\n private String appId;\n\n /**\n * 登录应用的时间\n */\n\n private Date loginDate;\n\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getAppId() {\n return appId;\n }\n\n public void setAppId(String appId) {\n this.appId = appId;\n }\n\n public Date getLoginDate() {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate) {\n this.loginDate = loginDate;\n }\n}" ]
import com.github.ebnew.ki4so.core.app.KnightApp; import com.github.ebnew.ki4so.core.app.KnightAppService; import com.github.ebnew.ki4so.core.authentication.KnightAuthentication; import com.github.ebnew.ki4so.core.authentication.KnightAuthenticationManager; import com.github.ebnew.ki4so.core.authentication.KnightCredential; import com.github.ebnew.ki4so.core.authentication.status.KnightUserLoggedStatusStore; import com.github.ebnew.ki4so.core.authentication.status.KnightUserLoginStatus; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List;
package com.github.ebnew.ki4so.core.service; /** * @author zhenglu * @since 15/4/29 */ public class KnightServiceImpl implements KnightService { private Logger logger = Logger.getLogger(KnightServiceImpl.class); private KnightAuthenticationManager authenticationManager; private KnightAppService appService; private KnightUserLoggedStatusStore userLoggedStatusStore; @Override public LoginResult login(KnightCredential credential) { //若没有凭据,则返回空 if(credential == null){ return null; } LoginResult result = new LoginResult(); result.setSuccess(false); //调用认证处理器进行认证 try{
KnightAuthentication authentication = authenticationManager.authentication(credential);
2
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/controller/UserController.java
[ "public class AuthenticationFailedException extends ServletException {\n private static final long serialVersionUID = -8799659324455306881L;\n\n public AuthenticationFailedException(String message) {\n super(message);\n }\n}", "public class JWTTokenAuthFilter extends OncePerRequestFilter {\n private static List<Pattern> AUTH_ROUTES = new ArrayList<>();\n private static List<String> NO_AUTH_ROUTES = new ArrayList<>();\n public static final String JWT_KEY = \"JWT-TOKEN-SECRET\";\n\n static {\n AUTH_ROUTES.add(Pattern.compile(\"/api/*\"));\n NO_AUTH_ROUTES.add(\"/api/user/authenticate\");\n NO_AUTH_ROUTES.add(\"/api/user/register\");\n }\n\n private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class);\n\n @Autowired\n private UserService userService;\n\n @Override\n protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,\n FilterChain filterChain) throws ServletException, IOException {\n String authorizationHeader = request.getHeader(\"authorization\");\n String authenticationHeader = request.getHeader(\"authentication\");\n String route = request.getRequestURI();\n\n // no auth route matching\n boolean needsAuthentication = false;\n\n for (Pattern p : AUTH_ROUTES) {\n if (p.matcher(route).matches()) {\n needsAuthentication = true;\n break;\n }\n }\n\n if(route.startsWith(\"/api/\")) {\n needsAuthentication = true;\n }\n\n if (NO_AUTH_ROUTES.contains(route)) {\n needsAuthentication = false;\n }\n\n // Checking whether the current route needs to be authenticated\n if (needsAuthentication) {\n // Check for authorization header presence\n String authHeader = null;\n if (authorizationHeader == null || authorizationHeader.equalsIgnoreCase(\"\")) {\n if (authenticationHeader == null || authenticationHeader.equalsIgnoreCase(\"\")) {\n authHeader = null;\n } else {\n authHeader = authenticationHeader;\n LOG.info(\"authentication: \" + authenticationHeader);\n }\n } else {\n authHeader = authorizationHeader;\n LOG.info(\"authorization: \" + authorizationHeader);\n }\n\n if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(\"Bearer \")) {\n throw new AuthCredentialsMissingException(\"Missing or invalid Authorization header.\");\n }\n\n final String token = authHeader.substring(7); // The part after \"Bearer \"\n try {\n final Claims claims = Jwts.parser().setSigningKey(JWT_KEY)\n .parseClaimsJws(token).getBody();\n request.setAttribute(\"claims\", claims);\n\n // Now since the authentication process if finished\n // move the request forward\n filterChain.doFilter(request, response);\n } catch (final Exception e) {\n throw new AuthenticationFailedException(\"Invalid token. Cause:\"+e.getMessage());\n }\n } else {\n filterChain.doFilter(request, response);\n }\n }\n}", "@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class APIResponse {\n public static final String API_RESPONSE = \"apiResponse\";\n Object result;\n String time;\n long code;\n\n public static class ExceptionAPIResponse extends APIResponse {\n Object details;\n\n public Object getDetails() {\n return details;\n }\n\n public void setDetails(Object details) {\n this.details = details;\n }\n }\n\n public Object getResult() {\n return result;\n }\n\n public void setResult(Object result) {\n this.result = result;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public long getCode() {\n return code;\n }\n\n public void setCode(long code) {\n this.code = code;\n }\n\n public static APIResponse toOkResponse(Object data) {\n return toAPIResponse(data, 200);\n }\n\n public static APIResponse toErrorResponse(Object data) {\n return toAPIResponse(data, 2001);\n }\n\n public static ExceptionAPIResponse toExceptionResponse(String result, Object details) {\n ExceptionAPIResponse response = new ExceptionAPIResponse();\n response.setResult(result);\n response.setDetails(details);\n response.setCode(2001);\n return response;\n }\n\n public APIResponse withModelAndView(ModelAndView modelAndView) {\n modelAndView.addObject(API_RESPONSE, this);\n return this;\n }\n\n public static APIResponse toAPIResponse(Object data, long code) {\n APIResponse response = new APIResponse();\n response.setResult(data);\n response.setCode(code);\n return response;\n }\n}", "public abstract class BaseController {\n protected static final String JSON_API_CONTENT_HEADER = \"Content-type=application/json\";\n\n public String extractPostRequestBody(HttpServletRequest request) throws IOException {\n if (\"POST\".equalsIgnoreCase(request.getMethod())) {\n Scanner s = new Scanner(request.getInputStream(), \"UTF-8\").useDelimiter(\"\\\\A\");\n return s.hasNext() ? s.next() : \"\";\n }\n return \"\";\n }\n\n public JSONObject parseJSON(String object) {\n return new JSONObject(object);\n }\n\n public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {\n String[] basicAuth = authHeader.split(\" \");\n Validate.isTrue(basicAuth.length == 2, \"the auth header is not splittable with space\");\n Validate.isTrue(basicAuth[0].equalsIgnoreCase(\"basic\"), \"not basic auth: \"+basicAuth[0]);\n Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), \"encoded value not base64\");\n\n String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes()));\n String[] creds = decodedAuthHeader.split(\":\");\n Validate.isTrue(creds.length == 2, \"the creds were not concatenated using ':', could not split the decoded header\");\n\n userDTO.setEmail(creds[0]);\n userDTO.setPassword(creds[1]);\n }\n}", "public class UserDTO {\n String email;\n String password;\n String displayName;\n String encryptedPassword;\n String iv;\n String salt;\n int keySize;\n int iterations;\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public String getEncryptedPassword() {\n return encryptedPassword;\n }\n\n public void setEncryptedPassword(String encryptedPassword) {\n this.encryptedPassword = encryptedPassword;\n }\n\n public String getIv() {\n return iv;\n }\n\n public void setIv(String iv) {\n this.iv = iv;\n }\n\n public String getSalt() {\n return salt;\n }\n\n public void setSalt(String salt) {\n this.salt = salt;\n }\n\n public int getKeySize() {\n return keySize;\n }\n\n public void setKeySize(int keySize) {\n this.keySize = keySize;\n }\n\n public int getIterations() {\n return iterations;\n }\n\n public void setIterations(int iterations) {\n this.iterations = iterations;\n }\n}", "@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(indexes = { @Index(name=\"email_idx\", columnList = \"email\", unique = true),\n @Index(name=\"displayName_idx\", columnList = \"display_name\") })\npublic class User extends JPAEntity<Long> implements Serializable {\n public enum Role {\n USER,\n ADMIN\n }\n\n private String email;\n private @JsonIgnore String password;\n private boolean enabled;\n private Role role;\n private String displayName;\n\n private @JsonIgnore Integer loginCount;\n private Date currentLoginAt;\n private Date lastLoginAt;\n private @JsonIgnore String currentLoginIp;\n private @JsonIgnore String lastLoginIp;\n\n private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();\n\n @Column @Email @NotNull @NotBlank\n public String getEmail() {\n return this.email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n @JsonIgnore @Column(nullable = false, length = 60)\n public String getPassword() {\n return this.password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Column(nullable = false)\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n @Column(nullable = false)\n public Role getRole() {\n return this.role;\n }\n\n public void setRole(Role role) {\n this.role = role;\n }\n\n @Column(name=\"display_name\")\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n @JsonIgnore @Column\n public Integer getLoginCount() {\n return loginCount;\n }\n\n public void setLoginCount(Integer loginCount) {\n this.loginCount = loginCount;\n }\n\n @Column\n public Date getCurrentLoginAt() {\n return currentLoginAt;\n }\n\n public void setCurrentLoginAt(Date currentLoginAt) {\n this.currentLoginAt = currentLoginAt;\n }\n\n @Column\n public Date getLastLoginAt() {\n return lastLoginAt;\n }\n\n public void setLastLoginAt(Date lastLoginAt) {\n this.lastLoginAt = lastLoginAt;\n }\n\n @JsonIgnore @Column\n public String getCurrentLoginIp() {\n return currentLoginIp;\n }\n\n public void setCurrentLoginIp(String currentLoginIp) {\n this.currentLoginIp = currentLoginIp;\n }\n\n @JsonIgnore @Column\n public String getLastLoginIp() {\n return lastLoginIp;\n }\n\n public void setLastLoginIp(String lastLoginIp) {\n this.lastLoginIp = lastLoginIp;\n }\n\n /**\n * Method to create the hash of the password before storing\n *\n * @param pass\n *\n * @return SHA hash digest of the password\n */\n public static synchronized String hashPassword(String pass) {\n return passwordEncoder.encode(pass);\n }\n\n public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {\n return passwordEncoder.matches(rawPass, encodedPass);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"email='\" + email + '\\'' +\n \", password='\" + password + '\\'' +\n \", enabled=\" + enabled +\n \", role=\" + role +\n \", displayName='\" + displayName + '\\'' +\n \", loginCount=\" + loginCount +\n \", currentLoginAt=\" + currentLoginAt +\n \", lastLoginAt=\" + lastLoginAt +\n \", currentLoginIp='\" + currentLoginIp + '\\'' +\n \", lastLoginIp='\" + lastLoginIp + '\\'' +\n '}';\n }\n}", "public interface MailJobService extends BaseService<Job, Long> {\n\n /**\n * Sends the confirmation mail to user.\n *\n * @param user\n */\n public void sendConfirmationMail(User user);\n}", "public interface UserService extends BaseService<User, Long> {\n\n /**\n * Register a new user into the system\n *\n * @param user\n * @param request\n *\n * @return\n */\n public User registerUser(User user, HttpServletRequest request);\n\n\n /**\n * Login a new user into the system\n *\n * @param user\n * @param request\n *\n * @return\n */\n public User loginUser(User user, HttpServletRequest request);\n\n\n /**\n * Method to validate whether the given password\n * is same as users password stored in the system\n *\n * @param user\n * @param pass\n *\n * @return\n */\n public boolean isValidPass(User user, String pass);\n\n\n /**\n * Validates whether the given email already\n * exists in the system.\n *\n * @param email\n *\n * @return\n */\n public boolean isEmailExists(String email);\n\n\n /**\n * Finds a user entity by the given email\n *\n * @param email\n * @return\n */\n public User findByEmail(String email) throws EmailNotFoundException;\n}" ]
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import yourwebproject2.auth.AuthenticationFailedException; import yourwebproject2.auth.JWTTokenAuthFilter; import yourwebproject2.framework.api.APIResponse; import yourwebproject2.framework.controller.BaseController; import yourwebproject2.model.dto.UserDTO; import yourwebproject2.model.entity.User; import yourwebproject2.service.MailJobService; import yourwebproject2.service.UserService; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Date; import java.util.HashMap;
package yourwebproject2.controller; /** * @author: kameshr * * Referred: https://github.com/mpetersen/aes-example, http://niels.nu/blog/2015/json-web-tokens.html */ @Controller @RequestMapping("user") public class UserController extends BaseController { private static Logger LOG = LoggerFactory.getLogger(UserController.class); private @Autowired UserService userService; private @Autowired MailJobService mailJobService; /** * Authenticate a user * * @param userDTO * @return */ @RequestMapping(value = "/authenticate", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER}) public @ResponseBody APIResponse authenticate(@RequestBody UserDTO userDTO, HttpServletRequest request, HttpServletResponse response) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, AuthenticationFailedException { Validate.isTrue(StringUtils.isNotBlank(userDTO.getEmail()), "Email is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getEncryptedPassword()), "Encrypted password is blank"); String password = decryptPassword(userDTO); LOG.info("Looking for user by email: "+userDTO.getEmail()); User user = userService.findByEmail(userDTO.getEmail()); HashMap<String, Object> authResp = new HashMap<>(); if(userService.isValidPass(user, password)) { LOG.info("User authenticated: "+user.getEmail()); userService.loginUser(user, request); createAuthResponse(user, authResp); } else { throw new AuthenticationFailedException("Invalid username/password combination"); } return APIResponse.toOkResponse(authResp); } /** * Register new user * POST body expected in the format - {"user":{"displayName":"Display Name", "email":"[email protected]"}} * * @param userDTO * @return */ @RequestMapping(value = "/register", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER}) public @ResponseBody APIResponse register(@RequestBody UserDTO userDTO, HttpServletRequest request) throws NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { Validate.isTrue(StringUtils.isNotBlank(userDTO.getEmail()), "Email is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getEncryptedPassword()), "Encrypted password is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getDisplayName()), "Display name is blank"); String password = decryptPassword(userDTO); LOG.info("Looking for user by email: "+userDTO.getEmail()); if(userService.isEmailExists(userDTO.getEmail())) { return APIResponse.toErrorResponse("Email is taken"); } LOG.info("Creating user: "+userDTO.getEmail()); User user = new User(); user.setEmail(userDTO.getEmail()); user.setDisplayName(userDTO.getDisplayName()); user.setPassword(password); user.setEnabled(true); user.setRole(User.Role.USER); userService.registerUser(user, request); HashMap<String, Object> authResp = new HashMap<>(); createAuthResponse(user, authResp); return APIResponse.toOkResponse(authResp); } private void createAuthResponse(User user, HashMap<String, Object> authResp) { String token = Jwts.builder().setSubject(user.getEmail()) .claim("role", user.getRole().name()).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, JWTTokenAuthFilter.JWT_KEY).compact();
1
giancosta86/EasyPmd
src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
[ "public class NoOpPmdScannerStrategy implements PmdScannerStrategy {\n\n @Override\n public Set<ScanMessage> scan(Path path) {\n return Collections.emptySet();\n }\n}", "public class LinkedPmdScanningStrategy implements PmdScannerStrategy {\n\n private final PMD pmd;\n private final RuleSets ruleSets;\n private final String sourceFileEncoding;\n\n public LinkedPmdScanningStrategy(Options options) {\n LanguageVersionParser languageVersionParser = Injector.lookup(LanguageVersionParser.class);\n\n ClassLoader pmdBasedClassLoader = PmdBasedClassLoader.create(options.getAdditionalClassPathUrls());\n\n RuleSetFactory ruleSetFactory = new RuleSetFactory();\n\n String ruleSetsString = buildRuleSetsString(options.getRuleSets());\n\n try {\n ruleSetFactory.setClassLoader(pmdBasedClassLoader);\n ruleSetFactory.setMinimumPriority(options.getMinimumPriority());\n\n ruleSets = ruleSetFactory.createRuleSets(ruleSetsString);\n } catch (RuleSetNotFoundException ex) {\n throw new RuntimeException(ex);\n }\n\n LanguageVersion languageVersion = languageVersionParser.parse(options.getTargetJavaVersion());\n sourceFileEncoding = options.getSourceFileEncoding();\n\n pmd = new PMD();\n PMDConfiguration pmdConfiguration = pmd.getConfiguration();\n pmdConfiguration.setDefaultLanguageVersion(languageVersion);\n pmdConfiguration.setSuppressMarker(options.getSuppressMarker());\n pmdConfiguration.setClassLoader(pmdBasedClassLoader);\n pmdConfiguration.setMinimumPriority(options.getMinimumPriority());\n\n String auxiliaryClassPath = options.getAuxiliaryClassPath();\n\n if (auxiliaryClassPath != null && !auxiliaryClassPath.isEmpty()) {\n try {\n pmdConfiguration.prependClasspath(auxiliaryClassPath);\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n }\n\n private String buildRuleSetsString(Collection<String> ruleSets) {\n StringBuilder result = new StringBuilder();\n\n Iterator<String> iterator = ruleSets.iterator();\n\n iterator.forEachRemaining(ruleSet -> {\n result.append(ruleSet);\n\n if (iterator.hasNext()) {\n result.append(\",\");\n }\n });\n\n return result.toString();\n }\n\n @Override\n public Set<ScanMessage> scan(Path path) {\n String pathString = path.toAbsolutePath().toString();\n\n Report report = new Report();\n\n RuleContext ruleContext = new RuleContext();\n ruleContext.setReport(report);\n ruleContext.setSourceCodeFilename(pathString);\n\n Set<ScanMessage> scanMessages = new HashSet<>();\n\n RuleSets applicableRuleSets = new RuleSets();\n Iterator<RuleSet> ruleSetsIterator = ruleSets.getRuleSetsIterator();\n\n ruleSetsIterator.forEachRemaining(currentRuleSet -> {\n if (currentRuleSet.applies(path.toFile())) {\n applicableRuleSets.addRuleSet(currentRuleSet);\n }\n });\n\n try {\n try (Reader reader = new InputStreamReader(new FileInputStream(pathString), sourceFileEncoding)) {\n pmd.getSourceCodeProcessor().processSourceCode(reader, applicableRuleSets, ruleContext);\n }\n\n ReportTree violationTree = report.getViolationTree();\n\n Iterator<RuleViolation> violationsIterator = violationTree.iterator();\n\n violationsIterator.forEachRemaining(violation -> {\n scanMessages.add(new ScanViolation(violation));\n });\n } catch (IOException | PMDException ex) {\n scanMessages.add(new ScanError(ex));\n }\n\n return scanMessages;\n }\n}", "public class CacheBasedLinkedPmdScanningStrategy extends LinkedPmdScanningStrategy {\n\n private static final Logger logger = Logger.getLogger(CacheBasedLinkedPmdScanningStrategy.class.getName());\n\n private final ScanMessagesCache scanMessagesCache = Injector.lookup(ScanMessagesCache.class);\n\n public CacheBasedLinkedPmdScanningStrategy(Options options) {\n super(options);\n }\n\n @Override\n public Set<ScanMessage> scan(Path path) {\n try {\n String pathString = path.toString();\n long lastModificationMillis = Files.getLastModifiedTime(path).toMillis();\n\n final Optional<Set<ScanMessage>> cachedScanMessagesOption = scanMessagesCache.getScanMessagesFor(\n pathString,\n lastModificationMillis\n );\n\n return cachedScanMessagesOption.orElseGet(() -> {\n logger.info(() -> String.format(\"No valid cache entry found for path: %s\", pathString));\n\n Set<ScanMessage> scanMessages = super.scan(path);\n\n scanMessagesCache.putScanMessagesFor(pathString, lastModificationMillis, scanMessages);\n\n return scanMessages;\n });\n } catch (IOException ex) {\n return Collections.singleton(\n new ScanError(ex)\n );\n }\n }\n}", "public class ScanError implements ScanMessage {\n\n private static final int ERROR_LINE_NUMBER = 1;\n private static final int MAX_STACK_TRACE_STRING_LENGTH = 2000;\n private static final String ELLIPSIS_STRING = \"\\n<...>\";\n\n private final String exceptionMessage;\n private final String stackTraceString;\n\n public ScanError(Exception exception) {\n this.exceptionMessage = Throwables.getNonEmptyMessage(exception);\n\n String fullStackTraceString = Throwables.getStackTraceString(exception);\n\n if (fullStackTraceString.length() <= MAX_STACK_TRACE_STRING_LENGTH) {\n this.stackTraceString = fullStackTraceString;\n } else {\n this.stackTraceString = fullStackTraceString.substring(0, MAX_STACK_TRACE_STRING_LENGTH - ELLIPSIS_STRING.length() - 1) + ELLIPSIS_STRING;\n }\n }\n\n @Override\n public boolean isShowableInGuardedSections() {\n return true;\n }\n\n @Override\n public int getLineNumber() {\n return ERROR_LINE_NUMBER;\n }\n\n @Override\n public Task createTask(Options options, FileObject fileObject) {\n return Task.create(\n fileObject,\n \"info.gianlucacosta.easypmd.ide.tasklist.ScanError\",\n exceptionMessage,\n ERROR_LINE_NUMBER\n );\n }\n\n @Override\n public Annotation createAnnotation(Options options) {\n return new BasicAnnotation(\n \"info.gianlucacosta.easypmd.ide.annotations.ScanError\",\n stackTraceString\n );\n }\n}", "public interface Options {\n\n static OptionsChanges computeChanges(Options oldOptions, Options newOptions) {\n if (oldOptions == null) {\n return OptionsChanges.ENGINE;\n }\n\n boolean noEngineChanges\n = Objects.equals(oldOptions.getTargetJavaVersion(), newOptions.getTargetJavaVersion())\n && Objects.equals(oldOptions.getSourceFileEncoding(), newOptions.getSourceFileEncoding())\n && Objects.equals(oldOptions.getSuppressMarker(), newOptions.getSuppressMarker())\n && CollectionItems.equals(oldOptions.getAdditionalClassPathUrls(), newOptions.getAdditionalClassPathUrls())\n && CollectionItems.equals(oldOptions.getRuleSets(), newOptions.getRuleSets())\n && (oldOptions.isShowAllMessagesInGuardedSections() == newOptions.isShowAllMessagesInGuardedSections())\n && Objects.equals(oldOptions.getPathFilteringOptions(), newOptions.getPathFilteringOptions())\n && (oldOptions.getMinimumPriority() == newOptions.getMinimumPriority())\n && Objects.equals(oldOptions.getAuxiliaryClassPath(), newOptions.getAuxiliaryClassPath())\n && (oldOptions.isUseScanMessagesCache() == newOptions.isUseScanMessagesCache());\n\n if (noEngineChanges) {\n boolean noChanges\n = (oldOptions.isShowRulePriorityInTasks() == newOptions.isShowRulePriorityInTasks())\n && (oldOptions.isShowDescriptionInTasks() == newOptions.isShowDescriptionInTasks())\n && (oldOptions.isShowRuleInTasks() == newOptions.isShowRuleInTasks())\n && (oldOptions.isShowRuleSetInTasks() == newOptions.isShowRuleSetInTasks())\n && (oldOptions.isShowAnnotationsInEditor() == newOptions.isShowAnnotationsInEditor());\n\n if (noChanges) {\n return OptionsChanges.NONE;\n } else {\n return OptionsChanges.VIEW_ONLY;\n }\n } else {\n return OptionsChanges.ENGINE;\n }\n }\n\n String getTargetJavaVersion();\n\n String getSourceFileEncoding();\n\n String getSuppressMarker();\n\n Collection<URL> getAdditionalClassPathUrls();\n\n Collection<String> getRuleSets();\n\n boolean isUseScanMessagesCache();\n\n boolean isShowRulePriorityInTasks();\n\n boolean isShowDescriptionInTasks();\n\n boolean isShowRuleInTasks();\n\n boolean isShowRuleSetInTasks();\n\n boolean isShowAnnotationsInEditor();\n\n boolean isShowAllMessagesInGuardedSections();\n\n PathFilteringOptions getPathFilteringOptions();\n\n RulePriority getMinimumPriority();\n\n String getAuxiliaryClassPath();\n\n Options clone();\n}" ]
import java.util.logging.Logger; import info.gianlucacosta.easypmd.pmdscanner.strategies.NoOpPmdScannerStrategy; import info.gianlucacosta.easypmd.pmdscanner.strategies.LinkedPmdScanningStrategy; import info.gianlucacosta.easypmd.pmdscanner.strategies.CacheBasedLinkedPmdScanningStrategy; import info.gianlucacosta.easypmd.pmdscanner.messages.ScanError; import info.gianlucacosta.easypmd.ide.options.Options; import java.nio.file.Path; import java.util.Collections; import java.util.Set;
/* * ==========================================================================%%# * EasyPmd * ===========================================================================%% * Copyright (C) 2009 - 2017 Gianluca Costa * ===========================================================================%% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * ==========================================================================%## */ package info.gianlucacosta.easypmd.pmdscanner; /** * Scans files using PMD, returning a list of ScanMessage for each scanned file */ public class PmdScanner { private static final Logger logger = Logger.getLogger(PmdScanner.class.getName()); private final PmdScannerStrategy strategy; public PmdScanner(Options options) { if (options.getRuleSets().isEmpty()) { logger.info(() -> "Setting a NOP scanning strategy"); strategy = new NoOpPmdScannerStrategy(); return; } if (options.isUseScanMessagesCache()) { logger.info(() -> "Setting a cached scanning strategy"); strategy = new CacheBasedLinkedPmdScanningStrategy(options); } else { logger.info(() -> "Setting a non-cached scanning strategy");
strategy = new LinkedPmdScanningStrategy(options);
1
handexing/geekHome
geekHome-backend/src/main/java/com/geekhome/controller/MenuController.java
[ "public enum ErrorCode {\n\t\n\tEXCEPTION(\"程序异常\", \"00001\"),\n\tUSER_NOT_EXIST(\"用户未注册\", \"00002\"),\n VERIFY_CODE_WRONG(\"验证码错误\",\"00003\"),\n OLD_PWD_WRONG(\"旧密码错误\",\"00004\"),\n USERNAME_PASSWORD_WRONG(\"用户名或密码错误\",\"00005\"),\n TODAY_HAVE_SIGN(\"今日已签到\",\"00006\");\n\n\tprivate String errorMsg;\n\tprivate String errorCode;\n\n\tprivate ErrorCode(final String errorMsg, final String errorCode) {\n\t\tthis.errorMsg = errorMsg;\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic String getErrorCode() {\n\t\treturn errorCode;\n\t}\n\n\tpublic String getErrorMsg() {\n\t\treturn errorMsg;\n\t}\n\n\tpublic void setErrorCode(String errorCode) {\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic void setErrorMsg(String errorMsg) {\n\t\tthis.errorMsg = errorMsg;\n\t}\n\n}", "public class ExecuteResult<T> {\n\t\n\tprivate final long timeOut = 50000L;\n\tprivate boolean isSuccess;\n\tprivate T data;\n\n\tprivate String errorCode;\n\tprivate String errorMsg;\n\tprivate String fromUrl;\n\n\tprivate Long processTime;\n\t@SuppressWarnings(\"unused\")\n\tprivate Long flushTimeOut;\n\n\tpublic T getData() {\n\t\treturn data;\n\t}\n\n\tpublic String getErrorCode() {\n\t\treturn errorCode == null ? \"\" : errorCode;\n\t}\n\n\tpublic String getErrorMsg() {\n\t\treturn errorMsg == null ? \"\" : errorMsg;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn isSuccess;\n\t}\n\n\tpublic void setData(T data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic void setErrorCode(String errorCode) {\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic void setErrorMsg(String errorMsg) {\n\t\tthis.errorMsg = errorMsg;\n\t}\n\n\tpublic void setSuccess(boolean isSuccess) {\n\t\tthis.isSuccess = isSuccess;\n\t}\n\n\tpublic Date getFlushTime() {\n\t\treturn new Date();\n\t\t// return flushTime;\n\t}\n\n\tpublic Long getProcessTime() {\n\t\treturn processTime;\n\t}\n\n\tpublic void setProcessTime(Long processTime) {\n\t\tthis.processTime = processTime;\n\t}\n\n\tpublic String getFromUrl() {\n\t\treturn fromUrl;\n\t}\n\n\tpublic void setFromUrl(String fromUrl) {\n\t\tthis.fromUrl = fromUrl;\n\t}\n\n\tpublic Long getFlushTimeOut() {\n\t\treturn timeOut;\n\t\t// return flushTimeOut;\n\t}\n\n\tpublic void setFlushTimeOut(Long flushTimeOut) {\n\t\tthis.flushTimeOut = flushTimeOut;\n\t}\n\n}", "@Entity\n@Table(name = \"MENU\")\npublic class Menu implements Serializable {\n\n\tprivate static final long serialVersionUID = 6423970748458325777L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\t@Column(name = \"ID\")\n\tprivate Long id;\n\t@Column(name = \"NAME\")\n\tprivate String name;\n\t@Column(name = \"TYPE\")\n\tprivate String type;\n\t@Column(name = \"URL\")\n\tprivate String url;\n\t@Column(name = \"CODE\")\n\tprivate String code;\n\t@Column(name = \"PARENT_ID\")\n\tprivate Long parentId;\n\t@Column(name = \"PARENT_IDS\")\n\tprivate String parentIds;\n\t@Column(name = \"SORT\")\n\tprivate Integer sort;\n\t@JsonSerialize(using = CustomDateSerializer.class)\n\t@Column(name = \"CREATE_TIME\")\n\tprivate Date createTime;\n\t@JsonSerialize(using = CustomDateSerializer.class)\n\t@Column(name = \"UPDATE_TIME\")\n\tprivate Date updateTime;\n\n\t// @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)\n\t// @JoinColumn(name=\"MENU_ID\")\n\t// private List<RoleMenu> roleMenuList;\n\n\t// public List<RoleMenu> getRoleMenuList() {\n\t// return roleMenuList;\n\t// }\n\t//\n\t// public void setRoleMenuList(List<RoleMenu> roleMenuList) {\n\t// this.roleMenuList = roleMenuList;\n\t// }\n\n\t@Transient\n\tprivate List<Menu> children;\n\n\tpublic List<Menu> getChildren() {\n\t\treturn children;\n\t}\n\n\tpublic void setChildren(List<Menu> children) {\n\t\tthis.children = children;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\n\tpublic void setUrl(String url) {\n\t\tthis.url = url;\n\t}\n\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\n\tpublic void setCode(String code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic Long getParentId() {\n\t\treturn parentId;\n\t}\n\n\tpublic void setParentId(Long parentId) {\n\t\tthis.parentId = parentId;\n\t}\n\n\tpublic String getParentIds() {\n\t\treturn parentIds;\n\t}\n\n\tpublic void setParentIds(String parentIds) {\n\t\tthis.parentIds = parentIds;\n\t}\n\n\tpublic Integer getSort() {\n\t\treturn sort;\n\t}\n\n\tpublic void setSort(Integer sort) {\n\t\tthis.sort = sort;\n\t}\n\n\tpublic Date getCreateTime() {\n\t\treturn createTime;\n\t}\n\n\tpublic void setCreateTime(Date createTime) {\n\t\tthis.createTime = createTime;\n\t}\n\n\tpublic Date getUpdateTime() {\n\t\treturn updateTime;\n\t}\n\n\tpublic void setUpdateTime(Date updateTime) {\n\t\tthis.updateTime = updateTime;\n\t}\n\n\tpublic Menu() {\n\t\tsuper();\n\t}\n\n\tpublic Menu(Long id, String name, String type, String url, String code, Long parentId, String parentIds,\n\t\t\tInteger sort, Date createTime, Date updateTime) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.parentId = parentId;\n\t\tthis.parentIds = parentIds;\n\t\tthis.sort = sort;\n\t\tthis.createTime = createTime;\n\t\tthis.updateTime = updateTime;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Menu [id=\" + id + \", name=\" + name + \", type=\" + type + \", url=\" + url + \", code=\" + code\n\t\t\t\t+ \", parentId=\" + parentId + \", parentIds=\" + parentIds + \", sort=\" + sort + \", createTime=\"\n\t\t\t\t+ createTime + \", updateTime=\" + updateTime + \"]\";\n\t}\n\n}", "public interface MenuDao extends JpaRepository<Menu, Long>{\n\n\t@Query(nativeQuery = true, value = \"SELECT CODE FROM MENU\")\n\tpublic Set<String> getAllMenuCode();\n\t\n\t@Query(nativeQuery = true, value = \"SELECT m.CODE FROM MENU m , ROLE_MENU rm, ADMIN_ROLE ar WHERE ar.ADMIN_ID =:id AND m.ID = rm.MENU_ID AND rm.ROLE_ID = ar.ROLE_ID\")\n\tpublic Set<String> findMenuCodeByUserId(@Param(\"id\") Long id);\n\n\t@Query(nativeQuery = true, value = \"SELECT * FROM MENU WHERE PARENT_ID=:parentId ORDER BY SORT ASC,CREATE_TIME DESC\")\n\tpublic List<Menu> findMenuByParentId(@Param(\"parentId\") Long parentId);\n\n\t\n\t@Modifying(clearAutomatically = true)\n\t@Transactional\n\t@Query(nativeQuery = true, value = \"UPDATE MENU SET SORT=:sort WHERE ID =:id\")\n\tint updateOrder(@Param(\"id\") Long id, @Param(\"sort\") Integer sort);\n\t\n\t@Query(nativeQuery = true, value = \"SELECT COUNT(1) FROM MENU WHERE ID=:parentId\")\n\tint getMenuByParentIdCnt(@Param(\"parentId\") Long parentId);\n\n\t@Modifying(clearAutomatically = true)\n\t@Transactional\n\t@Query(nativeQuery = true, value = \"DELETE FROM MENU WHERE ID=:parentId OR PARENT_ID=:parentId\")\n\tpublic void delete(@Param(\"parentId\") Long parentId);\n\n\t@Query(nativeQuery = true, value = \"SELECT * FROM menu WHERE ID in(SELECT MENU_ID FROM role_menu WHERE ROLE_ID = (SELECT ROLE_ID FROM admin_role WHERE ADMIN_ID=:id))\")\n\tpublic List<Menu> findMenuById(@Param(\"id\") Long id);\n}", "@Service\npublic class MenuService {\n\n\t@Autowired\n\tprivate MenuDao menuDao;\n\t@Autowired\n\tRoleMenuDao roleMenuDao;\n\n\tpublic List<Menu> getChildMenuList(ArrayList<Menu> menuLists, Long parentId) {\n\n\t\tList<Menu> List = menuDao.findMenuByParentId(parentId);\n\t\tfor (Menu menu : List) {\n\t\t\tmenuLists.add(menu);\n\t\t\tgetChildMenuList(menuLists, menu.getId());\n\t\t}\n\t\treturn menuLists;\n\t}\n\n\t@Transactional\n\tpublic void saveMenu(Menu menu) {\n\t\tif (menu.getId() != null) {\n\t\t\tMenu m = menuDao.findOne(menu.getId());\n\t\t\tm.setUpdateTime(new Date());\n\t\t\tm.setName(menu.getName());\n\t\t\tm.setCode(menu.getCode());\n\t\t\tm.setUrl(menu.getUrl());\n\t\t\tm.setType(menu.getType());\n\t\t\tmenuDao.save(m);\n\t\t} else {\n\t\t\tmenu.setCreateTime(new Date());\n\t\t\tmenu.setSort(1);\n\t\t\tmenuDao.save(menu);\n\t\t}\n\n\t\tif (menu.getParentId() != 0) {\n\t\t\tmenu = menuDao.findOne(menu.getParentId());\n\t\t\tmenu.setUpdateTime(new Date());\n\t\t\tmenuDao.save(menu);\n\t\t}\n\n\t}\n\t\n\t@Transactional\n\tpublic void delMenu(Long id) {\n\t\tmenuDao.delete(id);\n\t\troleMenuDao.delete(id);\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import com.geekhome.common.vo.ErrorCode; import com.geekhome.common.vo.ExecuteResult; import com.geekhome.entity.Menu; import com.geekhome.entity.dao.MenuDao; import com.geekhome.entity.service.MenuService;
package com.geekhome.controller; @RestController @RequestMapping("menu") public class MenuController { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired MenuService menuService; @Autowired
private MenuDao menuDao;
3
DDoS/JICI
src/main/java/ca/sapon/jici/parser/expression/ClassAccess.java
[ "public interface SourceIndexed {\n int getStart();\n\n int getEnd();\n}", "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n static {\n for (String name : ReflectionUtil.JAVA_LANG_CLASSES) {\n try {\n DEFAULT_CLASSES.put(name, Class.forName(\"java.lang.\" + name));\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(\"class java.lang.\" + name + \" not found\");\n }\n }\n }\n\n public void importClass(Class<?> _class) {\n final String name = _class.getCanonicalName();\n // Validate the type of class\n if (_class.isPrimitive()) {\n throw new UnsupportedOperationException(\"Can't import a primitive type: \" + name);\n }\n if (_class.isArray()) {\n throw new UnsupportedOperationException(\"Can't import an array class: \" + name);\n }\n if (_class.isAnonymousClass()) {\n throw new UnsupportedOperationException(\"Can't import an anonymous class: \" + name);\n }\n // Check for existing import under the same simple name\n final String simpleName = _class.getSimpleName();\n final Class<?> existing = classes.get(simpleName);\n // ignore cases where the classes are the same as redundant imports are allowed\n if (existing != null && _class != existing) {\n throw new UnsupportedOperationException(\"Class \" + name + \" clashes with existing import \" + existing.getCanonicalName());\n }\n // Add the class to the imports\n classes.put(simpleName, _class);\n }\n\n public Class<?> findClass(Identifier name) {\n return classes.get(name.getSource());\n }\n\n public Class<?> getClass(Identifier name) {\n final Class<?> _class = findClass(name);\n if (_class == null) {\n throw new UnsupportedOperationException(\"Class \" + name.getSource() + \" does not exist\");\n }\n return _class;\n }\n\n public Collection<Class<?>> getClasses() {\n return classes.values();\n }\n\n public boolean hasClass(Identifier name) {\n return classes.containsKey(name.getSource());\n }\n\n public boolean hasClass(Class<?> _class) {\n return classes.containsValue(_class);\n }\n\n public void declareVariable(Identifier name, LiteralType type, Value value) {\n if (hasVariable(name)) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" is already declared\");\n }\n variables.put(name.getSource(), new Variable(name, type, value));\n }\n\n public LiteralType getVariableType(Identifier name) {\n return findVariable(name).getType();\n }\n\n public Value getVariable(Identifier name) {\n return findVariable(name).getValue();\n }\n\n public Collection<Variable> getVariables() {\n return variables.values();\n }\n\n public void setVariable(Identifier name, Value value) {\n findVariable(name).setValue(value);\n }\n\n public boolean hasVariable(Identifier name) {\n return variables.containsKey(name.getSource());\n }\n\n private Variable findVariable(Identifier name) {\n final String nameString = name.getSource();\n final Variable variable = variables.get(nameString);\n if (variable == null) {\n throw new UnsupportedOperationException(\"Variable \" + nameString + \" does not exist\");\n }\n return variable;\n }\n\n public static class Variable {\n private final Identifier name;\n private final LiteralType type;\n private Value value;\n\n private Variable(Identifier name, LiteralType type, Value value) {\n this.name = name;\n this.type = type;\n this.value = value;\n }\n\n public Identifier getName() {\n return name;\n }\n\n public LiteralType getType() {\n return type;\n }\n\n public boolean initialized() {\n return value != null;\n }\n\n public Value getValue() {\n if (!initialized()) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" has not been initialized\");\n }\n return value;\n }\n\n private void setValue(Value value) {\n this.value = value;\n }\n }\n}", "public class LiteralReferenceType extends SingleReferenceType implements LiteralType, TypeArgument {\n public static final LiteralReferenceType THE_STRING = LiteralReferenceType.of(String.class);\n public static final LiteralReferenceType THE_OBJECT = LiteralReferenceType.of(Object.class);\n public static final LiteralReferenceType THE_CLONEABLE = LiteralReferenceType.of(Cloneable.class);\n public static final LiteralReferenceType THE_SERIALIZABLE = LiteralReferenceType.of(Serializable.class);\n private static final Map<Class<?>, PrimitiveType> UNBOXING_CONVERSIONS = new HashMap<>();\n private final Class<?> type;\n private PrimitiveType unbox;\n private boolean unboxCached = false;\n private java.lang.reflect.TypeVariable<?>[] parameters = null;\n\n static {\n UNBOXING_CONVERSIONS.put(Boolean.class, PrimitiveType.THE_BOOLEAN);\n UNBOXING_CONVERSIONS.put(Byte.class, PrimitiveType.THE_BYTE);\n UNBOXING_CONVERSIONS.put(Short.class, PrimitiveType.THE_SHORT);\n UNBOXING_CONVERSIONS.put(Character.class, PrimitiveType.THE_CHAR);\n UNBOXING_CONVERSIONS.put(Integer.class, PrimitiveType.THE_INT);\n UNBOXING_CONVERSIONS.put(Long.class, PrimitiveType.THE_LONG);\n UNBOXING_CONVERSIONS.put(Float.class, PrimitiveType.THE_FLOAT);\n UNBOXING_CONVERSIONS.put(Double.class, PrimitiveType.THE_DOUBLE);\n }\n\n protected LiteralReferenceType(Class<?> type) {\n this.type = type;\n }\n\n @Override\n public String getName() {\n return type.getCanonicalName();\n }\n\n @Override\n public boolean isArray() {\n return type.isArray();\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n public boolean isRaw() {\n return getTypeParameters().length > 0;\n }\n\n public boolean isInterface() {\n return type.isInterface();\n }\n\n public boolean isEnum() {\n return type.isEnum();\n }\n\n public boolean isAbstract() {\n return Modifier.isAbstract(type.getModifiers());\n }\n\n public boolean isPublic() {\n return Modifier.isPublic(type.getModifiers());\n }\n\n public boolean isStatic() {\n return Modifier.isStatic(type.getModifiers());\n }\n\n public boolean isInnerClassOf(LiteralReferenceType enclosing) {\n if (enclosing == null) {\n // Enclosing as null means that it should not be an inner class\n return isStatic() || type.getEnclosingClass() == null;\n }\n return !isStatic() && type.getEnclosingClass() == enclosing.getTypeClass();\n }\n\n @Override\n public Class<?> getTypeClass() {\n return type;\n }\n\n protected java.lang.reflect.TypeVariable<?>[] getTypeParameters() {\n if (this.parameters == null) {\n // If this is an array, we need to get to the base component type\n Class<?> base = type;\n while (base.isArray()) {\n base = base.getComponentType();\n }\n this.parameters = base.getTypeParameters();\n }\n return parameters;\n }\n\n public boolean isBox() {\n if (!unboxCached) {\n unbox = UNBOXING_CONVERSIONS.get(type);\n unboxCached = true;\n }\n return unbox != null;\n }\n\n public PrimitiveType unbox() {\n if (isBox()) {\n return unbox;\n }\n throw new UnsupportedOperationException(type.getCanonicalName() + \" is not a box type\");\n }\n\n public LiteralType tryUnbox() {\n if (isBox()) {\n return unbox;\n }\n return this;\n }\n\n @Override\n public LiteralReferenceType getErasure() {\n return this;\n }\n\n @Override\n public Set<LiteralReferenceType> getDirectSuperTypes() {\n final Set<LiteralReferenceType> superTypes = new HashSet<>();\n if (isArray()) {\n // Find the number of dimensions of the array and the base component type\n int dimensions = 0;\n ComponentType componentType = this;\n do {\n if (!(componentType instanceof ReferenceType)) {\n break;\n }\n componentType = ((ReferenceType) componentType).getComponentType();\n dimensions++;\n } while (componentType.isArray());\n if (componentType.equals(LiteralReferenceType.THE_OBJECT)) {\n // For an object component type we use the actual array direct super types\n superTypes.add(LiteralReferenceType.THE_OBJECT.asArray(dimensions - 1));\n superTypes.add(LiteralReferenceType.THE_SERIALIZABLE.asArray(dimensions - 1));\n superTypes.add(LiteralReferenceType.THE_CLONEABLE.asArray(dimensions - 1));\n } else {\n // Add all the component direct super types as arrays of the same dimension\n if (componentType instanceof LiteralReferenceType) {\n for (LiteralReferenceType superType : ((LiteralReferenceType) componentType).getDirectSuperTypes()) {\n superTypes.add(superType.asArray(dimensions));\n }\n }\n }\n } else {\n // Add the direct super class and the directly implemented interfaces\n if (isInterface()) {\n // Interfaces have object as an implicit direct super class\n superTypes.add(LiteralReferenceType.THE_OBJECT);\n } else {\n // This will always return something unless this class is object\n final LiteralReferenceType superClass = getDirectSuperClass();\n if (superClass != null) {\n superTypes.add(superClass);\n }\n }\n Collections.addAll(superTypes, getDirectlyImplementedInterfaces());\n }\n return superTypes;\n }\n\n @Override\n public LinkedHashSet<LiteralReferenceType> getSuperTypes() {\n final LinkedHashSet<LiteralReferenceType> result = new LinkedHashSet<>();\n final Queue<LiteralReferenceType> queue = new ArrayDeque<>();\n queue.add(capture());\n final boolean raw = isRaw();\n while (!queue.isEmpty()) {\n LiteralReferenceType child = queue.remove();\n if (raw) {\n child = child.getErasure();\n }\n if (result.add(child)) {\n queue.addAll(child.getDirectSuperTypes());\n }\n }\n return result;\n }\n\n @Override\n public LiteralReferenceType substituteTypeVariables(Substitutions substitution) {\n return this;\n }\n\n @Override\n public Set<TypeVariable> getTypeVariables() {\n return new HashSet<>();\n }\n\n public LiteralReferenceType getDirectSuperClass() {\n final java.lang.reflect.Type superClass = type.getGenericSuperclass();\n if (superClass != null) {\n final LiteralReferenceType wrappedClass = (LiteralReferenceType) TypeCache.wrapType(superClass);\n return isRaw() ? wrappedClass.getErasure() : wrappedClass;\n }\n return null;\n }\n\n public LiteralReferenceType[] getDirectlyImplementedInterfaces() {\n final java.lang.reflect.Type[] interfaces = type.getGenericInterfaces();\n final boolean raw = isRaw();\n final LiteralReferenceType[] wrapped = new LiteralReferenceType[interfaces.length];\n for (int i = 0; i < interfaces.length; i++) {\n final LiteralReferenceType wrappedInterface = (LiteralReferenceType) TypeCache.wrapType(interfaces[i]);\n wrapped[i] = raw ? wrappedInterface.getErasure() : wrappedInterface;\n }\n return wrapped;\n }\n\n @Override\n public LiteralReferenceType capture() {\n return this;\n }\n\n @Override\n public ComponentType getComponentType() {\n final Class<?> componentType = type.getComponentType();\n if (componentType == null) {\n throw new UnsupportedOperationException(\"Not an array type\");\n }\n return (ComponentType) TypeCache.wrapClass(componentType);\n }\n\n @Override\n public LiteralReferenceType asArray(int dimensions) {\n return of(ReflectionUtil.asArrayType(type, dimensions));\n }\n\n @Override\n public Object newArray(int length) {\n return Array.newInstance(type, length);\n }\n\n @Override\n public Object newArray(int[] lengths) {\n return Array.newInstance(type, lengths);\n }\n\n @Override\n public boolean contains(TypeArgument other) {\n return equals(other);\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Literal class types might be convertible to a primitive if they can be unboxed\n if (to.isPrimitive()) {\n return isBox() && unbox().convertibleTo(to);\n }\n // If the target literal type is parametrized, this type must have a parent with\n // the same erasure and compatible type arguments\n if (to instanceof ParametrizedType) {\n final ParametrizedType parametrized = (ParametrizedType) to;\n final LiteralReferenceType erasure = parametrized.getErasure();\n for (LiteralReferenceType superType : getSuperTypes()) {\n if (superType.getErasure().equals(erasure)) {\n return !(superType instanceof ParametrizedType)\n || parametrized.argumentsContain(((ParametrizedType) superType).getArguments());\n }\n }\n return false;\n }\n // Else they can be converted to another literal class if they are a subtype\n if (to instanceof LiteralReferenceType) {\n final LiteralReferenceType target = (LiteralReferenceType) to;\n return target.type.isAssignableFrom(type);\n }\n // They can also be converted to a type variable lower bound\n if (to instanceof TypeVariable) {\n final TypeVariable target = (TypeVariable) to;\n return convertibleTo(target.getLowerBound());\n }\n // They can also be converted to an intersection if they can be converted to each member\n if (to instanceof IntersectionType) {\n final IntersectionType target = (IntersectionType) to;\n for (SingleReferenceType type : target.getTypes()) {\n if (!convertibleTo(type)) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean isUncheckedConversion(Type to) {\n if (!(to instanceof ParametrizedType)) {\n return false;\n }\n final ParametrizedType parametrized = (ParametrizedType) to;\n final LiteralReferenceType erasure = parametrized.getErasure();\n for (LiteralReferenceType superType : getSuperTypes()) {\n if (superType.getErasure().equals(erasure)) {\n return !(superType instanceof ParametrizedType);\n }\n }\n return false;\n }\n\n public LiteralReferenceType getDeclaredInnerClass(String name, TypeArgument[] typeArguments) {\n for (Class<?> _class : type.getDeclaredClasses()) {\n final int modifiers = _class.getModifiers();\n // Ignore non-public classes and synthetic classes generated by the compiler\n // Class must be non-static to be an inner class\n if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers) || _class.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!_class.getSimpleName().equals(name)) {\n continue;\n }\n // If this enclosing class is parametrized, than it is an owner and the inner class is also parametrized\n return typeArguments.length > 0 || this instanceof ParametrizedType ?\n ParametrizedType.of((ParametrizedType) this, _class, Arrays.asList(typeArguments)) :\n LiteralReferenceType.of(_class);\n }\n return null;\n }\n\n public ClassVariable getDeclaredField(String name) {\n // Array length field must be handled specially because the reflection API doesn't declare it\n if (isArray() && \"length\".equals(name)) {\n return ArrayLengthVariable.of(this);\n }\n // Only one field can match the name, not overloads are possible\n for (Field field : type.getDeclaredFields()) {\n // Ignore non-public fields and synthetic fields generated by the compiler\n if (!Modifier.isPublic(field.getModifiers()) || field.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!field.getName().equals(name)) {\n continue;\n }\n return InstanceVariable.of(this, field);\n }\n return null;\n }\n\n public Set<ConstructorCallable> getDeclaredConstructors(TypeArgument[] typeArguments) {\n final Set<ConstructorCallable> constructors = new HashSet<>();\n for (Constructor<?> constructor : type.getDeclaredConstructors()) {\n // Ignore non-public constructors and synthetic constructors generated by the compiler\n if (!Modifier.isPublic(constructor.getModifiers()) || constructor.isSynthetic()) {\n continue;\n }\n // Try to create a callable for the constructor, might fail if the type arguments are out of bounds\n final ConstructorCallable callable = ConstructorCallable.of(this, constructor, typeArguments);\n if (callable != null) {\n constructors.add(callable);\n }\n }\n return constructors;\n }\n\n public Set<? extends Callable> getDeclaredMethods(String name, TypeArgument[] typeArguments) {\n // Array clone method must be handled specially because the reflection API doesn't declare it\n if (isArray() && \"clone\".equals(name)) {\n return Collections.singleton(ArrayCloneCallable.of(this));\n }\n final Set<MethodCallable> methods = new HashSet<>();\n for (Method method : type.getDeclaredMethods()) {\n // Ignore non-public methods and synthetic methods generated by the compiler\n if (!Modifier.isPublic(method.getModifiers()) || method.isSynthetic()) {\n continue;\n }\n // Check name match\n if (!method.getName().equals(name)) {\n continue;\n }\n // Try to create a callable for the method, might fail if the type arguments are out of bounds\n final MethodCallable callable = MethodCallable.of(this, method, typeArguments);\n if (callable != null) {\n methods.add(callable);\n }\n }\n return methods;\n }\n\n @Override\n public LiteralReferenceType getInnerClass(String name, TypeArgument[] typeArguments) {\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n final LiteralReferenceType innerClass = type.getDeclaredInnerClass(name, typeArguments);\n if (innerClass != null) {\n return innerClass;\n }\n }\n throw new UnsupportedOperationException(\"No inner class for signature \" + name +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n \" in \" + getName());\n }\n\n @Override\n public ClassVariable getField(String name) {\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n final ClassVariable field = type.getDeclaredField(name);\n if (field != null) {\n return field;\n }\n }\n throw new UnsupportedOperationException(\"No field named \" + name + \" in \" + getName());\n }\n\n @Override\n public ConstructorCallable getConstructor(TypeArgument[] typeArguments, Type[] arguments) {\n // Get the declared constructors and look for applicable candidates with and without using vararg\n final Set<ConstructorCallable> regularCandidates = new HashSet<>();\n final Set<ConstructorCallable> varargCandidates = new HashSet<>();\n final Set<ConstructorCallable> constructors = getDeclaredConstructors(typeArguments);\n for (ConstructorCallable constructor : constructors) {\n if (constructor.isApplicable(arguments)) {\n regularCandidates.add(constructor);\n }\n if (!constructor.supportsVararg()) {\n continue;\n }\n final ConstructorCallable varargConstructor = constructor.useVararg();\n if (varargConstructor.isApplicable(arguments)) {\n varargCandidates.add(varargConstructor);\n }\n }\n // Resolve overloads\n ConstructorCallable callable = reduceCallableCandidates(regularCandidates, arguments);\n // If the regular callables don't work, try with vararg\n if (callable == null) {\n callable = reduceCallableCandidates(varargCandidates, arguments);\n }\n if (callable != null) {\n return callable.requiresUncheckedConversion(arguments) ? callable.eraseReturnType() : callable;\n }\n throw new UnsupportedOperationException(\"No constructor for signature: \" +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n type.getSimpleName() + \"(\" + StringUtil.toString(Arrays.asList(arguments), \", \") + \") in \" + getName());\n }\n\n @Override\n public Callable getMethod(String name, TypeArgument[] typeArguments, Type[] arguments) {\n // Get the declared methods and look for applicable candidates with and without using vararg\n final Set<Callable> regularCandidates = new HashSet<>();\n final Set<Callable> varargCandidates = new HashSet<>();\n final LinkedHashSet<LiteralReferenceType> superTypes = getSuperTypes();\n for (LiteralReferenceType type : superTypes) {\n // Check that the type is accessible\n if (!type.isPublic()) {\n // TODO: proper access control, for now exclude non-public types\n continue;\n }\n for (Callable method : type.getDeclaredMethods(name, typeArguments)) {\n if (method.isApplicable(arguments)) {\n regularCandidates.add(method);\n }\n if (!method.supportsVararg()) {\n continue;\n }\n final Callable varargMethod = method.useVararg();\n if (varargMethod.isApplicable(arguments)) {\n varargCandidates.add(varargMethod);\n }\n }\n }\n // Resolve overloads\n Callable callable = reduceCallableCandidates(regularCandidates, arguments);\n // If the regular callables don't work, try with vararg\n if (callable == null) {\n callable = reduceCallableCandidates(varargCandidates, arguments);\n }\n if (callable != null) {\n return callable.requiresUncheckedConversion(arguments) ? callable.eraseReturnType() : callable;\n }\n throw new UnsupportedOperationException(\"No method for signature: \" +\n (typeArguments.length > 0 ? '<' + StringUtil.toString(typeArguments, \", \") + '>' : \"\") +\n name + \"(\" + StringUtil.toString(Arrays.asList(arguments), \", \") + \") in \" + getName());\n }\n\n private static <C extends Callable> C reduceCallableCandidates(Set<C> candidates, Type[] arguments) {\n // Reduce the regular candidates to keep only the most applicable ones\n for (Iterator<C> iterator = candidates.iterator(); iterator.hasNext(); ) {\n final C candidate1 = iterator.next();\n for (C candidate2 : candidates) {\n // Don't compare with itself\n if (candidate1 == candidate2) {\n continue;\n }\n // Remove candidate1 is candidate2 is more applicable\n if (candidate2.isMoreApplicableThan(candidate1, arguments)) {\n iterator.remove();\n break;\n }\n }\n }\n return candidates.size() != 1 ? null : candidates.iterator().next();\n }\n\n public Substitutions getSubstitutions() {\n return Substitutions.NONE;\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || (other instanceof LiteralReferenceType) && this.type == ((LiteralReferenceType) other).type;\n }\n\n @Override\n public int hashCode() {\n return type.getName().hashCode();\n }\n\n public static LiteralReferenceType of(Class<?> type) {\n checkOwner(null, type);\n return new LiteralReferenceType(type);\n }\n\n protected static ParametrizedType checkOwner(ParametrizedType paramOwner, Class<?> inner) {\n return checkOwner(paramOwner, inner, Collections.<TypeArgument>emptyList());\n }\n\n protected static ParametrizedType checkOwner(ParametrizedType paramOwner, Class<?> inner, List<TypeArgument> arguments) {\n final LiteralReferenceType owner;\n final Class<?> enclosingClass = inner.getEnclosingClass();\n if (paramOwner != null) {\n // If the owner is given, check that it matches what is actually declared in the code\n if (!paramOwner.getTypeClass().equals(enclosingClass)) {\n throw new UnsupportedOperationException(\"Mismatch between given owner and actual one: \" + paramOwner + \" and \" + enclosingClass);\n }\n // Also check that the inner type is selectable (that is, not static)\n if (Modifier.isStatic(inner.getModifiers())) {\n throw new UnsupportedOperationException(\"Inner type \" + inner.getSimpleName() + \" cannot be used in a static context\");\n }\n owner = paramOwner;\n } else if (enclosingClass != null) {\n // If it's not given, check if enclosing class is applicable: the inner class cannot be static\n if (!Modifier.isStatic(inner.getModifiers())) {\n owner = LiteralReferenceType.of(enclosingClass);\n } else {\n // The enclosing class isn't an owner type\n owner = null;\n }\n } else {\n // No enclosing class\n owner = null;\n }\n if (owner != null) {\n // Now that we found an owner, make sure we don't have a partially raw owner/inner combination\n // Owner and inner cannot have one be raw and one not raw\n final boolean ownerParam = owner instanceof ParametrizedType;\n final boolean ownerRaw = owner.isRaw();\n final boolean innerParam = !arguments.isEmpty();\n final boolean innerRaw = inner.getTypeParameters().length > 0 && arguments.isEmpty();\n if ((ownerParam || ownerRaw) && (innerParam || innerRaw) && ownerRaw != innerRaw) {\n throw new UnsupportedOperationException(\"Cannot have a mix of raw and generic outer and inner classes\");\n }\n // We only care of the owner if it is parametrized, as the type arguments are accessible by inner types\n // We want to access those, the rest doesn't matter\n return ownerParam ? (ParametrizedType) owner : null;\n }\n return null;\n }\n}", "public interface Type {\n String getName();\n\n ValueKind getKind();\n\n boolean isVoid();\n\n boolean isNull();\n\n boolean isPrimitive();\n\n boolean isNumeric();\n\n boolean isIntegral();\n\n boolean isBoolean();\n\n boolean isArray();\n\n boolean isReference();\n\n boolean isReifiable();\n\n boolean convertibleTo(Type to);\n\n Type capture();\n\n @Override\n String toString();\n\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}", "public class ObjectValue implements Value {\n private static final ObjectValue THE_NULL = new ObjectValue();\n private final Object value;\n private final ValueKind kind;\n private final Value unboxed;\n\n private ObjectValue() {\n value = null;\n kind = ValueKind.OBJECT;\n unboxed = null;\n }\n\n private ObjectValue(Object value) {\n this.value = value;\n unboxed = ValueKind.unbox(value);\n kind = unboxed == null ? ValueKind.OBJECT : unboxed.getKind();\n }\n\n @Override\n public boolean asBoolean() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a boolean\");\n }\n return unboxed.asBoolean();\n }\n\n @Override\n public byte asByte() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a byte\");\n }\n return unboxed.asByte();\n }\n\n @Override\n public short asShort() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a short\");\n }\n return unboxed.asShort();\n }\n\n @Override\n public char asChar() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a char\");\n }\n return unboxed.asChar();\n }\n\n @Override\n public int asInt() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a int\");\n }\n return unboxed.asInt();\n }\n\n @Override\n public long asLong() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a long\");\n }\n return unboxed.asLong();\n }\n\n @Override\n public float asFloat() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a float\");\n }\n return unboxed.asFloat();\n }\n\n @Override\n public double asDouble() {\n if (kind == ValueKind.OBJECT) {\n throw new UnsupportedOperationException(\"Cannot convert an object to a double\");\n }\n return unboxed.asDouble();\n }\n\n @Override\n public Object asObject() {\n return value;\n }\n\n @Override\n public String asString() {\n return value == null ? \"null\" : value.toString();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T> T as() {\n return (T) asObject();\n }\n\n @Override\n public ValueKind getKind() {\n return kind;\n }\n\n @Override\n public boolean isPrimitive() {\n return false;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return value == null ? null : value.getClass();\n }\n\n @Override\n public String toString() {\n return '\"' + asString() + '\"';\n }\n\n public static ObjectValue of(Object value) {\n if (value == null) {\n return THE_NULL;\n }\n return new ObjectValue(value);\n }\n\n public static ObjectValue defaultValue() {\n return THE_NULL;\n }\n}", "public interface Value {\n boolean asBoolean();\n\n byte asByte();\n\n short asShort();\n\n char asChar();\n\n int asInt();\n\n long asLong();\n\n float asFloat();\n\n double asDouble();\n\n Object asObject();\n\n String asString();\n\n <T> T as();\n\n ValueKind getKind();\n\n boolean isPrimitive();\n\n Class<?> getTypeClass();\n\n String toString();\n}", "public abstract class Token implements SourceIndexed {\n private final TokenID id;\n private final String source;\n private int start;\n private int end;\n\n protected Token(TokenID id, String source, int index) {\n this.id = id;\n this.source = source;\n this.start = index;\n this.end = index + source.length() - 1;\n }\n\n protected Token(TokenID id, String source, int start, int end) {\n this.id = id;\n this.source = source;\n this.start = start;\n this.end = end;\n }\n\n public TokenID getID() {\n return id;\n }\n\n public TokenGroup getGroup() {\n return id.getGroup();\n }\n\n public String getSource() {\n return source;\n }\n\n public int getIndex() {\n return start;\n }\n\n @Override\n public int getStart() {\n return start;\n }\n\n @Override\n public int getEnd() {\n return end;\n }\n\n public void setStart(int start) {\n this.start = start;\n }\n\n public void setEnd(int end) {\n this.end = end;\n }\n\n @Override\n public String toString() {\n return getSource();\n }\n}", "public enum TokenID {\n IDENTIFIER(TokenGroup.IDENTIFIER),\n KEYWORD_ASSERT(TokenGroup.UNSPECIFIED),\n KEYWORD_IF(TokenGroup.UNSPECIFIED),\n KEYWORD_ELSE(TokenGroup.UNSPECIFIED),\n KEYWORD_WHILE(TokenGroup.UNSPECIFIED),\n KEYWORD_DO(TokenGroup.UNSPECIFIED),\n KEYWORD_FOR(TokenGroup.UNSPECIFIED),\n KEYWORD_BREAK(TokenGroup.UNSPECIFIED),\n KEYWORD_CONTINUE(TokenGroup.UNSPECIFIED),\n KEYWORD_SWITCH(TokenGroup.UNSPECIFIED),\n KEYWORD_CASE(TokenGroup.UNSPECIFIED),\n KEYWORD_DEFAULT(TokenGroup.UNSPECIFIED),\n KEYWORD_RETURN(TokenGroup.UNSPECIFIED),\n KEYWORD_THROW(TokenGroup.UNSPECIFIED),\n KEYWORD_TRY(TokenGroup.UNSPECIFIED),\n KEYWORD_CATCH(TokenGroup.UNSPECIFIED),\n KEYWORD_FINALLY(TokenGroup.UNSPECIFIED),\n KEYWORD_VOID(TokenGroup.UNSPECIFIED),\n KEYWORD_BOOLEAN(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_BYTE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_SHORT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CHAR(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_INT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_LONG(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_FLOAT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_DOUBLE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CLASS(TokenGroup.CLASS_TYPE),\n KEYWORD_INTERFACE(TokenGroup.CLASS_TYPE),\n KEYWORD_ENUM(TokenGroup.CLASS_TYPE),\n KEYWORD_EXTENDS(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPLEMENTS(TokenGroup.UNSPECIFIED),\n KEYWORD_SUPER(TokenGroup.SELF_REFERENCE),\n KEYWORD_THIS(TokenGroup.SELF_REFERENCE),\n KEYWORD_PACKAGE(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPORT(TokenGroup.UNSPECIFIED),\n KEYWORD_PUBLIC(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PROTECTED(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PRIVATE(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_THROWS(TokenGroup.UNSPECIFIED),\n KEYWORD_ABSTRACT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STRICTFP(TokenGroup.OTHER_MODIFIER),\n KEYWORD_TRANSIENT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_VOLATILE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_FINAL(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STATIC(TokenGroup.OTHER_MODIFIER),\n KEYWORD_SYNCHRONIZED(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NATIVE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NEW(TokenGroup.UNSPECIFIED),\n KEYWORD_INSTANCEOF(TokenGroup.BINARY_OPERATOR),\n KEYWORD_GOTO(TokenGroup.UNUSED),\n KEYWORD_CONST(TokenGroup.UNUSED),\n SYMBOL_PERIOD(TokenGroup.CALL_OPERATOR),\n SYMBOL_COMMA(TokenGroup.UNSPECIFIED),\n SYMBOL_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_SEMICOLON(TokenGroup.UNSPECIFIED),\n SYMBOL_PLUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MINUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MULTIPLY(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_DIVIDE(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_MODULO(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_INCREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_DECREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_XOR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LOGICAL_LEFT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_LOGICAL_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_BOOLEAN_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BOOLEAN_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BOOLEAN_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LESSER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_LESSER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_NOT_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ADD_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_SUBTRACT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_MULTIPLY_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_DIVIDE_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_REMAINDER_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_AND_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_OR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_XOR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_OPEN_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_SLASH_STAR(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_STAR_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_QUESTION_MARK(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_PERIOD(TokenGroup.UNUSED),\n SYMBOL_TRIPLE_PERIOD(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_ARROW(TokenGroup.UNSPECIFIED),\n SYMBOL_AT(TokenGroup.UNSPECIFIED),\n LITERAL_TRUE(TokenGroup.LITERAL),\n LITERAL_FALSE(TokenGroup.LITERAL),\n LITERAL_CHARACTER(TokenGroup.LITERAL),\n LITERAL_NULL(TokenGroup.LITERAL),\n LITERAL_STRING(TokenGroup.LITERAL),\n LITERAL_DOUBLE(TokenGroup.LITERAL),\n LITERAL_FLOAT(TokenGroup.LITERAL),\n LITERAL_INT(TokenGroup.LITERAL),\n LITERAL_LONG(TokenGroup.LITERAL);\n private final TokenGroup group;\n\n TokenID(TokenGroup group) {\n this.group = group;\n }\n\n public TokenGroup getGroup() {\n return group;\n }\n}", "public interface TypeName extends SourceIndexed {\n LiteralType getType(Environment environment);\n\n @Override\n String toString();\n}" ]
import ca.sapon.jici.lexer.TokenID; import ca.sapon.jici.parser.name.TypeName; import ca.sapon.jici.SourceIndexed; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.type.LiteralReferenceType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.ObjectValue; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.lexer.Token;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ca.sapon.jici.parser.expression; public class ClassAccess implements Expression { private static final LiteralReferenceType TYPE = LiteralReferenceType.of(Class.class); private final TypeName typeName; private final SourceIndexed source; private int start; private int end; private Type type = null; private Class<?> typeClass = null; public ClassAccess(Token voidToken, int end) {
if (voidToken.getID() != TokenID.KEYWORD_VOID) {
7
SergiusIW/collider
demos-core/src/com/matthewmichelotti/collider/demos/comps/CCoagParticle.java
[ "public final class HBCircle extends HBPositioned {\n\tdouble startRad;\n\tdouble velRad;\n\t\n\tHBCircle(Collider collider) {\n\t\tsuper(collider);\n\t}\n\n\t@Override\n\tvoid init() {\n\t\tsuper.init();\n\t\tthis.startRad = 0.0;\n\t\tthis.velRad = 0.0;\n\t}\n\n\t@Override\n\tvoid markTransitionStart() {\n\t\tdouble time = collider.getTime();\n\t\tstartRad = getRad(time);\n\t\tsuper.markTransitionStart();\n\t}\n\n\t@Override\n\tpublic void free() {\n\t\tcollider.free(this);\n\t\tsuper.free();\n\t}\n\t\n\t/**\n\t * Set the diameter.\n\t * @param diam Diameter.\n\t */\n\tpublic void setDiam(double diam) {\n\t\tcollider.altering(this);\n\t\tthis.startRad = .5*diam;\n\t}\n\t\n\t/**\n\t * Set the velocity of the diameter.\n\t * @param velDiam Velocity of the diameter.\n\t */\n\tpublic void setVelDiam(double velDiam) {\n\t\tcollider.altering(this);\n\t\tthis.velRad = .5*velDiam;\n\t}\n\t\n\tdouble getRad(double time) {return startRad + (time - startTime)*velRad;}\n\t\n\t/**\n\t * Get the diameter.\n\t * @return Diameter.\n\t */\n\tpublic double getDiam() {return 2*getRad(collider.getTime());}\n\t\n\t/**\n\t * Get the velocity of the diameter.\n\t * @return Velocity of the diameter.\n\t */\n\tpublic double getVelDiam() {return 2*velRad;}\n\t\n\tdouble getStartEdgeComp(int edge) {\n\t\treturn getStartPosComp(edge) + startRad;\n\t}\n\t\n\tdouble getVelEdgeComp(int edge) {\n\t\treturn getVelComp(edge) + velRad;\n\t}\n\n\t@Override\n\tdouble getBoundEdgeComp(int edge, double startTime, double endTime) {\n\t\tdouble base = getStartEdgeComp(edge);\n\t\tdouble vel = getVelEdgeComp(edge);\n\t\tdouble evalTime = (vel > 0.0) ? endTime : startTime;\n\t\treturn base + vel*(evalTime - this.startTime);\n\t}\n\n\t@Override\n\tboolean isMoving() {\n\t\treturn velX != 0.0 || velY != 0.0 || velRad != 0.0;\n\t}\n\n\t@Override\n\tdouble getMaxBoundEdgeVel() {\n\t\tdouble vel = 0.0;\n\t\tdouble absVelRad = Arith.abs(velRad);\n\t\tfor(int dir = 0; dir < 2; dir++) {\n\t\t\tvel = Math.max(vel, Arith.abs(getVelComp(dir)) + absVelRad);\n\t\t}\n\t\treturn vel;\n\t}\n}", "public final class HBRect extends HBPositioned {\n\tdouble startHW, startHH;\n\tdouble velHW, velHH;\n\t\n\tHBRect(Collider collider) {\n\t\tsuper(collider);\n\t}\n\n\t@Override\n\tvoid init() {\n\t\tsuper.init();\n\t\tthis.startHW = 0.0;\n\t\tthis.startHH = 0.0;\n\t\tthis.velHW = 0.0;\n\t\tthis.velHH = 0.0;\n\t}\n\n\t@Override\n\tvoid markTransitionStart() {\n\t\tdouble time = collider.getTime();\n\t\tstartHW = getHW(time);\n\t\tstartHH = getHH(time);\n\t\tsuper.markTransitionStart();\n\t}\n\n\t@Override\n\tpublic void free() {\n\t\tcollider.free(this);\n\t\tsuper.free();\n\t}\n\t\n\t/**\n\t * Set the width.\n\t * @param width Width.\n\t */\n\tpublic void setWidth(double width) {\n\t\tcollider.altering(this);\n\t\tthis.startHW = .5*width;\n\t}\n\t\n\t/**\n\t * Set the height.\n\t * @param height Height.\n\t */\n\tpublic void setHeight(double height) {\n\t\tcollider.altering(this);\n\t\tthis.startHH = .5*height;\n\t}\n\t\n\t/**\n\t * Set the velocity of the width.\n\t * @param velWidth Velocity of the width.\n\t */\n\tpublic void setVelWidth(double velWidth) {\n\t\tcollider.altering(this);\n\t\tthis.velHW = .5*velWidth;\n\t}\n\t\n\t/**\n\t * Set the velocity of the height.\n\t * @param velHeight Velocity of the height.\n\t */\n\tpublic void setVelHeight(double velHeight) {\n\t\tcollider.altering(this);\n\t\tthis.velHH = .5*velHeight;\n\t}\n\n\t\n\t/**\n\t * Set the width and height to the same value.\n\t * @param dim Width and height.\n\t */\n\tpublic void setDims(double dim) {\n\t\tcollider.altering(this);\n\t\tthis.startHW = .5*dim;\n\t\tthis.startHH = startHW;\n\t}\n\n\t/**\n\t * Set the width and height.\n\t * @param width Width.\n\t * @param height Height.\n\t */\n\tpublic void setDims(double width, double height) {\n\t\tcollider.altering(this);\n\t\tthis.startHW = .5*width;\n\t\tthis.startHH = .5*height;\n\t}\n\t\n\t/**\n\t * Set the velocities of the width and height to the same value.\n\t * @param velDim Velocity of the width/height.\n\t */\n\tpublic void setVelDims(double velDim) {\n\t\tcollider.altering(this);\n\t\tthis.velHW = .5*velDim;\n\t\tthis.velHH = velHW;\n\t}\n\t\n\t/**\n\t * Set the velocities of the width and height;\n\t * @param velWidth Velocity of the width.\n\t * @param velHeight Velocity of the height.\n\t */\n\tpublic void setVelDims(double velWidth, double velHeight) {\n\t\tcollider.altering(this);\n\t\tthis.velHW = .5*velWidth;\n\t\tthis.velHH = .5*velHeight;\n\t}\n\t\n\tdouble getHW(double time) {return startHW + (time - startTime)*velHW;}\n\tdouble getHH(double time) {return startHH + (time - startTime)*velHH;}\n\t\n\t/**\n\t * Get the width.\n\t * @return Width.\n\t */\n\tpublic double getWidth() {return 2*getHW(collider.getTime());}\n\t\n\t/**\n\t * Get the height.\n\t * @return Height.\n\t */\n\tpublic double getHeight() {return 2*getHH(collider.getTime());}\n\t\n\t/**\n\t * Get the velocity of the width.\n\t * @return Velocity of the width.\n\t */\n\tpublic double getVelWidth() {return 2*velHW;}\n\t\n\t/**\n\t * Get the velocity of the height.\n\t * @return Velocity of the height.\n\t */\n\tpublic double getVelHeight() {return 2*velHH;}\n\t\n\tdouble getStartHDim(int dir) {\n\t\tswitch(dir) {\n\t\tcase Dir.R: case Dir.L: return startHW;\n\t\tcase Dir.U: case Dir.D: return startHH;\n\t\tdefault: throw new IllegalArgumentException();\n\t\t}\n\t}\n\t\n\tdouble getVelHDim(int dir) {\n\t\tswitch(dir) {\n\t\tcase Dir.R: case Dir.L: return velHW;\n\t\tcase Dir.U: case Dir.D: return velHH;\n\t\tdefault: throw new IllegalArgumentException();\n\t\t}\n\t}\n\t\n\tdouble getStartEdgeComp(int edge) {\n\t\treturn getStartPosComp(edge) + getStartHDim(edge);\n\t}\n\t\n\tdouble getVelEdgeComp(int edge) {\n\t\treturn getVelComp(edge) + getVelHDim(edge);\n\t}\n\t\n\tdouble getEdgeComp(int edge, double time) {\n\t\treturn getStartEdgeComp(edge) + (time - startTime)*getVelEdgeComp(edge);\n\t}\n\n\t@Override\n\tdouble getBoundEdgeComp(int edge, double startTime, double endTime) {\n\t\tdouble base = getStartEdgeComp(edge);\n\t\tdouble vel = getVelEdgeComp(edge);\n\t\tdouble evalTime = (vel > 0.0) ? endTime : startTime;\n\t\treturn base + vel*(evalTime - this.startTime);\n\t}\n\n\t@Override\n\tboolean isMoving() {\n\t\treturn velX != 0.0 || velY != 0.0 || velHW != 0.0 || velHH != 0.0;\n\t}\n\n\t@Override\n\tdouble getMaxBoundEdgeVel() {\n\t\tdouble vel = 0.0;\n\t\tfor(int dir = 0; dir < 2; dir++) {\n\t\t\tvel = Math.max(vel, Arith.abs(getVelComp(dir)) + Arith.abs(getVelHDim(dir)));\n\t\t}\n\t\treturn vel;\n\t}\n\t\n\tvoid dummyMimicCircle(HBCircle c) {\n\t\tstartTime = c.startTime;\n\t\tstartX = c.startX;\n\t\tstartY = c.startY;\n\t\tstartHW = c.startRad;\n\t\tstartHH = c.startRad;\n\t\tvelX = c.velX;\n\t\tvelY = c.velY;\n\t\tvelHW = c.velRad;\n\t\tvelHH = c.velRad;\n\t}\n}", "public abstract class Component implements Comparable<Component> {\n\tprivate static int NEXT_ID = 0;\n\tprivate final int id;\n\tprivate HBPositioned hitBox;\n\n\tprotected Component(HBPositioned hitBox) {\n\t\tif(hitBox == null) throw new IllegalArgumentException();\n\t\tthis.hitBox = hitBox;\n\t\thitBox.setOwner(this);\n\t\tid = NEXT_ID++;\n\t\tGame.engine.addComp(this);\n\t}\n\n\tprotected final void delete() {\n\t\tif(hitBox == null) return;\n\t\tGame.engine.removeComp(this);\n\t\thitBox.free();\n\t\thitBox = null;\n\t}\n\t\n\tprotected final boolean isInBounds() {return Game.engine.isInBounds(hitBox);}\n\tpublic final boolean isDeleted() {return hitBox == null;}\n\tpublic final int getId() {return id;}\n\t\n\tpublic final HBPositioned hitBox() {return hitBox;}\n\tpublic final HBCircle circ() {return (HBCircle)hitBox;}\n\tpublic final HBRect rect() {return (HBRect)hitBox;}\n\tpublic final boolean isRect() {return hitBox instanceof HBRect;}\n\tpublic final boolean isCirc() {return hitBox instanceof HBCircle;}\n\t\n\tpublic abstract void onCollide(Component other);\n\tpublic abstract void onSeparate(Component other);\n\tpublic abstract boolean canInteract(Component other);\n\tpublic abstract boolean interactsWithBullets();\n\tpublic abstract Color getColor();\n\tpublic String getMessage() {return null;}\n\t\n\t@Override public final int compareTo(Component o) {\n\t\treturn id - o.id;\n\t}\n}", "public class Game {\n\tpublic final static GameEngine engine = new GameEngine();\n\tpublic final static Random rand = new Random();\n\t\n\tprivate Game() {}\n}", "public class GameEngine {\n\tpublic final static int SCREEN_WIDTH = 1280; //960\n\tpublic final static int SCREEN_HEIGHT = 720;\n\t\n\tpublic final static int GROUP_NORMAL = 0;\n\tpublic final static int GROUP_BULLET = 1;\n\n\tprivate final static int[] ALL_GROUPS_ARR = new int[] {GROUP_NORMAL, GROUP_BULLET};\n\tprivate final static int[] NORMAL_GROUP_ARR = new int[] {GROUP_NORMAL};\n\n\tprivate ContProcesses processes;\n\tprivate Collider collider;\n\tprivate HashSet<Component> comps = new HashSet<Component>();\n\tprivate PriorityQueue<FunctionEvent> events = new PriorityQueue<FunctionEvent>();\n\tprivate MousePosListener mouseListener;\n\tprivate CBounds bounds;\n\t\n\tprivate ShapeRenderer shapeR = new ShapeRenderer();\n\tprivate SpriteBatch spriteB = new SpriteBatch();\n\tprivate BitmapFont font = new BitmapFont();\n\tprivate Color bgColor = Color.BLACK;\n\tprivate OrthographicCamera camera;\n\t\n\tprivate long renderWork = 0;\n\tprivate long otherWork = 0;\n\n\tpublic GameEngine() {\n\t\tclear();\n\t\tcamera = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT);\n\t\tcamera.translate(.5f*SCREEN_WIDTH, .5f*SCREEN_HEIGHT, 0);\n\t\tcamera.update();\n\t}\n\t\n\tpublic void clear() {\n\t\tprocesses = new ContProcesses();\n\t\t\n\t\tColliderOpts opts = new ColliderOpts();\n\t\topts.cellWidth = 22.0;\n\t\topts.separateBuffer = .1;\n\t\topts.maxForesightTime = 2.0;\n\t\topts.interactTester = new CompInteractTester();\n\t\tcollider = new Collider(opts);\n\t\t\n\t\tcomps.clear();\n\t\tevents.clear();\n\t\tmouseListener = null;\n\t\tbounds = null;\n\t\t\n\t\tbgColor = Color.BLACK;\n\n\t\tprocesses.addProcess(new ColliderProcess(collider, new MyColliderListener()));\n\t\tprocesses.addProcess(new EventProcess());\n\t\tevents.add(new LogEvent(0.0));\n\t}\n\t\n\tpublic HBRect makeRect() {return collider.makeRect();}\n\tpublic HBCircle makeCircle() {return collider.makeCircle();}\n\n\tpublic void addEvent(FunctionEvent event) {\n\t\tevents.add(event);\n\t}\n\t\n\tpublic void addComp(Component comp) {\n\t\tboolean success = comps.add(comp);\n\t\tif(!success) throw new RuntimeException();\n\t\tif(comp instanceof MousePosListener) {\n\t\t\tif(mouseListener != null) throw new RuntimeException();\n\t\t\tmouseListener = (MousePosListener)comp;\n\t\t}\n\t\tif(comp instanceof CBounds) {\n\t\t\tif(bounds != null) throw new RuntimeException();\n\t\t\tbounds = (CBounds)comp;\n\t\t}\n\t}\n\t\n\tpublic void removeComp(Component comp) {\n\t\tboolean success = comps.remove(comp);\n\t\tif(!success) throw new RuntimeException();\n\t\tif(mouseListener == comp) mouseListener = null;\n\t\tif(bounds == comp) bounds = null;\n\t}\n\t\n\tpublic boolean isInBounds(HitBox hitBox) {\n\t\treturn hitBox.getOverlap(bounds.hitBox()) >= .1;\n\t}\n\t\n\tpublic void stepToTime(double time) {\n\t\tif(time < getTime()) return;\n\t\tlong startNanoTime = TimeUtils.nanoTime();\n\t\tif(time > getTime() && mouseListener != null) {\n\t\t\tdouble x = SCREEN_WIDTH*Gdx.input.getX()/(double)Gdx.graphics.getWidth();\n\t\t\tdouble y = SCREEN_HEIGHT*(1.0 - Gdx.input.getY()/(double)Gdx.graphics.getHeight());\n\t\t\tx = Math.max(0, Math.min(SCREEN_WIDTH, x));\n\t\t\ty = Math.max(0, Math.min(SCREEN_HEIGHT, y));\n\t\t\tmouseListener.updateMousePos(time, x, y);\n\t\t}\n\t\tprocesses.stepToTime(time);\n\t\totherWork += (TimeUtils.nanoTime() - startNanoTime);\n\t}\n\t\n\tpublic double getTime() {\n\t\treturn processes.getTime();\n\t}\n\t\n\tpublic void setBG(Color color) {\n\t\tthis.bgColor = color;\n\t}\n\t\n\tpublic void render(boolean drawFPS) {\n\t\tlong startNanoTime = TimeUtils.nanoTime();\n\t\t\n\t\tspriteB.setProjectionMatrix(camera.combined);\n\t\tshapeR.setProjectionMatrix(camera.combined);\n\n\t\tGdx.gl.glClearColor(bgColor.r, bgColor.g, bgColor.b, bgColor.a);\n\t\tGdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);\n\t\t\n\t\tArrayList<Component> orderedComps = new ArrayList<Component>(comps);\n\t\tArrayList<Component> messageComps = new ArrayList<Component>();\n\t\tCollections.sort(orderedComps);\n\n\t\tshapeR.begin(ShapeType.Filled);\n\t\tfor(Component c : orderedComps) {\n\t\t\tif(c.getMessage() != null) messageComps.add(c);\n\t\t\tColor color = c.getColor();\n\t\t\tif(color == null) continue;\n\t\t\tshapeR.setColor(color);\n\t\t\tif(c.isRect()) {\n\t\t\t\tHBRect rect = c.rect();\n\t\t\t\tdouble l = rect.getX() - .5*rect.getWidth();\n\t\t\t\tdouble b = rect.getY() - .5*rect.getHeight();\n\t\t\t\tshapeR.rect((float)l, (float)b, (float)rect.getWidth(), (float)rect.getHeight());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tHBCircle circle = c.circ();\n\t\t\t\tshapeR.circle((float)circle.getX(), (float)circle.getY(), .5f*(float)circle.getDiam());\n\t\t\t}\n\t\t}\n\t\tshapeR.end();\n\n\t\tspriteB.begin();\n\t\t\n\t\tfont.setColor(Color.WHITE);\n\t\tfor(Component c : messageComps) {\n\t\t\tString message = c.getMessage();\n\t\t\tBitmapFont.TextBounds tb = font.getBounds(message);\n\t\t\tfloat x = (float)c.hitBox().getX() - .5f*tb.width;\n\t\t\tfloat y = (float)c.hitBox().getY() + .5f*tb.height;\n\t\t\tfont.draw(spriteB, message, x, y);\n\t\t}\n\t\t\n\t\tif(drawFPS) {\n\t\t\tfont.draw(spriteB, \"FPS: \"+ Gdx.graphics.getFramesPerSecond(), 0, SCREEN_HEIGHT);\n\t\t}\n\t\t\n\t\tspriteB.end();\n\t\t\n\t\trenderWork += (TimeUtils.nanoTime() - startNanoTime);\n\t}\n\t\n\tpublic void dispose() {\n\t\tshapeR.dispose();\n\t\tspriteB.dispose();\n\t\tfont.dispose();\n\t}\n\t\n\tprivate class LogEvent extends FunctionEvent {\n\t\tprivate LogEvent(double time) {super(time);}\n\t\t\n\t\t@Override public void resolve() {\n\t\t\tcollider.log();\n\t\t\tSystem.out.println(\"Free Memory: \" + Runtime.getRuntime().freeMemory());\n\t\t\tSystem.out.println(\"Total Memory: \" + Runtime.getRuntime().totalMemory());\n\t\t\tSystem.out.println(\"Rendering Work: \" + renderWork*1e-9);\n\t\t\tSystem.out.println(\"Other Work: \" + otherWork*1e-9);\n\t\t\tSystem.out.println(\"FPS: \" + Gdx.graphics.getFramesPerSecond());\n\t\t\trenderWork = 0;\n\t\t\totherWork = 0;\n\t\t\tsetTime(getTime() + 3.0);\n\t\t\taddEvent(this);\n\t\t}\n\t}\n\n\tprivate static class MyColliderListener implements ColliderListener {\n\t\t@Override public void collision(ColliderEvent evt) {\n\t\t\tComponent compA = (Component)evt.getFirst().getOwner();\n\t\t\tComponent compB = (Component)evt.getSecond().getOwner();\n\t\t\tcompA.onCollide(compB);\n\t\t\tif(!compA.isDeleted() && !compB.isDeleted()) compB.onCollide(compA);\n\t\t}\n\t\t@Override public void separation(ColliderEvent evt) {\n\t\t\tComponent compA = (Component)evt.getFirst().getOwner();\n\t\t\tComponent compB = (Component)evt.getSecond().getOwner();\n\t\t\tcompA.onSeparate(compB);\n\t\t\tif(!compA.isDeleted() && !compB.isDeleted()) compB.onSeparate(compA);\n\t\t}\n\t}\n\t\n\tprivate class EventProcess implements ContProcess {\n\t\t@Override public double peekNextEventTime() {\n\t\t\tFunctionEvent event = events.peek();\n\t\t\tif(event == null) return Double.POSITIVE_INFINITY;\n\t\t\treturn event.getTime();\n\t\t}\n\t\t@Override public void stepToTime(double time) {}\n\t\t@Override public void resolveEvent() {\n\t\t\tFunctionEvent event = events.poll();\n\t\t\tif(event.getTime() == processes.getTime()) event.resolve();\n\t\t}\n\t}\n\t\n\tprivate static class CompInteractTester implements InteractTester {\n\t\t@Override public boolean canInteract(HitBox a, HitBox b) {\n\t\t\tComponent compA = (Component)a.getOwner();\n\t\t\tComponent compB = (Component)b.getOwner();\n\t\t\treturn compA.canInteract(compB) || compB.canInteract(compA);\n\t\t}\n\n\t\t@Override public int[] getInteractGroups(HitBox hitBox) {\n\t\t\tif(((Component)hitBox.getOwner()).interactsWithBullets()) return ALL_GROUPS_ARR;\n\t\t\treturn NORMAL_GROUP_ARR;\n\t\t}\n\t}\n}", "public class Geom {\n\n\tprivate Geom() {}\n\t\n\tpublic static double area(HitBox hitBox) {\n\t\tif(hitBox instanceof HBCircle) {\n\t\t\tdouble r = .5*((HBCircle)hitBox).getDiam();\n\t\t\treturn Math.PI*r*r;\n\t\t}\n\t\telse {\n\t\t\tHBRect rect = (HBRect)hitBox;\n\t\t\treturn rect.getWidth()*rect.getHeight();\n\t\t}\n\t}\n\n\tpublic static double area2Diam(double area) {\n\t\treturn 2*Math.sqrt(area/Math.PI);\n\t}\n}" ]
import com.badlogic.gdx.graphics.Color; import com.matthewmichelotti.collider.HBCircle; import com.matthewmichelotti.collider.HBRect; import com.matthewmichelotti.collider.demos.Component; import com.matthewmichelotti.collider.demos.Game; import com.matthewmichelotti.collider.demos.GameEngine; import com.matthewmichelotti.collider.demos.Geom;
/* * Copyright 2013-2014 Matthew D. Michelotti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewmichelotti.collider.demos.comps; /** * A circular particle that can merge (aka coagulate) with other particles. * @author Matthew Michelotti */ public class CCoagParticle extends Component { public final static Color COLOR = new Color(0.1f, 0.4f, 1.0f, 1.0f); public CCoagParticle() { super(Game.engine.makeCircle()); double x = -CBounds.PAD + Math.random()*(GameEngine.SCREEN_WIDTH + 2*CBounds.PAD); double y = -CBounds.PAD + Math.random()*(GameEngine.SCREEN_HEIGHT + 2*CBounds.PAD); HBCircle circ = circ(); circ.setPos(x, y); circ.setVel(1000*(.5 - Math.random()), 1000*(.5 - Math.random())); circ.setDiam(3); circ.commit(Double.POSITIVE_INFINITY); if(!isInBounds()) throw new RuntimeException(); } @Override public boolean canInteract(Component other) { return other instanceof CCoagParticle || other instanceof CBounds; } @Override public boolean interactsWithBullets() {return false;} @Override public void onCollide(Component other) { if(isDeleted()) return; if(other instanceof CCoagParticle) { HBCircle circ = circ(); HBCircle oCirc = other.circ(); double area = Geom.area(circ); double oArea = Geom.area(oCirc); double newArea = area + oArea; circ.setDiam(Geom.area2Diam(newArea)); circ.setVelX(circ.getVelX()*area/newArea + oCirc.getVelX()*oArea/newArea); circ.setVelY(circ.getVelY()*area/newArea + oCirc.getVelY()*oArea/newArea); circ.setX(circ.getX()*area/newArea + oCirc.getX()*oArea/newArea); circ.setY(circ.getY()*area/newArea + oCirc.getY()*oArea/newArea); circ.commit(Double.POSITIVE_INFINITY); ((CCoagParticle)other).delete(); if(circ.getDiam() > 2*CBounds.PAD) { new CCircFade(circ, COLOR, .3, null); delete(); } } } @Override public void onSeparate(Component other) { if(other instanceof CBounds) { HBCircle circ = circ();
HBRect rect = other.rect();
1
joachimhs/Embriak
backend/src/main/java/no/haagensoftware/netty/webserver/plugin/PostSenseRouterPlugin.java
[ "public interface ServerInfo {\n\n\tpublic String getWebappPath();\n public String getDocumentsPath();\n}", "public class FileServerHandler extends SimpleChannelUpstreamHandler {\r\n\tprivate static Logger logger = Logger.getLogger(FileServerHandler.class.getName());\r\n\t\r\n private String rootPath;\r\n private String stripFromUri;\r\n private int cacheMaxAge = -1;\r\n private boolean fromClasspath = false;\r\n private MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();\r\n\r\n public FileServerHandler(String path) {\r\n if (path.startsWith(\"classpath://\")) {\r\n fromClasspath = true;\r\n //rootPath = getClass().getResource(path.replace(\"classpath://\", \"\")).getPath();\r\n rootPath = path.replace(\"classpath://\", \"\");\r\n if (rootPath.lastIndexOf(\"/\") == rootPath.length() -1)\r\n rootPath = rootPath.substring(0, rootPath.length() -1);\r\n } else {\r\n rootPath = path;\r\n }\r\n rootPath = rootPath.replace(File.separatorChar, '/');\r\n }\r\n\r\n public FileServerHandler(String path, String stripFromUri) {\r\n this(path);\r\n this.stripFromUri = stripFromUri;\r\n }\r\n\r\n public FileServerHandler(String path, int cacheMaxAge) {\r\n this(path);\r\n this.cacheMaxAge = cacheMaxAge;\r\n }\r\n\r\n public FileServerHandler(String path, int cacheMaxAge, String stripFromUri) {\r\n this(path, cacheMaxAge);\r\n this.stripFromUri = stripFromUri;\r\n }\r\n\r\n public MimetypesFileTypeMap getFileTypeMap() {\r\n\t\treturn fileTypeMap;\r\n\t}\r\n \r\n public int getCacheMaxAge() {\r\n\t\treturn cacheMaxAge;\r\n\t}\r\n \r\n public String getRootPath() {\r\n\t\treturn rootPath;\r\n\t}\r\n \r\n public String getUri(MessageEvent e) {\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n return request.getUri();\r\n }\r\n \r\n public boolean isPut(MessageEvent e) {\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tHttpMethod method = request.getMethod();\r\n\t\treturn method == HttpMethod.PUT;\r\n }\r\n \r\n public boolean isPost(MessageEvent e) {\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tHttpMethod method = request.getMethod();\r\n\t\treturn method == HttpMethod.POST;\r\n }\r\n \r\n public boolean isGet(MessageEvent e) {\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tHttpMethod method = request.getMethod();\r\n\t\treturn method == HttpMethod.GET;\r\n }\r\n \r\n public boolean isDelete(MessageEvent e) {\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tHttpMethod method = request.getMethod();\r\n\t\treturn method == HttpMethod.DELETE;\r\n }\r\n \r\n public String getCookieValue(MessageEvent e, String cookieName) {\r\n \tString cookieValue = null;\r\n \t\r\n \tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tString value = request.getHeader(\"Cookie\");\r\n\t\tlogger.info(\"cookie header: \\n\" + value);\r\n\t\tif (value != null) {\r\n\t\t\tSet<Cookie> cookies = new CookieDecoder().decode(value);\r\n\t\t\tfor (Cookie cookie : cookies) {\r\n\t\t\t\tif (cookie.getName().equals(cookieName)) {\r\n\t\t\t\t\tcookieValue = cookie.getValue();\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n \t\r\n \treturn cookieValue;\r\n }\r\n \r\n public String getHttpMessageContent(MessageEvent e) {\r\n\t\tString requestContent = null;\r\n\t\tHttpRequest request = (HttpRequest) e.getMessage();\r\n\t\tChannelBuffer content = request.getContent();\r\n if (content.readable()) {\r\n \trequestContent = content.toString(CharsetUtil.UTF_8);\r\n }\r\n\t\treturn requestContent;\r\n\t}\r\n \r\n @Override\r\n\tpublic void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {\r\n\t\tHttpRequest request = (HttpRequest) e.getMessage();\r\n if (request.getMethod() != GET) {\r\n sendError(ctx, METHOD_NOT_ALLOWED);\r\n return;\r\n }\r\n\r\n String uri = request.getUri();\r\n \r\n String path = sanitizeUri(uri);\r\n if (path == null) {\r\n sendError(ctx, FORBIDDEN);\r\n return;\r\n }\r\n\r\n\r\n if (path.startsWith(\"/document\")) {\r\n path = path.substring(9);\r\n }\r\n ChannelBuffer content = getFileContent(path);\r\n if (content == null) {\r\n logger.info(\"Unable to find file at path: \" + path);\r\n sendError(ctx, NOT_FOUND);\r\n return;\r\n }\r\n\r\n String contentType = ContentTypeUtil.getContentType(path);\r\n logger.info(\"contentType: \" + contentType + \" for path: \" + path);\r\n \r\n DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);;\r\n response.setHeader(HttpHeaders.Names.CONTENT_TYPE, contentType);\r\n setContentLength(response, content.readableBytes());\r\n\r\n response.setContent(content);\r\n ChannelFuture writeFuture = e.getChannel().write(response);\r\n\r\n // Decide whether to close the connection or not.\r\n if (!isKeepAlive(request)) {\r\n // Close the connection when the whole content is written out.\r\n writeFuture.addListener(ChannelFutureListener.CLOSE);\r\n }\r\n\t}\r\n\r\n protected ChannelBuffer getFileContent(String path) {\r\n InputStream is;\r\n try {\r\n if (fromClasspath) {\r\n is = this.getClass().getResourceAsStream(rootPath + path);\r\n } else {\r\n is = new FileInputStream(rootPath + \"/\" + path);\r\n }\r\n\r\n if (is == null) {\r\n return null;\r\n }\r\n \r\n final int maxSize = 512 * 1024;\r\n ByteArrayOutputStream out = new ByteArrayOutputStream(maxSize);\r\n byte[] bytes = new byte[maxSize];\r\n\r\n while (true) {\r\n int r = is.read(bytes);\r\n if (r == -1) break;\r\n \r\n out.write(bytes, 0, r);\r\n }\r\n\r\n ChannelBuffer cb = ChannelBuffers.copiedBuffer(out.toByteArray());\r\n out.close();\r\n is.close();\r\n return cb;\r\n } catch (IOException e) {\r\n return null;\r\n }\r\n }\r\n\r\n protected String getRawFileContent(String path) {\r\n String fileContent = \"\";\r\n\r\n InputStream is;\r\n try {\r\n if (fromClasspath) {\r\n is = this.getClass().getResourceAsStream(rootPath + path);\r\n } else {\r\n is = new FileInputStream(rootPath + \"/\" + path);\r\n }\r\n\r\n if (is == null) {\r\n return null;\r\n }\r\n\r\n java.util.Scanner s = new java.util.Scanner(is).useDelimiter(\"\\\\A\");\r\n fileContent = s.hasNext() ? s.next() : \"\";\r\n\r\n is.close();\r\n return fileContent;\r\n } catch (IOException e) {\r\n return null;\r\n }\r\n }\r\n\r\n @Override\r\n public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)\r\n throws Exception {\r\n Channel ch = e.getChannel();\r\n Throwable cause = e.getCause();\r\n if (cause instanceof TooLongFrameException) {\r\n sendError(ctx, BAD_REQUEST);\r\n return;\r\n }\r\n\r\n cause.printStackTrace();\r\n if (ch.isConnected()) {\r\n sendError(ctx, INTERNAL_SERVER_ERROR);\r\n }\r\n }\r\n\r\n protected String sanitizeUri(String uri) throws URISyntaxException {\r\n // Decode the path.\r\n try {\r\n uri = URLDecoder.decode(uri, \"UTF-8\");\r\n } catch (UnsupportedEncodingException e) {\r\n try {\r\n uri = URLDecoder.decode(uri, \"ISO-8859-1\");\r\n } catch (UnsupportedEncodingException e1) {\r\n throw new Error();\r\n }\r\n }\r\n\r\n // Convert file separators.\r\n uri = uri.replace(File.separatorChar, '/');\r\n\r\n // Simplistic dumb security check.\r\n // You will have to do something serious in the production environment.\r\n if (uri.contains(File.separator + \".\") ||\r\n uri.contains(\".\" + File.separator) ||\r\n uri.startsWith(\".\") || uri.endsWith(\".\")) {\r\n return null;\r\n }\r\n\r\n QueryStringDecoder decoder = new QueryStringDecoder(uri);\r\n uri = decoder.getPath();\r\n \t\r\n if (uri.endsWith(\"/\")) {\r\n uri += \"index.html\";\r\n }\r\n\r\n return uri;\r\n }\r\n\r\n public void writeContentsToBuffer(ChannelHandlerContext ctx, String responseText, String contentType) {\r\n \tif (responseText.length() == 0) {\r\n \t\tresponseText = \"{}\";\r\n \t}\r\n \t\r\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\r\n response.setHeader(CONTENT_TYPE, contentType + \"; charset=UTF-8\");\r\n response.setContent(ChannelBuffers.copiedBuffer(responseText + \"\\r\\n\", CharsetUtil.UTF_8));\r\n\r\n // Close the connection as soon as the error message is sent.\r\n ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);\r\n }\r\n\r\n protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {\r\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);\r\n response.setHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\r\n response.setContent(ChannelBuffers.copiedBuffer(\r\n \"Failure: \" + status.toString() + \"\\r\\n\",\r\n CharsetUtil.UTF_8));\r\n\r\n // Close the connection as soon as the error message is sent.\r\n ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);\r\n }\r\n}\r", "public class RiakEnv {\n\tprivate IRiakClient riakClient;\n\tprivate RiakBucketDao riakBucketDao;\n\t\n\tpublic RiakEnv() {\n\t\t\n\t}\n\t\n\tpublic void setup() throws RiakException {\n\t\t// Riak Protocol Buffers client with supplied IP and Port\n PBClusterConfig riakClusterConfig = new PBClusterConfig(20);\n // See above examples for client config options\n PBClientConfig riakClientConfig = PBClientConfig.defaults();\n riakClusterConfig.addHosts(riakClientConfig, System.getProperty(PropertyConstants.RIAK_HOST));\n riakClient = RiakFactory.newClient(riakClusterConfig);\n \n riakBucketDao = new RiakBucketDao(riakClient);\n\t}\n\t\n\tpublic void teardown() {\n\t\triakClient.shutdown();\n\t}\n\t\n\tpublic RiakBucketDao getRiakBucketDao() {\n\t\treturn riakBucketDao;\n\t}\n\t\n\tpublic void setRiakBucketDao(RiakBucketDao riakBucketDao) {\n\t\tthis.riakBucketDao = riakBucketDao;\n\t}\n}", "public abstract class NettyWebserverRouterPlugin {\n\n\tpublic abstract LinkedHashMap<String, SimpleChannelUpstreamHandler> getRoutes();\n\t\n\tpublic abstract ChannelHandler getHandlerForRoute(String route);\n\t\n\tpublic abstract void setServerInfo(ServerInfo serverInfo);\n}", "public class PropertyConstants {\n public static final String NETTY_PORT = \"no.haagensoftware.netty.port\";\n public static final String WEBAPP_DIR = \"no.haagensoftware.netty.webappDir\";\n public static final String SCRIPTS_CACHE_SECONDS = \"no.haagensoftware.netty.scriptsCacheSeconds\";\n public static final String RIAK_HOST = \"no.haagensoftware.riak.host\";\n public static final String RIAK_PORT = \"no.haagensoftware.riak.port\";\n}", "public class IntegerParser {\n\n\tpublic static Integer parseIntegerFromString(String input, Integer fallbackValue) {\n\t\tInteger retInt = null;\n\t\t\n\t\ttry {\n\t\t\tif (input != null) {\n\t\t\t\tretInt = Integer.parseInt(input.trim());\n\t\t\t} else {\n\t\t\t\tretInt = fallbackValue;\n\t\t\t}\n\t\t} catch (NumberFormatException nfe) {\n\t\t\tretInt = fallbackValue;\n\t\t}\n\t\t\n\t\treturn retInt;\n\t}\n}" ]
import java.util.LinkedHashMap; import no.haagensoftware.netty.webserver.ServerInfo; import no.haagensoftware.netty.webserver.handler.FileServerHandler; import no.haagensoftware.riak.RiakEnv; import org.haagensoftware.netty.webserver.spi.NettyWebserverRouterPlugin; import org.haagensoftware.netty.webserver.spi.PropertyConstants; import org.haagensoftware.netty.webserver.util.IntegerParser; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
package no.haagensoftware.netty.webserver.plugin; /** * A simple router plugin to be able to serve the Haagen-Software.no website. * @author joahaa * */ public class PostSenseRouterPlugin extends NettyWebserverRouterPlugin { private LinkedHashMap<String, SimpleChannelUpstreamHandler> routes; private ServerInfo serverInfo; public PostSenseRouterPlugin(ServerInfo serverInfo, RiakEnv dbEnv) { //authenticationContext = new AuthenticationContext(dbEnv);
int scriptCacheSeconds = IntegerParser.parseIntegerFromString(System.getProperty(PropertyConstants.SCRIPTS_CACHE_SECONDS), 0);
4
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/ShowImageView.java
[ "public interface OnImageClickListener {\n void onImgClick();\n}", "public class ImageCache {\n private static LruCache<String, Bitmap> mCache;\n\n private ImageCache() {\n }\n\n public static LruCache<String, Bitmap> getInstance() {\n if (mCache == null)\n synchronized (ImageCache.class) {\n if (mCache == null)\n mCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory() / 8) {\n @Override\n protected int sizeOf(String key, Bitmap value) {\n if (Build.VERSION.SDK_INT > 12)\n return value.getByteCount();\n else\n return value.getRowBytes() * value.getHeight();\n }\n };\n }\n return mCache;\n }\n}", "public class ImageUtils {\n private ImageUtils() {\n throw new UnsupportedOperationException(\"cannot be instantiated\");\n }\n\n /**\n * 压缩图片的像素\n *\n * @param path\n * @param requestWidth\n * @param requestHeight\n * @return\n */\n public static Bitmap compressImgBySize(String path, int requestWidth, int requestHeight) {\n if (null == path || TextUtils.isEmpty(path) || !new File(path).exists())\n return null;\n //第一次解析图片的时候将inJustDecodeBounds设置为true,来获取图片的大小\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(path, options);\n options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight);\n options.inJustDecodeBounds = false;\n return BitmapFactory.decodeFile(path, options);\n }\n\n private static int calculateInSampleSize(BitmapFactory.Options options, int requestWidth, int requestHeight) {\n int width = options.outWidth;\n int height = options.outHeight;\n int inSampleSize = 1;\n if (width > requestWidth || height > requestHeight) {\n final int heightRatio = Math.round((float) height / (float) requestHeight);\n final int widthRatio = Math.round((float) width / (float) requestWidth);\n inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;\n }\n return inSampleSize;\n }\n}", "public class PhotoView extends ImageView implements IPhotoView {\n\n private final PhotoViewAttacher mAttacher;\n\n private ScaleType mPendingScaleType;\n\n public PhotoView(Context context) {\n this(context, null);\n }\n\n public PhotoView(Context context, AttributeSet attr) {\n this(context, attr, 0);\n }\n\n public PhotoView(Context context, AttributeSet attr, int defStyle) {\n super(context, attr, defStyle);\n super.setScaleType(ScaleType.MATRIX);\n mAttacher = new PhotoViewAttacher(this);\n\n if (null != mPendingScaleType) {\n setScaleType(mPendingScaleType);\n mPendingScaleType = null;\n }\n }\n\n @Override\n public void setPhotoViewRotation(float rotationDegree) {\n mAttacher.setPhotoViewRotation(rotationDegree);\n }\n\n @Override\n public boolean canZoom() {\n return mAttacher.canZoom();\n }\n\n @Override\n public RectF getDisplayRect() {\n return mAttacher.getDisplayRect();\n }\n\n @Override\n public Matrix getDisplayMatrix() {\n return mAttacher.getDrawMatrix();\n }\n\n @Override\n public boolean setDisplayMatrix(Matrix finalRectangle) {\n return mAttacher.setDisplayMatrix(finalRectangle);\n }\n\n @Override\n @Deprecated\n public float getMinScale() {\n return getMinimumScale();\n }\n\n @Override\n public float getMinimumScale() {\n return mAttacher.getMinimumScale();\n }\n\n @Override\n @Deprecated\n public float getMidScale() {\n return getMediumScale();\n }\n\n @Override\n public float getMediumScale() {\n return mAttacher.getMediumScale();\n }\n\n @Override\n @Deprecated\n public float getMaxScale() {\n return getMaximumScale();\n }\n\n @Override\n public float getMaximumScale() {\n return mAttacher.getMaximumScale();\n }\n\n @Override\n public float getScale() {\n return mAttacher.getScale();\n }\n\n @Override\n public ScaleType getScaleType() {\n return mAttacher.getScaleType();\n }\n\n @Override\n public void setAllowParentInterceptOnEdge(boolean allow) {\n mAttacher.setAllowParentInterceptOnEdge(allow);\n }\n\n @Override\n @Deprecated\n public void setMinScale(float minScale) {\n setMinimumScale(minScale);\n }\n\n @Override\n public void setMinimumScale(float minimumScale) {\n mAttacher.setMinimumScale(minimumScale);\n }\n\n @Override\n @Deprecated\n public void setMidScale(float midScale) {\n setMediumScale(midScale);\n }\n\n @Override\n public void setMediumScale(float mediumScale) {\n mAttacher.setMediumScale(mediumScale);\n }\n\n @Override\n @Deprecated\n public void setMaxScale(float maxScale) {\n setMaximumScale(maxScale);\n }\n\n @Override\n public void setMaximumScale(float maximumScale) {\n mAttacher.setMaximumScale(maximumScale);\n }\n\n @Override\n // setImageBitmap calls through to this method\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (null != mAttacher) {\n mAttacher.update();\n }\n }\n\n @Override\n public void setImageResource(int resId) {\n super.setImageResource(resId);\n if (null != mAttacher) {\n mAttacher.update();\n }\n }\n\n @Override\n public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n if (null != mAttacher) {\n mAttacher.update();\n }\n }\n\n @Override\n public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {\n mAttacher.setOnMatrixChangeListener(listener);\n }\n\n @Override\n public void setOnLongClickListener(OnLongClickListener l) {\n mAttacher.setOnLongClickListener(l);\n }\n\n @Override\n public void setOnPhotoTapListener(OnPhotoTapListener listener) {\n mAttacher.setOnPhotoTapListener(listener);\n }\n\n @Override\n public OnPhotoTapListener getOnPhotoTapListener() {\n return mAttacher.getOnPhotoTapListener();\n }\n\n @Override\n public void setOnViewTapListener(OnViewTapListener listener) {\n mAttacher.setOnViewTapListener(listener);\n }\n\n @Override\n public OnViewTapListener getOnViewTapListener() {\n return mAttacher.getOnViewTapListener();\n }\n\n @Override\n public void setScale(float scale) {\n mAttacher.setScale(scale);\n }\n\n @Override\n public void setScale(float scale, boolean animate) {\n mAttacher.setScale(scale, animate);\n }\n\n @Override\n public void setScale(float scale, float focalX, float focalY, boolean animate) {\n mAttacher.setScale(scale, focalX, focalY, animate);\n }\n\n @Override\n public void setScaleType(ScaleType scaleType) {\n if (null != mAttacher) {\n mAttacher.setScaleType(scaleType);\n } else {\n mPendingScaleType = scaleType;\n }\n }\n\n @Override\n public void setZoomable(boolean zoomable) {\n mAttacher.setZoomable(zoomable);\n }\n\n @Override\n public Bitmap getVisibleRectangleBitmap() {\n return mAttacher.getVisibleRectangleBitmap();\n }\n\n @Override\n public void setZoomTransitionDuration(int milliseconds) {\n mAttacher.setZoomTransitionDuration(milliseconds);\n }\n\n @Override\n protected void onDetachedFromWindow() {\n mAttacher.cleanup();\n super.onDetachedFromWindow();\n }\n\n}", "public class PhotoViewAttacher implements IPhotoView, View.OnTouchListener,\n OnGestureListener,\n ViewTreeObserver.OnGlobalLayoutListener {\n\n private static final String LOG_TAG = \"PhotoViewAttacher\";\n\n // let debug flag be dynamic, but still Proguard can be used to remove from\n // release builds\n private static final boolean DEBUG = Log.isLoggable(LOG_TAG, Log.DEBUG);\n\n static final Interpolator sInterpolator = new AccelerateDecelerateInterpolator();\n int ZOOM_DURATION = DEFAULT_ZOOM_DURATION;\n\n static final int EDGE_NONE = -1;\n static final int EDGE_LEFT = 0;\n static final int EDGE_RIGHT = 1;\n static final int EDGE_BOTH = 2;\n\n private float mMinScale = DEFAULT_MIN_SCALE;\n private float mMidScale = DEFAULT_MID_SCALE;\n private float mMaxScale = DEFAULT_MAX_SCALE;\n\n private boolean mAllowParentInterceptOnEdge = true;\n\n private static void checkZoomLevels(float minZoom, float midZoom,\n float maxZoom) {\n if (minZoom >= midZoom) {\n throw new IllegalArgumentException(\n \"MinZoom has to be less than MidZoom\");\n } else if (midZoom >= maxZoom) {\n throw new IllegalArgumentException(\n \"MidZoom has to be less than MaxZoom\");\n }\n }\n\n /**\n * @return true if the ImageView exists, and it's Drawable existss\n */\n private static boolean hasDrawable(ImageView imageView) {\n return null != imageView && null != imageView.getDrawable();\n }\n\n /**\n * @return true if the ScaleType is supported.\n */\n private static boolean isSupportedScaleType(final ScaleType scaleType) {\n if (null == scaleType) {\n return false;\n }\n\n switch (scaleType) {\n case MATRIX:\n throw new IllegalArgumentException(scaleType.name()\n + \" is not supported in PhotoView\");\n\n default:\n return true;\n }\n }\n\n /**\n * Set's the ImageView's ScaleType to Matrix.\n */\n private static void setImageViewScaleTypeMatrix(ImageView imageView) {\n /**\n * PhotoView sets it's own ScaleType to Matrix, then diverts all calls\n * setScaleType to this.setScaleType automatically.\n */\n if (null != imageView && !(imageView instanceof IPhotoView)) {\n if (!ScaleType.MATRIX.equals(imageView.getScaleType())) {\n imageView.setScaleType(ScaleType.MATRIX);\n }\n }\n }\n\n private WeakReference<ImageView> mImageView;\n\n // Gesture Detectors\n private GestureDetector mGestureDetector;\n private uk.co.senab.photoview.gestures.GestureDetector mScaleDragDetector;\n\n // These are set so we don't keep allocating them on the heap\n private final Matrix mBaseMatrix = new Matrix();\n private final Matrix mDrawMatrix = new Matrix();\n private final Matrix mSuppMatrix = new Matrix();\n private final RectF mDisplayRect = new RectF();\n private final float[] mMatrixValues = new float[9];\n\n // Listeners\n private OnMatrixChangedListener mMatrixChangeListener;\n private OnPhotoTapListener mPhotoTapListener;\n private OnViewTapListener mViewTapListener;\n private OnLongClickListener mLongClickListener;\n\n private int mIvTop, mIvRight, mIvBottom, mIvLeft;\n private FlingRunnable mCurrentFlingRunnable;\n private int mScrollEdge = EDGE_BOTH;\n\n private boolean mRotationDetectionEnabled = false;\n private boolean mZoomEnabled;\n private ScaleType mScaleType = ScaleType.FIT_CENTER;\n\n public PhotoViewAttacher(ImageView imageView) {\n mImageView = new WeakReference<ImageView>(imageView);\n\n imageView.setDrawingCacheEnabled(true);\n imageView.setOnTouchListener(this);\n\n ViewTreeObserver observer = imageView.getViewTreeObserver();\n if (null != observer)\n observer.addOnGlobalLayoutListener(this);\n\n // Make sure we using MATRIX Scale Type\n setImageViewScaleTypeMatrix(imageView);\n\n if (imageView.isInEditMode()) {\n return;\n }\n // Create Gesture Detectors...\n mScaleDragDetector = VersionedGestureDetector.newInstance(\n imageView.getContext(), this);\n\n mGestureDetector = new GestureDetector(imageView.getContext(),\n new GestureDetector.SimpleOnGestureListener() {\n\n // forward long click listener\n @Override\n public void onLongPress(MotionEvent e) {\n if (null != mLongClickListener) {\n mLongClickListener.onLongClick(getImageView());\n }\n }\n });\n\n mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));\n\n // Finally, update the UI so that we're zoomable\n setZoomable(true);\n }\n\n /**\n * Sets custom double tap listener, to intercept default given functions. To reset behavior to\n * default, you can just pass in \"null\" or public field of PhotoViewAttacher.defaultOnDoubleTapListener\n *\n * @param newOnDoubleTapListener custom OnDoubleTapListener to be set on ImageView\n */\n public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {\n if (newOnDoubleTapListener != null)\n this.mGestureDetector.setOnDoubleTapListener(newOnDoubleTapListener);\n else\n this.mGestureDetector.setOnDoubleTapListener(new DefaultOnDoubleTapListener(this));\n }\n\n @Override\n public boolean canZoom() {\n return mZoomEnabled;\n }\n\n /**\n * Clean-up the resources attached to this object. This needs to be called when the ImageView is\n * no longer used. A good example is from {@link View#onDetachedFromWindow()} or\n * from {@link android.app.Activity#onDestroy()}. This is automatically called if you are using\n * {@link PhotoView}.\n */\n @SuppressWarnings(\"deprecation\")\n public void cleanup() {\n if (null == mImageView) {\n return; // cleanup already done\n }\n\n final ImageView imageView = mImageView.get();\n\n if (null != imageView) {\n // Remove this as a global layout listener\n ViewTreeObserver observer = imageView.getViewTreeObserver();\n if (null != observer && observer.isAlive()) {\n observer.removeGlobalOnLayoutListener(this);\n }\n\n // Remove the ImageView's reference to this\n imageView.setOnTouchListener(null);\n\n // make sure a pending fling runnable won't be run\n cancelFling();\n }\n\n if (null != mGestureDetector) {\n mGestureDetector.setOnDoubleTapListener(null);\n }\n\n // Clear listeners too\n mMatrixChangeListener = null;\n mPhotoTapListener = null;\n mViewTapListener = null;\n\n // Finally, clear ImageView\n mImageView = null;\n }\n\n @Override\n public RectF getDisplayRect() {\n checkMatrixBounds();\n return getDisplayRect(getDrawMatrix());\n }\n\n @Override\n public boolean setDisplayMatrix(Matrix finalMatrix) {\n if (finalMatrix == null)\n throw new IllegalArgumentException(\"Matrix cannot be null\");\n\n ImageView imageView = getImageView();\n if (null == imageView)\n return false;\n\n if (null == imageView.getDrawable())\n return false;\n\n mSuppMatrix.set(finalMatrix);\n setImageViewMatrix(getDrawMatrix());\n checkMatrixBounds();\n\n return true;\n }\n\n private float mLastRotation = 0;\n\n @Override\n public void setPhotoViewRotation(float degrees) {\n degrees %= 360;\n mSuppMatrix.postRotate(mLastRotation - degrees);\n mLastRotation = degrees;\n checkAndDisplayMatrix();\n }\n\n public ImageView getImageView() {\n ImageView imageView = null;\n\n if (null != mImageView) {\n imageView = mImageView.get();\n }\n\n // If we don't have an ImageView, call cleanup()\n if (null == imageView) {\n cleanup();\n Log.i(LOG_TAG,\n \"ImageView no longer exists. You should not use this PhotoViewAttacher any more.\");\n }\n\n return imageView;\n }\n\n @Override\n @Deprecated\n public float getMinScale() {\n return getMinimumScale();\n }\n\n @Override\n public float getMinimumScale() {\n return mMinScale;\n }\n\n @Override\n @Deprecated\n public float getMidScale() {\n return getMediumScale();\n }\n\n @Override\n public float getMediumScale() {\n return mMidScale;\n }\n\n @Override\n @Deprecated\n public float getMaxScale() {\n return getMaximumScale();\n }\n\n @Override\n public float getMaximumScale() {\n return mMaxScale;\n }\n\n @Override\n public float getScale() {\n return (float) Math.sqrt((float) Math.pow(getValue(mSuppMatrix, Matrix.MSCALE_X), 2) + (float) Math.pow(getValue(mSuppMatrix, Matrix.MSKEW_Y), 2));\n }\n\n @Override\n public ScaleType getScaleType() {\n return mScaleType;\n }\n\n @Override\n public void onDrag(float dx, float dy) {\n if (mScaleDragDetector.isScaling()) {\n return; // Do not drag if we are already scaling\n }\n\n// if (DEBUG) {\n// LogManager.getLogger().d(LOG_TAG,\n// String.format(\"onDrag: dx: %.2f. dy: %.2f\", dx, dy));\n// }\n\n ImageView imageView = getImageView();\n mSuppMatrix.postTranslate(dx, dy);\n checkAndDisplayMatrix();\n\n /**\n * Here we decide whether to let the ImageView's parent to start taking\n * over the touch event.\n *\n * First we check whether this function is enabled. We never want the\n * parent to take over if we're scaling. We then check the edge we're\n * on, and the direction of the scroll (i.e. if we're pulling against\n * the edge, aka 'overscrolling', let the parent take over).\n */\n ViewParent parent = imageView.getParent();\n if (mAllowParentInterceptOnEdge) {\n if (mScrollEdge == EDGE_BOTH\n || (mScrollEdge == EDGE_LEFT && dx >= 1f)\n || (mScrollEdge == EDGE_RIGHT && dx <= -1f)) {\n if (null != parent)\n parent.requestDisallowInterceptTouchEvent(false);\n }\n } else {\n if (null != parent) {\n parent.requestDisallowInterceptTouchEvent(true);\n }\n }\n }\n\n @Override\n public void onFling(float startX, float startY, float velocityX,\n float velocityY) {\n// if (DEBUG) {\n// LogManager.getLogger().d(\n// LOG_TAG,\n// \"onFling. sX: \" + startX + \" sY: \" + startY + \" Vx: \"\n// + velocityX + \" Vy: \" + velocityY);\n// }\n ImageView imageView = getImageView();\n mCurrentFlingRunnable = new FlingRunnable(imageView.getContext());\n mCurrentFlingRunnable.fling(getImageViewWidth(imageView),\n getImageViewHeight(imageView), (int) velocityX, (int) velocityY);\n imageView.post(mCurrentFlingRunnable);\n }\n\n @Override\n public void onGlobalLayout() {\n ImageView imageView = getImageView();\n\n if (null != imageView) {\n if (mZoomEnabled) {\n final int top = imageView.getTop();\n final int right = imageView.getRight();\n final int bottom = imageView.getBottom();\n final int left = imageView.getLeft();\n\n /**\n * We need to check whether the ImageView's bounds have changed.\n * This would be easier if we targeted API 11+ as we could just use\n * View.OnLayoutChangeListener. Instead we have to replicate the\n * work, keeping track of the ImageView's bounds and then checking\n * if the values change.\n */\n if (top != mIvTop || bottom != mIvBottom || left != mIvLeft\n || right != mIvRight) {\n // Update our base matrix, as the bounds have changed\n updateBaseMatrix(imageView.getDrawable());\n\n // Update values as something has changed\n mIvTop = top;\n mIvRight = right;\n mIvBottom = bottom;\n mIvLeft = left;\n }\n } else {\n updateBaseMatrix(imageView.getDrawable());\n }\n }\n }\n\n @Override\n public void onScale(float scaleFactor, float focusX, float focusY) {\n if (DEBUG) {\n// LogManager.getLogger().d(\n// LOG_TAG,\n// String.format(\"onScale: scale: %.2f. fX: %.2f. fY: %.2f\",\n// scaleFactor, focusX, focusY));\n }\n\n if (getScale() < mMaxScale || scaleFactor < 1f) {\n mSuppMatrix.postScale(scaleFactor, scaleFactor, focusX, focusY);\n checkAndDisplayMatrix();\n }\n }\n\n @Override\n public boolean onTouch(View v, MotionEvent ev) {\n boolean handled = false;\n\n if (mZoomEnabled && hasDrawable((ImageView) v)) {\n ViewParent parent = v.getParent();\n switch (ev.getAction()) {\n case ACTION_DOWN:\n // First, disable the Parent from intercepting the touch\n // event\n if (null != parent)\n parent.requestDisallowInterceptTouchEvent(true);\n else\n Log.i(LOG_TAG, \"onTouch getParent() returned null\");\n\n // If we're flinging, and the user presses down, cancel\n // fling\n cancelFling();\n break;\n\n case ACTION_CANCEL:\n case ACTION_UP:\n // If the user has zoomed less than min scale, zoom back\n // to min scale\n if (getScale() < mMinScale) {\n RectF rect = getDisplayRect();\n if (null != rect) {\n v.post(new AnimatedZoomRunnable(getScale(), mMinScale,\n rect.centerX(), rect.centerY()));\n handled = true;\n }\n }\n break;\n }\n\n // Try the Scale/Drag detector\n if (null != mScaleDragDetector\n && mScaleDragDetector.onTouchEvent(ev)) {\n handled = true;\n }\n\n // Check to see if the user double tapped\n if (null != mGestureDetector && mGestureDetector.onTouchEvent(ev)) {\n handled = true;\n }\n }\n\n return handled;\n }\n\n @Override\n public void setAllowParentInterceptOnEdge(boolean allow) {\n mAllowParentInterceptOnEdge = allow;\n }\n\n @Override\n @Deprecated\n public void setMinScale(float minScale) {\n setMinimumScale(minScale);\n }\n\n @Override\n public void setMinimumScale(float minimumScale) {\n checkZoomLevels(minimumScale, mMidScale, mMaxScale);\n mMinScale = minimumScale;\n }\n\n @Override\n @Deprecated\n public void setMidScale(float midScale) {\n setMediumScale(midScale);\n }\n\n @Override\n public void setMediumScale(float mediumScale) {\n checkZoomLevels(mMinScale, mediumScale, mMaxScale);\n mMidScale = mediumScale;\n }\n\n @Override\n @Deprecated\n public void setMaxScale(float maxScale) {\n setMaximumScale(maxScale);\n }\n\n @Override\n public void setMaximumScale(float maximumScale) {\n checkZoomLevels(mMinScale, mMidScale, maximumScale);\n mMaxScale = maximumScale;\n }\n\n @Override\n public void setOnLongClickListener(OnLongClickListener listener) {\n mLongClickListener = listener;\n }\n\n @Override\n public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {\n mMatrixChangeListener = listener;\n }\n\n @Override\n public void setOnPhotoTapListener(OnPhotoTapListener listener) {\n mPhotoTapListener = listener;\n }\n\n @Override\n public OnPhotoTapListener getOnPhotoTapListener() {\n return mPhotoTapListener;\n }\n\n @Override\n public void setOnViewTapListener(OnViewTapListener listener) {\n mViewTapListener = listener;\n }\n\n @Override\n public OnViewTapListener getOnViewTapListener() {\n return mViewTapListener;\n }\n\n @Override\n public void setScale(float scale) {\n setScale(scale, false);\n }\n\n @Override\n public void setScale(float scale, boolean animate) {\n ImageView imageView = getImageView();\n\n if (null != imageView) {\n setScale(scale,\n (imageView.getRight()) / 2,\n (imageView.getBottom()) / 2,\n animate);\n }\n }\n\n @Override\n public void setScale(float scale, float focalX, float focalY,\n boolean animate) {\n ImageView imageView = getImageView();\n\n if (null != imageView) {\n // Check to see if the scale is within bounds\n if (scale < mMinScale || scale > mMaxScale) {\n// LogManager\n// .getLogger()\n// .i(LOG_TAG,\n// \"Scale must be within the range of minScale and maxScale\");\n return;\n }\n\n if (animate) {\n imageView.post(new AnimatedZoomRunnable(getScale(), scale,\n focalX, focalY));\n } else {\n mSuppMatrix.setScale(scale, scale, focalX, focalY);\n checkAndDisplayMatrix();\n }\n }\n }\n\n @Override\n public void setScaleType(ScaleType scaleType) {\n if (isSupportedScaleType(scaleType) && scaleType != mScaleType) {\n mScaleType = scaleType;\n\n // Finally update\n update();\n }\n }\n\n @Override\n public void setZoomable(boolean zoomable) {\n mZoomEnabled = zoomable;\n update();\n }\n\n public void update() {\n ImageView imageView = getImageView();\n\n if (null != imageView) {\n if (mZoomEnabled) {\n // Make sure we using MATRIX Scale Type\n setImageViewScaleTypeMatrix(imageView);\n\n // Update the base matrix using the current drawable\n updateBaseMatrix(imageView.getDrawable());\n } else {\n // Reset the Matrix...\n resetMatrix();\n }\n }\n }\n\n @Override\n public Matrix getDisplayMatrix() {\n return new Matrix(getDrawMatrix());\n }\n\n public Matrix getDrawMatrix() {\n mDrawMatrix.set(mBaseMatrix);\n mDrawMatrix.postConcat(mSuppMatrix);\n return mDrawMatrix;\n }\n\n private void cancelFling() {\n if (null != mCurrentFlingRunnable) {\n mCurrentFlingRunnable.cancelFling();\n mCurrentFlingRunnable = null;\n }\n }\n\n /**\n * Helper method that simply checks the Matrix, and then displays the result\n */\n private void checkAndDisplayMatrix() {\n if (checkMatrixBounds()) {\n setImageViewMatrix(getDrawMatrix());\n }\n }\n\n private void checkImageViewScaleType() {\n ImageView imageView = getImageView();\n\n /**\n * PhotoView's getScaleType() will just divert to this.getScaleType() so\n * only call if we're not attached to a PhotoView.\n */\n if (null != imageView && !(imageView instanceof IPhotoView)) {\n if (!ScaleType.MATRIX.equals(imageView.getScaleType())) {\n throw new IllegalStateException(\n \"The ImageView's ScaleType has been changed since attaching a PhotoViewAttacher\");\n }\n }\n }\n\n private boolean checkMatrixBounds() {\n final ImageView imageView = getImageView();\n if (null == imageView) {\n return false;\n }\n\n final RectF rect = getDisplayRect(getDrawMatrix());\n if (null == rect) {\n return false;\n }\n\n final float height = rect.height(), width = rect.width();\n float deltaX = 0, deltaY = 0;\n\n final int viewHeight = getImageViewHeight(imageView);\n if (height <= viewHeight) {\n switch (mScaleType) {\n case FIT_START:\n deltaY = -rect.top;\n break;\n case FIT_END:\n deltaY = viewHeight - height - rect.top;\n break;\n default:\n deltaY = (viewHeight - height) / 2 - rect.top;\n break;\n }\n } else if (rect.top > 0) {\n deltaY = -rect.top;\n } else if (rect.bottom < viewHeight) {\n deltaY = viewHeight - rect.bottom;\n }\n\n final int viewWidth = getImageViewWidth(imageView);\n if (width <= viewWidth) {\n switch (mScaleType) {\n case FIT_START:\n deltaX = -rect.left;\n break;\n case FIT_END:\n deltaX = viewWidth - width - rect.left;\n break;\n default:\n deltaX = (viewWidth - width) / 2 - rect.left;\n break;\n }\n mScrollEdge = EDGE_BOTH;\n } else if (rect.left > 0) {\n mScrollEdge = EDGE_LEFT;\n deltaX = -rect.left;\n } else if (rect.right < viewWidth) {\n deltaX = viewWidth - rect.right;\n mScrollEdge = EDGE_RIGHT;\n } else {\n mScrollEdge = EDGE_NONE;\n }\n\n // Finally actually translate the matrix\n mSuppMatrix.postTranslate(deltaX, deltaY);\n return true;\n }\n\n /**\n * Helper method that maps the supplied Matrix to the current Drawable\n *\n * @param matrix - Matrix to map Drawable against\n * @return RectF - Displayed Rectangle\n */\n private RectF getDisplayRect(Matrix matrix) {\n ImageView imageView = getImageView();\n\n if (null != imageView) {\n Drawable d = imageView.getDrawable();\n if (null != d) {\n mDisplayRect.set(0, 0, d.getIntrinsicWidth(),\n d.getIntrinsicHeight());\n matrix.mapRect(mDisplayRect);\n return mDisplayRect;\n }\n }\n return null;\n }\n\n public Bitmap getVisibleRectangleBitmap() {\n ImageView imageView = getImageView();\n return imageView == null ? null : imageView.getDrawingCache();\n }\n\n @Override\n public void setZoomTransitionDuration(int milliseconds) {\n if (milliseconds < 0)\n milliseconds = DEFAULT_ZOOM_DURATION;\n this.ZOOM_DURATION = milliseconds;\n }\n\n /**\n * Helper method that 'unpacks' a Matrix and returns the required value\n *\n * @param matrix - Matrix to unpack\n * @param whichValue - Which value from Matrix.M* to return\n * @return float - returned value\n */\n private float getValue(Matrix matrix, int whichValue) {\n matrix.getValues(mMatrixValues);\n return mMatrixValues[whichValue];\n }\n\n /**\n * Resets the Matrix back to FIT_CENTER, and then displays it.s\n */\n private void resetMatrix() {\n mSuppMatrix.reset();\n setImageViewMatrix(getDrawMatrix());\n checkMatrixBounds();\n }\n\n private void setImageViewMatrix(Matrix matrix) {\n ImageView imageView = getImageView();\n if (null != imageView) {\n\n checkImageViewScaleType();\n imageView.setImageMatrix(matrix);\n\n // Call MatrixChangedListener if needed\n if (null != mMatrixChangeListener) {\n RectF displayRect = getDisplayRect(matrix);\n if (null != displayRect) {\n mMatrixChangeListener.onMatrixChanged(displayRect);\n }\n }\n }\n }\n\n /**\n * Calculate Matrix for FIT_CENTER\n *\n * @param d - Drawable being displayed\n */\n private void updateBaseMatrix(Drawable d) {\n ImageView imageView = getImageView();\n if (null == imageView || null == d) {\n return;\n }\n\n final float viewWidth = getImageViewWidth(imageView);\n final float viewHeight = getImageViewHeight(imageView);\n final int drawableWidth = d.getIntrinsicWidth();\n final int drawableHeight = d.getIntrinsicHeight();\n\n mBaseMatrix.reset();\n\n final float widthScale = viewWidth / drawableWidth;\n final float heightScale = viewHeight / drawableHeight;\n\n if (mScaleType == ScaleType.CENTER) {\n mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F,\n (viewHeight - drawableHeight) / 2F);\n\n } else if (mScaleType == ScaleType.CENTER_CROP) {\n float scale = Math.max(widthScale, heightScale);\n mBaseMatrix.postScale(scale, scale);\n mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,\n (viewHeight - drawableHeight * scale) / 2F);\n\n } else if (mScaleType == ScaleType.CENTER_INSIDE) {\n float scale = Math.min(1.0f, Math.min(widthScale, heightScale));\n mBaseMatrix.postScale(scale, scale);\n mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,\n (viewHeight - drawableHeight * scale) / 2F);\n\n } else {\n RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight);\n RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight);\n\n switch (mScaleType) {\n case FIT_CENTER:\n mBaseMatrix\n .setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);\n break;\n\n case FIT_START:\n mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);\n break;\n\n case FIT_END:\n mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);\n break;\n\n case FIT_XY:\n mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);\n break;\n\n default:\n break;\n }\n }\n\n resetMatrix();\n }\n\n private int getImageViewWidth(ImageView imageView) {\n if (null == imageView)\n return 0;\n return imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();\n }\n\n private int getImageViewHeight(ImageView imageView) {\n if (null == imageView)\n return 0;\n return imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom();\n }\n\n /**\n * Interface definition for a callback to be invoked when the internal Matrix has changed for\n * this View.\n *\n * @author Chris Banes\n */\n public static interface OnMatrixChangedListener {\n /**\n * Callback for when the Matrix displaying the Drawable has changed. This could be because\n * the View's bounds have changed, or the user has zoomed.\n *\n * @param rect - Rectangle displaying the Drawable's new bounds.\n */\n void onMatrixChanged(RectF rect);\n }\n\n /**\n * Interface definition for a callback to be invoked when the Photo is tapped with a single\n * tap.\n *\n * @author Chris Banes\n */\n public static interface OnPhotoTapListener {\n\n /**\n * A callback to receive where the user taps on a photo. You will only receive a callback if\n * the user taps on the actual photo, tapping on 'whitespace' will be ignored.\n *\n * @param view - View the user tapped.\n * @param x - where the user tapped from the of the Drawable, as percentage of the\n * Drawable width.\n * @param y - where the user tapped from the top of the Drawable, as percentage of the\n * Drawable height.\n */\n void onPhotoTap(View view, float x, float y);\n }\n\n /**\n * Interface definition for a callback to be invoked when the ImageView is tapped with a single\n * tap.\n *\n * @author Chris Banes\n */\n public static interface OnViewTapListener {\n\n /**\n * A callback to receive where the user taps on a ImageView. You will receive a callback if\n * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored.\n *\n * @param view - View the user tapped.\n * @param x - where the user tapped from the left of the View.\n * @param y - where the user tapped from the top of the View.\n */\n void onViewTap(View view, float x, float y);\n }\n\n private class AnimatedZoomRunnable implements Runnable {\n\n private final float mFocalX, mFocalY;\n private final long mStartTime;\n private final float mZoomStart, mZoomEnd;\n\n public AnimatedZoomRunnable(final float currentZoom, final float targetZoom,\n final float focalX, final float focalY) {\n mFocalX = focalX;\n mFocalY = focalY;\n mStartTime = System.currentTimeMillis();\n mZoomStart = currentZoom;\n mZoomEnd = targetZoom;\n }\n\n @Override\n public void run() {\n ImageView imageView = getImageView();\n if (imageView == null) {\n return;\n }\n\n float t = interpolate();\n float scale = mZoomStart + t * (mZoomEnd - mZoomStart);\n float deltaScale = scale / getScale();\n\n mSuppMatrix.postScale(deltaScale, deltaScale, mFocalX, mFocalY);\n checkAndDisplayMatrix();\n\n // We haven't hit our target scale yet, so post ourselves again\n if (t < 1f) {\n Compat.postOnAnimation(imageView, this);\n }\n }\n\n private float interpolate() {\n float t = 1f * (System.currentTimeMillis() - mStartTime) / ZOOM_DURATION;\n t = Math.min(1f, t);\n t = sInterpolator.getInterpolation(t);\n return t;\n }\n }\n\n private class FlingRunnable implements Runnable {\n\n private final ScrollerProxy mScroller;\n private int mCurrentX, mCurrentY;\n\n public FlingRunnable(Context context) {\n mScroller = ScrollerProxy.getScroller(context);\n }\n\n public void cancelFling() {\n// if (DEBUG) {\n// LogManager.getLogger().d(LOG_TAG, \"Cancel Fling\");\n// }\n mScroller.forceFinished(true);\n }\n\n public void fling(int viewWidth, int viewHeight, int velocityX,\n int velocityY) {\n final RectF rect = getDisplayRect();\n if (null == rect) {\n return;\n }\n\n final int startX = Math.round(-rect.left);\n final int minX, maxX, minY, maxY;\n\n if (viewWidth < rect.width()) {\n minX = 0;\n maxX = Math.round(rect.width() - viewWidth);\n } else {\n minX = maxX = startX;\n }\n\n final int startY = Math.round(-rect.top);\n if (viewHeight < rect.height()) {\n minY = 0;\n maxY = Math.round(rect.height() - viewHeight);\n } else {\n minY = maxY = startY;\n }\n\n mCurrentX = startX;\n mCurrentY = startY;\n\n// if (DEBUG) {\n// LogManager.getLogger().d(\n// LOG_TAG,\n// \"fling. StartX:\" + startX + \" StartY:\" + startY\n// + \" MaxX:\" + maxX + \" MaxY:\" + maxY);\n// }\n\n // If we actually can move, fling the scroller\n if (startX != maxX || startY != maxY) {\n mScroller.fling(startX, startY, velocityX, velocityY, minX,\n maxX, minY, maxY, 0, 0);\n }\n }\n\n @Override\n public void run() {\n if (mScroller.isFinished()) {\n return; // remaining post that should not be handled\n }\n\n ImageView imageView = getImageView();\n if (null != imageView && mScroller.computeScrollOffset()) {\n\n final int newX = mScroller.getCurrX();\n final int newY = mScroller.getCurrY();\n\n// if (DEBUG) {\n// LogManager.getLogger().d(\n// LOG_TAG,\n// \"fling run(). CurrentX:\" + mCurrentX + \" CurrentY:\"\n// + mCurrentY + \" NewX:\" + newX + \" NewY:\"\n// + newY);\n// }\n\n mSuppMatrix.postTranslate(mCurrentX - newX, mCurrentY - newY);\n setImageViewMatrix(getDrawMatrix());\n\n mCurrentX = newX;\n mCurrentY = newY;\n\n // Post On animation\n Compat.postOnAnimation(imageView, this);\n }\n }\n }\n}" ]
import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cocolover2.lis.interf.OnImageClickListener; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import uk.co.senab.photoview.PhotoView; import uk.co.senab.photoview.PhotoViewAttacher;
package com.cocolover2.lis; public class ShowImageView extends Fragment { private String key_prefix = "big_img_";
private PhotoView imageView;
3
markusfisch/ShaderEditor
app/src/main/java/de/markusfisch/android/shadereditor/fragment/AbstractSamplerPropertiesFragment.java
[ "public class AddUniformActivity extends AbstractContentActivity {\n\tpublic static final String STATEMENT = \"statement\";\n\tpublic static final int PICK_IMAGE = 1;\n\tpublic static final int CROP_IMAGE = 2;\n\tpublic static final int PICK_TEXTURE = 3;\n\n\tpublic static void setAddUniformResult(Activity activity, String name) {\n\t\tBundle bundle = new Bundle();\n\t\tbundle.putString(STATEMENT, name);\n\n\t\tIntent data = new Intent();\n\t\tdata.putExtras(bundle);\n\n\t\tactivity.setResult(RESULT_OK, data);\n\t}\n\n\t@Override\n\tpublic void onActivityResult(\n\t\t\tint requestCode,\n\t\t\tint resultCode,\n\t\t\tIntent data) {\n\t\tsuper.onActivityResult(requestCode, resultCode, data);\n\n\t\tif (resultCode != RESULT_OK) {\n\t\t\treturn;\n\t\t}\n\n\t\tUri imageUri;\n\n\t\tif (requestCode == PICK_IMAGE &&\n\t\t\t\tdata != null &&\n\t\t\t\t(imageUri = data.getData()) != null) {\n\t\t\tstartActivityForResult(\n\t\t\t\t\tCropImageActivity.getIntentForImage(\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\timageUri),\n\t\t\t\t\tCROP_IMAGE);\n\t\t} else if (requestCode == CROP_IMAGE ||\n\t\t\t\trequestCode == PICK_TEXTURE) {\n\t\t\tsetResult(RESULT_OK, data);\n\t\t\tfinish();\n\t\t}\n\t}\n\n\t@Override\n\tprotected Fragment defaultFragment() {\n\t\tstartActivityForIntent(getIntent());\n\t\treturn new UniformPagesFragment();\n\t}\n\n\tprivate void startActivityForIntent(Intent intent) {\n\t\tif (intent == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tString type;\n\t\tif (!Intent.ACTION_SEND.equals(intent.getAction()) ||\n\t\t\t\t(type = intent.getType()) == null ||\n\t\t\t\t!type.startsWith(\"image/\")) {\n\t\t\treturn;\n\t\t}\n\n\t\tUri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);\n\t\tif (imageUri == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tstartActivity(CropImageActivity.getIntentForImage(this, imageUri));\n\t}\n}", "public class ShaderRenderer implements GLSurfaceView.Renderer {\n\tpublic interface OnRendererListener {\n\t\tvoid onInfoLog(String error);\n\n\t\tvoid onFramesPerSecond(int fps);\n\t}\n\n\tpublic static final String UNIFORM_BACKBUFFER = \"backbuffer\";\n\tpublic static final String UNIFORM_BATTERY = \"battery\";\n\tpublic static final String UNIFORM_CAMERA_ADDENT = \"cameraAddent\";\n\tpublic static final String UNIFORM_CAMERA_BACK = \"cameraBack\";\n\tpublic static final String UNIFORM_CAMERA_FRONT = \"cameraFront\";\n\tpublic static final String UNIFORM_CAMERA_ORIENTATION = \"cameraOrientation\";\n\tpublic static final String UNIFORM_DATE = \"date\";\n\tpublic static final String UNIFORM_DAYTIME = \"daytime\";\n\tpublic static final String UNIFORM_FRAME_NUMBER = \"frame\";\n\tpublic static final String UNIFORM_FTIME = \"ftime\";\n\tpublic static final String UNIFORM_GRAVITY = \"gravity\";\n\tpublic static final String UNIFORM_GYROSCOPE = \"gyroscope\";\n\tpublic static final String UNIFORM_LIGHT = \"light\";\n\tpublic static final String UNIFORM_LINEAR = \"linear\";\n\tpublic static final String UNIFORM_MAGNETIC = \"magnetic\";\n\tpublic static final String UNIFORM_MOUSE = \"mouse\";\n\tpublic static final String UNIFORM_OFFSET = \"offset\";\n\tpublic static final String UNIFORM_ORIENTATION = \"orientation\";\n\tpublic static final String UNIFORM_INCLINATION = \"inclination\";\n\tpublic static final String UNIFORM_INCLINATION_MATRIX = \"inclinationMatrix\";\n\tpublic static final String UNIFORM_POINTERS = \"pointers\";\n\tpublic static final String UNIFORM_POINTER_COUNT = \"pointerCount\";\n\tpublic static final String UNIFORM_POSITION = \"position\";\n\tpublic static final String UNIFORM_POWER_CONNECTED = \"powerConnected\";\n\tpublic static final String UNIFORM_PRESSURE = \"pressure\";\n\tpublic static final String UNIFORM_PROXIMITY = \"proximity\";\n\tpublic static final String UNIFORM_RESOLUTION = \"resolution\";\n\tpublic static final String UNIFORM_ROTATION_MATRIX = \"rotationMatrix\";\n\tpublic static final String UNIFORM_ROTATION_VECTOR = \"rotationVector\";\n\tpublic static final String UNIFORM_SECOND = \"second\";\n\tpublic static final String UNIFORM_START_RANDOM = \"startRandom\";\n\tpublic static final String UNIFORM_SUB_SECOND = \"subsecond\";\n\tpublic static final String UNIFORM_TIME = \"time\";\n\tpublic static final String UNIFORM_TOUCH = \"touch\";\n\n\tprivate static final int[] TEXTURE_UNITS = {\n\t\t\tGLES20.GL_TEXTURE0,\n\t\t\tGLES20.GL_TEXTURE1,\n\t\t\tGLES20.GL_TEXTURE2,\n\t\t\tGLES20.GL_TEXTURE3,\n\t\t\tGLES20.GL_TEXTURE4,\n\t\t\tGLES20.GL_TEXTURE5,\n\t\t\tGLES20.GL_TEXTURE6,\n\t\t\tGLES20.GL_TEXTURE7,\n\t\t\tGLES20.GL_TEXTURE8,\n\t\t\tGLES20.GL_TEXTURE9,\n\t\t\tGLES20.GL_TEXTURE10,\n\t\t\tGLES20.GL_TEXTURE11,\n\t\t\tGLES20.GL_TEXTURE12,\n\t\t\tGLES20.GL_TEXTURE13,\n\t\t\tGLES20.GL_TEXTURE14,\n\t\t\tGLES20.GL_TEXTURE15,\n\t\t\tGLES20.GL_TEXTURE16,\n\t\t\tGLES20.GL_TEXTURE17,\n\t\t\tGLES20.GL_TEXTURE18,\n\t\t\tGLES20.GL_TEXTURE19,\n\t\t\tGLES20.GL_TEXTURE20,\n\t\t\tGLES20.GL_TEXTURE21,\n\t\t\tGLES20.GL_TEXTURE22,\n\t\t\tGLES20.GL_TEXTURE23,\n\t\t\tGLES20.GL_TEXTURE24,\n\t\t\tGLES20.GL_TEXTURE25,\n\t\t\tGLES20.GL_TEXTURE26,\n\t\t\tGLES20.GL_TEXTURE27,\n\t\t\tGLES20.GL_TEXTURE28,\n\t\t\tGLES20.GL_TEXTURE29,\n\t\t\tGLES20.GL_TEXTURE30,\n\t\t\tGLES20.GL_TEXTURE31};\n\tprivate static final int[] CUBE_MAP_TARGETS = {\n\t\t\t// all sides of a cube are stored in a single\n\t\t\t// rectangular source image for compactness:\n\t\t\t//\n\t\t\t// +----+ +----+----+\n\t\t\t// /| -Z | | -X | -Z |\n\t\t\t// -X + +----+ > +----+----+ +----+----+\n\t\t\t// |/ -Y / | -Y | | -X | -Z |\n\t\t\t// +----+ +----+ +----+----+\n\t\t\t// > | +Y | -Y |\n\t\t\t// +----+ +----+ +----+----+\n\t\t\t// / +Y /| | +Y | | +Z | +X |\n\t\t\t// +----+ + +X > +----+----+ +----+----+\n\t\t\t// | +Z |/ | +Z | +X |\n\t\t\t// +----+ +----+----+\n\t\t\t//\n\t\t\t// so, from left to right, top to bottom:\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,\n\t\t\tGL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_X};\n\tprivate static final float NS_PER_SECOND = 1000000000f;\n\tprivate static final long FPS_UPDATE_FREQUENCY_NS = 200000000L;\n\tprivate static final long BATTERY_UPDATE_INTERVAL = 10000000000L;\n\tprivate static final long DATE_UPDATE_INTERVAL = 1000000000L;\n\tprivate static final String SAMPLER_2D = \"2D\";\n\tprivate static final String SAMPLER_CUBE = \"Cube\";\n\tprivate static final String SAMPLER_EXTERNAL_OES = \"ExternalOES\";\n\tprivate static final Pattern PATTERN_SAMPLER = Pattern.compile(\n\t\t\tString.format(\n\t\t\t\t\t\"uniform[ \\t]+sampler(\" +\n\t\t\t\t\t\t\tSAMPLER_2D + \"|\" +\n\t\t\t\t\t\t\tSAMPLER_CUBE + \"|\" +\n\t\t\t\t\t\t\tSAMPLER_EXTERNAL_OES +\n\t\t\t\t\t\t\t\")+[ \\t]+(%s);[ \\t]*(.*)\",\n\t\t\t\t\tAbstractSamplerPropertiesFragment.TEXTURE_NAME_PATTERN));\n\tprivate static final Pattern PATTERN_FTIME = Pattern.compile(\n\t\t\t\"^#define[ \\\\t]+FTIME_PERIOD[ \\\\t]+([0-9\\\\.]+)[ \\\\t]*$\",\n\t\t\tPattern.MULTILINE);\n\tprivate static final Pattern PATTERN_VERSION = Pattern.compile(\n\t\t\t\"^#version 3[0-9]{2} es$\", Pattern.MULTILINE);\n\tprivate static final String OES_EXTERNAL =\n\t\t\t\"#extension GL_OES_EGL_image_external : require\\n\";\n\tprivate static final String VERTEX_SHADER =\n\t\t\t\"attribute vec2 position;\" +\n\t\t\t\t\t\"void main() {\" +\n\t\t\t\t\t\"gl_Position = vec4(position, 0., 1.);\" +\n\t\t\t\t\t\"}\";\n\tprivate static final String VERTEX_SHADER_3 =\n\t\t\t\"in vec2 position;\" +\n\t\t\t\t\t\"void main() {\" +\n\t\t\t\t\t\"gl_Position = vec4(position, 0., 1.);\" +\n\t\t\t\t\t\"}\";\n\tprivate static final String FRAGMENT_SHADER =\n\t\t\t\"#ifdef GL_FRAGMENT_PRECISION_HIGH\\n\" +\n\t\t\t\t\t\"precision highp float;\\n\" +\n\t\t\t\t\t\"#else\\n\" +\n\t\t\t\t\t\"precision mediump float;\\n\" +\n\t\t\t\t\t\"#endif\\n\" +\n\t\t\t\t\t\"uniform vec2 resolution;\" +\n\t\t\t\t\t\"uniform sampler2D frame;\" +\n\t\t\t\t\t\"void main(void) {\" +\n\t\t\t\t\t\"gl_FragColor = texture2D(frame,\" +\n\t\t\t\t\t\"gl_FragCoord.xy / resolution.xy).rgba;\" +\n\t\t\t\t\t\"}\";\n\n\tprivate final TextureBinder textureBinder = new TextureBinder();\n\tprivate final ArrayList<String> textureNames = new ArrayList<>();\n\tprivate final ArrayList<TextureParameters> textureParameters =\n\t\t\tnew ArrayList<>();\n\tprivate final BackBufferParameters backBufferTextureParams =\n\t\t\tnew BackBufferParameters();\n\tprivate final int[] fb = new int[]{0, 0};\n\tprivate final int[] tx = new int[]{0, 0};\n\tprivate final int[] textureLocs = new int[32];\n\tprivate final int[] textureTargets = new int[32];\n\tprivate final int[] textureIds = new int[32];\n\tprivate final float[] surfaceResolution = new float[]{0, 0};\n\tprivate final float[] resolution = new float[]{0, 0};\n\tprivate final float[] touch = new float[]{0, 0};\n\tprivate final float[] mouse = new float[]{0, 0};\n\tprivate final float[] pointers = new float[30];\n\tprivate final float[] offset = new float[]{0, 0};\n\tprivate final float[] daytime = new float[]{0, 0, 0};\n\tprivate final float[] dateTime = new float[]{0, 0, 0, 0};\n\tprivate final float[] rotationMatrix = new float[9];\n\tprivate final float[] inclinationMatrix = new float[9];\n\tprivate final float[] orientation = new float[]{0, 0, 0};\n\tprivate final Context context;\n\tprivate final ByteBuffer vertexBuffer;\n\n\tprivate AccelerometerListener accelerometerListener;\n\tprivate CameraListener cameraListener;\n\tprivate GravityListener gravityListener;\n\tprivate GyroscopeListener gyroscopeListener;\n\tprivate MagneticFieldListener magneticFieldListener;\n\tprivate LightListener lightListener;\n\tprivate LinearAccelerationListener linearAccelerationListener;\n\tprivate PressureListener pressureListener;\n\tprivate ProximityListener proximityListener;\n\tprivate RotationVectorListener rotationVectorListener;\n\tprivate OnRendererListener onRendererListener;\n\tprivate String fragmentShader;\n\tprivate int version = 2;\n\tprivate int deviceRotation;\n\tprivate int surfaceProgram = 0;\n\tprivate int surfacePositionLoc;\n\tprivate int surfaceResolutionLoc;\n\tprivate int surfaceFrameLoc;\n\tprivate int program = 0;\n\tprivate int positionLoc;\n\tprivate int timeLoc;\n\tprivate int secondLoc;\n\tprivate int subSecondLoc;\n\tprivate int frameNumLoc;\n\tprivate int fTimeLoc;\n\tprivate int resolutionLoc;\n\tprivate int touchLoc;\n\tprivate int mouseLoc;\n\tprivate int pointerCountLoc;\n\tprivate int pointersLoc;\n\tprivate int powerConnectedLoc;\n\tprivate int gravityLoc;\n\tprivate int linearLoc;\n\tprivate int gyroscopeLoc;\n\tprivate int magneticLoc;\n\tprivate int rotationMatrixLoc;\n\tprivate int rotationVectorLoc;\n\tprivate int orientationLoc;\n\tprivate int inclinationMatrixLoc;\n\tprivate int inclinationLoc;\n\tprivate int lightLoc;\n\tprivate int pressureLoc;\n\tprivate int proximityLoc;\n\tprivate int offsetLoc;\n\tprivate int batteryLoc;\n\tprivate int dateTimeLoc;\n\tprivate int daytimeLoc;\n\tprivate int startRandomLoc;\n\tprivate int backBufferLoc;\n\tprivate int cameraOrientationLoc;\n\tprivate int cameraAddentLoc;\n\tprivate int numberOfTextures;\n\tprivate int pointerCount;\n\tprivate int frontTarget;\n\tprivate int backTarget = 1;\n\tprivate int frameNum;\n\tprivate long startTime;\n\tprivate long lastRender;\n\tprivate long lastBatteryUpdate;\n\tprivate long lastDateUpdate;\n\tprivate float batteryLevel;\n\tprivate float quality = 1f;\n\tprivate float startRandom;\n\tprivate float fTimeMax;\n\tprivate float[] gravityValues;\n\tprivate float[] linearValues;\n\n\tprivate volatile byte[] thumbnail = new byte[1];\n\tprivate volatile long nextFpsUpdate = 0;\n\tprivate volatile float sum;\n\tprivate volatile float samples;\n\tprivate volatile int lastFps;\n\n\tpublic ShaderRenderer(Context context) {\n\t\tthis.context = context;\n\n\t\t// -1/1 1/1\n\t\t// +---+\n\t\t// | /|\n\t\t// | 0 |\n\t\t// |/ |\n\t\t// +---+\n\t\t// -1/-1 1/-1\n\t\tvertexBuffer = ByteBuffer.allocateDirect(8);\n\t\tvertexBuffer.put(new byte[]{\n\t\t\t\t-1, 1, // left top\n\t\t\t\t-1, -1, // left bottom\n\t\t\t\t1, 1, // right top, first triangle from last 3 vertices\n\t\t\t\t1, -1 // right bottom, second triangle from last 3 vertices\n\t\t}).position(0);\n\t}\n\n\tpublic void setVersion(int version) {\n\t\tthis.version = version;\n\t}\n\n\tpublic void setFragmentShader(String source, float quality) {\n\t\tsetQuality(quality);\n\t\tsetFragmentShader(source);\n\t}\n\n\tprivate void setFragmentShader(String source) {\n\t\tfTimeMax = parseFTime(source);\n\t\tresetFps();\n\t\tfragmentShader = indexTextureNames(source);\n\t}\n\n\tpublic void setQuality(float quality) {\n\t\tthis.quality = quality;\n\t}\n\n\tpublic void setOnRendererListener(OnRendererListener listener) {\n\t\tonRendererListener = listener;\n\t}\n\n\t@Override\n\tpublic void onSurfaceCreated(GL10 gl, EGLConfig config) {\n\t\tGLES20.glDisable(GLES20.GL_CULL_FACE);\n\t\tGLES20.glDisable(GLES20.GL_BLEND);\n\t\tGLES20.glDisable(GLES20.GL_DEPTH_TEST);\n\n\t\tGLES20.glClearColor(0f, 0f, 0f, 1f);\n\n\t\tif (surfaceProgram != 0) {\n\t\t\t// Don't glDeleteProgram(surfaceProgram) because\n\t\t\t// GLSurfaceView::onPause() destroys the GL context\n\t\t\t// what also deletes all programs.\n\t\t\t// With glDeleteProgram():\n\t\t\t// <core_glDeleteProgram:594>: GL_INVALID_VALUE\n\t\t\tsurfaceProgram = 0;\n\t\t}\n\n\t\tif (program != 0) {\n\t\t\t// Don't glDeleteProgram(program);\n\t\t\t// same as above\n\t\t\tprogram = 0;\n\t\t\tdeleteTargets();\n\t\t}\n\n\t\tif (fragmentShader != null && fragmentShader.length() > 0) {\n\t\t\tresetFps();\n\t\t\tcreateTextures();\n\t\t\tloadPrograms();\n\t\t\tindexLocations();\n\t\t\tenableAttribArrays();\n\t\t\tregisterListeners();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onSurfaceChanged(GL10 gl, int width, int height) {\n\t\tstartTime = lastRender = System.nanoTime();\n\t\tstartRandom = (float) Math.random();\n\t\tframeNum = 0;\n\n\t\tsurfaceResolution[0] = width;\n\t\tsurfaceResolution[1] = height;\n\t\tdeviceRotation = getDeviceRotation(context);\n\n\t\tfloat w = Math.round(width * quality);\n\t\tfloat h = Math.round(height * quality);\n\n\t\tif (w != resolution[0] || h != resolution[1]) {\n\t\t\tdeleteTargets();\n\t\t}\n\n\t\tresolution[0] = w;\n\t\tresolution[1] = h;\n\n\t\tresetFps();\n\t\topenCameraListener();\n\t}\n\n\t@Override\n\tpublic void onDrawFrame(GL10 gl) {\n\t\tif (surfaceProgram == 0 || program == 0) {\n\t\t\tGLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT |\n\t\t\t\t\tGLES20.GL_DEPTH_BUFFER_BIT);\n\n\t\t\treturn;\n\t\t}\n\n\t\tGLES20.glUseProgram(program);\n\t\tGLES20.glVertexAttribPointer(positionLoc, 2, GLES20.GL_BYTE,\n\t\t\t\tfalse, 0, vertexBuffer);\n\n\t\tfinal long now = System.nanoTime();\n\t\tfloat delta = (now - startTime) / NS_PER_SECOND;\n\n\t\tif (timeLoc > -1) {\n\t\t\tGLES20.glUniform1f(timeLoc, delta);\n\t\t}\n\t\tif (secondLoc > -1) {\n\t\t\tGLES20.glUniform1i(secondLoc, (int) delta);\n\t\t}\n\t\tif (subSecondLoc > -1) {\n\t\t\tGLES20.glUniform1f(subSecondLoc, delta - (int) delta);\n\t\t}\n\t\tif (frameNumLoc > -1) {\n\t\t\tGLES20.glUniform1i(frameNumLoc, frameNum);\n\t\t}\n\t\tif (fTimeLoc > -1) {\n\t\t\tGLES20.glUniform1f(fTimeLoc,\n\t\t\t\t\t((delta % fTimeMax) / fTimeMax * 2f - 1f));\n\t\t}\n\t\tif (resolutionLoc > -1) {\n\t\t\tGLES20.glUniform2fv(resolutionLoc, 1, resolution, 0);\n\t\t}\n\t\tif (touchLoc > -1) {\n\t\t\tGLES20.glUniform2fv(touchLoc, 1, touch, 0);\n\t\t}\n\t\tif (mouseLoc > -1) {\n\t\t\tGLES20.glUniform2fv(mouseLoc, 1, mouse, 0);\n\t\t}\n\t\tif (pointerCountLoc > -1) {\n\t\t\tGLES20.glUniform1i(pointerCountLoc, pointerCount);\n\t\t}\n\t\tif (pointersLoc > -1) {\n\t\t\tGLES20.glUniform3fv(pointersLoc, pointerCount, pointers, 0);\n\t\t}\n\t\tif (gravityLoc > -1 && gravityValues != null) {\n\t\t\tGLES20.glUniform3fv(gravityLoc, 1, gravityValues, 0);\n\t\t}\n\t\tif (linearLoc > -1 && linearValues != null) {\n\t\t\tGLES20.glUniform3fv(linearLoc, 1, linearValues, 0);\n\t\t}\n\t\tif (gyroscopeLoc > -1 && gyroscopeListener != null) {\n\t\t\tGLES20.glUniform3fv(gyroscopeLoc, 1, gyroscopeListener.rotation, 0);\n\t\t}\n\t\tif (magneticLoc > -1 && magneticFieldListener != null) {\n\t\t\tGLES20.glUniform3fv(magneticLoc, 1, magneticFieldListener.values, 0);\n\t\t}\n\t\tif ((rotationMatrixLoc > -1 || orientationLoc > -1 ||\n\t\t\t\tinclinationMatrixLoc > -1 || inclinationLoc > -1) &&\n\t\t\t\tgravityValues != null) {\n\t\t\tsetRotationMatrix();\n\t\t}\n\t\tif (lightLoc > -1 && lightListener != null) {\n\t\t\tGLES20.glUniform1f(lightLoc, lightListener.getAmbient());\n\t\t}\n\t\tif (pressureLoc > -1 && pressureListener != null) {\n\t\t\tGLES20.glUniform1f(pressureLoc, pressureListener.getPressure());\n\t\t}\n\t\tif (proximityLoc > -1 && proximityListener != null) {\n\t\t\tGLES20.glUniform1f(proximityLoc, proximityListener.getCentimeters());\n\t\t}\n\t\tif (rotationVectorLoc > -1 && rotationVectorListener != null) {\n\t\t\tGLES20.glUniform3fv(rotationVectorLoc, 1,\n\t\t\t\t\trotationVectorListener.values, 0);\n\t\t}\n\t\tif (offsetLoc > -1) {\n\t\t\tGLES20.glUniform2fv(offsetLoc, 1, offset, 0);\n\t\t}\n\t\tif (batteryLoc > -1) {\n\t\t\tif (now - lastBatteryUpdate > BATTERY_UPDATE_INTERVAL) {\n\t\t\t\t// profiled getBatteryLevel() on slow/old devices\n\t\t\t\t// and it can take up to 6ms, so better do that\n\t\t\t\t// not for every frame but only once in a while\n\t\t\t\tbatteryLevel = getBatteryLevel();\n\t\t\t\tlastBatteryUpdate = now;\n\t\t\t}\n\t\t\tGLES20.glUniform1f(batteryLoc, batteryLevel);\n\t\t}\n\t\tif (powerConnectedLoc > -1) {\n\t\t\tGLES20.glUniform1i(powerConnectedLoc,\n\t\t\t\t\tShaderEditorApp.preferences.isPowerConnected() ? 1 : 0);\n\t\t}\n\t\tif (dateTimeLoc > -1 || daytimeLoc > -1) {\n\t\t\tif (now - lastDateUpdate > DATE_UPDATE_INTERVAL) {\n\t\t\t\tCalendar calendar = Calendar.getInstance();\n\t\t\t\tif (dateTimeLoc > -1) {\n\t\t\t\t\tdateTime[0] = calendar.get(Calendar.YEAR);\n\t\t\t\t\tdateTime[1] = calendar.get(Calendar.MONTH);\n\t\t\t\t\tdateTime[2] = calendar.get(Calendar.DAY_OF_MONTH);\n\t\t\t\t\tdateTime[3] = calendar.get(Calendar.HOUR_OF_DAY) * 3600f +\n\t\t\t\t\t\t\tcalendar.get(Calendar.MINUTE) * 60f +\n\t\t\t\t\t\t\tcalendar.get(Calendar.SECOND);\n\t\t\t\t}\n\t\t\t\tif (daytimeLoc > -1) {\n\t\t\t\t\tdaytime[0] = calendar.get(Calendar.HOUR_OF_DAY);\n\t\t\t\t\tdaytime[1] = calendar.get(Calendar.MINUTE);\n\t\t\t\t\tdaytime[2] = calendar.get(Calendar.SECOND);\n\t\t\t\t}\n\t\t\t\tlastDateUpdate = now;\n\t\t\t}\n\t\t\tif (dateTimeLoc > -1) {\n\t\t\t\tGLES20.glUniform4fv(dateTimeLoc, 1, dateTime, 0);\n\t\t\t}\n\t\t\tif (daytimeLoc > -1) {\n\t\t\t\tGLES20.glUniform3fv(daytimeLoc, 1, daytime, 0);\n\t\t\t}\n\t\t}\n\t\tif (startRandomLoc > -1) {\n\t\t\tGLES20.glUniform1f(startRandomLoc, startRandom);\n\t\t}\n\n\t\tif (fb[0] == 0) {\n\t\t\tcreateTargets((int) resolution[0], (int) resolution[1]);\n\t\t}\n\n\t\t// first draw custom shader in framebuffer\n\t\tGLES20.glViewport(0, 0, (int) resolution[0], (int) resolution[1]);\n\n\t\ttextureBinder.reset();\n\n\t\tif (backBufferLoc > -1) {\n\t\t\ttextureBinder.bind(backBufferLoc, GLES20.GL_TEXTURE_2D,\n\t\t\t\t\ttx[backTarget]);\n\t\t}\n\t\tif (cameraListener != null) {\n\t\t\tif (cameraOrientationLoc > -1) {\n\t\t\t\tGLES20.glUniformMatrix2fv(cameraOrientationLoc, 1, false,\n\t\t\t\t\t\tcameraListener.getOrientationMatrix());\n\t\t\t}\n\t\t\tif (cameraAddentLoc > -1) {\n\t\t\t\tGLES20.glUniform2fv(cameraAddentLoc, 1,\n\t\t\t\t\t\tcameraListener.addent, 0);\n\t\t\t}\n\t\t\tcameraListener.update();\n\t\t}\n\n\t\tfor (int i = 0; i < numberOfTextures; ++i) {\n\t\t\ttextureBinder.bind(\n\t\t\t\t\ttextureLocs[i],\n\t\t\t\t\ttextureTargets[i],\n\t\t\t\t\ttextureIds[i]);\n\t\t}\n\n\t\tGLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[frontTarget]);\n\t\tGLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);\n\n\t\t// then draw framebuffer on screen\n\t\tGLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);\n\t\tGLES20.glViewport(0, 0,\n\t\t\t\t(int) surfaceResolution[0],\n\t\t\t\t(int) surfaceResolution[1]);\n\t\tGLES20.glUseProgram(surfaceProgram);\n\t\tGLES20.glVertexAttribPointer(surfacePositionLoc, 2, GLES20.GL_BYTE,\n\t\t\t\tfalse, 0, vertexBuffer);\n\n\t\tGLES20.glUniform2fv(surfaceResolutionLoc, 1, surfaceResolution, 0);\n\n\t\tGLES20.glUniform1i(surfaceFrameLoc, 0);\n\t\tGLES20.glActiveTexture(GLES20.GL_TEXTURE0);\n\t\tGLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tx[frontTarget]);\n\n\t\tGLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);\n\t\tGLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);\n\n\t\t// swap buffers so the next image will be rendered\n\t\t// over the current backbuffer and the current image\n\t\t// will be the backbuffer for the next image\n\t\tint t = frontTarget;\n\t\tfrontTarget = backTarget;\n\t\tbackTarget = t;\n\n\t\tif (thumbnail == null) {\n\t\t\tthumbnail = saveThumbnail();\n\t\t}\n\n\t\tif (onRendererListener != null) {\n\t\t\tupdateFps(now);\n\t\t}\n\n\t\t++frameNum;\n\t}\n\n\tpublic void unregisterListeners() {\n\t\tif (accelerometerListener != null) {\n\t\t\taccelerometerListener.unregister();\n\t\t\tgravityValues = linearValues = null;\n\t\t}\n\n\t\tif (gravityListener != null) {\n\t\t\tgravityListener.unregister();\n\t\t\tgravityValues = null;\n\t\t}\n\n\t\tif (linearAccelerationListener != null) {\n\t\t\tlinearAccelerationListener.unregister();\n\t\t\tlinearValues = null;\n\t\t}\n\n\t\tif (gyroscopeListener != null) {\n\t\t\tgyroscopeListener.unregister();\n\t\t}\n\n\t\tif (magneticFieldListener != null) {\n\t\t\tmagneticFieldListener.unregister();\n\t\t}\n\n\t\tif (lightListener != null) {\n\t\t\tlightListener.unregister();\n\t\t}\n\n\t\tif (pressureListener != null) {\n\t\t\tpressureListener.unregister();\n\t\t}\n\n\t\tif (proximityListener != null) {\n\t\t\tproximityListener.unregister();\n\t\t}\n\n\t\tif (rotationVectorListener != null) {\n\t\t\trotationVectorListener.unregister();\n\t\t}\n\n\t\tunregisterCameraListener();\n\t}\n\n\tpublic void touchAt(MotionEvent e) {\n\t\tfloat x = e.getX() * quality;\n\t\tfloat y = e.getY() * quality;\n\n\t\ttouch[0] = x;\n\t\ttouch[1] = resolution[1] - y;\n\n\t\t// to be compatible with http://glslsandbox.com/\n\t\tmouse[0] = x / resolution[0];\n\t\tmouse[1] = 1 - y / resolution[1];\n\n\t\tswitch (e.getActionMasked()) {\n\t\t\tcase MotionEvent.ACTION_UP:\n\t\t\tcase MotionEvent.ACTION_CANCEL:\n\t\t\t\tpointerCount = 0;\n\t\t\t\treturn;\n\t\t}\n\n\t\tpointerCount = Math.min(\n\t\t\t\te.getPointerCount(),\n\t\t\t\tpointers.length / 3);\n\n\t\tfor (int i = 0, offset = 0; i < pointerCount; ++i) {\n\t\t\tpointers[offset++] = e.getX(i) * quality;\n\t\t\tpointers[offset++] = resolution[1] - e.getY(i) * quality;\n\t\t\tpointers[offset++] = e.getTouchMajor(i);\n\t\t}\n\t}\n\n\tpublic void setOffset(float x, float y) {\n\t\toffset[0] = x;\n\t\toffset[1] = y;\n\t}\n\n\tpublic byte[] getThumbnail() {\n\t\t// settings thumbnail to null triggers\n\t\t// the capture on the OpenGL thread in\n\t\t// onDrawFrame()\n\t\tthumbnail = null;\n\n\t\ttry {\n\t\t\tfor (int trys = 10;\n\t\t\t\t\ttrys-- > 0 && program > 0 && thumbnail == null; ) {\n\t\t\t\tThread.sleep(100);\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tThread.currentThread().interrupt();\n\t\t}\n\n\t\t// don't clone() because the data doesn't need to be\n\t\t// protected from modification what means copying would\n\t\t// only mean using more memory than necessary\n\t\treturn thumbnail;\n\t}\n\n\tprivate void resetFps() {\n\t\tsum = samples = 0;\n\t\tlastFps = 0;\n\t\tnextFpsUpdate = 0;\n\t}\n\n\tprivate void loadPrograms() {\n\t\tif (((surfaceProgram = Program.loadProgram(\n\t\t\t\tVERTEX_SHADER,\n\t\t\t\tFRAGMENT_SHADER)) == 0 ||\n\t\t\t\t(program = Program.loadProgram(\n\t\t\t\t\t\tgetVertexShader(),\n\t\t\t\t\t\tfragmentShader)) == 0) &&\n\t\t\t\tonRendererListener != null) {\n\t\t\tonRendererListener.onInfoLog(Program.getInfoLog());\n\t\t}\n\t}\n\n\tprivate String getVertexShader() {\n\t\tMatcher m = PATTERN_VERSION.matcher(fragmentShader);\n\t\tif (version == 3 && m.find()) {\n\t\t\treturn m.group(0) + \"\\n\" + VERTEX_SHADER_3;\n\t\t} else {\n\t\t\treturn VERTEX_SHADER;\n\t\t}\n\t}\n\n\tprivate void indexLocations() {\n\t\tsurfacePositionLoc = GLES20.glGetAttribLocation(\n\t\t\t\tsurfaceProgram, \"position\");\n\t\tsurfaceResolutionLoc = GLES20.glGetUniformLocation(\n\t\t\t\tsurfaceProgram, \"resolution\");\n\t\tsurfaceFrameLoc = GLES20.glGetUniformLocation(\n\t\t\t\tsurfaceProgram, \"frame\");\n\n\t\tpositionLoc = GLES20.glGetAttribLocation(\n\t\t\t\tprogram, UNIFORM_POSITION);\n\t\ttimeLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_TIME);\n\t\tsecondLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_SECOND);\n\t\tsubSecondLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_SUB_SECOND);\n\t\tframeNumLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_FRAME_NUMBER);\n\t\tfTimeLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_FTIME);\n\t\tresolutionLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_RESOLUTION);\n\t\ttouchLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_TOUCH);\n\t\tmouseLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_MOUSE);\n\t\tpointerCountLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_POINTER_COUNT);\n\t\tpointersLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_POINTERS);\n\t\tpowerConnectedLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_POWER_CONNECTED);\n\t\tgravityLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_GRAVITY);\n\t\tgyroscopeLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_GYROSCOPE);\n\t\tlinearLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_LINEAR);\n\t\tmagneticLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_MAGNETIC);\n\t\trotationMatrixLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_ROTATION_MATRIX);\n\t\trotationVectorLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_ROTATION_VECTOR);\n\t\torientationLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_ORIENTATION);\n\t\tinclinationMatrixLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_INCLINATION_MATRIX);\n\t\tinclinationLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_INCLINATION);\n\t\tlightLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_LIGHT);\n\t\tpressureLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_PRESSURE);\n\t\tproximityLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_PROXIMITY);\n\t\toffsetLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_OFFSET);\n\t\tbatteryLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_BATTERY);\n\t\tdateTimeLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_DATE);\n\t\tdaytimeLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_DAYTIME);\n\t\tstartRandomLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_START_RANDOM);\n\t\tbackBufferLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_BACKBUFFER);\n\t\tcameraOrientationLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_CAMERA_ORIENTATION);\n\t\tcameraAddentLoc = GLES20.glGetUniformLocation(\n\t\t\t\tprogram, UNIFORM_CAMERA_ADDENT);\n\n\t\tfor (int i = numberOfTextures; i-- > 0; ) {\n\t\t\ttextureLocs[i] = GLES20.glGetUniformLocation(\n\t\t\t\t\tprogram,\n\t\t\t\t\ttextureNames.get(i));\n\t\t}\n\t}\n\n\tprivate void enableAttribArrays() {\n\t\tGLES20.glEnableVertexAttribArray(surfacePositionLoc);\n\t\tGLES20.glEnableVertexAttribArray(positionLoc);\n\t}\n\n\tprivate void registerListeners() {\n\t\tif (gravityLoc > -1 || rotationMatrixLoc > -1 ||\n\t\t\t\torientationLoc > -1 || inclinationMatrixLoc > -1 ||\n\t\t\t\tinclinationLoc > -1) {\n\t\t\tif (gravityListener == null) {\n\t\t\t\tgravityListener = new GravityListener(context);\n\t\t\t}\n\t\t\tif (!gravityListener.register()) {\n\t\t\t\tgravityListener = null;\n\t\t\t\tAccelerometerListener l = getAccelerometerListener();\n\t\t\t\tgravityValues = l != null ? l.gravity : null;\n\t\t\t} else {\n\t\t\t\tgravityValues = gravityListener.values;\n\t\t\t}\n\t\t}\n\n\t\tif (linearLoc > -1) {\n\t\t\tif (linearAccelerationListener == null) {\n\t\t\t\tlinearAccelerationListener =\n\t\t\t\t\t\tnew LinearAccelerationListener(context);\n\t\t\t}\n\t\t\tif (!linearAccelerationListener.register()) {\n\t\t\t\tlinearAccelerationListener = null;\n\t\t\t\tAccelerometerListener l = getAccelerometerListener();\n\t\t\t\tlinearValues = l != null ? l.linear : null;\n\t\t\t} else {\n\t\t\t\tlinearValues = linearAccelerationListener.values;\n\t\t\t}\n\t\t}\n\n\t\tif (gyroscopeLoc > -1) {\n\t\t\tif (gyroscopeListener == null) {\n\t\t\t\tgyroscopeListener = new GyroscopeListener(context);\n\t\t\t}\n\t\t\tif (!gyroscopeListener.register()) {\n\t\t\t\tgyroscopeListener = null;\n\t\t\t}\n\t\t}\n\n\t\tif (magneticLoc > -1 || rotationMatrixLoc > -1 ||\n\t\t\t\torientationLoc > -1 || inclinationMatrixLoc > -1 ||\n\t\t\t\tinclinationLoc > -1) {\n\t\t\tif (magneticFieldListener == null) {\n\t\t\t\tmagneticFieldListener = new MagneticFieldListener(context);\n\t\t\t}\n\t\t\tif (!magneticFieldListener.register()) {\n\t\t\t\tmagneticFieldListener = null;\n\t\t\t}\n\t\t}\n\n\t\tif (lightLoc > -1) {\n\t\t\tif (lightListener == null) {\n\t\t\t\tlightListener = new LightListener(context);\n\t\t\t}\n\t\t\tif (!lightListener.register()) {\n\t\t\t\tlightListener = null;\n\t\t\t}\n\t\t}\n\n\t\tif (pressureLoc > -1) {\n\t\t\tif (pressureListener == null) {\n\t\t\t\tpressureListener = new PressureListener(context);\n\t\t\t}\n\t\t\tif (!pressureListener.register()) {\n\t\t\t\tpressureListener = null;\n\t\t\t}\n\t\t}\n\n\t\tif (proximityLoc > -1) {\n\t\t\tif (proximityListener == null) {\n\t\t\t\tproximityListener = new ProximityListener(context);\n\t\t\t}\n\t\t\tif (!proximityListener.register()) {\n\t\t\t\tproximityListener = null;\n\t\t\t}\n\t\t}\n\n\t\tif (rotationVectorLoc > -1 || (magneticFieldListener == null &&\n\t\t\t\t(orientationLoc > -1 || rotationMatrixLoc > -1))) {\n\t\t\tif (rotationVectorListener == null) {\n\t\t\t\trotationVectorListener = new RotationVectorListener(context);\n\t\t\t}\n\t\t\tif (!rotationVectorListener.register()) {\n\t\t\t\trotationVectorListener = null;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate AccelerometerListener getAccelerometerListener() {\n\t\tif (accelerometerListener == null) {\n\t\t\taccelerometerListener = new AccelerometerListener(context);\n\t\t}\n\t\tif (!accelerometerListener.register()) {\n\t\t\treturn null;\n\t\t}\n\t\treturn accelerometerListener;\n\t}\n\n\tprivate byte[] saveThumbnail() {\n\t\tfinal int min = (int) Math.min(\n\t\t\t\tsurfaceResolution[0],\n\t\t\t\tsurfaceResolution[1]);\n\t\tfinal int pixels = min * min;\n\t\tfinal int[] rgba = new int[pixels];\n\t\tfinal int[] bgra = new int[pixels];\n\t\tfinal IntBuffer colorBuffer = IntBuffer.wrap(rgba);\n\n\t\tGLES20.glReadPixels(\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\tmin,\n\t\t\t\tmin,\n\t\t\t\tGLES20.GL_RGBA,\n\t\t\t\tGLES20.GL_UNSIGNED_BYTE,\n\t\t\t\tcolorBuffer);\n\n\t\tfor (int i = 0, e = pixels; i < pixels; ) {\n\t\t\te -= min;\n\n\t\t\tfor (int x = min, b = e; x-- > 0; ++i, ++b) {\n\t\t\t\tfinal int c = rgba[i];\n\n\t\t\t\tbgra[b] = ((c >> 16) & 0xff) |\n\t\t\t\t\t\t((c << 16) & 0xff0000) |\n\t\t\t\t\t\t(c & 0xff00ff00);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\t\tBitmap.createScaledBitmap(\n\t\t\t\t\tBitmap.createBitmap(\n\t\t\t\t\t\t\tbgra,\n\t\t\t\t\t\t\tmin,\n\t\t\t\t\t\t\tmin,\n\t\t\t\t\t\t\tBitmap.Config.ARGB_8888),\n\t\t\t\t\t144,\n\t\t\t\t\t144,\n\t\t\t\t\ttrue).compress(\n\t\t\t\t\tBitmap.CompressFormat.PNG,\n\t\t\t\t\t100,\n\t\t\t\t\tout);\n\n\t\t\treturn out.toByteArray();\n\t\t} catch (IllegalArgumentException e) {\n\t\t\t// will never happen because neither\n\t\t\t// width nor height <= 0\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate void setRotationMatrix() {\n\t\tboolean haveInclination = false;\n\t\tif (gravityListener != null && magneticFieldListener != null &&\n\t\t\t\tSensorManager.getRotationMatrix(\n\t\t\t\t\t\trotationMatrix,\n\t\t\t\t\t\tinclinationMatrix,\n\t\t\t\t\t\tgravityValues,\n\t\t\t\t\t\tmagneticFieldListener.filtered)) {\n\t\t\thaveInclination = true;\n\t\t} else if (rotationVectorListener != null) {\n\t\t\tSensorManager.getRotationMatrixFromVector(\n\t\t\t\t\trotationMatrix,\n\t\t\t\t\trotationVectorListener.values);\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t\tif (deviceRotation != 0) {\n\t\t\tint x = SensorManager.AXIS_Y;\n\t\t\tint y = SensorManager.AXIS_MINUS_X;\n\t\t\tswitch (deviceRotation) {\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\tcase 270:\n\t\t\t\t\tx = SensorManager.AXIS_MINUS_Y;\n\t\t\t\t\ty = SensorManager.AXIS_X;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tSensorManager.remapCoordinateSystem(\n\t\t\t\t\trotationMatrix,\n\t\t\t\t\tx,\n\t\t\t\t\ty,\n\t\t\t\t\trotationMatrix);\n\t\t}\n\t\tif (rotationMatrixLoc > -1) {\n\t\t\tGLES20.glUniformMatrix3fv(rotationMatrixLoc, 1, true,\n\t\t\t\t\trotationMatrix, 0);\n\t\t}\n\t\tif (orientationLoc > -1) {\n\t\t\tSensorManager.getOrientation(rotationMatrix, orientation);\n\t\t\tGLES20.glUniform3fv(orientationLoc, 1, orientation, 0);\n\t\t}\n\t\tif (inclinationMatrixLoc > -1 && haveInclination) {\n\t\t\tGLES20.glUniformMatrix3fv(inclinationMatrixLoc, 1, true,\n\t\t\t\t\tinclinationMatrix, 0);\n\t\t}\n\t\tif (inclinationLoc > -1 && haveInclination) {\n\t\t\tGLES20.glUniform1f(inclinationLoc,\n\t\t\t\t\tSensorManager.getInclination(inclinationMatrix));\n\t\t}\n\t}\n\n\tprivate void updateFps(long now) {\n\t\tlong delta = now - lastRender;\n\n\t\t// because sum and samples are volatile\n\t\tsynchronized (this) {\n\t\t\tsum += Math.min(NS_PER_SECOND / delta, 60f);\n\n\t\t\tif (++samples > 0xffff) {\n\t\t\t\tsum = sum / samples;\n\t\t\t\tsamples = 1;\n\t\t\t}\n\t\t}\n\n\t\tif (now > nextFpsUpdate) {\n\t\t\tint fps = Math.round(sum / samples);\n\t\t\tif (fps != lastFps) {\n\t\t\t\tonRendererListener.onFramesPerSecond(fps);\n\t\t\t\tlastFps = fps;\n\t\t\t}\n\t\t\tnextFpsUpdate = now + FPS_UPDATE_FREQUENCY_NS;\n\t\t}\n\n\t\tlastRender = now;\n\t}\n\n\tprivate void deleteTargets() {\n\t\tif (fb[0] == 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tGLES20.glDeleteFramebuffers(2, fb, 0);\n\t\tGLES20.glDeleteTextures(2, tx, 0);\n\n\t\tfb[0] = 0;\n\t}\n\n\tprivate void createTargets(int width, int height) {\n\t\tdeleteTargets();\n\n\t\tGLES20.glGenFramebuffers(2, fb, 0);\n\t\tGLES20.glGenTextures(2, tx, 0);\n\n\t\tcreateTarget(frontTarget, width, height, backBufferTextureParams);\n\t\tcreateTarget(backTarget, width, height, backBufferTextureParams);\n\n\t\t// unbind textures that were bound in createTarget()\n\t\tGLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);\n\t\tGLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);\n\t}\n\n\tprivate void createTarget(\n\t\t\tint idx,\n\t\t\tint width,\n\t\t\tint height,\n\t\t\tBackBufferParameters tp) {\n\t\tGLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tx[idx]);\n\n\t\tboolean useBitmap = tp.setPresetBitmap(width, height);\n\t\tif (!useBitmap) {\n\t\t\tGLES20.glTexImage2D(\n\t\t\t\t\tGLES20.GL_TEXTURE_2D,\n\t\t\t\t\t0,\n\t\t\t\t\tGLES20.GL_RGBA,\n\t\t\t\t\twidth,\n\t\t\t\t\theight,\n\t\t\t\t\t0,\n\t\t\t\t\tGLES20.GL_RGBA,\n\t\t\t\t\tGLES20.GL_UNSIGNED_BYTE,\n\t\t\t\t\tnull);\n\t\t}\n\n\t\ttp.setParameters(GLES20.GL_TEXTURE_2D);\n\t\tGLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);\n\n\t\tGLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[idx]);\n\t\tGLES20.glFramebufferTexture2D(\n\t\t\t\tGLES20.GL_FRAMEBUFFER,\n\t\t\t\tGLES20.GL_COLOR_ATTACHMENT0,\n\t\t\t\tGLES20.GL_TEXTURE_2D,\n\t\t\t\ttx[idx],\n\t\t\t\t0);\n\n\t\tif (!useBitmap) {\n\t\t\t// clear texture because some drivers\n\t\t\t// don't initialize texture memory\n\t\t\tGLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT |\n\t\t\t\t\tGLES20.GL_DEPTH_BUFFER_BIT);\n\t\t}\n\t}\n\n\tprivate void deleteTextures() {\n\t\tif (textureIds[0] == 1 || numberOfTextures < 1) {\n\t\t\treturn;\n\t\t}\n\t\tGLES20.glDeleteTextures(numberOfTextures, textureIds, 0);\n\t}\n\n\tprivate void createTextures() {\n\t\tdeleteTextures();\n\t\tGLES20.glGenTextures(numberOfTextures, textureIds, 0);\n\n\t\tfor (int i = 0; i < numberOfTextures; ++i) {\n\t\t\tString name = textureNames.get(i);\n\t\t\tif (UNIFORM_CAMERA_BACK.equals(name) ||\n\t\t\t\t\tUNIFORM_CAMERA_FRONT.equals(name)) {\n\t\t\t\t// handled in onSurfaceChanged() because we need\n\t\t\t\t// the dimensions of the surface to pick a preview\n\t\t\t\t// resolution\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tBitmap bitmap = ShaderEditorApp.db.getTextureBitmap(name);\n\t\t\tif (bitmap == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (textureTargets[i]) {\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue;\n\t\t\t\tcase GLES20.GL_TEXTURE_2D:\n\t\t\t\t\tcreateTexture(textureIds[i], bitmap,\n\t\t\t\t\t\t\ttextureParameters.get(i));\n\t\t\t\t\tbreak;\n\t\t\t\tcase GLES20.GL_TEXTURE_CUBE_MAP:\n\t\t\t\t\tcreateCubeTexture(textureIds[i], bitmap,\n\t\t\t\t\t\t\ttextureParameters.get(i));\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbitmap.recycle();\n\t\t}\n\t}\n\n\tprivate void createTexture(\n\t\t\tint id,\n\t\t\tBitmap bitmap,\n\t\t\tTextureParameters tp) {\n\t\tGLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id);\n\t\ttp.setParameters(GLES20.GL_TEXTURE_2D);\n\t\tTextureParameters.setBitmap(bitmap);\n\t\tGLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);\n\t}\n\n\tprivate void createCubeTexture(\n\t\t\tint id,\n\t\t\tBitmap bitmap,\n\t\t\tTextureParameters tp) {\n\t\tGLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, id);\n\t\ttp.setParameters(GLES20.GL_TEXTURE_CUBE_MAP);\n\n\t\tint bitmapWidth = bitmap.getWidth();\n\t\tint bitmapHeight = bitmap.getHeight();\n\t\tint sideWidth = (int) Math.ceil(bitmapWidth / 2f);\n\t\tint sideHeight = Math.round(bitmapHeight / 3f);\n\t\tint sideLength = Math.min(sideWidth, sideHeight);\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tfor (int target : CUBE_MAP_TARGETS) {\n\t\t\tBitmap side = Bitmap.createBitmap(\n\t\t\t\t\tbitmap,\n\t\t\t\t\tx,\n\t\t\t\t\ty,\n\t\t\t\t\t// cube textures need to be quadratic\n\t\t\t\t\tsideLength,\n\t\t\t\t\tsideLength,\n\t\t\t\t\t// don't flip cube textures\n\t\t\t\t\tnull,\n\t\t\t\t\ttrue);\n\n\t\t\tGLUtils.texImage2D(\n\t\t\t\t\ttarget,\n\t\t\t\t\t0,\n\t\t\t\t\tGLES20.GL_RGBA,\n\t\t\t\t\tside,\n\t\t\t\t\tGLES20.GL_UNSIGNED_BYTE,\n\t\t\t\t\t0);\n\n\t\t\tside.recycle();\n\n\t\t\tif ((x += sideWidth) >= bitmapWidth) {\n\t\t\t\tx = 0;\n\t\t\t\ty += sideHeight;\n\t\t\t}\n\t\t}\n\n\t\tGLES20.glGenerateMipmap(GLES20.GL_TEXTURE_CUBE_MAP);\n\t}\n\n\tprivate void unregisterCameraListener() {\n\t\tif (cameraListener != null) {\n\t\t\tcameraListener.unregister();\n\t\t\tcameraListener = null;\n\t\t}\n\t}\n\n\tprivate void openCameraListener() {\n\t\tunregisterCameraListener();\n\n\t\tfor (int i = 0; i < numberOfTextures; ++i) {\n\t\t\tString name = textureNames.get(i);\n\t\t\tif (UNIFORM_CAMERA_BACK.equals(name) ||\n\t\t\t\t\tUNIFORM_CAMERA_FRONT.equals(name)) {\n\t\t\t\topenCameraListener(name, textureIds[i],\n\t\t\t\t\t\ttextureParameters.get(i));\n\n\t\t\t\t// only one camera can be opened at a time\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void openCameraListener(\n\t\t\tString name,\n\t\t\tint id,\n\t\t\tTextureParameters tp) {\n\t\tif (Build.VERSION.SDK_INT <\n\t\t\t\tBuild.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {\n\t\t\treturn;\n\t\t}\n\n\t\tint cameraId = CameraListener.findCameraId(\n\t\t\t\tUNIFORM_CAMERA_BACK.equals(name) ?\n\t\t\t\t\t\tCamera.CameraInfo.CAMERA_FACING_BACK :\n\t\t\t\t\t\tCamera.CameraInfo.CAMERA_FACING_FRONT);\n\n\t\tif (cameraId < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (cameraListener == null ||\n\t\t\t\tcameraListener.cameraId != cameraId) {\n\t\t\tunregisterCameraListener();\n\t\t\trequestCameraPermission();\n\t\t\tsetCameraTextureProperties(id, tp);\n\t\t\tcameraListener = new CameraListener(\n\t\t\t\t\tid,\n\t\t\t\t\tcameraId,\n\t\t\t\t\t(int) resolution[0],\n\t\t\t\t\t(int) resolution[1],\n\t\t\t\t\tdeviceRotation);\n\t\t}\n\n\t\tcameraListener.register();\n\t}\n\n\tprivate void requestCameraPermission() {\n\t\tString permission = android.Manifest.permission.CAMERA;\n\t\tif (ContextCompat.checkSelfPermission(context, permission) !=\n\t\t\t\tPackageManager.PERMISSION_GRANTED) {\n\t\t\tActivity activity;\n\t\t\ttry {\n\t\t\t\tactivity = (Activity) context;\n\t\t\t} catch (ClassCastException e) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tActivityCompat.requestPermissions(\n\t\t\t\t\tactivity,\n\t\t\t\t\tnew String[]{permission},\n\t\t\t\t\t1);\n\t\t}\n\t}\n\n\t@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)\n\tprivate static void setCameraTextureProperties(\n\t\t\tint id,\n\t\t\tTextureParameters tp) {\n\t\tif (Build.VERSION.SDK_INT <\n\t\t\t\tBuild.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {\n\t\t\treturn;\n\t\t}\n\t\tGLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, id);\n\t\ttp.setParameters(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);\n\t}\n\n\tprivate static float parseFTime(String source) {\n\t\tif (source != null) {\n\t\t\tMatcher m = PATTERN_FTIME.matcher(source);\n\t\t\tString s;\n\t\t\tif (m.find() && m.groupCount() > 0 &&\n\t\t\t\t\t(s = m.group(1)) != null) {\n\t\t\t\treturn Float.parseFloat(s);\n\t\t\t}\n\t\t}\n\t\treturn 3f;\n\t}\n\n\tprivate String indexTextureNames(String source) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttextureNames.clear();\n\t\ttextureParameters.clear();\n\t\tnumberOfTextures = 0;\n\t\tbackBufferTextureParams.reset();\n\n\t\tfinal int maxTextures = textureIds.length;\n\t\tfor (Matcher m = PATTERN_SAMPLER.matcher(source);\n\t\t\t\tm.find() && numberOfTextures < maxTextures; ) {\n\t\t\tString type = m.group(1);\n\t\t\tString name = m.group(2);\n\t\t\tString params = m.group(3);\n\n\t\t\tif (type == null || name == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (UNIFORM_BACKBUFFER.equals(name)) {\n\t\t\t\tbackBufferTextureParams.parse(params);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint target;\n\t\t\tswitch (type) {\n\t\t\t\tcase SAMPLER_2D:\n\t\t\t\t\ttarget = GLES20.GL_TEXTURE_2D;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SAMPLER_CUBE:\n\t\t\t\t\ttarget = GLES20.GL_TEXTURE_CUBE_MAP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SAMPLER_EXTERNAL_OES:\n\t\t\t\t\tif (Build.VERSION.SDK_INT >\n\t\t\t\t\t\t\tBuild.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {\n\t\t\t\t\t\t// needs to be done here or lint won't recognize\n\t\t\t\t\t\t// we're checking SDK version\n\t\t\t\t\t\ttarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// ignore that uniform on lower SDKs\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!source.contains(OES_EXTERNAL)) {\n\t\t\t\t\t\tsource = addPreprocessorDirective(source,\n\t\t\t\t\t\t\t\tOES_EXTERNAL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttextureTargets[numberOfTextures++] = target;\n\t\t\ttextureNames.add(name);\n\t\t\ttextureParameters.add(new TextureParameters(params));\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate static String addPreprocessorDirective(String source,\n\t\t\tString directive) {\n\t\t// #version must always be the very first directive\n\t\tif (source.trim().startsWith(\"#version\")) {\n\t\t\tint lf = source.indexOf(\"\\n\");\n\t\t\tif (lf < 0) {\n\t\t\t\t// no line break?\n\t\t\t\treturn source;\n\t\t\t}\n\t\t\t++lf;\n\t\t\treturn source.substring(0, lf) +\n\t\t\t\t\tdirective +\n\t\t\t\t\tsource.substring(lf);\n\t\t}\n\t\treturn directive + source;\n\t}\n\n\tprivate float getBatteryLevel() {\n\t\tIntent batteryStatus = context.registerReceiver(\n\t\t\t\tnull,\n\t\t\t\tnew IntentFilter(Intent.ACTION_BATTERY_CHANGED));\n\n\t\tif (batteryStatus == null) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tint level = batteryStatus.getIntExtra(\n\t\t\t\tBatteryManager.EXTRA_LEVEL, -1);\n\t\tint scale = batteryStatus.getIntExtra(\n\t\t\t\tBatteryManager.EXTRA_SCALE, -1);\n\n\t\treturn (float) level / scale;\n\t}\n\n\tprivate static int getDeviceRotation(Context context) {\n\t\tWindowManager wm = (WindowManager) context.getSystemService(\n\t\t\t\tContext.WINDOW_SERVICE);\n\t\tif (wm == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (wm.getDefaultDisplay().getRotation()) {\n\t\t\tdefault:\n\t\t\tcase Surface.ROTATION_0:\n\t\t\t\treturn 0;\n\t\t\tcase Surface.ROTATION_90:\n\t\t\t\treturn 90;\n\t\t\tcase Surface.ROTATION_180:\n\t\t\t\treturn 180;\n\t\t\tcase Surface.ROTATION_270:\n\t\t\t\treturn 270;\n\t\t}\n\t}\n\n\tprivate static class TextureBinder {\n\t\tprivate int index;\n\n\t\tprivate void reset() {\n\t\t\tindex = 0;\n\t\t}\n\n\t\tprivate void bind(int loc, int target, int textureId) {\n\t\t\tif (loc < 0 || index >= TEXTURE_UNITS.length) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tGLES20.glUniform1i(loc, index);\n\t\t\tGLES20.glActiveTexture(TEXTURE_UNITS[index]);\n\t\t\tGLES20.glBindTexture(target, textureId);\n\t\t\t++index;\n\t\t}\n\t}\n}", "public class TextureParameters {\n\tprotected static final String HEADER = \"///\";\n\tprotected static final String SEPARATOR = \";\";\n\tprotected static final String ASSIGN = \":\";\n\n\tprivate static final String MIN = \"min\";\n\tprivate static final String MAG = \"mag\";\n\tprivate static final String WRAP_S = \"s\";\n\tprivate static final String WRAP_T = \"t\";\n\tprivate static final Matrix flipMatrix = new Matrix();\n\n\tstatic {\n\t\tflipMatrix.postScale(1f, -1f);\n\t}\n\n\tprivate final int defaultMin;\n\tprivate final int defaultMag;\n\tprivate final int defaultWrapS;\n\tprivate final int defaultWrapT;\n\n\tprivate int min;\n\tprivate int mag;\n\tprivate int wrapS;\n\tprivate int wrapT;\n\n\tpublic TextureParameters() {\n\t\tdefaultMin = GLES20.GL_NEAREST;\n\t\tdefaultMag = GLES20.GL_LINEAR;\n\t\tdefaultWrapS = GLES20.GL_REPEAT;\n\t\tdefaultWrapT = GLES20.GL_REPEAT;\n\t\tset(defaultMin, defaultMag, defaultWrapS, defaultWrapT);\n\t}\n\n\tTextureParameters(int min, int mag, int wrapS, int wrapT) {\n\t\tdefaultMin = min;\n\t\tdefaultMag = mag;\n\t\tdefaultWrapS = wrapS;\n\t\tdefaultWrapT = wrapT;\n\t\tset(min, mag, wrapS, wrapT);\n\t}\n\n\tTextureParameters(String params) {\n\t\tthis();\n\t\tparse(params);\n\t}\n\n\tpublic void set(\n\t\t\tString minShortcut,\n\t\t\tString magShortcut,\n\t\t\tString wrapSShortcut,\n\t\t\tString wrapTShortcut) {\n\t\tmin = shortcutToMin(minShortcut);\n\t\tmag = shortcutToMag(magShortcut);\n\t\twrapS = shortcutToWrap(wrapSShortcut);\n\t\twrapT = shortcutToWrap(wrapTShortcut);\n\t}\n\n\t@NonNull\n\t@Override\n\tpublic String toString() {\n\t\tif (min == defaultMin &&\n\t\t\t\tmag == defaultMag &&\n\t\t\t\twrapS == defaultWrapS &&\n\t\t\t\twrapT == defaultWrapT) {\n\t\t\t// use empty string for default values\n\t\t\treturn \"\";\n\t\t}\n\t\treturn HEADER +\n\t\t\t\tMIN + ASSIGN + getMinShortcut() + SEPARATOR +\n\t\t\t\tMAG + ASSIGN + getMagShortcut() + SEPARATOR +\n\t\t\t\tWRAP_S + ASSIGN + getWrapSShortcut() + SEPARATOR +\n\t\t\t\tWRAP_T + ASSIGN + getWrapTShortcut() + SEPARATOR;\n\t}\n\n\tpublic String getMinShortcut() {\n\t\treturn minToShortcut(min);\n\t}\n\n\tpublic String getMagShortcut() {\n\t\treturn magToShortcut(mag);\n\t}\n\n\tpublic String getWrapSShortcut() {\n\t\treturn wrapToShortcut(wrapS);\n\t}\n\n\tpublic String getWrapTShortcut() {\n\t\treturn wrapToShortcut(wrapT);\n\t}\n\n\tvoid set(int min, int mag, int wrapS, int wrapT) {\n\t\tthis.min = min;\n\t\tthis.mag = mag;\n\t\tthis.wrapS = wrapS;\n\t\tthis.wrapT = wrapT;\n\t}\n\n\tvoid setParameters(int target) {\n\t\tGLES20.glTexParameteri(\n\t\t\t\ttarget,\n\t\t\t\tGLES20.GL_TEXTURE_MIN_FILTER,\n\t\t\t\tmin);\n\t\tGLES20.glTexParameteri(\n\t\t\t\ttarget,\n\t\t\t\tGLES20.GL_TEXTURE_MAG_FILTER,\n\t\t\t\tmag);\n\t\tGLES20.glTexParameteri(\n\t\t\t\ttarget,\n\t\t\t\tGLES20.GL_TEXTURE_WRAP_S,\n\t\t\t\twrapS);\n\t\tGLES20.glTexParameteri(\n\t\t\t\ttarget,\n\t\t\t\tGLES20.GL_TEXTURE_WRAP_T,\n\t\t\t\twrapT);\n\t}\n\n\tstatic void setBitmap(Bitmap bitmap) {\n\t\tif (bitmap == null) {\n\t\t\treturn;\n\t\t}\n\t\t// flip bitmap because 0/0 is bottom left in OpenGL\n\t\tBitmap flippedBitmap = Bitmap.createBitmap(\n\t\t\t\tbitmap,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\tbitmap.getWidth(),\n\t\t\t\tbitmap.getHeight(),\n\t\t\t\tflipMatrix,\n\t\t\t\ttrue);\n\t\tGLUtils.texImage2D(\n\t\t\t\tGLES20.GL_TEXTURE_2D,\n\t\t\t\t0,\n\t\t\t\tGLES20.GL_RGBA,\n\t\t\t\tflippedBitmap,\n\t\t\t\tGLES20.GL_UNSIGNED_BYTE,\n\t\t\t\t0);\n\t\tflippedBitmap.recycle();\n\t}\n\n\tvoid parse(String params) {\n\t\tif (params == null) {\n\t\t\treturn;\n\t\t}\n\t\tparams = params.trim();\n\t\tint p = params.indexOf(HEADER);\n\t\tif (p != 0) {\n\t\t\treturn;\n\t\t}\n\t\tparams = params.substring(p + 3);\n\t\tfor (String param : params.split(SEPARATOR)) {\n\t\t\tString[] exp = param.split(ASSIGN);\n\t\t\tif (exp.length != 2) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparseParameter(exp[0], exp[1]);\n\t\t}\n\t}\n\n\tprotected void parseParameter(String name, String value) {\n\t\tswitch (name) {\n\t\t\tdefault:\n\t\t\tcase MIN:\n\t\t\t\tmin = shortcutToMin(value);\n\t\t\t\tbreak;\n\t\t\tcase MAG:\n\t\t\t\tmag = shortcutToMag(value);\n\t\t\t\tbreak;\n\t\t\tcase WRAP_S:\n\t\t\t\twrapS = shortcutToWrap(value);\n\t\t\t\tbreak;\n\t\t\tcase WRAP_T:\n\t\t\t\twrapT = shortcutToWrap(value);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate static int shortcutToMin(String shortcut) {\n\t\tswitch (shortcut) {\n\t\t\tcase \"n\":\n\t\t\t\treturn GLES20.GL_NEAREST;\n\t\t\tcase \"l\":\n\t\t\t\treturn GLES20.GL_LINEAR;\n\t\t\tcase \"nn\":\n\t\t\t\treturn GLES20.GL_NEAREST_MIPMAP_NEAREST;\n\t\t\tcase \"ln\":\n\t\t\t\treturn GLES20.GL_LINEAR_MIPMAP_NEAREST;\n\t\t\tcase \"ll\":\n\t\t\t\treturn GLES20.GL_LINEAR_MIPMAP_LINEAR;\n\t\t\tdefault:\n\t\t\t\treturn GLES20.GL_NEAREST_MIPMAP_LINEAR;\n\t\t}\n\t}\n\n\tprivate static String minToShortcut(int min) {\n\t\tswitch (min) {\n\t\t\tcase GLES20.GL_NEAREST:\n\t\t\t\treturn \"n\";\n\t\t\tcase GLES20.GL_LINEAR:\n\t\t\t\treturn \"l\";\n\t\t\tcase GLES20.GL_NEAREST_MIPMAP_NEAREST:\n\t\t\t\treturn \"nn\";\n\t\t\tcase GLES20.GL_LINEAR_MIPMAP_NEAREST:\n\t\t\t\treturn \"ln\";\n\t\t\tcase GLES20.GL_LINEAR_MIPMAP_LINEAR:\n\t\t\t\treturn \"ll\";\n\t\t\tdefault:\n\t\t\t\treturn \"nl\";\n\t\t}\n\t}\n\n\tprivate static int shortcutToMag(String shortcut) {\n\t\tif (shortcut.equals(\"n\")) {\n\t\t\treturn GLES20.GL_NEAREST;\n\t\t} else {\n\t\t\treturn GLES20.GL_LINEAR;\n\t\t}\n\t}\n\n\tprivate static String magToShortcut(int mag) {\n\t\tswitch (mag) {\n\t\t\tcase GLES20.GL_NEAREST:\n\t\t\t\treturn \"n\";\n\t\t\tdefault:\n\t\t\t\treturn \"l\";\n\t\t}\n\t}\n\n\tprivate static int shortcutToWrap(String shortcut) {\n\t\tswitch (shortcut) {\n\t\t\tcase \"c\":\n\t\t\t\treturn GLES20.GL_CLAMP_TO_EDGE;\n\t\t\tcase \"m\":\n\t\t\t\treturn GLES20.GL_MIRRORED_REPEAT;\n\t\t\tdefault:\n\t\t\t\treturn GLES20.GL_REPEAT;\n\t\t}\n\t}\n\n\tprivate static String wrapToShortcut(int wrap) {\n\t\tswitch (wrap) {\n\t\t\tcase GLES20.GL_CLAMP_TO_EDGE:\n\t\t\t\treturn \"c\";\n\t\t\tcase GLES20.GL_MIRRORED_REPEAT:\n\t\t\t\treturn \"m\";\n\t\t\tdefault:\n\t\t\t\treturn \"r\";\n\t\t}\n\t}\n}", "public class SoftKeyboard {\n\tpublic static void hide(Context context, View view) {\n\t\tif (context != null && view != null) {\n\t\t\tInputMethodManager imm = ((InputMethodManager) context.getSystemService(\n\t\t\t\t\tContext.INPUT_METHOD_SERVICE));\n\t\t\tif (imm != null) {\n\t\t\t\timm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n\t\t\t}\n\t\t}\n\t}\n}", "public class TextureParametersView extends LinearLayout {\n\tprivate Spinner minView;\n\tprivate Spinner magView;\n\tprivate Spinner wrapSView;\n\tprivate Spinner wrapTView;\n\n\tpublic TextureParametersView(Context context) {\n\t\tsuper(context);\n\t}\n\n\tpublic TextureParametersView(Context context, AttributeSet attr) {\n\t\tsuper(context, attr);\n\t}\n\n\t@Override\n\tpublic void onFinishInflate() {\n\t\tsuper.onFinishInflate();\n\n\t\tminView = findViewById(R.id.min);\n\t\tmagView = findViewById(R.id.mag);\n\t\twrapSView = findViewById(R.id.wrap_s);\n\t\twrapTView = findViewById(R.id.wrap_t);\n\n\t\tinitSpinner(minView, R.array.min_names);\n\t\tinitSpinner(magView, R.array.mag_names);\n\t\tinitSpinner(wrapSView, R.array.wrap_names);\n\t\tinitSpinner(wrapTView, R.array.wrap_names);\n\t}\n\n\tpublic void setDefaults(TextureParameters tp) {\n\t\tsetSpinnerValue(minView, R.array.min_values, tp.getMinShortcut());\n\t\tsetSpinnerValue(magView, R.array.mag_values, tp.getMagShortcut());\n\t\tsetSpinnerValue(wrapSView, R.array.wrap_values, tp.getWrapSShortcut());\n\t\tsetSpinnerValue(wrapTView, R.array.wrap_values, tp.getWrapTShortcut());\n\t}\n\n\tpublic void setParameters(TextureParameters tp) {\n\t\ttp.set(getSpinnerValue(minView, R.array.min_values),\n\t\t\t\tgetSpinnerValue(magView, R.array.mag_values),\n\t\t\t\tgetSpinnerValue(wrapSView, R.array.wrap_values),\n\t\t\t\tgetSpinnerValue(wrapTView, R.array.wrap_values));\n\t}\n\n\tprivate void initSpinner(Spinner spinner, int namesId) {\n\t\tArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(\n\t\t\t\tspinner.getContext(),\n\t\t\t\tnamesId,\n\t\t\t\tandroid.R.layout.simple_spinner_item);\n\t\tadapter.setDropDownViewResource(\n\t\t\t\tandroid.R.layout.simple_spinner_dropdown_item);\n\t\tspinner.setAdapter(adapter);\n\t}\n\n\tprivate String getSpinnerValue(Spinner spinner, int valuesId) {\n\t\tString[] values = getResources().getStringArray(valuesId);\n\t\treturn values[spinner.getSelectedItemPosition()];\n\t}\n\n\tprivate void setSpinnerValue(\n\t\t\tSpinner spinner,\n\t\t\tint valuesId,\n\t\t\tString value) {\n\t\tString[] values = getResources().getStringArray(valuesId);\n\t\tfor (int i = 0; i < values.length; ++i) {\n\t\t\tif (values[i].equals(value)) {\n\t\t\t\tspinner.setSelection(i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}" ]
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.Locale; import java.util.regex.Pattern; import de.markusfisch.android.shadereditor.R; import de.markusfisch.android.shadereditor.activity.AddUniformActivity; import de.markusfisch.android.shadereditor.opengl.ShaderRenderer; import de.markusfisch.android.shadereditor.opengl.TextureParameters; import de.markusfisch.android.shadereditor.view.SoftKeyboard; import de.markusfisch.android.shadereditor.widget.TextureParametersView;
view.findViewById(R.id.save).setOnClickListener(v -> saveSamplerAsync()); if (activity.getCallingActivity() == null) { addUniformView.setVisibility(View.GONE); addUniformView.setChecked(false); textureParameterView.setVisibility(View.GONE); } initSizeView(); initNameView(); return view; } private void initSizeView() { setSizeView(sizeBarView.getProgress()); sizeBarView.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged( SeekBar seekBar, int progressValue, boolean fromUser) { setSizeView(progressValue); } @Override public void onStartTrackingTouch( SeekBar seekBar) { } @Override public void onStopTrackingTouch( SeekBar seekBar) { } }); } private void setSizeView(int power) { int size = getPower(power); sizeView.setText(String.format( Locale.US, "%d x %d", size, size)); } private void initNameView() { nameView.setFilters(new InputFilter[]{ (source, start, end, dest, dstart, dend) -> NAME_PATTERN .matcher(source) .find() ? null : ""}); } // this AsyncTask is running for a short and finite time only // and it's perfectly okay to delay garbage collection of the // parent instance until this task has ended @SuppressLint("StaticFieldLeak") private void saveSamplerAsync() { final Context context = getActivity(); if (context == null || inProgress) { return; } final String name = nameView.getText().toString(); final TextureParameters tp = new TextureParameters(); textureParameterView.setParameters(tp); final String params = tp.toString(); if (name.trim().length() < 1) { Toast.makeText( context, R.string.missing_name, Toast.LENGTH_SHORT).show(); return; } else if (!name.matches(TEXTURE_NAME_PATTERN) || name.equals(ShaderRenderer.UNIFORM_BACKBUFFER)) { Toast.makeText( context, R.string.invalid_texture_name, Toast.LENGTH_SHORT).show(); return; } SoftKeyboard.hide(context, nameView); final int size = getPower(sizeBarView.getProgress()); inProgress = true; progressView.setVisibility(View.VISIBLE); new AsyncTask<Void, Void, Integer>() { @Override protected Integer doInBackground(Void... nothings) { return saveSampler(context, name, size); } @Override protected void onPostExecute(Integer messageId) { inProgress = false; progressView.setVisibility(View.GONE); Activity activity = getActivity(); if (activity == null) { return; } if (messageId > 0) { Toast.makeText( activity, messageId, Toast.LENGTH_SHORT).show(); return; } if (addUniformView.isChecked()) {
AddUniformActivity.setAddUniformResult(
0
nikku/silent-disco
server/src/test/java/de/nixis/web/disco/db/DatabaseTest.java
[ "public class Position {\n\n public enum Status {\n PLAYING,\n STOPPED\n }\n\n private String trackId;\n\n private Date date;\n\n private Status status;\n\n private int position;\n\n public Position(String trackId, int position, Status status) {\n this.trackId = trackId;\n this.date = new Date();\n this.status = status;\n this.position = position;\n }\n\n public Position() {\n }\n\n public String getTrackId() {\n return trackId;\n }\n\n public Status getStatus() {\n return status;\n }\n\n public void setStatus(Status status) {\n this.status = status;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public int getPosition() {\n return position;\n }\n}", "public enum Status {\n PLAYING,\n STOPPED\n}", "@Entity\npublic class Room {\n\n @Id\n private ObjectId id;\n\n private String name;\n\n @Embedded\n private Position position;\n\n public Room() {\n }\n\n public Room(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void setPosition(Position position) {\n this.position = position;\n }\n\n public Position getPosition() {\n return position;\n }\n\n public String getId() {\n return id.toString();\n }\n\n public Set<Channel> channels() {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n public Map<Channel, String> channelMap() {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n\n public Collection<String> participantIds() {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n}", "@Entity\npublic class Track {\n\n @Id\n private ObjectId trackId;\n\n /**\n * The soundcloud id of the track\n */\n private String id;\n\n private String artwork_url;\n\n private Date added;\n\n private String permalink_url;\n\n private String title;\n\n @Embedded\n private SoundCloudUser user;\n\n private long duration;\n\n private String roomName;\n\n @JsonIgnore\n private boolean deleted = false;\n\n /**\n * The position of the track in the track list\n */\n @JsonIgnore\n private long position = 0;\n\n public Track() {\n\n }\n\n public Track(String id, String artwork_url, String permalink_url, String title, SoundCloudUser user, long duration, String roomName) {\n this.artwork_url = artwork_url;\n this.permalink_url = permalink_url;\n this.title = title;\n this.user = user;\n this.duration = duration;\n this.roomName = roomName;\n\n this.added = new Date();\n\n this.id = id;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public boolean isDeleted() {\n return deleted;\n }\n\n public void setDeleted(boolean deleted) {\n this.deleted = deleted;\n }\n\n public long getPosition() {\n return position;\n }\n\n public void setPosition(long position) {\n this.position = position;\n }\n\n public String getArtwork_url() {\n return artwork_url;\n }\n\n public void setArtwork_url(String artwork_url) {\n this.artwork_url = artwork_url;\n }\n\n public Date getAdded() {\n return added;\n }\n\n public void setAdded(Date added) {\n this.added = added;\n }\n\n public String getPermalink_url() {\n return permalink_url;\n }\n\n public void setPermalink_url(String permalink_url) {\n this.permalink_url = permalink_url;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public SoundCloudUser getUser() {\n return user;\n }\n\n public void setUser(SoundCloudUser user) {\n this.user = user;\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n public String getRoomName() {\n return roomName;\n }\n\n public void setRoomName(String roomName) {\n this.roomName = roomName;\n }\n\n public String getTrackId() {\n return trackId.toString();\n }\n\n @Override\n public String toString() {\n return \"Track(id=\" + getTrackId() + \")\";\n }\n}", "public class SoundCloudUser {\n\n private String username;\n\n private String permalink_url;\n\n public SoundCloudUser() {\n\n }\n\n public SoundCloudUser(String username, String permalink_url) {\n this.username = username;\n this.permalink_url = permalink_url;\n }\n\n public String getPermalink_url() {\n return permalink_url;\n }\n\n public void setPermalink_url(String permalink_url) {\n this.permalink_url = permalink_url;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n\n}", "public class TrackPosition {\n\n private int position = -1;\n\n public TrackPosition() {\n }\n\n public TrackPosition(int position) {\n this.position = position;\n }\n\n public int getPosition() {\n return position;\n }\n\n public void setPosition(int position) {\n this.position = position;\n }\n}" ]
import static org.fest.assertions.Assertions.assertThat; import java.net.UnknownHostException; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.github.jmkgreen.morphia.Datastore; import com.github.jmkgreen.morphia.Key; import de.nixis.web.disco.db.entity.Position; import de.nixis.web.disco.db.entity.Position.Status; import de.nixis.web.disco.db.entity.Room; import de.nixis.web.disco.db.entity.Track; import de.nixis.web.disco.db.entity.SoundCloudUser; import de.nixis.web.disco.dto.TrackPosition;
package de.nixis.web.disco.db; /** * * @author nico.rehwaldt */ public class DatabaseTest { private Datastore datastore; @Before public void before() throws UnknownHostException { datastore = Disco.createDatastore("localhost", "test-disco"); Disco.DATA_STORE = datastore; } @After public void after() { Disco.DATA_STORE = null; datastore.delete(datastore.find(Track.class)); datastore.delete(datastore.find(Room.class)); datastore.getMongo().close(); } @Test public void databaseTest() throws UnknownHostException { Room room = new Room("FOO"); datastore.save(room); Track track = new Track("1234112", "http://foo/aw", "http://foo", "foo", new SoundCloudUser("klaus", "http://klaus"), 200000, "FOO"); Key<Track> key = datastore.save(track); Object id = key.getId(); assertThat(datastore.exists(key)).isNotNull(); Track fromDB = datastore.get(Track.class, id); assertThat(fromDB).isNotNull(); assertThat(fromDB.getId()).isEqualTo(track.getId()); Room roomFromDB = datastore.find(Room.class, "name =", fromDB.getRoomName()).get(); assertThat(roomFromDB).isNotNull(); assertThat(roomFromDB.getId()).isEqualTo(room.getId()); } @Test public void shouldCreateRoom() { // when Room room = Disco.getRoom("foobar"); Room roomAgain = Disco.getRoom("foobar"); // then assertThat(room.getName()).isEqualTo("foobar"); assertThat(roomAgain.getName()).isEqualTo(room.getName()); } @Test public void shouldAddTrack() { // given Room room = Disco.getRoom("foobar"); // when Track track = Disco.addTrack(new Track(), room.getName(), null); List<Track> tracks = Disco.getTracks(room.getName()); Track firstTrack = tracks.get(0); // then assertThat(track.getRoomName()).isEqualTo(room.getName()); assertThat(tracks).hasSize(1); assertThat(firstTrack.getTrackId()).isEqualTo(track.getTrackId()); } @Test public void shouldPlayTrack() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Room roomNotPlaying = Disco.getRoom(room.getName()); Disco.startPlay(track.getTrackId(), 0); Room roomPlaying = Disco.getRoom(room.getName()); Position positionInitial = roomNotPlaying.getPosition(); Position positionPlaying = roomPlaying.getPosition(); // then assertThat(positionInitial).isNull(); assertThat(positionPlaying).isNotNull(); assertThat(positionPlaying.getTrackId()).isEqualTo(track.getTrackId()); assertThat(positionPlaying.getStatus()).isEqualTo(Status.PLAYING); } @Test public void shouldPlayTrackAtPosition() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Disco.startPlay(track.getTrackId(), 2000); Room roomPlaying = Disco.getRoom(room.getName()); Position positionPlaying = roomPlaying.getPosition(); // then assertThat(positionPlaying.getPosition()).isEqualTo(2000); } @Test public void shouldStopTrack() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Disco.startPlay(track.getTrackId(), 0); Disco.stopPlay(track.getTrackId()); Room roomAfterStop = Disco.getRoom(room.getName()); Position positionAfterStop = roomAfterStop.getPosition(); // then assertThat(positionAfterStop).isNotNull(); assertThat(positionAfterStop.getTrackId()).isEqualTo(track.getTrackId()); assertThat(positionAfterStop.getStatus()).isEqualTo(Status.STOPPED); } @Test public void shouldIncrementPositionOnAdd() { // given Room room = Disco.getRoom("foobar"); // when Track track0 = Disco.addTrack(new Track(), room.getName(), null); Track track1 = Disco.addTrack(new Track(), room.getName(), null); Track track2 = Disco.addTrack(new Track(), room.getName(), null); // then assertThat(track0.getPosition()).isLessThan(track1.getPosition()); assertThat(track1.getPosition()).isLessThan(track2.getPosition()); } @Test public void shouldMoveTrack() { // given Room room = Disco.getRoom("foobar"); Track track0 = Disco.addTrack(new Track(), room.getName(), null); Track track1 = Disco.addTrack(new Track(), room.getName(), null); Track track2 = Disco.addTrack(new Track(), room.getName(), null); // when // move track0 behind track1
Disco.moveTrack(track0.getTrackId(), new TrackPosition(1));
5
melloc/roguelike
engine/src/main/java/edu/brown/cs/roguelike/engine/level/Tile.java
[ "public final class Vec2i implements Serializable {\r\n\tprivate static final long serialVersionUID = 5659632794862666943L;\r\n\t\r\n\t/**\r\n\t * Since {@link Vec2i} instances are immutable, their x and y fields may be accessed without getters.\r\n\t */\r\n\tpublic final int x, y;\r\n\t\r\n\t/**\r\n\t * Creates a new vector from an x and y component.\r\n\t * @param x the x-component of the vector\r\n\t * @param y the y-component of the vector\r\n\t */\r\n\tpublic Vec2i(int x, int y) {\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by {@linkplain Math#round(float) rounding} the components of a {@link Vec2f} to the nearest integer.\r\n\t * @param v the Vec2f to round\r\n\t * @return a Vec2i created by rounding the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromRounded(Vec2f v) {\r\n\t\treturn new Vec2i(round(v.x), round(v.y));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#floor(double) floor} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to floor\r\n\t * @return a {@code Vec2i} created by taking the floor of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromFloored(Vec2f v) {\r\n\t\treturn new Vec2i((int)floor(v.x), (int)floor(v.y));\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#ceil(double) ceiling} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to ceil\r\n\t * @return a {@code Vec2i} created by taking the ceiling of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromCeiled(Vec2f v) {\r\n\t\treturn new Vec2i((int)ceil(v.x), (int)ceil(v.y));\r\n\t}\r\n\t\r\n\t/*\r\n\t * Vector ops\r\n\t */\r\n\t\r\n\t/**\r\n\t * Multiplies the vector by a scalar.\r\n\t * @param s the scalar by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by {@code s}\r\n\t */\r\n\tpublic final Vec2i smult(int s) {\r\n\t\treturn new Vec2i(x*s, y*s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector by a scalar. Note that this is integer division.\r\n\t * @param s\t\tthe scalar by which to divide this vector\r\n\t * @return\t\ta new {@link Vec2i} instance where each component has been divided by\r\n\t * \t\t\t\t{@code s}\r\n\t */\r\n\tpublic final Vec2i sdiv(int s) {\r\n\t\treturn new Vec2i(x/s, y/s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Multiplies the vector piecewise by another vector. NOT A DOT PRODUCT.\r\n\t * @param v the vector by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pmult(Vec2i v) {\r\n\t\treturn new Vec2i(x*v.x, y*v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pmult(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pmult(int x, int y) {\r\n\t\treturn new Vec2i(this.x * x, this.y * y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector piecewise by another vector.\r\n\t * @param v the vector by which to divide this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been divided by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pdiv(Vec2i v) {\r\n\t\treturn new Vec2i(x/v.x, y/v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pdiv(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pdiv(int x, int y) {\r\n\t\treturn new Vec2i(this.x/x, this.y/y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Adds another vector to this vector.\r\n\t * @param v the vector to add to this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i plus(Vec2i v) {\r\n\t\treturn new Vec2i(x + v.x, y + v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #plus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i plus(int x, int y) {\r\n\t\treturn new Vec2i(this.x + x, this.y + y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Subtracts another vector from this vector.\r\n\t * @param v the vector to subtract from this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i minus(Vec2i v) {\r\n\t\treturn new Vec2i(x - v.x, y - v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #minus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i minus(int x, int y) {\r\n\t\treturn new Vec2i(this.x - x, this.y - y);\r\n\t}\r\n\t\r\n\tpublic Dimension toDimension() {\r\n\t\treturn new Dimension(this.x, this.y);\r\n\t}\r\n\t\r\n\t/*\r\n\t * Object overrides\r\n\t */\r\n\r\n\t@Override\r\n\tpublic final int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + x;\r\n\t\tresult = prime * result + y;\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final boolean equals(Object obj) {\r\n\t\tif (obj == null || obj.getClass() != Vec2i.class)\r\n\t\t\treturn false;\r\n\t\tVec2i other = (Vec2i) obj;\r\n\t\treturn x == other.x && y == other.y;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final String toString() {\r\n\t\treturn new StringBuilder(\"(\").append(x).append(\", \").append(y).append(\")\").toString();\r\n\t}\r\n\r\n\tpublic static Vec2i fromPoint(Point pt) {\r\n\t\treturn new Vec2i(pt.x, pt.y);\r\n\t}\r\n\r\n\tpublic Point toPoint() {\r\n\t\treturn new Point(this.x, this.y);\r\n\t}\r\n}\r", "public abstract class Entity implements Drawable, Mappable, Saveable {\n\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 7459179832955737667L;\n\t\n\tprotected char character;\n\tprotected Color color;\n\tprotected Set<Stackable> inventory = new HashSet<Stackable>();\n\t\n\tprotected String name = \"No Name\";\n\t\t\n\t@Override\n\tpublic char getCharacter() {\n\t\treturn character;\n\t}\n\n\t@Override\n\tpublic Color getColor() {\t\n\t\treturn color;\n\t}\n\t\n\tprotected abstract Action generateNextAction();\n\t\n\tpublic abstract String getDescription();\n\tpublic String getName() { return this.name; }\n\t\n\tpublic Set<Stackable> getInventory() {return inventory;}\n\tpublic void addToInventory(Stackable item) {inventory.add(item);}\n\tpublic void removeFromInventory(Stackable item) {inventory.remove(item);}\n\n\tpublic abstract List<String> getCategories();\n\t\n\t/*** BEGIN Saveable ***/\n\n\tprivate UUID id;\n\t\n\t/** initialize id **/\n\t{\n\t\tthis.id = UUID.randomUUID();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tEntity other = (Entity) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (id.equals(other.id))\n\t\t\t// return true if ids are the same\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic UUID getId() {\n\t\treturn this.id;\n\t}\n\n\t/*** END Saveable ***/\n\t\n\t\n\n}", "public class MainCharacter extends Combatable {\n\n\t/**\n\t * Generated \n\t */\n\tprivate static final long serialVersionUID = -4240615722468534343L;\n\tprivate static final int MAX_INVENTORY_SIZE = 26;\n\tprivate static final float EXP_CURVE = 2.2f;\n\t\n\tList<String> categories = null;\n\tprivate int XP;\n\tprivate int nextLevelXP;\n\tprivate int playerLevel;\n\t\n\t{\n\t\tcategories = new ArrayList<String>();\n\t\tcategories.add(\"keyboard\");\n\t\tcategories.add(\"main\");\n\t}\n\n\tpublic int getXP() {\n\t\treturn XP;\n\t} \n\t\n\tpublic int getNextLevelXP() {\n\t\treturn nextLevelXP;\n\t}\n\n\tpublic int getPlayerLevel() {\n\t\treturn playerLevel;\n\t}\n\n\t\n\tpublic MainCharacter(String name) {\n\t\tthis.name = name;\n\t\tthis.color = Color.DEFAULT;\n\t\tthis.character = '@';\n\t\tthis.HP = 100;\n\t\tthis.startHP = this.HP;\n\t\tthis.stats = new Stats(10,4);\n\t\tbaseStats = stats;\n\t\tthis.team = 1;\n\t\tthis.XP = 0;\n\t\tnextLevelXP = 6;\n\t\tplayerLevel = 1;\n\t}\n\n\t@Override\n\tprotected void die() {\n\t\tthis.location.setEntity(null);\n\t\tthis.manager.call(Event.DEATH);\n\t}\n\n\t@Override\n\tprotected void onKillEntity(Combatable combatable) {\n\t\tAnnouncer.announce(\"You defeated the \" + combatable.getDescription());\n\t\tMonster m = (Monster) combatable;\n\t\tthis.XP += m.tier;\n\t\tif(XP >= nextLevelXP) {\n\t\t\tXP -=nextLevelXP;\n\t\t\tlevelUp();\n\t\t\tAnnouncer.announce(\"Welcome to level \" + playerLevel);\n\t\t}\n\t}\n\n\t\n\tprivate final int HP_GROWTH = 10;\n\tprivate final int ATTACK_GROWTH = 3;\n\tprivate final int DEFENSE_GROWTH = 1;\n\n\tprivate void levelUp() {\n\t\tplayerLevel++;\n\t\tthis.startHP += HP_GROWTH;\n\t\tthis.HP = startHP;\n\t\tthis.baseStats = new Stats(baseStats.attack+ATTACK_GROWTH, baseStats.defense+DEFENSE_GROWTH);\n\t\tthis.stats = new Stats(stats.attack+ATTACK_GROWTH, stats.defense+DEFENSE_GROWTH);\n\t\tnextLevelXP = (int) Math.ceil(nextLevelXP*EXP_CURVE);\n\t}\n\n\tpublic List<String> getCategories() {\n\t\treturn categories;\n\t}\n\t\n\t@Override \n\tpublic void move(Direction dir) {\n\t\tsuper.move(dir);\n\t\t\n\t\twhile(inventory.size() < MAX_INVENTORY_SIZE && this.location.getStackables().size()>0) {\n\t\t\tStackable s = this.location.getStackables().remove();\n\t\t\tthis.inventory.add(s);\n\t\t\tAnnouncer.announce(s.getDescription());\n\t\t}\n\t\tif(this.getLocation().getStackables().size() > 0) {\n\t\t\tAnnouncer.announce(\"Not enough room in inventory.\");\n\t\t}\n\t\t\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"You\";\n\t}\n\t\n\t/**\n\t * Main Character's next action is dependent on user input, and thus cannot\n\t * generate a next action\n\t */\n\t@Override\n\tprotected Action generateNextAction() { return null; }\n\n\n\t\n}", "public abstract class Stackable implements Drawable, Saveable {\r\n\t\r\n\t/**\r\n\t * Generated \r\n\t */\r\n\tprivate static final long serialVersionUID = -4791198502696211551L;\r\n\t\r\n\tprotected char character;\r\n\tprotected Color color;\r\n\t\r\n\tpublic char getCharacter() {return character;}\r\n\tpublic Color getColor() {return color;}\r\n\t\r\n\tpublic abstract String getDescription();\r\n\t\r\n\t\r\n\t/*** BEGIN Saveable ***/\r\n\r\n\tprivate UUID id;\r\n\r\n\tprotected ItemType type;\r\n\tprotected Action action;\r\n\t\r\n\t/** initialize id **/\r\n\t{\r\n\t\tthis.id = UUID.randomUUID();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tStackable other = (Stackable) obj;\r\n\t\tif (id == null) {\r\n\t\t\tif (other.id != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (id.equals(other.id))\r\n\t\t\t// return true if ids are the same\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic UUID getId() {\r\n\t\treturn this.id;\r\n\t}\r\n\tpublic ItemType getType() {\r\n\t\treturn type;\r\n\t}\r\n\t\r\n\r\n\t/*** END Saveable ***/\r\n}\r", "public interface Drawable {\n\n public char getCharacter();\n public Color getColor();\n\n}", "public abstract class AStarNode<N extends AStarNode<N>> \n extends GraphNode<N> implements Comparable<N> {\n \n private int fScore;\n private int gScore;\n \n public AStarNode() {\n }\n \n /**\n * Calculates an admissible heuristic estimate of getting\n * from this node to the goal node\n * @param goal\n * @return\n */\n protected abstract int getHScore(N goal);\n \n public void update(int gScore, N goal) {\n this.fScore = gScore + getHScore(goal);\n this.gScore = gScore;\n }\n \n public int getGScore() {\n return this.gScore;\n }\n\n public int getFScore() {\n return this.fScore;\n }\n \n /**\n * Calculate the distance between this node and a neighbor\n */\n public abstract int distance(N neighbor);\n\n public int compareTo(N node1) {\n return this.fScore - node1.getFScore();\n }\n \n}", "public interface Saveable extends Serializable {\n\t\n\t/**\n\t * @return globally unique UUID\n\t */\n\tpublic UUID getId();\n\n\t/**\n\t * Hash based on this classes id\n\t * \n\t * @return int hash code\n\t */\n\tpublic abstract int hashCode();\n\t\n\t/**\n\t * Overriding equals should use id to determine\n\t * equality\n\t * \n\t * @param o\n\t * @return boolean indicating object equality\n\t */\n\tpublic abstract boolean equals(Object o);\n}" ]
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.UUID; import com.googlecode.lanterna.terminal.Terminal.Color; import cs195n.Vec2i; import edu.brown.cs.roguelike.engine.entities.Entity; import edu.brown.cs.roguelike.engine.entities.MainCharacter; import edu.brown.cs.roguelike.engine.entities.Stackable; import edu.brown.cs.roguelike.engine.graphics.Drawable; import edu.brown.cs.roguelike.engine.pathfinding.AStarNode; import edu.brown.cs.roguelike.engine.save.Saveable;
package edu.brown.cs.roguelike.engine.level; /** * A tile object to make up each physical level * * @author jte * */ public class Tile extends AStarNode<Tile> implements Saveable, Drawable { // The Space I belong to protected Space space;
protected Vec2i location = null;
0
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/MongoDbSinkTask.java
[ "public abstract class CdcHandler {\n\n private final MongoDbSinkConnectorConfig config;\n\n public CdcHandler(MongoDbSinkConnectorConfig config) {\n this.config = config;\n }\n\n public MongoDbSinkConnectorConfig getConfig() {\n return this.config;\n }\n\n public abstract Optional<WriteModel<BsonDocument>> handle(SinkDocument doc);\n\n}", "public class SinkConverter {\n\n private static Logger logger = LoggerFactory.getLogger(SinkConverter.class);\n\n private RecordConverter schemafulConverter = new AvroJsonSchemafulRecordConverter();\n private RecordConverter schemalessConverter = new JsonSchemalessRecordConverter();\n private RecordConverter rawConverter = new JsonRawStringRecordConverter();\n\n public SinkDocument convert(SinkRecord record) {\n\n logger.debug(record.toString());\n\n BsonDocument keyDoc = null;\n if(record.key() != null) {\n keyDoc = getRecordConverter(record.key(),record.keySchema())\n .convert(record.keySchema(), record.key());\n }\n\n BsonDocument valueDoc = null;\n if(record.value() != null) {\n valueDoc = getRecordConverter(record.value(),record.valueSchema())\n .convert(record.valueSchema(), record.value());\n }\n\n return new SinkDocument(keyDoc, valueDoc);\n\n }\n\n private RecordConverter getRecordConverter(Object data, Schema schema) {\n\n //AVRO or JSON with schema\n if(schema != null && data instanceof Struct) {\n logger.debug(\"using schemaful converter\");\n return schemafulConverter;\n }\n\n //structured JSON without schema\n if(data instanceof Map) {\n logger.debug(\"using schemaless converter\");\n return schemalessConverter;\n }\n\n //raw JSON string\n if(data instanceof String) {\n logger.debug(\"using raw converter\");\n return rawConverter;\n }\n\n throw new DataException(\"error: no converter present due to unexpected object type \"\n + data.getClass().getName());\n }\n\n}", "public class SinkDocument {\n\n private final Optional<BsonDocument> keyDoc;\n private final Optional<BsonDocument> valueDoc;\n\n public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) {\n this.keyDoc = Optional.ofNullable(keyDoc);\n this.valueDoc = Optional.ofNullable(valueDoc);\n }\n\n public Optional<BsonDocument> getKeyDoc() {\n return keyDoc;\n }\n\n public Optional<BsonDocument> getValueDoc() {\n return valueDoc;\n }\n\n public SinkDocument clone() {\n BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null;\n BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null;\n return new SinkDocument(kd,vd);\n }\n\n}", "public abstract class PostProcessor {\n\n private final MongoDbSinkConnectorConfig config;\n private Optional<PostProcessor> next = Optional.empty();\n private final String collection;\n\n public PostProcessor(MongoDbSinkConnectorConfig config, String collection) {\n this.config = config;\n this.collection = collection;\n }\n\n public PostProcessor chain(PostProcessor next) {\n // intentionally throws NPE here if someone\n // tries to be 'smart' by chaining with null\n this.next = Optional.of(next);\n return this.next.get();\n }\n\n public abstract void process(SinkDocument doc, SinkRecord orig);\n\n public MongoDbSinkConnectorConfig getConfig() {\n return this.config;\n }\n\n public Optional<PostProcessor> getNext() {\n return this.next;\n }\n\n public String getCollection() {\n return this.collection;\n }\n\n}", "public interface WriteModelStrategy {\n\n WriteModel<BsonDocument> createWriteModel(SinkDocument document);\n\n default WriteModel<BsonDocument> createWriteModel(SinkDocument document, SinkRecord record) {\n return createWriteModel(document);\n }\n\n}" ]
import at.grahsl.kafka.connect.mongodb.cdc.CdcHandler; import at.grahsl.kafka.connect.mongodb.converter.SinkConverter; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.PostProcessor; import at.grahsl.kafka.connect.mongodb.writemodel.strategy.WriteModelStrategy; import com.mongodb.BulkWriteException; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoException; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.BulkWriteOptions; import com.mongodb.client.model.WriteModel; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.RetriableException; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.bson.BsonDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
/* * Copyright (c) 2017. Hans-Peter Grahsl ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.grahsl.kafka.connect.mongodb; public class MongoDbSinkTask extends SinkTask { private static Logger LOGGER = LoggerFactory.getLogger(MongoDbSinkTask.class); private static final BulkWriteOptions BULK_WRITE_OPTIONS = new BulkWriteOptions().ordered(true); private MongoDbSinkConnectorConfig sinkConfig; private MongoClient mongoClient; private MongoDatabase database; private int remainingRetries; private int deferRetryMs;
private Map<String, PostProcessor> processorChains;
3
littlezhou/SSM-1
smart-engine/src/main/java/org/smartdata/server/engine/RuleManager.java
[ "public class SmartConfKeys {\n public static final String SMART_DFS_ENABLED = \"smart.dfs.enabled\";\n public static final boolean SMART_DFS_ENABLED_DEFAULT = true;\n\n public static final String SMART_CONF_DIR_KEY = \"smart.conf.dir\";\n public static final String SMART_HADOOP_CONF_DIR_KEY = \"smart.hadoop.conf.path\";\n public static final String SMART_CONF_DIR_DEFAULT = \"conf\";\n public static final String SMART_LOG_DIR_KEY = \"smart.log.dir\";\n public static final String SMART_LOG_DIR_DEFAULT = \"logs\";\n\n public static final String SMART_SERVICE_MODE_KEY = \"smart.service.mode\";\n public static final String SMART_SERVICE_MODE_DEFAULT = \"HDFS\";\n public static final String SMART_NAMESPACE_FETCHER_BATCH_KEY = \"smart.namespace.fetcher.batch\";\n public static final int SMART_NAMESPACE_FETCHER_BATCH_DEFAULT = 500;\n\n public static final String SMART_DFS_NAMENODE_RPCSERVER_KEY = \"smart.dfs.namenode.rpcserver\";\n\n // Configure keys for HDFS\n public static final String SMART_NAMESPACE_FETCHER_IGNORE_UNSUCCESSIVE_INOTIFY_EVENT_KEY =\n \"smart.namespace.fetcher.ignore.unsuccessive.inotify.event\";\n public static final boolean SMART_NAMESPACE_FETCHER_IGNORE_UNSUCCESSIVE_INOTIFY_EVENT_DEFAULT =\n false;\n public static final String SMART_NAMESPACE_FETCHER_PRODUCERS_NUM_KEY =\n \"smart.namespace.fetcher.producers.num\";\n public static final int SMART_NAMESPACE_FETCHER_PRODUCERS_NUM_DEFAULT = 3;\n public static final String SMART_NAMESPACE_FETCHER_CONSUMERS_NUM_KEY =\n \"smart.namespace.fetcher.consumers.num\";\n public static final int SMART_NAMESPACE_FETCHER_CONSUMERS_NUM_DEFAULT = 3;\n\n // Configure keys for Alluxio\n public static final String SMART_ALLUXIO_MASTER_HOSTNAME_KEY = \"smart.alluxio.master.hostname\";\n public static final String SMART_ALLUXIO_CONF_DIR_KEY = \"smart.alluxio.conf.dir\";\n public static final String SMART_ALLUXIO_MASTER_JOURNAL_DIR_KEY =\n \"smart.alluxio.master.journal.dir\";\n\n // SSM\n public static final String SMART_SERVER_RPC_ADDRESS_KEY = \"smart.server.rpc.address\";\n public static final String SMART_SERVER_RPC_ADDRESS_DEFAULT = \"0.0.0.0:7042\";\n public static final String SMART_SERVER_RPC_HANDLER_COUNT_KEY = \"smart.server.rpc.handler.count\";\n public static final int SMART_SERVER_RPC_HANDLER_COUNT_DEFAULT = 80;\n public static final String SMART_SERVER_HTTP_ADDRESS_KEY = \"smart.server.http.address\";\n public static final String SMART_SERVER_HTTP_ADDRESS_DEFAULT = \"0.0.0.0:7045\";\n public static final String SMART_SERVER_HTTPS_ADDRESS_KEY = \"smart.server.https.address\";\n public static final String SMART_SECURITY_ENABLE = \"smart.security.enable\";\n public static final String SMART_SERVER_KEYTAB_FILE_KEY = \"smart.server.keytab.file\";\n public static final String SMART_SERVER_KERBEROS_PRINCIPAL_KEY =\n \"smart.server.kerberos.principal\";\n public static final String SMART_AGENT_KEYTAB_FILE_KEY = \"smart.server.keytab.file\";\n public static final String SMART_AGENT_KERBEROS_PRINCIPAL_KEY =\n \"smart.agent.kerberos.principal\";\n public static final String SMART_SECURITY_CLIENT_PROTOCOL_ACL =\n \"smart.security.client.protocol.acl\";\n public static final String SMART_SECURITY_ADMIN_PROTOCOL_ACL =\n \"smart.security.admin.protocol.acl\";\n public static final String SMART_METASTORE_DB_URL_KEY = \"smart.metastore.db.url\";\n\n // StatesManager\n\n // RuleManager\n public static final String SMART_RULE_EXECUTORS_KEY = \"smart.rule.executors\";\n public static final int SMART_RULE_EXECUTORS_DEFAULT = 5;\n\n public static final String SMART_CMDLET_EXECUTORS_KEY = \"smart.cmdlet.executors\";\n public static final int SMART_CMDLET_EXECUTORS_DEFAULT = 10;\n public static final String SMART_DISPATCH_CMDLETS_EXTRA_NUM_KEY =\n \"smart.dispatch.cmdlets.extra.num\";\n public static final int SMART_DISPATCH_CMDLETS_EXTRA_NUM_DEFAULT = 10;\n\n // Keep it only for test\n public static final String SMART_ENABLE_ZEPPELIN_WEB = \"smart.zeppelin.web.enable\";\n public static final boolean SMART_ENABLE_ZEPPELIN_WEB_DEFAULT = true;\n\n // Cmdlets\n public static final String SMART_CMDLET_MAX_NUM_PENDING_KEY =\n \"smart.cmdlet.max.num.pending\";\n public static final int SMART_CMDLET_MAX_NUM_PENDING_DEFAULT = 20000;\n public static final String SMART_CMDLET_HIST_MAX_NUM_RECORDS_KEY =\n \"smart.cmdlet.hist.max.num.records\";\n public static final int SMART_CMDLET_HIST_MAX_NUM_RECORDS_DEFAULT =\n 100000;\n public static final String SMART_CMDLET_HIST_MAX_RECORD_LIFETIME_KEY =\n \"smart.cmdlet.hist.max.record.lifetime\";\n public static final String SMART_CMDLET_HIST_MAX_RECORD_LIFETIME_DEFAULT =\n \"30day\";\n public static final String SMART_CMDLET_CACHE_BATCH =\n \"smart.cmdlet.cache.batch\";\n public static final int SMART_CMDLET_CACHE_BATCH_DEFAULT =\n 600;\n public static final String SMART_CMDLET_MOVER_MAX_CONCURRENT_BLOCKS_PER_SRV_INST_KEY =\n \"smart.cmdlet.mover.max.concurrent.blocks.per.srv.inst\";\n public static final int SMART_CMDLET_MOVER_MAX_CONCURRENT_BLOCKS_PER_SRV_INST_DEFAULT = 0;\n\n // Schedulers\n public static final String SMART_COPY_SCHEDULER_BASE_SYNC_BATCH =\n \"smart.copy.scheduler.base.sync.batch\";\n public static final int SMART_COPY_SCHEDULER_BASE_SYNC_BATCH_DEFAULT =\n 500;\n public static final String SMART_COPY_SCHEDULER_CHECK_INTERVAL =\n \"smart.copy.scheduler.check.interval\";\n public static final int SMART_COPY_SCHEDULER_CHECK_INTERVAL_DEFAULT =\n 500;\n public static final String SMART_FILE_DIFF_MAX_NUM_RECORDS_KEY =\n \"smart.file.diff.max.num.records\";\n public static final int SMART_FILE_DIFF_MAX_NUM_RECORDS_DEFAULT =\n 10000;\n\n // Dispatcher\n public static final String SMART_CMDLET_DISPATCHER_LOG_DISP_RESULT_KEY =\n \"smart.cmdlet.dispatcher.log.disp.result\";\n public static final boolean SMART_CMDLET_DISPATCHER_LOG_DISP_RESULT_DEFAULT = true;\n public static final String SMART_CMDLET_DISPATCHERS_KEY = \"smart.cmdlet.dispatchers\";\n public static final int SMART_CMDLET_DISPATCHERS_DEFAULT = 3;\n\n // Action\n public static final String SMART_ACTION_MOVE_THROTTLE_MB_KEY = \"smart.action.move.throttle.mb\";\n public static final long SMART_ACTION_MOVE_THROTTLE_MB_DEFAULT = 0L; // 0 means unlimited\n public static final String SMART_ACTION_COPY_THROTTLE_MB_KEY = \"smart.action.copy.throttle.mb\";\n public static final long SMART_ACTION_COPY_THROTTLE_MB_DEFAULT = 0L; // 0 means unlimited\n public static final String SMART_ACTION_LOCAL_EXECUTION_DISABLED_KEY =\n \"smart.action.local.execution.disabled\";\n public static final boolean SMART_ACTION_LOCAL_EXECUTION_DISABLED_DEFAULT = false;\n\n // SmartAgent\n public static final String SMART_AGENT_MASTER_PORT_KEY = \"smart.agent.master.port\";\n public static final int SMART_AGENT_MASTER_PORT_DEFAULT = 7051;\n public static final String SMART_AGENT_PORT_KEY = \"smart.agent.port\";\n public static final int SMART_AGENT_PORT_DEFAULT = 7048;\n\n /** Do NOT configure the following two options manually. They are set by the boot scripts. **/\n public static final String SMART_AGENT_MASTER_ADDRESS_KEY = \"smart.agent.master.address\";\n public static final String SMART_AGENT_ADDRESS_KEY = \"smart.agent.address\";\n\n // Small File Compact\n public static final String SMART_COMPACT_BATCH_SIZE_KEY =\n \"smart.compact.batch.size\";\n public static final int SMART_COMPACT_BATCH_SIZE_DEFAULT =\n 200;\n public static final String SMART_COMPACT_CONTAINER_FILE_THRESHOLD_MB_KEY =\n \"smart.compact.container.file.threshold.mb\";\n public static final long SMART_COMPACT_CONTAINER_FILE_THRESHOLD_MB_DEFAULT =\n 1024;\n\n // SmartClient\n\n // Common\n /**\n * Namespace, access info and other info related to files under these dirs will be ignored.\n * Clients will not report access event of these files to SSM.\n * Directories are separated with ','.\n */\n public static final String SMART_IGNORE_DIRS_KEY = \"smart.ignore.dirs\";\n\n // Target cluster\n public static final String SMART_STORAGE_INFO_UPDATE_INTERVAL_KEY =\n \"smart.storage.info.update.interval\";\n public static final int SMART_STORAGE_INFO_UPDATE_INTERVAL_DEFAULT = 60;\n public static final String SMART_STORAGE_INFO_SAMPLING_INTERVALS_KEY =\n \"smart.storage.info.sampling.intervals\";\n public static final String SMART_STORAGE_INFO_SAMPLING_INTERVALS_DEFAULT =\n \"60s,60;1hour,60;1day\";\n public static final String SMART_TOP_HOT_FILES_NUM_KEY = \"smart.top.hot.files.num\";\n public static final int SMART_TOP_HOT_FILES_NUM_DEFAULT = 200;\n\n //Status report\n public static final String SMART_STATUS_REPORT_PERIOD_KEY = \"smart.status.report.period\";\n public static final int SMART_STATUS_REPORT_PERIOD_DEFAULT = 10;\n public static final String SMART_STATUS_REPORT_PERIOD_MULTIPLIER_KEY =\n \"smart.status.report.period.multiplier\";\n public static final int SMART_STATUS_REPORT_PERIOD_MULTIPLIER_DEFAULT = 50;\n public static final String SMART_STATUS_REPORT_RATIO_KEY = \"smart.status.report.ratio\";\n public static final double SMART_STATUS_REPORT_RATIO_DEFAULT = 0.2;\n\n //Tidb\n public static final String SMART_TIDB_ENABLED = \"smart.tidb.enable\";\n public static final boolean SMART_TIDB_ENABLED_DEFAULT = false;\n\n public static final String PD_CLIENT_PORT_KEY = \"pd.client.port\";\n public static final String PD_CLIENT_PORT_DEFAULT = \"7060\";\n public static final String PD_PEER_PORT_KEY = \"pd.peer.port\";\n public static final String PD_PEER_PORT_DEFAULT = \"7061\";\n public static final String TIKV_SERVICE_PORT_KEY = \"tikv.service.port\";\n public static final String TIKV_SERVICE_PORT_DEFAULT = \"20160\";\n public static final String TIDB_SERVICE_PORT_KEY = \"tidb.service.port\";\n public static final String TIDB_SERVICE_PORT_KEY_DEFAULT = \"7070\";\n}", "public class MetaStore implements CopyMetaService, CmdletMetaService, BackupMetaService {\n static final Logger LOG = LoggerFactory.getLogger(MetaStore.class);\n\n private DBPool pool = null;\n private DBType dbType;\n\n private Map<Integer, String> mapStoragePolicyIdName = null;\n private Map<String, Integer> mapStoragePolicyNameId = null;\n private Map<String, StorageCapacity> mapStorageCapacity = null;\n private Set<String> setBackSrc = null;\n private RuleDao ruleDao;\n private CmdletDao cmdletDao;\n private ActionDao actionDao;\n private FileInfoDao fileInfoDao;\n private CacheFileDao cacheFileDao;\n private StorageDao storageDao;\n private StorageHistoryDao storageHistoryDao;\n private XattrDao xattrDao;\n private FileDiffDao fileDiffDao;\n private AccessCountDao accessCountDao;\n private MetaStoreHelper metaStoreHelper;\n private ClusterConfigDao clusterConfigDao;\n private GlobalConfigDao globalConfigDao;\n private DataNodeInfoDao dataNodeInfoDao;\n private DataNodeStorageInfoDao dataNodeStorageInfoDao;\n private BackUpInfoDao backUpInfoDao;\n private ClusterInfoDao clusterInfoDao;\n private SystemInfoDao systemInfoDao;\n private FileStateDao fileStateDao;\n private GeneralDao generalDao;\n private SmallFileDao smallFileDao;\n\n public MetaStore(DBPool pool) throws MetaStoreException {\n this.pool = pool;\n initDbInfo();\n ruleDao = new RuleDao(pool.getDataSource());\n cmdletDao = new CmdletDao(pool.getDataSource());\n actionDao = new ActionDao(pool.getDataSource());\n fileInfoDao = new FileInfoDao(pool.getDataSource());\n xattrDao = new XattrDao(pool.getDataSource());\n cacheFileDao = new CacheFileDao(pool.getDataSource());\n storageDao = new StorageDao(pool.getDataSource());\n storageHistoryDao = new StorageHistoryDao(pool.getDataSource());\n accessCountDao = new AccessCountDao(pool.getDataSource());\n fileDiffDao = new FileDiffDao(pool.getDataSource());\n metaStoreHelper = new MetaStoreHelper(pool.getDataSource());\n clusterConfigDao = new ClusterConfigDao(pool.getDataSource());\n globalConfigDao = new GlobalConfigDao(pool.getDataSource());\n dataNodeInfoDao = new DataNodeInfoDao(pool.getDataSource());\n dataNodeStorageInfoDao = new DataNodeStorageInfoDao(pool.getDataSource());\n backUpInfoDao = new BackUpInfoDao(pool.getDataSource());\n clusterInfoDao = new ClusterInfoDao(pool.getDataSource());\n systemInfoDao = new SystemInfoDao(pool.getDataSource());\n fileStateDao = new FileStateDao(pool.getDataSource());\n generalDao = new GeneralDao(pool.getDataSource());\n smallFileDao = new SmallFileDao(pool.getDataSource());\n }\n\n private void initDbInfo() throws MetaStoreException {\n Connection conn = null;\n try {\n try {\n conn = getConnection();\n String driver = conn.getMetaData().getDriverName();\n driver = driver.toLowerCase();\n if (driver.contains(\"sqlite\")) {\n dbType = DBType.SQLITE;\n } else if (driver.contains(\"mysql\")) {\n dbType = DBType.MYSQL;\n } else {\n throw new MetaStoreException(\"Unknown database: \" + driver);\n }\n } finally {\n if (conn != null) {\n closeConnection(conn);\n }\n }\n } catch (SQLException e) {\n throw new MetaStoreException(e);\n }\n }\n\n public Connection getConnection() throws MetaStoreException {\n if (pool != null) {\n try {\n return pool.getConnection();\n } catch (SQLException e) {\n throw new MetaStoreException(e);\n }\n }\n return null;\n }\n\n private void closeConnection(Connection conn) throws MetaStoreException {\n if (pool != null) {\n try {\n pool.closeConnection(conn);\n } catch (SQLException e) {\n throw new MetaStoreException(e);\n }\n }\n }\n\n public DBType getDbType() {\n return dbType;\n }\n\n public Long queryForLong(String sql) throws MetaStoreException {\n try {\n return generalDao.queryForLong(sql);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n /**\n * Store a single file info into database.\n *\n * @param file\n */\n public void insertFile(FileInfo file)\n throws MetaStoreException {\n updateCache();\n fileInfoDao.insert(file);\n }\n\n\n /**\n * Store files info into database.\n *\n * @param files\n */\n public void insertFiles(FileInfo[] files)\n throws MetaStoreException {\n updateCache();\n fileInfoDao.insert(files);\n }\n\n public int updateFileStoragePolicy(String path, String policyName)\n throws MetaStoreException {\n if (mapStoragePolicyIdName == null) {\n updateCache();\n }\n if (!mapStoragePolicyNameId.containsKey(policyName)) {\n throw new MetaStoreException(\"Unknown storage policy name '\"\n + policyName + \"'\");\n }\n try {\n return storageDao.updateFileStoragePolicy(path, mapStoragePolicyNameId.get(policyName));\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public FileInfo getFile(long fid) throws MetaStoreException {\n updateCache();\n try {\n return fileInfoDao.getById(fid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public FileInfo getFile(String path) throws MetaStoreException {\n updateCache();\n try {\n return fileInfoDao.getByPath(path);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileInfo> getFile() throws MetaStoreException {\n updateCache();\n try {\n return fileInfoDao.getAll();\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileInfo> getFilesByPrefix(String path) throws MetaStoreException {\n updateCache();\n try {\n return fileInfoDao.getFilesByPrefix(path);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileInfo> getFilesByPrefixInOrder(String path) throws MetaStoreException {\n updateCache();\n try {\n return fileInfoDao.getFilesByPrefixInOrder(path);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileInfo> getFilesByPaths(Collection<String> paths)\n throws MetaStoreException {\n try {\n return fileInfoDao.getFilesByPaths(paths);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public Map<String, Long> getFileIDs(Collection<String> paths)\n throws MetaStoreException {\n try {\n return fileInfoDao.getPathFids(paths);\n } catch (EmptyResultDataAccessException e) {\n return new HashMap<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public Map<Long, String> getFilePaths(Collection<Long> ids)\n throws MetaStoreException {\n try {\n return fileInfoDao.getFidPaths(ids);\n } catch (EmptyResultDataAccessException e) {\n return new HashMap<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileAccessInfo> getHotFiles(\n List<AccessCountTable> tables,\n int topNum) throws MetaStoreException {\n Iterator<AccessCountTable> tableIterator = tables.iterator();\n if (tableIterator.hasNext()) {\n try {\n Map<Long, Integer> accessCounts =\n accessCountDao.getHotFiles(tables, topNum);\n if (accessCounts.size() == 0) {\n return new ArrayList<>();\n }\n Map<Long, String> idToPath = getFilePaths(accessCounts.keySet());\n List<FileAccessInfo> result = new ArrayList<>();\n for (Map.Entry<Long, Integer> entry : accessCounts.entrySet()) {\n Long fid = entry.getKey();\n if (idToPath.containsKey(fid) && entry.getValue() > 0) {\n result.add(\n new FileAccessInfo(fid, idToPath.get(fid), entry.getValue()));\n }\n }\n return result;\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n } finally {\n for (AccessCountTable accessCountTable : tables) {\n if (accessCountTable.isEphemeral()) {\n this.dropTable(accessCountTable.getTableName());\n }\n }\n }\n } else {\n return new ArrayList<>();\n }\n }\n\n public void deleteAllFileInfo() throws MetaStoreException {\n try {\n fileInfoDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteFileByPath(String path) throws MetaStoreException {\n try {\n fileInfoDao.deleteByPath(path);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<AccessCountTable> getAllSortedTables() throws MetaStoreException {\n try {\n return accessCountDao.getAllSortedTables();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAccessCountTable(\n AccessCountTable table) throws MetaStoreException {\n try {\n accessCountDao.delete(table);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertAccessCountTable(\n AccessCountTable accessCountTable) throws MetaStoreException {\n try {\n accessCountDao.insert(accessCountTable);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertUpdateStoragesTable(StorageCapacity[] storages)\n throws MetaStoreException {\n mapStorageCapacity = null;\n try {\n storageDao.insertUpdateStoragesTable(storages);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertUpdateStoragesTable(List<StorageCapacity> storages)\n throws MetaStoreException {\n mapStorageCapacity = null;\n try {\n storageDao.insertUpdateStoragesTable(\n storages.toArray(new StorageCapacity[storages.size()]));\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertUpdateStoragesTable(StorageCapacity storage)\n throws MetaStoreException {\n insertUpdateStoragesTable(new StorageCapacity[]{storage});\n }\n\n public Map<String, StorageCapacity> getStorageCapacity() throws MetaStoreException {\n updateCache();\n\n Map<String, StorageCapacity> ret = new HashMap<>();\n Map<String, StorageCapacity> currentMapStorageCapacity = mapStorageCapacity;\n if (currentMapStorageCapacity != null) {\n for (String key : currentMapStorageCapacity.keySet()) {\n ret.put(key, currentMapStorageCapacity.get(key));\n }\n }\n return ret;\n }\n\n public void deleteStorage(String storageType) throws MetaStoreException {\n try {\n mapStorageCapacity = null;\n storageDao.deleteStorage(storageType);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public StorageCapacity getStorageCapacity(\n String type) throws MetaStoreException {\n updateCache();\n Map<String, StorageCapacity> currentMapStorageCapacity = mapStorageCapacity;\n while (currentMapStorageCapacity == null) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException ex) {\n LOG.error(ex.getMessage());\n }\n currentMapStorageCapacity = mapStorageCapacity;\n }\n try {\n return currentMapStorageCapacity.get(type);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateStoragesTable(String type,\n Long capacity, Long free) throws MetaStoreException {\n try {\n mapStorageCapacity = null;\n return storageDao.updateStoragesTable(type, capacity, free);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertStorageHistTable(StorageCapacity[] storages, long interval)\n throws MetaStoreException {\n try {\n storageHistoryDao.insertStorageHistTable(storages, interval);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<StorageCapacity> getStorageHistoryData(String type, long interval,\n long startTime, long endTime) {\n return storageHistoryDao.getStorageHistoryData(type, interval, startTime, endTime);\n }\n\n public void deleteStorageHistoryOldRecords(String type, long interval, long beforTimeStamp)\n throws MetaStoreException {\n try {\n storageHistoryDao.deleteOldRecords(type, interval, beforTimeStamp);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n private void updateCache() throws MetaStoreException {\n if (mapStoragePolicyIdName == null) {\n mapStoragePolicyNameId = null;\n try {\n mapStoragePolicyIdName = storageDao.getStoragePolicyIdNameMap();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n mapStoragePolicyNameId = new HashMap<>();\n for (Integer key : mapStoragePolicyIdName.keySet()) {\n mapStoragePolicyNameId.put(mapStoragePolicyIdName.get(key), key);\n }\n }\n\n if (mapStorageCapacity == null) {\n try {\n mapStorageCapacity = storageDao.getStorageTablesItem();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n }\n\n public void insertCachedFiles(long fid, String path,\n long fromTime,\n long lastAccessTime, int numAccessed) throws MetaStoreException {\n try {\n cacheFileDao.insert(fid, path, fromTime, lastAccessTime, numAccessed);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertCachedFiles(List<CachedFileStatus> s)\n throws MetaStoreException {\n try {\n cacheFileDao.insert(s.toArray(new CachedFileStatus[s.size()]));\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllCachedFile() throws MetaStoreException {\n try {\n cacheFileDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateCachedFiles(Long fid,\n Long lastAccessTime,\n Integer numAccessed) throws MetaStoreException {\n try {\n return cacheFileDao.update(fid, lastAccessTime, numAccessed) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void updateCachedFiles(Map<String, Long> pathToIds,\n List<FileAccessEvent> events)\n throws MetaStoreException {\n try {\n cacheFileDao.update(pathToIds, events);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteCachedFile(long fid) throws MetaStoreException {\n try {\n cacheFileDao.deleteById(fid);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<CachedFileStatus> getCachedFileStatus() throws MetaStoreException {\n try {\n return cacheFileDao.getAll();\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<Long> getCachedFids() throws MetaStoreException {\n try {\n return cacheFileDao.getFids();\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public CachedFileStatus getCachedFileStatus(\n long fid) throws MetaStoreException {\n try {\n return cacheFileDao.getById(fid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void createProportionTable(AccessCountTable dest,\n AccessCountTable source)\n throws MetaStoreException {\n try {\n accessCountDao.createProportionTable(dest, source);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void dropTable(String tableName) throws MetaStoreException {\n try {\n LOG.debug(\"Drop table = {}\", tableName);\n metaStoreHelper.dropTable(tableName);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void execute(String sql) throws MetaStoreException {\n try {\n LOG.debug(\"Execute sql = {}\", sql);\n metaStoreHelper.execute(sql);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n //Todo: optimize\n public void execute(List<String> statements) throws MetaStoreException {\n for (String statement : statements) {\n execute(statement);\n }\n }\n\n public List<String> executeFilesPathQuery(\n String sql) throws MetaStoreException {\n try {\n LOG.debug(\"ExecuteFilesPathQuery sql = {}\", sql);\n return metaStoreHelper.getFilesPath(sql);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<DetailedFileAction> listFileActions(long rid,\n int size) throws MetaStoreException {\n if (mapStoragePolicyIdName == null) {\n updateCache();\n }\n List<ActionInfo> actionInfos = getActions(rid, size);\n List<DetailedFileAction> detailedFileActions = new ArrayList<>();\n\n for (ActionInfo actionInfo : actionInfos) {\n DetailedFileAction detailedFileAction = new DetailedFileAction(actionInfo);\n String filePath = actionInfo.getArgs().get(\"-file\");\n FileInfo fileInfo = getFile(filePath);\n if (fileInfo == null) {\n // LOG.debug(\"Namespace is not sync! File {} not in file table!\", filePath);\n // Add a mock fileInfo\n fileInfo = new FileInfo(filePath, 0L, 0L, false,\n (short) 0, 0L, 0L, 0L, (short) 0,\n \"root\", \"root\", (byte) 0);\n }\n detailedFileAction.setFileLength(fileInfo.getLength());\n detailedFileAction.setFilePath(filePath);\n if (actionInfo.getActionName().contains(\"allssd\")\n || actionInfo.getActionName().contains(\"onessd\")\n || actionInfo.getActionName().contains(\"archive\")\n || actionInfo.getActionName().contains(\"alldisk\")\n || actionInfo.getActionName().contains(\"onedisk\")\n || actionInfo.getActionName().contains(\"ramdisk\")) {\n detailedFileAction.setTarget(actionInfo.getActionName());\n detailedFileAction.setSrc(mapStoragePolicyIdName.get((int) fileInfo.getStoragePolicy()));\n } else {\n detailedFileAction.setSrc(actionInfo.getArgs().get(\"-src\"));\n detailedFileAction.setTarget(actionInfo.getArgs().get(\"-dest\"));\n }\n detailedFileActions.add(detailedFileAction);\n }\n return detailedFileActions;\n }\n\n public List<DetailedFileAction> listFileActions(long rid, long start, long offset)\n throws MetaStoreException {\n if (mapStoragePolicyIdName == null) {\n updateCache();\n }\n List<ActionInfo> actionInfos = getActions(rid, start, offset);\n List<DetailedFileAction> detailedFileActions = new ArrayList<>();\n for (ActionInfo actionInfo : actionInfos) {\n DetailedFileAction detailedFileAction = new DetailedFileAction(actionInfo);\n String filePath = actionInfo.getArgs().get(\"-file\");\n FileInfo fileInfo = getFile(filePath);\n if (fileInfo == null) {\n // LOG.debug(\"Namespace is not sync! File {} not in file table!\", filePath);\n // Add a mock fileInfo\n fileInfo = new FileInfo(filePath, 0L, 0L, false,\n (short) 0, 0L, 0L, 0L, (short) 0,\n \"root\", \"root\", (byte) 0);\n }\n detailedFileAction.setFileLength(fileInfo.getLength());\n detailedFileAction.setFilePath(filePath);\n if (actionInfo.getActionName().contains(\"allssd\")\n || actionInfo.getActionName().contains(\"onessd\")\n || actionInfo.getActionName().contains(\"archive\")\n || actionInfo.getActionName().contains(\"alldisk\")\n || actionInfo.getActionName().contains(\"onedisk\")\n || actionInfo.getActionName().contains(\"ramdisk\")) {\n detailedFileAction.setTarget(actionInfo.getActionName());\n detailedFileAction.setSrc(mapStoragePolicyIdName.get((int) fileInfo.getStoragePolicy()));\n } else {\n detailedFileAction.setSrc(actionInfo.getArgs().get(\"-src\"));\n detailedFileAction.setTarget(actionInfo.getArgs().get(\"-dest\"));\n }\n detailedFileActions.add(detailedFileAction);\n }\n return detailedFileActions;\n }\n\n public long getNumFileAction(long rid) throws MetaStoreException {\n return listFileActions(rid, 0).size();\n }\n\n public List<DetailedRuleInfo> listMoveRules() throws MetaStoreException {\n List<RuleInfo> ruleInfos = getRuleInfo();\n List<DetailedRuleInfo> detailedRuleInfos = new ArrayList<>();\n for (RuleInfo ruleInfo : ruleInfos) {\n if (ruleInfo.getRuleText().contains(\"allssd\")\n || ruleInfo.getRuleText().contains(\"onessd\")\n || ruleInfo.getRuleText().contains(\"archive\")\n || ruleInfo.getRuleText().contains(\"alldisk\")\n || ruleInfo.getRuleText().contains(\"onedisk\")\n || ruleInfo.getRuleText().contains(\"ramdisk\")) {\n DetailedRuleInfo detailedRuleInfo = new DetailedRuleInfo(ruleInfo);\n // Add mover progress\n List<CmdletInfo> cmdletInfos = cmdletDao.getByRid(ruleInfo.getId());\n int currPos = 0;\n for (CmdletInfo cmdletInfo : cmdletInfos) {\n if (cmdletInfo.getState().getValue() <= 4) {\n break;\n }\n currPos += 1;\n }\n int countRunning = 0;\n for (CmdletInfo cmdletInfo : cmdletInfos) {\n if (cmdletInfo.getState().getValue() <= 4) {\n countRunning++;\n }\n }\n detailedRuleInfo\n .setBaseProgress(cmdletInfos.size() - currPos);\n detailedRuleInfo.setRunningProgress(countRunning);\n detailedRuleInfos.add(detailedRuleInfo);\n }\n }\n return detailedRuleInfos;\n }\n\n\n public List<DetailedRuleInfo> listSyncRules() throws MetaStoreException {\n List<RuleInfo> ruleInfos = getRuleInfo();\n List<DetailedRuleInfo> detailedRuleInfos = new ArrayList<>();\n for (RuleInfo ruleInfo : ruleInfos) {\n if (ruleInfo.getState() == RuleState.DELETED) {\n continue;\n }\n if (ruleInfo.getRuleText().contains(\"sync\")) {\n DetailedRuleInfo detailedRuleInfo = new DetailedRuleInfo(ruleInfo);\n // Add sync progress\n BackUpInfo backUpInfo = getBackUpInfo(ruleInfo.getId());\n // Get total matched files\n if (backUpInfo != null) {\n detailedRuleInfo\n .setBaseProgress(getFilesByPrefix(backUpInfo.getSrc()).size());\n long count = fileDiffDao.getPendingDiff(backUpInfo.getSrc()).size();\n count += fileDiffDao.getByState(backUpInfo.getSrc(), FileDiffState.RUNNING).size();\n if (count > detailedRuleInfo.baseProgress) {\n count = detailedRuleInfo.baseProgress;\n }\n detailedRuleInfo.setRunningProgress(count);\n } else {\n detailedRuleInfo\n .setBaseProgress(0);\n detailedRuleInfo.setRunningProgress(0);\n }\n detailedRuleInfos.add(detailedRuleInfo);\n }\n }\n return detailedRuleInfos;\n }\n\n public boolean insertNewRule(RuleInfo info)\n throws MetaStoreException {\n try {\n return ruleDao.insert(info) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateRuleInfo(long ruleId, RuleState rs,\n long lastCheckTime, long checkedCount, int commandsGen)\n throws MetaStoreException {\n try {\n if (rs == null) {\n return ruleDao.update(ruleId,\n lastCheckTime, checkedCount, commandsGen) >= 0;\n }\n return ruleDao.update(ruleId,\n rs.getValue(), lastCheckTime, checkedCount, commandsGen) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateRuleState(long ruleId, RuleState rs)\n throws MetaStoreException {\n if (rs == null) {\n throw new MetaStoreException(\"Rule state can not be null, ruleId = \" + ruleId);\n }\n try {\n return ruleDao.update(ruleId, rs.getValue()) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public RuleInfo getRuleInfo(long ruleId) throws MetaStoreException {\n try {\n return ruleDao.getById(ruleId);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<RuleInfo> listPageRule(long start, long offset, List<String> orderBy,\n List<Boolean> desc)\n throws MetaStoreException {\n LOG.debug(\"List Rule, start {}, offset {}\", start, offset);\n try {\n if (orderBy.size() == 0) {\n return ruleDao.getAPageOfRule(start, offset);\n } else {\n return ruleDao.getAPageOfRule(start, offset, orderBy, desc);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public List<RuleInfo> getRuleInfo() throws MetaStoreException {\n try {\n return ruleDao.getAll();\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<CmdletInfo> listPageCmdlets(long rid, long start, long offset,\n List<String> orderBy, List<Boolean> desc)\n throws MetaStoreException {\n LOG.debug(\"List cmdlet, start {}, offset {}\", start, offset);\n try {\n if (orderBy.size() == 0) {\n return cmdletDao.getByRid(rid, start, offset);\n } else {\n return cmdletDao.getByRid(rid, start, offset, orderBy, desc);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public long getNumCmdletsByRid(long rid) {\n try {\n return cmdletDao.getNumByRid(rid);\n } catch (Exception e) {\n return 0;\n }\n }\n\n public List<CmdletInfo> listPageCmdlets(long start, long offset,\n List<String> orderBy, List<Boolean> desc)\n throws MetaStoreException {\n LOG.debug(\"List cmdlet, start {}, offset {}\", start, offset);\n try {\n if (orderBy.size() == 0) {\n return cmdletDao.getAPageOfCmdlet(start, offset);\n } else {\n return cmdletDao.getAPageOfCmdlet(start, offset, orderBy, desc);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllRules() throws MetaStoreException {\n try {\n ruleDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public void insertCmdlets(CmdletInfo[] commands)\n throws MetaStoreException {\n if (commands.length == 0) {\n return;\n }\n try {\n cmdletDao.replace(commands);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertCmdlet(CmdletInfo command)\n throws MetaStoreException {\n try {\n // Update if exists\n if (getCmdletById(command.getCid()) != null) {\n cmdletDao.update(command);\n } else {\n cmdletDao.insert(command);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public long getMaxCmdletId() throws MetaStoreException {\n try {\n return cmdletDao.getMaxId();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public CmdletInfo getCmdletById(long cid) throws MetaStoreException {\n LOG.debug(\"Get cmdlet by cid {}\", cid);\n try {\n return cmdletDao.getById(cid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public List<CmdletInfo> getCmdlets(String cidCondition,\n String ridCondition,\n CmdletState state) throws MetaStoreException {\n try {\n return cmdletDao.getByCondition(cidCondition, ridCondition, state);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<CmdletInfo> getCmdlets(CmdletState state) throws MetaStoreException {\n try {\n return cmdletDao.getByState(state);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateCmdlet(CmdletInfo cmdletInfo)\n throws MetaStoreException {\n try {\n return cmdletDao.update(cmdletInfo) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public boolean updateCmdlet(long cid, CmdletState state)\n throws MetaStoreException {\n try {\n return cmdletDao.update(cid, state.getValue()) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public boolean updateCmdlet(long cid, String parameters, CmdletState state)\n throws MetaStoreException {\n try {\n return cmdletDao.update(cid, parameters, state.getValue()) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public void deleteCmdlet(long cid) throws MetaStoreException {\n try {\n cmdletDao.delete(cid);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void batchDeleteCmdlet(List<Long> cids) throws MetaStoreException {\n try {\n cmdletDao.batchDelete(cids);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n /**\n * Delete finished cmdlets before given timestamp, actions belonging to these cmdlets\n * will also be deleted. Cmdlet's generate_time is used for comparison.\n *\n * @param timestamp\n * @return number of cmdlets deleted\n * @throws MetaStoreException\n */\n public int deleteFinishedCmdletsWithGenTimeBefore(long timestamp) throws MetaStoreException {\n try {\n return cmdletDao.deleteBeforeTime(timestamp);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public int deleteKeepNewCmdlets(long num) throws MetaStoreException {\n try {\n return cmdletDao.deleteKeepNewCmd(num);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public int getNumCmdletsInTerminiatedStates() throws MetaStoreException {\n try {\n return cmdletDao.getNumCmdletsInTerminiatedStates();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertActions(ActionInfo[] actionInfos)\n throws MetaStoreException {\n try {\n actionDao.replace(actionInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertAction(ActionInfo actionInfo)\n throws MetaStoreException {\n LOG.debug(\"Insert Action ID {}\", actionInfo.getActionId());\n try {\n if (getActionById(actionInfo.getActionId()) != null) {\n actionDao.update(actionInfo);\n } else {\n actionDao.insert(actionInfo);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> listPageAction(long start, long offset, List<String> orderBy,\n List<Boolean> desc)\n throws MetaStoreException {\n LOG.debug(\"List Action, start {}, offset {}\", start, offset);\n try {\n if (orderBy.size() == 0) {\n return actionDao.getAPageOfAction(start, offset);\n } else {\n return actionDao.getAPageOfAction(start, offset, orderBy, desc);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> searchAction(String path, long start,\n long offset, List<String> orderBy, List<Boolean> desc,\n long[] retTotalNumActions) throws MetaStoreException {\n try {\n return actionDao.searchAction(path, start, offset, orderBy, desc, retTotalNumActions);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteCmdletActions(long cmdletId) throws MetaStoreException {\n try {\n actionDao.deleteCmdletActions(cmdletId);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void batchDeleteCmdletActions(List<Long> cmdletIds) throws MetaStoreException {\n try {\n actionDao.batchDeleteCmdletActions(cmdletIds);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllActions() throws MetaStoreException {\n try {\n actionDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n /**\n * Mark action {aid} as failed.\n *\n * @param aid\n * @throws MetaStoreException\n */\n public void markActionFailed(long aid) throws MetaStoreException {\n ActionInfo actionInfo = getActionById(aid);\n if (actionInfo != null) {\n // Finished\n actionInfo.setFinished(true);\n // Failed\n actionInfo.setSuccessful(false);\n // 100 % progress\n actionInfo.setProgress(1);\n // Finish time equals to create time\n actionInfo.setFinishTime(actionInfo.getCreateTime());\n updateAction(actionInfo);\n }\n }\n\n public void updateAction(ActionInfo actionInfo) throws MetaStoreException {\n if (actionInfo == null) {\n return;\n }\n LOG.debug(\"Update Action ID {}\", actionInfo.getActionId());\n try {\n actionDao.update(actionInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void updateActions(ActionInfo[] actionInfos)\n throws MetaStoreException {\n if (actionInfos == null || actionInfos.length == 0) {\n return;\n }\n LOG.debug(\"Update Action ID {}\", actionInfos[0].getActionId());\n try {\n actionDao.update(actionInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getNewCreatedActions(\n int size) throws MetaStoreException {\n if (size < 0) {\n return new ArrayList<>();\n }\n try {\n return actionDao.getLatestActions(size);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getNewCreatedActions(String actionName,\n int size) throws MetaStoreException {\n if (size < 0) {\n return new ArrayList<>();\n }\n try {\n return actionDao.getLatestActions(actionName, size);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getNewCreatedActions(String actionName,\n int size, boolean successful,\n boolean finished) throws MetaStoreException {\n if (size < 0) {\n return new ArrayList<>();\n }\n try {\n return actionDao.getLatestActions(actionName, size, successful, finished);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getNewCreatedActions(String actionName,\n int size,\n boolean finished) throws MetaStoreException {\n if (size < 0) {\n return new ArrayList<>();\n }\n try {\n return actionDao.getLatestActions(actionName, size, finished);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getNewCreatedActions(String actionName,\n boolean successful,\n int size) throws MetaStoreException {\n if (size < 0) {\n return new ArrayList<>();\n }\n try {\n return actionDao.getLatestActions(actionName, size, successful);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public List<ActionInfo> getActions(\n List<Long> aids) throws MetaStoreException {\n if (aids == null || aids.size() == 0) {\n return new ArrayList<>();\n }\n LOG.debug(\"Get Action ID {}\", aids.toString());\n try {\n return actionDao.getByIds(aids);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getActions(String aidCondition,\n String cidCondition) throws MetaStoreException {\n LOG.debug(\"Get aid {} cid {}\", aidCondition, cidCondition);\n try {\n return actionDao.getByCondition(aidCondition, cidCondition);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ActionInfo> getActions(long rid, int size) throws MetaStoreException {\n if (size <= 0) {\n size = Integer.MAX_VALUE;\n }\n List<CmdletInfo> cmdletInfos = cmdletDao.getByRid(rid);\n List<ActionInfo> runningActions = new ArrayList<>();\n List<ActionInfo> finishedActions = new ArrayList<>();\n int total = 0;\n for (CmdletInfo cmdletInfo : cmdletInfos) {\n if (total >= size) {\n break;\n }\n List<Long> aids = cmdletInfo.getAids();\n for (Long aid : aids) {\n if (total >= size) {\n break;\n }\n ActionInfo actionInfo = getActionById(aid);\n if (actionInfo != null && actionInfo.isFinished()) {\n finishedActions.add(actionInfo);\n } else {\n runningActions.add(actionInfo);\n }\n total++;\n }\n }\n runningActions.addAll(finishedActions);\n return runningActions;\n }\n\n public List<ActionInfo> getActions(long rid, long start, long offset) throws MetaStoreException {\n long mark = 0;\n long count = 0;\n List<CmdletInfo> cmdletInfos = cmdletDao.getByRid(rid);\n List<ActionInfo> totalActions = new ArrayList<>();\n for (CmdletInfo cmdletInfo : cmdletInfos) {\n List<Long> aids = cmdletInfo.getAids();\n if (mark + aids.size() >= start + 1) {\n long gap;\n gap = start - mark;\n for (Long aid : aids) {\n if (gap > 0) {\n gap--;\n mark++;\n continue;\n }\n if (count < offset) {\n ActionInfo actionInfo = getActionById(aid);\n totalActions.add(actionInfo);\n count++;\n mark++;\n } else {\n return totalActions;\n }\n }\n } else {\n mark += aids.size();\n }\n\n }\n return totalActions;\n }\n\n public ActionInfo getActionById(long aid) throws MetaStoreException {\n LOG.debug(\"Get actioninfo by aid {}\", aid);\n try {\n return actionDao.getById(aid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public long getMaxActionId() throws MetaStoreException {\n try {\n return actionDao.getMaxId();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public long getCountOfAllAction() throws MetaStoreException {\n try {\n return actionDao.getCountOfAction();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertStoragePolicy(StoragePolicy s)\n throws MetaStoreException {\n try {\n storageDao.insertStoragePolicyTable(s);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public String getStoragePolicyName(int sid) throws MetaStoreException {\n updateCache();\n try {\n return mapStoragePolicyIdName.get(sid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public Integer getStoragePolicyID(\n String policyName) throws MetaStoreException {\n try {\n updateCache();\n return mapStoragePolicyNameId.get(policyName);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean insertXattrList(Long fid,\n List<XAttribute> attributes) throws MetaStoreException {\n try {\n return xattrDao.insertXattrList(fid, attributes);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<XAttribute> getXattrList(Long fid) throws MetaStoreException {\n try {\n return xattrDao.getXattrList(fid);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public long insertFileDiff(FileDiff fileDiff)\n throws MetaStoreException {\n try {\n return fileDiffDao.insert(fileDiff);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertFileDiffs(FileDiff[] fileDiffs)\n throws MetaStoreException {\n try {\n fileDiffDao.insert(fileDiffs);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public Long[] insertFileDiffs(List<FileDiff> fileDiffs)\n throws MetaStoreException {\n try {\n return fileDiffDao.insert(fileDiffs);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public FileDiff getFileDiff(long did) throws MetaStoreException {\n try {\n return fileDiffDao.getById(did);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileDiff> getFileDiffsByFileName(String fileName) throws MetaStoreException {\n try {\n return fileDiffDao.getByFileName(fileName);\n } catch (EmptyResultDataAccessException e) {\n return new ArrayList<>();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<FileDiff> getFileDiffs(FileDiffState fileDiffState) throws MetaStoreException {\n try {\n return fileDiffDao.getByState(fileDiffState);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public boolean updateFileDiff(long did,\n FileDiffState state) throws MetaStoreException {\n try {\n return fileDiffDao.update(did, state) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean batchUpdateFileDiff(\n List<Long> did, List<FileDiffState> states, List<String> parameters)\n throws MetaStoreException {\n try {\n return fileDiffDao.batchUpdate(did, states, parameters).length > 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean batchUpdateFileDiff(\n List<Long> did, FileDiffState state)\n throws MetaStoreException {\n try {\n return fileDiffDao.batchUpdate(did, state).length > 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateFileDiff(long did,\n FileDiffState state, String parameters) throws MetaStoreException {\n try {\n return fileDiffDao.update(did, state, parameters) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateFileDiff(long did,\n String src) throws MetaStoreException {\n try {\n return fileDiffDao.update(did, src) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean updateFileDiff(FileDiff fileDiff)\n throws MetaStoreException {\n long did = fileDiff.getDiffId();\n FileDiff preFileDiff = getFileDiff(did);\n if (preFileDiff == null) {\n insertFileDiff(fileDiff);\n }\n try {\n return fileDiffDao.update(fileDiff) >= 0;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void updateFileDiff(List<FileDiff> fileDiffs)\n throws MetaStoreException {\n if (fileDiffs == null || fileDiffs.size() == 0) {\n return;\n }\n try {\n fileDiffDao.update(fileDiffs.toArray(new FileDiff[fileDiffs.size()]));\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public int getUselessFileDiffNum() throws MetaStoreException {\n try {\n return fileDiffDao.getUselessRecordsNum();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public int deleteUselessFileDiff(int maxNumRecords) throws MetaStoreException {\n try {\n return fileDiffDao.deleteUselessRecords(maxNumRecords);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<String> getSyncPath(int size) throws MetaStoreException {\n return fileDiffDao.getSyncPath(size);\n }\n\n @Override\n public List<FileDiff> getPendingDiff() throws MetaStoreException {\n return fileDiffDao.getPendingDiff();\n }\n\n @Override\n public List<FileDiff> getPendingDiff(long rid) throws MetaStoreException {\n return fileDiffDao.getPendingDiff(rid);\n }\n\n @Override\n public void deleteAllFileDiff() throws MetaStoreException {\n fileDiffDao.deleteAll();\n }\n\n public void dropAllTables() throws MetaStoreException {\n Connection conn = getConnection();\n try {\n String url = conn.getMetaData().getURL();\n if (url.startsWith(MetaStoreUtils.SQLITE_URL_PREFIX)) {\n MetaStoreUtils.dropAllTablesSqlite(conn);\n } else if (url.startsWith(MetaStoreUtils.MYSQL_URL_PREFIX)) {\n MetaStoreUtils.dropAllTablesMysql(conn, url);\n } else {\n throw new MetaStoreException(\"Unsupported database\");\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n } finally {\n closeConnection(conn);\n }\n }\n\n public void initializeDataBase() throws MetaStoreException {\n Connection conn = getConnection();\n try {\n MetaStoreUtils.initializeDataBase(conn);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n } finally {\n closeConnection(conn);\n }\n }\n\n public void checkTables() throws MetaStoreException {\n try {\n int num = getTablesNum(MetaStoreUtils.TABLESET);\n if (num == 0) {\n LOG.info(\"The table set required by SSM does not exist. \"\n + \"The configured database will be formatted.\");\n formatDataBase();\n } else if (num < MetaStoreUtils.TABLESET.length) {\n LOG.error(\"One or more tables required by SSM are missing! \"\n + \"You can restart SSM with -format option or configure another database.\");\n System.exit(1);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public int getTablesNum(String tableSet[]) throws MetaStoreException {\n Connection conn = getConnection();\n return MetaStoreUtils.getTableSetNum(conn, tableSet);\n }\n\n public void formatDataBase() throws MetaStoreException {\n dropAllTables();\n initializeDataBase();\n }\n\n public void aggregateTables(AccessCountTable destinationTable\n , List<AccessCountTable> tablesToAggregate) throws MetaStoreException {\n try {\n accessCountDao.aggregateTables(destinationTable, tablesToAggregate);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void setClusterConfig(\n ClusterConfig clusterConfig) throws MetaStoreException {\n try {\n\n if (clusterConfigDao.getCountByName(clusterConfig.getNodeName()) == 0) {\n //insert\n clusterConfigDao.insert(clusterConfig);\n } else {\n //update\n clusterConfigDao.updateByNodeName(clusterConfig.getNodeName(),\n clusterConfig.getConfigPath());\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void delClusterConfig(\n ClusterConfig clusterConfig) throws MetaStoreException {\n try {\n if (clusterConfigDao.getCountByName(clusterConfig.getNodeName()) > 0) {\n //insert\n clusterConfigDao.delete(clusterConfig.getCid());\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ClusterConfig> listClusterConfig() throws MetaStoreException {\n try {\n return clusterConfigDao.getAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public GlobalConfig getDefaultGlobalConfigByName(\n String configName) throws MetaStoreException {\n try {\n if (globalConfigDao.getCountByName(configName) > 0) {\n //the property is existed\n return globalConfigDao.getByPropertyName(configName);\n } else {\n return null;\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void setGlobalConfig(\n GlobalConfig globalConfig) throws MetaStoreException {\n try {\n if (globalConfigDao.getCountByName(globalConfig.getPropertyName()) > 0) {\n globalConfigDao.update(globalConfig.getPropertyName(),\n globalConfig.getPropertyValue());\n } else {\n globalConfigDao.insert(globalConfig);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeInfo(DataNodeInfo dataNodeInfo)\n throws MetaStoreException {\n try {\n dataNodeInfoDao.insert(dataNodeInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeInfos(DataNodeInfo[] dataNodeInfos)\n throws MetaStoreException {\n try {\n dataNodeInfoDao.insert(dataNodeInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeInfos(List<DataNodeInfo> dataNodeInfos)\n throws MetaStoreException {\n try {\n dataNodeInfoDao.insert(dataNodeInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<DataNodeInfo> getDataNodeInfoByUuid(String uuid)\n throws MetaStoreException {\n try {\n return dataNodeInfoDao.getByUuid(uuid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<DataNodeInfo> getAllDataNodeInfo()\n throws MetaStoreException {\n try {\n return dataNodeInfoDao.getAll();\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteDataNodeInfo(String uuid)\n throws MetaStoreException {\n try {\n dataNodeInfoDao.delete(uuid);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllDataNodeInfo()\n throws MetaStoreException {\n try {\n dataNodeInfoDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeStorageInfo(DataNodeStorageInfo dataNodeStorageInfo)\n throws MetaStoreException {\n try {\n dataNodeStorageInfoDao.insert(dataNodeStorageInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeStorageInfos(\n DataNodeStorageInfo[] dataNodeStorageInfos)\n throws MetaStoreException {\n try {\n dataNodeStorageInfoDao.insert(dataNodeStorageInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertDataNodeStorageInfos(\n List<DataNodeStorageInfo> dataNodeStorageInfos)\n throws MetaStoreException {\n try {\n dataNodeStorageInfoDao.insert(dataNodeStorageInfos);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean judgeTheRecordIfExist(String storageType) throws MetaStoreException {\n try {\n if (storageDao.getCountOfStorageType(storageType) < 1) {\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n //need to be triggered when DataNodeStorageInfo table is changed\n public long getStoreCapacityOfDifferentStorageType(String storageType) throws MetaStoreException {\n try {\n int sid = 0;\n\n if (storageType.equals(\"ram\")) {\n sid = 0;\n }\n\n if (storageType.equals(\"ssd\")) {\n sid = 1;\n }\n\n if (storageType.equals(\"disk\")) {\n sid = 2;\n }\n\n if (storageType.equals(\"archive\")) {\n sid = 3;\n }\n List<DataNodeStorageInfo> lists = dataNodeStorageInfoDao.getBySid(sid);\n long allCapacity = 0;\n for (DataNodeStorageInfo info : lists) {\n allCapacity = allCapacity + info.getCapacity();\n }\n return allCapacity;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n //need to be triggered when DataNodeStorageInfo table is changed\n public long getStoreFreeOfDifferentStorageType(String storageType) throws MetaStoreException {\n try {\n int sid = 0;\n\n if (storageType.equals(\"ram\")) {\n sid = 0;\n }\n\n if (storageType.equals(\"ssd\")) {\n sid = 1;\n }\n\n if (storageType.equals(\"disk\")) {\n sid = 2;\n }\n\n if (storageType.equals(\"archive\")) {\n sid = 3;\n }\n List<DataNodeStorageInfo> lists = dataNodeStorageInfoDao.getBySid(sid);\n long allFree = 0;\n for (DataNodeStorageInfo info : lists) {\n allFree = allFree + info.getRemaining();\n }\n return allFree;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<DataNodeStorageInfo> getDataNodeStorageInfoByUuid(String uuid)\n throws MetaStoreException {\n try {\n return dataNodeStorageInfoDao.getByUuid(uuid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public List<DataNodeStorageInfo> getAllDataNodeStorageInfo()\n throws MetaStoreException {\n try {\n return dataNodeStorageInfoDao.getAll();\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteDataNodeStorageInfo(String uuid)\n throws MetaStoreException {\n try {\n dataNodeStorageInfoDao.delete(uuid);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllDataNodeStorageInfo()\n throws MetaStoreException {\n try {\n dataNodeStorageInfoDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public List<BackUpInfo> listAllBackUpInfo() throws MetaStoreException {\n try {\n return backUpInfoDao.getAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean srcInbackup(String src) throws MetaStoreException {\n if (setBackSrc == null) {\n setBackSrc = new HashSet<>();\n List<BackUpInfo> backUpInfos = listAllBackUpInfo();\n for (BackUpInfo backUpInfo : backUpInfos) {\n setBackSrc.add(backUpInfo.getSrc());\n }\n }\n // LOG.info(\"Backup src = {}, setBackSrc {}\", src, setBackSrc);\n for (String srcDir : setBackSrc) {\n if (src.startsWith(srcDir)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public BackUpInfo getBackUpInfo(long rid) throws MetaStoreException {\n try {\n return backUpInfoDao.getByRid(rid);\n } catch (EmptyResultDataAccessException e) {\n return null;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<BackUpInfo> getBackUpInfoBySrc(String src) throws MetaStoreException {\n try {\n // More than one dest may exist for one same src\n List<BackUpInfo> backUpInfos = new ArrayList<>();\n for (BackUpInfo backUpInfo : listAllBackUpInfo()) {\n if (src.startsWith(backUpInfo.getSrc())) {\n backUpInfos.add(backUpInfo);\n }\n }\n return backUpInfos;\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public void deleteAllBackUpInfo() throws MetaStoreException {\n try {\n backUpInfoDao.deleteAll();\n setBackSrc.clear();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public void deleteBackUpInfo(long rid) throws MetaStoreException {\n try {\n BackUpInfo backUpInfo = getBackUpInfo(rid);\n if (backUpInfo != null) {\n if (backUpInfoDao.getBySrc(backUpInfo.getSrc()).size() == 1) {\n if (setBackSrc != null) {\n setBackSrc.remove(backUpInfo.getSrc());\n }\n }\n backUpInfoDao.delete(rid);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n @Override\n public void insertBackUpInfo (\n BackUpInfo backUpInfo) throws MetaStoreException {\n try {\n backUpInfoDao.insert(backUpInfo);\n if (setBackSrc == null) {\n setBackSrc = new HashSet<>();\n }\n setBackSrc.add(backUpInfo.getSrc());\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<ClusterInfo> listAllClusterInfo() throws MetaStoreException {\n try {\n return clusterInfoDao.getAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<SystemInfo> listAllSystemInfo() throws MetaStoreException {\n try {\n return systemInfoDao.getAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n\n public ClusterInfo getClusterInfoByCid(long id) throws MetaStoreException {\n try {\n return clusterInfoDao.getById(id);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public SystemInfo getSystemInfoByProperty(\n String property) throws MetaStoreException {\n try {\n return systemInfoDao.getByProperty(property);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public boolean containSystemInfo(String property) throws MetaStoreException {\n try {\n return systemInfoDao.containsProperty(property);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteAllClusterInfo() throws MetaStoreException {\n try {\n clusterInfoDao.deleteAll();\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void updateSystemInfo(\n SystemInfo systemInfo) throws MetaStoreException {\n try {\n systemInfoDao.update(systemInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void updateAndInsertIfNotExist(\n SystemInfo systemInfo) throws MetaStoreException {\n try {\n if (systemInfoDao.update(systemInfo) <= 0) {\n systemInfoDao.insert(systemInfo);\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteClusterInfo(long cid) throws MetaStoreException {\n try {\n clusterInfoDao.delete(cid);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteSystemInfo(\n String property) throws MetaStoreException {\n try {\n systemInfoDao.delete(property);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertClusterInfo(\n ClusterInfo clusterInfo) throws MetaStoreException {\n try {\n if (clusterInfoDao.getCountByName(clusterInfo.getName()) != 0) {\n throw new Exception(\"name has already exist\");\n }\n clusterInfoDao.insert(clusterInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertSystemInfo(SystemInfo systemInfo)\n throws MetaStoreException {\n try {\n if (systemInfoDao.containsProperty(systemInfo.getProperty())) {\n throw new Exception(\"The system property already exists\");\n }\n systemInfoDao.insert(systemInfo);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertUpdateFileState(FileState fileState)\n throws MetaStoreException {\n try {\n // Update corresponding tables according to the file state\n fileStateDao.insertUpdate(fileState);\n switch (fileState.getFileType()) {\n case COMPACT:\n CompactFileState compactFileState = (CompactFileState) fileState;\n smallFileDao.insertUpdate(compactFileState);\n break;\n case COMPRESSION:\n break;\n case S3:\n break;\n default:\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void insertCompactFileStates(CompactFileState[] compactFileStates)\n throws MetaStoreException {\n try {\n fileStateDao.batchInsertUpdate(compactFileStates);\n smallFileDao.batchInsertUpdate(compactFileStates);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public FileState getFileState(String path) throws MetaStoreException {\n FileState fileState;\n try {\n fileState = fileStateDao.getByPath(path);\n // Fetch info from corresponding table to regenerate a specific file state\n switch (fileState.getFileType()) {\n case NORMAL:\n fileState = new NormalFileState(path);\n break;\n case COMPACT:\n fileState = smallFileDao.getFileStateByPath(path);\n break;\n case COMPRESSION:\n break;\n case S3:\n fileState = new S3FileState(path);\n break;\n default:\n }\n } catch (EmptyResultDataAccessException e1) {\n fileState = new NormalFileState(path);\n } catch (Exception e2) {\n throw new MetaStoreException(e2);\n }\n return fileState;\n }\n\n public Map<String, FileState> getFileStates(List<String> paths)\n throws MetaStoreException {\n try {\n return fileStateDao.getByPaths(paths);\n } catch (EmptyResultDataAccessException e1) {\n return new HashMap<>();\n } catch (Exception e2) {\n throw new MetaStoreException(e2);\n }\n }\n\n public void deleteFileState(String filePath) throws MetaStoreException {\n try {\n FileState fileState = getFileState(filePath);\n fileStateDao.deleteByPath(filePath, false);\n switch (fileState.getFileType()) {\n case COMPACT:\n smallFileDao.deleteByPath(filePath, false);\n break;\n case COMPRESSION:\n break;\n case S3:\n break;\n default:\n }\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public void deleteCompactFileStates(List<String> paths)\n throws MetaStoreException {\n try {\n fileStateDao.batchDelete(paths);\n smallFileDao.batchDelete(paths);\n } catch (Exception e) {\n throw new MetaStoreException(e);\n }\n }\n\n public List<String> getSmallFilesByContainerFile(String containerFilePath)\n throws MetaStoreException {\n try {\n return smallFileDao.getSmallFilesByContainerFile(containerFilePath);\n } catch (EmptyResultDataAccessException e1) {\n return new ArrayList<>();\n } catch (Exception e2) {\n throw new MetaStoreException(e2);\n }\n }\n\n public List<String> getAllContainerFiles() throws MetaStoreException {\n try {\n return smallFileDao.getAllContainerFiles();\n } catch (EmptyResultDataAccessException e1) {\n return new ArrayList<>();\n } catch (Exception e2) {\n throw new MetaStoreException(e2);\n }\n }\n}", "public class TimeBasedScheduleInfo {\n public static final long FOR_EVER = Long.MAX_VALUE;\n private long startTime;\n private long endTime;\n private long every;\n private long subScheduleTime;\n\n public TimeBasedScheduleInfo() {\n }\n\n public TimeBasedScheduleInfo(long startTime, long endTime, long every) {\n this.startTime = startTime;\n this.endTime = endTime;\n this.every = every;\n }\n\n public void setStartTime(long startTime) {\n this.startTime = startTime;\n }\n\n public void setEndTime(long endTime) {\n this.endTime = endTime;\n }\n\n public void setEvery(long every) {\n this.every = every;\n }\n\n public long getStartTime() {\n return startTime;\n }\n\n public long getEndTime() {\n return endTime;\n }\n\n public long getEvery() {\n return every;\n }\n\n public boolean isOnce() {\n return startTime == endTime && startTime == 0 && every == 0;\n }\n\n public boolean isOneShot() {\n return startTime == endTime && every == 0;\n }\n\n public void setSubScheduleTime(long subScheduleTime) {\n this.subScheduleTime = subScheduleTime;\n }\n\n public long getSubScheduleTime() {\n return subScheduleTime;\n }\n}", "public class SmartRuleStringParser {\n private String rule;\n private TranslationContext ctx = null;\n\n private static Map<String, String> optCond = new HashMap<>();\n\n static {\n optCond.put(\"allssd\", \"storagePolicy != \\\"ALL_SSD\\\"\");\n optCond.put(\"onessd\", \"storagePolicy != \\\"ONE_SSD\\\"\");\n optCond.put(\"archive\", \"storagePolicy != \\\"COLD\\\"\");\n optCond.put(\"alldisk\", \"storagePolicy != \\\"HOT\\\"\");\n optCond.put(\"onedisk\", \"storagePolicy != \\\"WARM\\\"\");\n optCond.put(\"ramdisk\", \"storagePolicy != \\\"LAZY_PERSIST\\\"\");\n optCond.put(\"cache\", \"not inCache\");\n optCond.put(\"uncache\", \"inCache\");\n optCond.put(\"sync\", \"unsynced\");\n }\n\n List<RecognitionException> parseErrors = new ArrayList<RecognitionException>();\n String parserErrorMessage = \"\";\n\n public class SSMRuleErrorListener extends BaseErrorListener {\n @Override\n public void syntaxError(\n Recognizer<?, ?> recognizer,\n Object offendingSymbol,\n int line,\n int charPositionInLine,\n String msg,\n RecognitionException e) {\n List<String> stack = ((Parser) recognizer).getRuleInvocationStack();\n Collections.reverse(stack);\n parserErrorMessage += \"Line \" + line + \", Char \" + charPositionInLine + \" : \" + msg + \"\\n\";\n parseErrors.add(e);\n }\n }\n\n public SmartRuleStringParser(String rule, TranslationContext ctx) {\n this.rule = rule;\n this.ctx = ctx;\n }\n\n public TranslateResult translate() throws IOException {\n TranslateResult tr = doTranslate(rule);\n CmdletDescriptor cmdDes = tr.getCmdDescriptor();\n if (cmdDes.getActionSize() == 0) {\n throw new IOException(\"No cmdlet specified in Rule\");\n }\n String actName = cmdDes.getActionName(0);\n if (cmdDes.getActionSize() != 1 || optCond.get(actName) == null) {\n return tr;\n }\n int[] condPosition = tr.getCondPosition();\n String cond = rule.substring(condPosition[0], condPosition[1] + 1);\n String optRule = rule.replace(cond, optCond.get(actName) + \" and (\" + cond + \")\");\n return doTranslate(optRule);\n }\n\n private TranslateResult doTranslate(String rule) throws IOException {\n parseErrors.clear();\n parserErrorMessage = \"\";\n\n InputStream input = new ByteArrayInputStream(rule.getBytes());\n ANTLRInputStream antlrInput = new ANTLRInputStream(input);\n SmartRuleLexer lexer = new SmartRuleLexer(antlrInput);\n CommonTokenStream tokens = new CommonTokenStream(lexer);\n SmartRuleParser parser = new SmartRuleParser(tokens);\n parser.removeErrorListeners();\n parser.addErrorListener(new SSMRuleErrorListener());\n ParseTree tree = parser.ssmrule();\n\n if (parseErrors.size() > 0) {\n throw new IOException(parserErrorMessage);\n }\n\n SmartRuleVisitTranslator visitor = new SmartRuleVisitTranslator(ctx);\n try {\n visitor.visit(tree);\n } catch (RuntimeException e) {\n throw new IOException(e.getMessage());\n }\n\n TranslateResult result = visitor.generateSql();\n return result;\n }\n}", "public class ExecutorScheduler {\n private ScheduledExecutorService service;\n\n public ExecutorScheduler(int numThreads) {\n service = Executors.newScheduledThreadPool(numThreads);\n }\n\n public void addPeriodicityTask(RuleExecutor re) {\n TimeBasedScheduleInfo si = re.getTranslateResult().getTbScheduleInfo();\n long now = System.currentTimeMillis();\n si.setSubScheduleTime(now);\n long startDelay = si.getStartTime() - now;\n if (startDelay < 0) {\n startDelay = 0;\n }\n long every = si.getEvery();\n if (every <= 0) {\n every = 5000;\n }\n service.scheduleAtFixedRate(re, startDelay, every, TimeUnit.MILLISECONDS);\n }\n\n public void addPeriodicityTask(ScheduleInfo schInfo, Runnable work) {\n long now = System.currentTimeMillis();\n service.scheduleAtFixedRate(work, schInfo.getStartTime() - now,\n schInfo.getRate(), TimeUnit.MILLISECONDS);\n }\n\n // TODO: to be defined\n public void addEventTask() {\n }\n\n public void shutdown() {\n try {\n service.shutdown();\n if (!service.awaitTermination(3000, TimeUnit.MILLISECONDS)) {\n service.shutdownNow();\n }\n } catch (InterruptedException e) {\n service.shutdownNow();\n }\n }\n\n\n /**\n * This will be used for extension: a full event based scheduler.\n */\n private class EventGenTask implements Runnable {\n private long id;\n private ScheduleInfo scheduleInfo;\n private int triggered;\n\n public EventGenTask(long id) {\n this.id = id;\n }\n\n @Override\n public void run() {\n triggered++;\n if (triggered <= scheduleInfo.getRounds()) {\n } else {\n exitSchduler();\n }\n }\n\n private void exitSchduler() {\n String[] temp = new String[1];\n temp[1] += \"The exception is created deliberately\";\n }\n }\n}", "public class FileCopy2S3Plugin implements RuleExecutorPlugin {\n\n private static final Logger LOG =\n LoggerFactory.getLogger(FileCopy2S3Plugin.class.getName());\n private List<String> srcBases;\n\n public FileCopy2S3Plugin() {\n srcBases = null;\n }\n\n\n @Override\n public void onNewRuleExecutor(RuleInfo ruleInfo,\n TranslateResult tResult) {\n srcBases = new ArrayList<>();\n List<String> pathsCheckGlob = tResult.getGlobPathCheck();\n if (pathsCheckGlob.size() == 0) {\n pathsCheckGlob = Collections.singletonList(\"/*\");\n }\n // Get src base list\n srcBases = getPathMatchesList(pathsCheckGlob);\n LOG.debug(\"Source base list = {}\", srcBases);\n }\n\n private List<String> getPathMatchesList(List<String> paths) {\n List<String> ret = new ArrayList<>();\n for (String p : paths) {\n String dir = StringUtil.getBaseDir(p);\n if (dir == null) {\n continue;\n }\n ret.add(dir);\n }\n return ret;\n }\n\n @Override\n public boolean preExecution(RuleInfo ruleInfo,\n TranslateResult tResult) {\n return true;\n }\n\n @Override\n public List<String> preSubmitCmdlet(RuleInfo ruleInfo,\n List<String> objects) {\n return objects;\n }\n\n @Override\n public CmdletDescriptor preSubmitCmdletDescriptor(RuleInfo ruleInfo,\n TranslateResult tResult, CmdletDescriptor descriptor) {\n for (int i = 0; i < descriptor.getActionSize(); i++) {\n // O(n)\n if (descriptor.getActionName(i).equals(\"copy2s3\")) {\n String srcPath = descriptor.getActionArgs(i).get(Copy2S3Action.SRC);\n String destBase = descriptor.getActionArgs(i).get(Copy2S3Action.DEST);\n String workPath = null;\n // O(n)\n for (String srcBase : srcBases) {\n if (srcPath.startsWith(srcBase)) {\n workPath = srcPath.replaceFirst(srcBase, \"\");\n break;\n }\n }\n if (workPath == null) {\n LOG.error(\"Rule {} CmdletDescriptor {} Working Path is empty!\", ruleInfo, descriptor);\n }\n // Update dest path\n // dest base + work path = dest full path\n descriptor.addActionArg(i, Copy2S3Action.DEST, destBase + workPath);\n }\n }\n return descriptor;\n }\n\n @Override\n public void onRuleExecutorExit(RuleInfo ruleInfo) {\n srcBases = null;\n }\n}", "public class FileCopyDrPlugin implements RuleExecutorPlugin {\n private MetaStore metaStore;\n private Map<Long, List<BackUpInfo>> backups = new HashMap<>();\n private static final Logger LOG =\n LoggerFactory.getLogger(FileCopyDrPlugin.class.getName());\n\n public FileCopyDrPlugin(MetaStore metaStore) {\n this.metaStore = metaStore;\n }\n\n public void onNewRuleExecutor(final RuleInfo ruleInfo, TranslateResult tResult) {\n long ruleId = ruleInfo.getId();\n List<String> pathsCheckGlob = tResult.getGlobPathCheck();\n if (pathsCheckGlob.size() == 0) {\n pathsCheckGlob = Arrays.asList(\"/*\");\n }\n List<String> pathsCheck = getPathMatchesList(pathsCheckGlob);\n String dirs = StringUtil.join(\",\", pathsCheck);\n CmdletDescriptor des = tResult.getCmdDescriptor();\n for (int i = 0; i < des.getActionSize(); i++) {\n if (des.getActionName(i).equals(\"sync\")) {\n\n List<String> statements = tResult.getSqlStatements();\n String before = statements.get(statements.size() - 1);\n String after = before.replace(\";\", \" UNION \" + referenceNonExists(tResult, pathsCheck));\n statements.set(statements.size() - 1, after);\n\n BackUpInfo backUpInfo = new BackUpInfo();\n backUpInfo.setRid(ruleId);\n backUpInfo.setSrc(dirs);\n String dest = des.getActionArgs(i).get(SyncAction.DEST);\n if (!dest.endsWith(\"/\")) {\n dest += \"/\";\n des.addActionArg(i, SyncAction.DEST, dest);\n }\n backUpInfo.setDest(dest);\n backUpInfo.setPeriod(tResult.getTbScheduleInfo().getEvery());\n\n des.addActionArg(i, SyncAction.SRC, dirs);\n\n LOG.debug(\"Rule executor added for sync rule {} src={} dest={}\", ruleInfo, dirs, dest);\n\n synchronized (backups) {\n if (!backups.containsKey(ruleId)) {\n backups.put(ruleId, new LinkedList<BackUpInfo>());\n }\n }\n\n List<BackUpInfo> infos = backups.get(ruleId);\n synchronized (infos) {\n try {\n metaStore.deleteBackUpInfo(ruleId);\n // Add base Sync tag\n FileDiff fileDiff = new FileDiff(FileDiffType.BASESYNC);\n fileDiff.setSrc(backUpInfo.getSrc());\n fileDiff.getParameters().put(\"-dest\", backUpInfo.getDest());\n metaStore.insertFileDiff(fileDiff);\n metaStore.insertBackUpInfo(backUpInfo);\n infos.add(backUpInfo);\n } catch (MetaStoreException e) {\n LOG.error(\"Insert backup info error:\" + backUpInfo, e);\n }\n }\n break;\n }\n }\n }\n\n private List<String> getPathMatchesList(List<String> paths) {\n List<String> ret = new ArrayList<>();\n for (String p : paths) {\n String dir = StringUtil.getBaseDir(p);\n if (dir == null) {\n continue;\n }\n ret.add(dir);\n }\n return ret;\n }\n\n private String referenceNonExists(TranslateResult tr, List<String> dirs) {\n String temp = \"SELECT src FROM file_diff WHERE \"\n + \"state = 0 AND diff_type IN (1,2) AND (%s);\";\n String srcs = \"src LIKE '\" + dirs.get(0) + \"%'\";\n for (int i = 1; i < dirs.size(); i++) {\n srcs += \" OR src LIKE '\" + dirs.get(i) + \"%'\";\n }\n return String.format(temp, srcs);\n }\n\n public boolean preExecution(final RuleInfo ruleInfo, TranslateResult tResult) {\n return true;\n }\n\n public List<String> preSubmitCmdlet(final RuleInfo ruleInfo, List<String> objects) {\n return objects;\n }\n\n public CmdletDescriptor preSubmitCmdletDescriptor(\n final RuleInfo ruleInfo, TranslateResult tResult, CmdletDescriptor descriptor) {\n return descriptor;\n }\n\n public void onRuleExecutorExit(final RuleInfo ruleInfo) {\n long ruleId = ruleInfo.getId();\n List<BackUpInfo> infos = backups.get(ruleId);\n if (infos == null) {\n return;\n }\n synchronized (infos) {\n try {\n if (infos.size() != 0) {\n infos.remove(0);\n }\n\n if (infos.size() == 0) {\n backups.remove(ruleId);\n metaStore.deleteBackUpInfo(ruleId);\n }\n } catch (MetaStoreException e) {\n LOG.error(\"Remove backup info error:\" + ruleInfo, e);\n }\n }\n }\n}", "public class RuleExecutor implements Runnable {\n private RuleManager ruleManager;\n private TranslateResult tr;\n private ExecutionContext ctx;\n private MetaStore adapter;\n private volatile boolean exited = false;\n private long exitTime;\n private Stack<String> dynamicCleanups = new Stack<>();\n private static final Logger LOG = LoggerFactory.getLogger(RuleExecutor.class.getName());\n\n private static Pattern varPattern = Pattern.compile(\"\\\\$([a-zA-Z_]+[a-zA-Z0-9_]*)\");\n private static Pattern callPattern =\n Pattern.compile(\"\\\\$@([a-zA-Z_]+[a-zA-Z0-9_]*)\\\\(([a-zA-Z_][a-zA-Z0-9_]*)?\\\\)\");\n\n public RuleExecutor(\n RuleManager ruleManager, ExecutionContext ctx, TranslateResult tr, MetaStore adapter) {\n this.ruleManager = ruleManager;\n this.ctx = ctx;\n this.tr = tr;\n this.adapter = adapter;\n }\n\n public TranslateResult getTranslateResult() {\n return tr;\n }\n\n private String unfoldSqlStatement(String sql) {\n return unfoldVariables(unfoldFunctionCalls(sql));\n }\n\n private String unfoldVariables(String sql) {\n String ret = sql;\n ctx.setProperty(\"NOW\", System.currentTimeMillis());\n Matcher m = varPattern.matcher(sql);\n while (m.find()) {\n String rep = m.group();\n String varName = m.group(1);\n String value = ctx.getString(varName);\n ret = ret.replace(rep, value);\n }\n return ret;\n }\n\n private String unfoldFunctionCalls(String sql) {\n String ret = sql;\n Matcher m = callPattern.matcher(sql);\n while (m.find()) {\n String rep = m.group();\n String funcName = m.group(1);\n String paraName = m.groupCount() == 2 ? m.group(2) : null;\n List<Object> params = tr.getParameter(paraName);\n String value = callFunction(funcName, params);\n ret = ret.replace(rep, value == null ? \"\" : value);\n }\n return ret;\n }\n\n public List<String> executeFileRuleQuery() {\n int index = 0;\n List<String> ret = new ArrayList<>();\n for (String sql : tr.getSqlStatements()) {\n sql = unfoldSqlStatement(sql);\n try {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Rule \" + ctx.getRuleId() + \" --> \" + sql);\n }\n if (index == tr.getRetSqlIndex()) {\n ret = adapter.executeFilesPathQuery(sql);\n } else {\n sql = sql.trim();\n if (sql.length() > 5) {\n adapter.execute(sql);\n }\n }\n index++;\n } catch (MetaStoreException e) {\n LOG.error(\"Rule \" + ctx.getRuleId() + \" exception\", e);\n return ret;\n }\n }\n\n while (!dynamicCleanups.empty()) {\n String sql = dynamicCleanups.pop();\n try {\n adapter.execute(sql);\n } catch (MetaStoreException e) {\n LOG.error(\"Rule \" + ctx.getRuleId() + \" exception\", e);\n }\n }\n return ret;\n }\n\n public String callFunction(String funcName, List<Object> parameters) {\n try {\n Method m = getClass().getMethod(funcName, List.class);\n String ret = (String) (m.invoke(this, parameters));\n return ret;\n } catch (Exception e) {\n LOG.error(\"Rule \" + ctx.getRuleId() + \" exception when call \" + funcName, e);\n return null;\n }\n }\n\n public String genVirtualAccessCountTableTopValue(List<Object> parameters) {\n genVirtualAccessCountTableValue(parameters, true);\n return null;\n }\n\n public String genVirtualAccessCountTableBottomValue(List<Object> parameters) {\n genVirtualAccessCountTableValue(parameters, false);\n return null;\n }\n\n private void genVirtualAccessCountTableValue(List<Object> parameters, boolean top) {\n List<Object> paraList = (List<Object>) parameters.get(0);\n String table = (String) parameters.get(1);\n String var = (String) parameters.get(2);\n Long num = (Long) paraList.get(1);\n String sql0 = String.format(\n \"SELECT %s(count) FROM ( SELECT * FROM %s ORDER BY count %sLIMIT %d ) AS %s_TMP;\",\n top ? \"min\" : \"max\", table, top ? \"DESC \" : \"\", num, table);\n Long count = null;\n try {\n count = adapter.queryForLong(sql0);\n } catch (MetaStoreException e) {\n LOG.error(\"Get \" + (top ? \"top\" : \"bottom\") + \" access count from table '\"\n + table + \"' error.\", e);\n }\n ctx.setProperty(var, count == null ? 0L : count);\n }\n\n public String genVirtualAccessCountTableTopValueOnStoragePolicy(List<Object> parameters) {\n genVirtualAccessCountTableValueOnStoragePolicy(parameters, true);\n return null;\n }\n\n public String genVirtualAccessCountTableBottomValueOnStoragePolicy(List<Object> parameters) {\n genVirtualAccessCountTableValueOnStoragePolicy(parameters, false);\n return null;\n }\n\n private void genVirtualAccessCountTableValueOnStoragePolicy(List<Object> parameters,\n boolean top) {\n List<Object> paraList = (List<Object>) parameters.get(0);\n String table = (String) parameters.get(1);\n String var = (String) parameters.get(2);\n Long num = (Long) paraList.get(1);\n String storage = ((String) paraList.get(2)).toUpperCase();\n String sqlsub;\n if (storage.equals(\"CACHE\")) {\n sqlsub = String.format(\"SELECT %s.fid, %s.count FROM %s LEFT JOIN cached_file ON \"\n + \"(%s.fid = cached_file.fid)\", table, table, table, table);\n } else {\n Integer id = null;\n try {\n id = adapter.getStoragePolicyID(storage);\n } catch (Exception e) {\n // Ignore\n }\n if (id == null) {\n id = -1; // safe return\n }\n sqlsub = String.format(\"SELECT %s.fid, %s.count FROM %s LEFT JOIN file ON \"\n + \"(%s.fid = file.fid) WHERE file.sid = %d\",\n table, table, table, table, id);\n }\n\n String sql0 = String.format(\n \"SELECT %s(count) FROM ( SELECT * FROM (%s) AS %s ORDER BY count %sLIMIT %d ) AS %s;\",\n top ? \"min\" : \"max\",\n sqlsub,\n table + \"_AL1_TMP\",\n top ? \"DESC \" : \"\",\n num,\n table + \"_AL2_TMP\");\n Long count = null;\n try {\n count = adapter.queryForLong(sql0);\n } catch (MetaStoreException e) {\n LOG.error(String.format(\"Get %s access count on storage [%s] from table '%s' error [%s].\",\n top ? \"top\" : \"bottom\", storage, table, sql0), e);\n }\n ctx.setProperty(var, count == null ? 0L : count);\n }\n\n public String genVirtualAccessCountTable(List<Object> parameters) {\n List<Object> paraList = (List<Object>) parameters.get(0);\n String newTable = (String) parameters.get(1);\n Long interval = (Long) paraList.get(0);\n String countFilter = \"\";\n List<String> tableNames = getAccessCountTablesDuringLast(interval);\n return generateSQL(tableNames, newTable, countFilter, adapter);\n }\n\n @VisibleForTesting\n static String generateSQL(\n List<String> tableNames, String newTable, String countFilter, MetaStore adapter) {\n String sqlFinal, sqlCreate;\n if (tableNames.size() <= 1) {\n String tableName = tableNames.size() == 0 ? \"blank_access_count_info\" : tableNames.get(0);\n sqlCreate = \"CREATE TABLE \" + newTable + \"(fid INTEGER NOT NULL, count INTEGER NOT NULL);\";\n try {\n adapter.execute(sqlCreate);\n } catch (MetaStoreException e) {\n LOG.error(\"Cannot create table \" + newTable, e);\n }\n sqlFinal = \"INSERT INTO \" + newTable + \" SELECT * FROM \" + tableName + \";\";\n } else {\n String sqlPrefix = \"SELECT fid, SUM(count) AS count FROM (\\n\";\n String sqlUnion = \"SELECT fid, count FROM \" + tableNames.get(0) + \" \\n\";\n for (int i = 1; i < tableNames.size(); i++) {\n sqlUnion += \"UNION ALL\\n\" + \"SELECT fid, count FROM \" + tableNames.get(i) + \" \\n\";\n }\n String sqlSufix = \") as tmp GROUP BY fid \";\n String sqlCountFilter =\n (countFilter == null || countFilter.length() == 0)\n ? \"\"\n : \"HAVING SUM(count) \" + countFilter;\n String sqlRe = sqlPrefix + sqlUnion + sqlSufix + sqlCountFilter;\n sqlCreate = \"CREATE TABLE \" + newTable + \"(fid INTEGER NOT NULL, count INTEGER NOT NULL);\";\n try {\n adapter.execute(sqlCreate);\n } catch (MetaStoreException e) {\n LOG.error(\"Cannot create table \" + newTable, e);\n }\n sqlFinal = \"INSERT INTO \" + newTable + \" SELECT * FROM (\" + sqlRe + \") temp;\";\n }\n return sqlFinal;\n }\n\n /**\n * @param lastInterval\n * @return\n */\n private List<String> getAccessCountTablesDuringLast(long lastInterval) {\n List<String> tableNames = new ArrayList<>();\n if (ruleManager == null || ruleManager.getStatesManager() == null) {\n return tableNames;\n }\n\n List<AccessCountTable> accTables = null;\n try {\n accTables = ruleManager.getStatesManager().getTablesInLast(lastInterval);\n } catch (MetaStoreException e) {\n LOG.error(\"Rule \" + ctx.getRuleId() + \" get access info tables exception\", e);\n }\n\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Rule \" + ctx.getRuleId() + \" got \" + accTables.size() + \" tables:\");\n int idx = 1;\n for (AccessCountTable t : accTables) {\n LOG.debug(\n idx + \". \" + (t.isEphemeral() ? \" [TABLE] \" : \" \") + t.getTableName() + \" \");\n }\n }\n\n if (accTables == null || accTables.size() == 0) {\n return tableNames;\n }\n\n for (AccessCountTable t : accTables) {\n tableNames.add(t.getTableName());\n if (t.isEphemeral()) {\n dynamicCleanups.push(\"DROP TABLE IF EXISTS \" + t.getTableName() + \";\");\n }\n }\n return tableNames;\n }\n\n @Override\n public void run() {\n long startCheckTime = System.currentTimeMillis();\n if (exited) {\n exitSchedule();\n }\n\n List<RuleExecutorPlugin> plugins = RuleExecutorPluginManager.getPlugins();\n\n long rid = ctx.getRuleId();\n try {\n if (ruleManager.isClosed()) {\n exitSchedule();\n }\n\n long endCheckTime;\n int numCmdSubmitted = 0;\n List<String> files = new ArrayList<>();\n\n RuleInfo info = ruleManager.getRuleInfo(rid);\n\n boolean doExec = true;\n for (RuleExecutorPlugin plugin : plugins) {\n doExec &= plugin.preExecution(info, tr);\n if (!doExec) {\n break;\n }\n }\n\n RuleState state = info.getState();\n if (exited\n || state == RuleState.DELETED\n || state == RuleState.FINISHED\n || state == RuleState.DISABLED) {\n exitSchedule();\n }\n TimeBasedScheduleInfo scheduleInfo = tr.getTbScheduleInfo();\n\n if (!scheduleInfo.isOnce() && scheduleInfo.getEndTime() != TimeBasedScheduleInfo.FOR_EVER) {\n boolean befExit = false;\n if (scheduleInfo.isOneShot()) {\n if (scheduleInfo.getSubScheduleTime() > scheduleInfo.getStartTime()) {\n befExit = true;\n }\n } else if (startCheckTime - scheduleInfo.getEndTime() > 0) {\n befExit = true;\n }\n\n if (befExit) {\n LOG.info(\"Rule \" + ctx.getRuleId() + \" exit rule executor due to time passed\");\n ruleManager.updateRuleInfo(rid, RuleState.FINISHED, System.currentTimeMillis(), 0, 0);\n exitSchedule();\n }\n }\n\n if (doExec) {\n files = executeFileRuleQuery();\n if (exited) {\n exitSchedule();\n }\n }\n endCheckTime = System.currentTimeMillis();\n if (doExec) {\n for (RuleExecutorPlugin plugin : plugins) {\n files = plugin.preSubmitCmdlet(info, files);\n }\n numCmdSubmitted = submitCmdlets(info, files);\n }\n ruleManager.updateRuleInfo(rid, null, System.currentTimeMillis(), 1, numCmdSubmitted);\n\n long endProcessTime = System.currentTimeMillis();\n if (endProcessTime - startCheckTime > 2000 || LOG.isDebugEnabled()) {\n LOG.warn(\n \"Rule \"\n + ctx.getRuleId()\n + \" execution took \"\n + (endProcessTime - startCheckTime)\n + \"ms. QueryTime = \"\n + (endCheckTime - startCheckTime)\n + \"ms, SubmitTime = \"\n + (endProcessTime - endCheckTime)\n + \"ms, fileNum = \"\n + numCmdSubmitted\n + \".\");\n }\n\n if (scheduleInfo.isOneShot()) {\n ruleManager.updateRuleInfo(rid, RuleState.FINISHED, System.currentTimeMillis(), 0, 0);\n exitSchedule();\n }\n\n if (endProcessTime + scheduleInfo.getEvery() > scheduleInfo.getEndTime()) {\n LOG.info(\"Rule \" + ctx.getRuleId() + \" exit rule executor due to finished\");\n ruleManager.updateRuleInfo(rid, RuleState.FINISHED, System.currentTimeMillis(), 0, 0);\n exitSchedule();\n }\n\n if (exited) {\n exitSchedule();\n }\n } catch (IOException e) {\n LOG.error(\"Rule \" + ctx.getRuleId() + \" exception\", e);\n }\n }\n\n private void exitSchedule() {\n // throw an exception\n exitTime = System.currentTimeMillis();\n exited = true;\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Rule \" + ctx.getRuleId() + \" exit rule executor.\");\n }\n String[] temp = new String[1];\n temp[1] += \"The exception is created deliberately\";\n }\n\n private int submitCmdlets(RuleInfo ruleInfo, List<String> files) {\n long ruleId = ruleInfo.getId();\n if (files == null || files.size() == 0 || ruleManager.getCmdletManager() == null) {\n return 0;\n }\n int nSubmitted = 0;\n List<RuleExecutorPlugin> plugins = RuleExecutorPluginManager.getPlugins();\n String template = tr.getCmdDescriptor().toCmdletString();\n for (String file : files) {\n if (!exited) {\n try {\n CmdletDescriptor cmd = new CmdletDescriptor(template, ruleId);\n cmd.setCmdletParameter(CmdletDescriptor.HDFS_FILE_PATH, file);\n for (RuleExecutorPlugin plugin : plugins) {\n cmd = plugin.preSubmitCmdletDescriptor(ruleInfo, tr, cmd);\n }\n ruleManager.getCmdletManager().submitCmdlet(cmd);\n nSubmitted++;\n } catch (QueueFullException e) {\n break;\n } catch (IOException e) {\n // it's common here, ignore this and continue submit\n LOG.debug(\"Failed to submit cmdlet for file: \" + file, e);\n } catch (ParseException e) {\n LOG.error(\"Failed to submit cmdlet for file: \" + file, e);\n }\n } else {\n break;\n }\n }\n return nSubmitted;\n }\n\n public boolean isExited() {\n return exited;\n }\n\n public void setExited() {\n exitTime = System.currentTimeMillis();\n exited = true;\n }\n\n public long getExitTime() {\n return exitTime;\n }\n}" ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smartdata.AbstractService; import org.smartdata.action.ActionRegistry; import org.smartdata.conf.SmartConfKeys; import org.smartdata.metastore.MetaStore; import org.smartdata.metastore.MetaStoreException; import org.smartdata.model.CmdletDescriptor; import org.smartdata.model.DetailedRuleInfo; import org.smartdata.model.RuleInfo; import org.smartdata.model.RuleState; import org.smartdata.model.rule.RuleExecutorPluginManager; import org.smartdata.model.rule.RulePluginManager; import org.smartdata.model.rule.TimeBasedScheduleInfo; import org.smartdata.model.rule.TranslateResult; import org.smartdata.rule.parser.SmartRuleStringParser; import org.smartdata.rule.parser.TranslationContext; import org.smartdata.server.engine.rule.ExecutorScheduler; import org.smartdata.server.engine.rule.FileCopy2S3Plugin; import org.smartdata.server.engine.rule.FileCopyDrPlugin; import org.smartdata.server.engine.rule.RuleExecutor; import org.smartdata.server.engine.rule.RuleInfoRepo; import org.smartdata.server.engine.rule.SmallFilePlugin; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentHashMap;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartdata.server.engine; /** * Manage and execute rules. We can have 'cache' here to decrease the needs to execute a SQL query. */ public class RuleManager extends AbstractService { private ServerContext serverContext; private StatesManager statesManager; private CmdletManager cmdletManager; private MetaStore metaStore; private boolean isClosed = false; public static final Logger LOG = LoggerFactory.getLogger(RuleManager.class.getName()); private ConcurrentHashMap<Long, RuleInfoRepo> mapRules = new ConcurrentHashMap<>(); public ExecutorScheduler execScheduler; public RuleManager( ServerContext context, StatesManager statesManager, CmdletManager cmdletManager) { super(context); int numExecutors = context .getConf() .getInt( SmartConfKeys.SMART_RULE_EXECUTORS_KEY, SmartConfKeys.SMART_RULE_EXECUTORS_DEFAULT); execScheduler = new ExecutorScheduler(numExecutors); this.statesManager = statesManager; this.cmdletManager = cmdletManager; this.serverContext = context; this.metaStore = context.getMetaStore(); RuleExecutorPluginManager.addPlugin(new FileCopyDrPlugin(context.getMetaStore()));
RuleExecutorPluginManager.addPlugin(new FileCopy2S3Plugin());
5
amao12580/BookmarkHelper
app/src/main/java/pro/kisscat/www/bookmarkhelper/converter/support/impl/chrome/impl/xingchen/XingchenBrowserAble.java
[ "public class ChromeBrowserAble extends BasicBrowser {\n public String TAG = null;\n\n protected List<Bookmark> fetchBookmarks(java.io.File file) throws FileNotFoundException {\n JSONReader jsonReader = null;\n List<Bookmark> result = new LinkedList<>();\n try {\n jsonReader = new JSONReader(new FileReader(file));\n ChromeBookmark chromeBookmark = jsonReader.readObject(ChromeBookmark.class);\n if (chromeBookmark == null) {\n LogHelper.v(\"chromeBookmark is null.\");\n return result;\n }\n File fileShow = FileUtil.formatFileSize(file);\n if (fileShow.isOver10KB()) {\n LogHelper.v(\"书签数据文件大小超过10KB,skip print.size:\" + fileShow.toString());\n } else {\n LogHelper.v(\"书签数据:\" + JsonUtil.toJson(chromeBookmark));\n }\n List<Bookmark> bookmarks = chromeBookmark.fetchAll();\n if (bookmarks == null) {\n LogHelper.v(\"bookmarks is null.\");\n return result;\n }\n LogHelper.v(\"书签条数:\" + bookmarks.size());\n return bookmarks;\n } catch (Exception e) {\n e.printStackTrace();\n throw e;\n } finally {\n if (jsonReader != null) {\n jsonReader.close();\n }\n }\n }\n}", "public class Bookmark {\n @Getter\n @Setter\n private String title;\n @Getter\n @Setter\n private String url;\n @Getter\n @Setter\n private String folder;\n\n// public boolean equals(Object anObject) {\n// if (this == anObject) {\n// return true;\n// }\n// if (anObject instanceof Bookmark) {\n// Bookmark anotherBookmark = (Bookmark) anObject;\n// if (getUrl() == anotherBookmark.getUrl()) {\n// return true;\n// }\n// }\n// return false;\n// }\n}", "public class DBHelper {\n /**\n * read-only\n */\n public synchronized static SQLiteDatabase openReadOnlyDatabase(String dbFilePath) {\n return openDatabase(dbFilePath, true);\n }\n\n /**\n * read-write\n */\n public synchronized static SQLiteDatabase openDatabase(String dbFilePath) {\n return openDatabase(dbFilePath, false);\n }\n\n private static SQLiteDatabase openDatabase(String dbFilePath, boolean isReadOnly) {\n try {\n return SQLiteDatabase.openDatabase(dbFilePath, null, isReadOnly ? SQLiteDatabase.OPEN_READONLY : SQLiteDatabase.OPEN_READWRITE);\n } catch (Exception e) {\n LogHelper.w(\"first open \" + (isReadOnly ? \"read-only\" : \"read-write\") + \" database error,will try agin later.\");\n LogHelper.e(e);\n e.printStackTrace();\n try {\n int sleep = 50 + RandomUtil.nextInt(50);\n LogHelper.v(\"sleep:\" + sleep);\n Thread.sleep(sleep);\n } catch (InterruptedException e1) {\n LogHelper.e(\"got a interruptedException.\");\n LogHelper.e(e1);\n e1.printStackTrace();\n return null;\n }\n LogHelper.v(\"sleep completed,try agin begining.\");\n try {\n return SQLiteDatabase.openDatabase(dbFilePath, null, SQLiteDatabase.OPEN_READWRITE);\n } catch (Exception e1) {\n LogHelper.e(\"second open \" + (isReadOnly ? \"read-only\" : \"read-write\") + \" database error,will throw exception.\" + e1.getMessage());\n LogHelper.e(e1);\n e1.printStackTrace();\n throw e1;\n }\n }\n }\n\n /**\n * if table exists\n */\n public static boolean checkTableExist(SQLiteDatabase sqLiteDatabase, String tableName) {\n if (sqLiteDatabase == null) {\n LogHelper.e(\"checkTableExist.sqLiteDatabase is null.\");\n return false;\n }\n if (tableName == null || tableName.isEmpty()) {\n LogHelper.e(\"checkTableExist.tableName is isEmpty.\");\n return false;\n }\n Cursor cursor = sqLiteDatabase.rawQuery(\"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='\" + tableName + \"'\", null);\n if (cursor.moveToNext()) {\n int count = cursor.getInt(0);\n if (count > 0) {\n return true;\n }\n }\n cursor.close();\n return false;\n }\n}", "public class Path {\n public final static String FILE_SPLIT = File.separator;\n\n private static final String INNER_PATH_ROOT = FILE_SPLIT + \"data\";\n public static final String INNER_PATH_DATA = INNER_PATH_ROOT + INNER_PATH_ROOT + FILE_SPLIT;\n public static String SDCARD_ROOTPATH = \"\";\n public static final String SDCARD_APP_ROOTPATH = FILE_SPLIT + \"BookmarkHelper\" + FILE_SPLIT;\n public static final String SDCARD_LOG_ROOTPATH = \"logs\" + FILE_SPLIT;\n public static final String SDCARD_TMP_ROOTPATH = \"tmp\" + FILE_SPLIT;\n}", "public class LogHelper {\n private static String LOG_DIR = Path.SDCARD_APP_ROOTPATH + Path.SDCARD_LOG_ROOTPATH;// 日志聚集的目录名\n private static String MYLOG_PATH_SDCARD_DIR = null;// 日志文件在sdcard中的路径\n private static int SDCARD_LOG_FILE_SAVE_DAYS = 30;// sd卡中日志文件的最多保存天数\n private static String MYLOGFILEName = \"Log.txt\";// 本类输出的日志文件名称\n private static SimpleDateFormat myLogSdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSS\");// 日志的输出格式\n private static SimpleDateFormat logfile = new SimpleDateFormat(\"yyyy-MM-dd\");// 日志文件格式\n\n private static ConcurrentLinkedQueue<LogEntry> logQueue = new ConcurrentLinkedQueue<>();\n\n public static void v(String msg) {\n v(MetaData.LOG_V_DEFAULT, msg);\n }\n\n public static void w(Object msg) { // 警告信息\n log(MetaData.LOG_W_DEFAULT, msg.toString(), 'w');\n }\n\n public static void w(String tag, Object msg) { // 警告信息\n log(tag, msg.toString(), 'w');\n }\n\n public static void e(Throwable throwable) { // 错误信息\n e(MetaData.LOG_E_DEFAULT, printException(throwable));\n }\n\n public static void e(String tag, Throwable throwable) { // 错误信息\n log(tag, printException(throwable), 'e');\n }\n\n private static String printException(Throwable throwable) {\n String msg = null;\n Writer result = null;\n PrintWriter printWriter = null;\n try {\n result = new StringWriter();\n printWriter = new PrintWriter(result);\n throwable.printStackTrace(printWriter);\n msg = result.toString();\n } finally {\n if (printWriter != null) {\n printWriter.flush();\n printWriter.close();\n }\n if (result != null) {\n try {\n result.flush();\n result.close();\n } catch (IOException e) {\n LogHelper.e(\"printException finally IOException:\" + e.getMessage());\n LogHelper.write();\n e.printStackTrace();\n }\n }\n }\n return msg == null ? \"\" : msg;\n }\n\n public static void d(String tag, Object msg) {// 调试信息\n log(tag, msg.toString(), 'd');\n }\n\n public static void i(String tag, Object msg) {//\n log(tag, msg.toString(), 'i');\n }\n\n public static void v(String tag, Object msg) {\n v(tag, msg.toString(), true);\n }\n\n public static void v(String msg, boolean trim) {\n v(MetaData.LOG_V_DEFAULT, msg, trim);\n }\n\n public static void w(String tag, String text) {\n log(tag, text, 'w');\n }\n\n public static void e(String tag, String text) {\n log(tag, text, 'e');\n }\n\n public static void e(String text) {\n e(MetaData.LOG_E_DEFAULT, text);\n }\n\n public static void d(String tag, String text) {\n log(tag, text, 'd');\n }\n\n public static void i(String tag, String text) {\n log(tag, text, 'i');\n }\n\n public static void v(String tag, String text, boolean trim) {\n if (text == null || text.isEmpty()) {\n return;\n }\n if (!BuildConfig.DEBUG && trim && text.length() > 1024) {\n text = text.substring(0, 1024);\n text += \"...\";\n }\n if (BuildConfig.DEBUG) {\n System.out.println(\"v \" + tag + \" \" + text);\n } else {\n log(tag, text, 'v');\n }\n }\n\n /**\n * 根据tag, msg和等级,输出日志\n */\n private static void log(String tag, String msg, char level) {\n recordLogToQueue(String.valueOf(level), tag, msg);\n }\n\n public static void write() {\n if (!logQueue.isEmpty() && !WriteThread.isWriteThreadRuning) {//监察写线程是否工作中,没有 则创建\n new WriteThread().start();\n }\n }\n\n private static void recordLogToQueue(String level, String tag, String text) {\n logQueue.add(new LogEntry(level, tag, text));\n write();\n }\n\n /**\n * 打开日志文件并写入日志\n **/\n synchronized static void flush() {// 新建或打开日志文件\n if (logQueue.isEmpty()) {\n return;\n }\n if (!isInit()) {\n init();\n if (!isInit()) {\n System.out.println(\"LogHelper init not work.\");\n return;\n }\n }\n FileWriter filerWriter = null;\n BufferedWriter bufWriter = null;\n try {\n while (!logQueue.isEmpty()) {\n LogEntry logEntry = logQueue.poll();\n if (logEntry == null) {\n break;\n }\n Date recordTime = logEntry.getTime();\n String needWriteFile = logfile.format(recordTime);\n String needWriteMessage = myLogSdf.format(recordTime) + \" \" + logEntry.getLevel() + \" \" + logEntry.getTag() + \" \" + logEntry.getText();\n File dir = new File(MYLOG_PATH_SDCARD_DIR);\n dir.mkdirs();\n File file = new File(MYLOG_PATH_SDCARD_DIR, needWriteFile + MYLOGFILEName);\n if (!file.exists()) {\n if (file.createNewFile()) {\n file.setReadable(true);\n file.setWritable(true);\n } else {\n file.createNewFile();\n }\n filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖\n bufWriter = new BufferedWriter(filerWriter);\n }\n if (filerWriter == null) {\n filerWriter = new FileWriter(file, true);\n bufWriter = new BufferedWriter(filerWriter);\n }\n bufWriter.write(needWriteMessage);\n bufWriter.newLine();\n }\n if (bufWriter != null) {\n bufWriter.flush();\n bufWriter.close();\n }\n if (filerWriter != null) {\n filerWriter.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (bufWriter != null) {\n try {\n bufWriter.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (filerWriter != null) {\n try {\n filerWriter.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n /**\n * 删除指定的日志文件\n */\n public static void delFile() {// 删除日志文件\n String needDelFiel = logfile.format(getDateBefore());\n File file = new File(MYLOG_PATH_SDCARD_DIR, needDelFiel + MYLOGFILEName);\n if (file.exists()) {\n file.delete();\n }\n }\n\n /**\n * 得到现在时间前的几天日期,用来得到需要删除的日志文件名\n */\n private static Date getDateBefore() {\n Date nowtime = new Date();\n Calendar now = Calendar.getInstance();\n now.setTime(nowtime);\n now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS);\n return now.getTime();\n }\n\n private static boolean isSuccessInit = false;\n\n private static boolean isInit() {\n return isSuccessInit;\n }\n\n\n public static void init() {\n String exPath = new ExternalStorageUtil().getRootPath();\n String inPath = new InternalStorageUtil().getRootPath();\n if (exPath != null && !exPath.isEmpty()) {\n Path.SDCARD_ROOTPATH = exPath;\n } else if (inPath != null && !inPath.isEmpty()) {\n Path.SDCARD_ROOTPATH = inPath;\n } else {\n throw new IllegalArgumentException(\"无法获取日志目录\");\n }\n MYLOG_PATH_SDCARD_DIR = Path.SDCARD_ROOTPATH + LOG_DIR;\n File appDirectory = new File(MYLOG_PATH_SDCARD_DIR);\n if (!appDirectory.exists()) {\n appDirectory.mkdir();\n }\n isSuccessInit = true;\n }\n}", "public final class ExternalStorageUtil extends BasicStorageUtil {\n /**\n * 获取外置SD卡路径\n */\n @Override\n public String getRootPath() {\n List<String> lResult = new ArrayList<>();\n try {\n Runtime rt = Runtime.getRuntime();\n Process proc = rt.exec(\"mount\");\n InputStream is = proc.getInputStream();\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr);\n String line;\n while ((line = br.readLine()) != null) {\n if (line.contains(\"extSdCard\")) {\n String[] arr = line.split(\" \");\n String path = arr[1];\n File file = new File(path);\n if (file.isDirectory()) {\n lResult.add(path);\n }\n }\n }\n isr.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return lResult.isEmpty() ? null : lResult.get(0);\n }\n\n /**\n * 拷贝文件\n * <p>\n * 借用root权限\n * <p>\n * 可以读写系统文件\n * <p>\n * root\n */\n public static File copyFile(String source, String target, String mark) {\n /**\n * -f 强制覆盖,不询问yes/no(-i的默认的,即默认为交互模式,询问是否覆盖)\n * -r 递归复制,包含目录\n * -a 做一个备份,这里可以不用这个参数,我们可以先备份整个test目录\n * -p 保持新文件的属性不变\n */\n String cmd = \"cp -fr \" + source + \" \" + target;\n boolean result = RootUtil.executeCmd(cmd, true);\n if (!result) {\n throw new ConverterException(ContextUtil.buildFileCPErrorMessage(mark));\n }\n if (!isExistFile(target)) {\n throw new ConverterException(ContextUtil.buildFileCPErrorMessage(mark));\n }\n return new File(target);\n }\n\n public static void mkdir(String dirPath, String mark) {\n mkdir(dirPath, mark, true);\n }\n\n public static boolean remountSDCardDir() {\n boolean readWriteAble = checkReadWriteAble(Path.SDCARD_ROOTPATH + Path.SDCARD_APP_ROOTPATH);\n LogHelper.v(\"remountSDCardDir 读写权限检查结果:\" + readWriteAble);\n if (readWriteAble) {\n return true;\n }\n String command = \"mount -o remount, rw /sdcard\";\n boolean ret = RootUtil.executeCmd(command);\n if (!ret) {\n //记录mount信息\n command = \"mount\";\n RootUtil.executeCmd(command);\n return false;\n }\n boolean readWriteAbleAgin = checkReadWriteAble(Path.SDCARD_ROOTPATH + Path.SDCARD_APP_ROOTPATH);\n LogHelper.v(\"readWriteAbleAgin 读写权限检查结果:\" + readWriteAbleAgin);\n return readWriteAbleAgin;\n }\n}", "public final class InternalStorageUtil extends BasicStorageUtil {\n /**\n * 获取内置SD卡路径\n */\n @Override\n public String getRootPath() {\n java.io.File sdDir = null;\n boolean sdCardExist = Environment.getExternalStorageState()\n .equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在\n if (sdCardExist) {\n sdDir = Environment.getExternalStorageDirectory();//获取根目录\n }\n return sdDir == null ? null : sdDir.toString();\n }\n\n /**\n * 删除文件\n * <p>\n * 失败后重试一次\n * <p>\n * 借用root权限\n * <p>\n */\n public static boolean deleteFile(String filePath, String mark) {\n return deleteFile(true, filePath, mark);\n }\n\n private static boolean deleteFile(boolean needRetry, String filePath, String mark) {\n String cmd = \"rm -rf \" + filePath;\n boolean result = RootUtil.executeCmd(cmd);\n if (!result) {\n if (needRetry) {\n boolean retry = deleteFile(false, filePath, mark);\n if (!retry) {\n throw new ConverterException(ContextUtil.buildFileDeleteErrorMessage(mark));\n }\n } else {\n throw new ConverterException(ContextUtil.buildFileDeleteErrorMessage(mark));\n }\n }\n return true;\n }\n\n /**\n * 列出dir下的所有dir\n */\n public static List<String> lsDir(String dir) {\n try {\n StringBuilder command = new StringBuilder(\"ls \");\n if (dir == null || dir.isEmpty()) {\n //不指定dir可能造成命令过量输出,refuse\n return null;\n }\n command.append(dir);\n CommandResult commandResult = RootUtil.executeCmd(new String[]{command.toString()}, false);\n if (commandResult != null && commandResult.isSuccess()) {\n return commandResult.getSuccessMsg();\n }\n return null;\n } catch (Exception e) {\n LogHelper.e(e.getMessage());\n return null;\n }\n }\n\n /**\n * 列出文件夹下,所有文件名称符合regularRule规则的文件。regularRule为null是,列出全部\n * <p>\n * 不能用find、locate等高级命令,android shell bash 自身是一个裁剪版linux,不支持\n * <p>\n * 不能用高级特性,ls -t -au等,不支持\n */\n public static List<String> lsFileAndSortByRegular(String dir, String regularRule) {\n return lsFileByRegular(dir, regularRule, true);\n }\n\n private static List<String> lsFileByRegular(String dir, String regularRule, boolean needSort) {\n try {\n StringBuilder command = new StringBuilder(\"ls \");\n if (dir == null || dir.isEmpty()) {\n //不指定dir可能造成命令过量输出,refuse\n return null;\n }\n command.append(dir);\n if (regularRule != null && !regularRule.isEmpty()) {\n command.append(regularRule);\n }\n command.append(\" -l\");\n CommandResult commandResult = RootUtil.executeCmd(new String[]{command.toString()}, false);\n if (commandResult != null && commandResult.isSuccess()) {\n if (needSort) {\n return parseFileAndSortByFileChangeTimeDesc(commandResult.getSuccessMsg());\n } else {\n return parseFile(commandResult.getSuccessMsg());\n }\n }\n return null;\n } catch (Exception e) {\n LogHelper.e(e.getMessage());\n return null;\n }\n }\n\n private static List<String> parseFile(List<String> fileProperty) {\n if (fileProperty == null || fileProperty.isEmpty()) {\n return null;\n }\n List<File> files = new LinkedList<>();\n for (String item : fileProperty) {\n if (item == null) {\n continue;\n }\n String[] property = item.split(\" \");\n if (property.length == 0) {\n continue;\n }\n files.add(new File(property));\n }\n if (files.isEmpty()) {\n return null;\n }\n List<String> result = new LinkedList<>();\n if (files.size() == 1) {\n result.add(files.get(0).getNameWithSuffix());\n return result;\n }\n for (File item : files) {\n result.add(item.getNameWithSuffix());\n }\n return result;\n }\n\n /**\n * 将文件以修改时间进行倒序排序后返回\n */\n private static List<String> parseFileAndSortByFileChangeTimeDesc(List<String> fileProperty) {\n List<String> files = parseFile(fileProperty);\n Collections.sort(files);\n return files;\n }\n\n public static boolean remountDataDir() {\n return remountDataDir(false);\n }\n\n private static boolean isReadOnlyNow = true;\n\n /**\n * 重新挂载data目录为读写或只读\n */\n private static boolean remountDataDir(boolean isNeedReadOnly) {\n boolean readWriteable = checkReadWriteAble(Path.INNER_PATH_DATA + AppListUtil.thisAppPackageName + Path.FILE_SPLIT);\n LogHelper.v(\"remountDataDir 读写权限检查结果:\" + readWriteable);\n if (readWriteable) {\n return true;\n }\n String command;\n if (isNeedReadOnly) {\n// if (isReadOnlyNow) {\n// LogHelper.v(\"unnecessary remount.isReadOnlyNow:\" + isReadOnlyNow + \",isNeedReadOnly:\" + isNeedReadOnly);\n// return;\n// } else {\n command = \"mount -o remount, ro /data\";\n// }\n } else {\n// if (!isReadOnlyNow) {\n// LogHelper.v(\"unnecessary remount.isReadOnlyNow:\" + isReadOnlyNow + \",isNeedReadOnly:\" + isNeedReadOnly);\n// return;\n// } else {\n command = \"mount -o remount, rw /data\";\n// }\n }\n boolean ret = RootUtil.executeCmd(command);\n if (isNeedReadOnly) {\n if (ret) {\n isReadOnlyNow = true;\n }\n } else {\n if (ret) {\n isReadOnlyNow = false;\n }\n }\n if (!ret) {\n //记录mount信息\n command = \"mount\";\n RootUtil.executeCmd(command);\n //尝试挂载根目录为读写\n command = \"mount -o remount, rw /\";\n RootUtil.executeCmd(command);\n return false;\n }\n LogHelper.v(\"isReadOnlyNow:\" + isReadOnlyNow + \",isNeedReadOnly:\" + isNeedReadOnly);\n return true;\n }\n}" ]
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.List; import pro.kisscat.www.bookmarkhelper.converter.support.impl.chrome.ChromeBrowserAble; import pro.kisscat.www.bookmarkhelper.entry.app.Bookmark; import pro.kisscat.www.bookmarkhelper.database.SQLite.DBHelper; import pro.kisscat.www.bookmarkhelper.util.Path; import pro.kisscat.www.bookmarkhelper.util.log.LogHelper; import pro.kisscat.www.bookmarkhelper.util.storage.ExternalStorageUtil; import pro.kisscat.www.bookmarkhelper.util.storage.InternalStorageUtil;
package pro.kisscat.www.bookmarkhelper.converter.support.impl.chrome.impl.xingchen; /** * Created with Android Studio. * Project:BookmarkHelper * User:ChengLiang * Mail:[email protected] * Date:2016/12/8 * Time:17:54 * <p> * 星尘浏览器 */ public class XingchenBrowserAble extends ChromeBrowserAble { protected List<Bookmark> fetchBookmarksByHomePage(String filePath_origin, String filePath_cp) { String origin_dir = filePath_origin + Path.FILE_SPLIT + "databases" + Path.FILE_SPLIT; String fileUserDBName_origin = "useraction.db"; String origin_file = origin_dir + fileUserDBName_origin; String cp_file = filePath_cp + fileUserDBName_origin; LogHelper.v(TAG + ":开始读取已登录用户的书签sqlite数据库:" + origin_dir); List<Bookmark> result = new LinkedList<>(); LogHelper.v(TAG + ":origin file path:" + origin_file); LogHelper.v(TAG + ":tmp file path:" + cp_file); try { ExternalStorageUtil.copyFile(origin_file, cp_file, this.getName()); } catch (Exception e) { LogHelper.e(e.getMessage()); return result; } SQLiteDatabase sqLiteDatabase = null; Cursor cursor = null; String tableName = "ntp"; boolean tableExist; String[] columns = new String[]{"title", "url", "timestamp"}; try { sqLiteDatabase = DBHelper.openReadOnlyDatabase(cp_file); tableExist = DBHelper.checkTableExist(sqLiteDatabase, tableName); if (!tableExist) { LogHelper.v(TAG + ":database table " + tableName + " not exist."); return result; } cursor = sqLiteDatabase.query(false, tableName, columns, null, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { while (cursor.moveToNext()) { long timestamp = cursor.getLong(cursor.getColumnIndex("timestamp")); if (timestamp > 0) { Bookmark item = new Bookmark(); item.setTitle(cursor.getString(cursor.getColumnIndex("title"))); item.setUrl(cursor.getString(cursor.getColumnIndex("url"))); result.add(item); } } } } finally { if (cursor != null) { cursor.close(); } if (sqLiteDatabase != null) { sqLiteDatabase.close(); } } LogHelper.v(TAG + ":读取已登录用户书签sqlite数据库结束"); return result; } protected List<Bookmark> fetchBookmarks(String originPathDir, String originFileName, String cpPath) { List<Bookmark> result = new LinkedList<>(); String originFilePathFull = originPathDir + originFileName;
if (InternalStorageUtil.isExistFile(originFilePathFull)) {
6
researchgate/restler
restler-service/src/main/java/net/researchgate/restler/service/resources/AccountResource.java
[ "public class RestDslException extends RuntimeException {\n //TODO: generialize types, rethink them.\n // TODO: need something like generic conflict state\n public enum Type {\n // DB constraint violation\n DUPLICATE_KEY,\n\n // Entity provided is not valid\n ENTITY_ERROR,\n\n // Unknown or implementation error\n GENERAL_ERROR,\n\n // params supplied via HTTP are invalid\n PARAMS_ERROR,\n\n // Service query contains errors\n QUERY_ERROR\n }\n\n // default type\n private Type type = Type.GENERAL_ERROR;\n\n public RestDslException(String message) {\n super(message);\n }\n\n public RestDslException(String message, Type type) {\n super(message);\n this.type = type;\n }\n\n public RestDslException(String message, Throwable cause, Type type) {\n super(message, cause);\n this.type = type;\n }\n\n public Type getType() {\n return type;\n }\n\n}", "public interface ServiceQueryParams {\n ServiceQueryParams ALL_QUERY_PARAMS =\n ServiceQueryParamsImpl.builder().defaultLimit(Integer.MAX_VALUE).defaultFields(Sets.newHashSet(\"*\")).build();\n\n ServiceQueryParams DEFAULT_QUERY_PARAMS =\n ServiceQueryParamsImpl.builder().defaultLimit(100).defaultFields(Sets.newHashSet(\"*\")).build();\n\n int getDefaultLimit();\n Set<String> getDefaultFields();\n Multimap<String, Object> getDefaultCriteria();\n}", "public class ServiceQueryParamsImpl implements ServiceQueryParams{\n private int defaultLimit = 10000;\n private Set<String> defaultFields;\n private Multimap<String, Object> defaultCriteria;\n\n @Override\n public int getDefaultLimit() {\n return defaultLimit;\n }\n\n @Override\n public Set<String> getDefaultFields() {\n return defaultFields;\n }\n\n @Override\n public Multimap<String, Object> getDefaultCriteria() {\n return defaultCriteria;\n }\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n ServiceQueryParamsImpl params = new ServiceQueryParamsImpl();\n\n private Builder() {\n }\n\n public Builder defaultLimit(int defaultLimit) {\n params.defaultLimit = defaultLimit;\n return this;\n }\n\n public Builder defaultFields(Set<String> defaultFields) {\n params.defaultFields = Collections.unmodifiableSet(defaultFields);\n return this;\n }\n\n public Builder defaultCriteria(Multimap<String, Object> defaultCriteria) {\n params.defaultCriteria = defaultCriteria;\n return this;\n }\n\n public Builder addDefaultCriteriaItem(String key, Iterable<Object> values) {\n if (params.defaultCriteria == null) {\n params.defaultCriteria = ArrayListMultimap.create();\n }\n params.defaultCriteria.putAll(key, values);\n return this;\n }\n\n public ServiceQueryParams build() {\n return params;\n }\n\n }\n\n @Override\n public String toString() {\n return \"ServiceQueryParamsImpl{\" +\n \"defaultLimit=\" + defaultLimit +\n \", defaultFields=\" + defaultFields +\n \", defaultCriteria=\" + defaultCriteria +\n '}';\n }\n}", "public abstract class ServiceResource<V, K> extends BaseServiceResource<V, K> {\n private final ServiceModel<V, K> serviceModel;\n\n public ServiceResource(ServiceModel<V, K> serviceModel, Class<V> entityClazz, Class<K> idClazz) {\n super(serviceModel, entityClazz, idClazz);\n this.serviceModel = serviceModel;\n }\n\n @POST\n public Response createEntity(V entity, @Context UriInfo uriInfo) throws RestDslException {\n validatePostEntity(entity);\n V persisted = serviceModel.save(entity);\n return Response.status(CREATED).entity(persisted).build();\n }\n\n @PATCH\n public V patchEntity(V entity, @Context UriInfo uriInfo) throws RestDslException {\n validatePatchEntity(entity);\n return serviceModel.patch(entity, RequestUtil.getPatchContext(uriInfo));\n }\n\n @Path(PATH_SEGMENT_PATTERN)\n @PUT\n public Response updateEntity(@PathParam(\"segment\") String id, V entity, @Context UriInfo uriInfo) throws RestDslException {\n K key = getId(id);\n if (key == null) {\n throw new RestDslException(\"Key cannot be null\", RestDslException.Type.PARAMS_ERROR);\n }\n validatePut(key, entity);\n\n entityInfo.setIdFieldValue(entity, key);\n V persisted = serviceModel.save(entity);\n return Response.status(OK).entity(persisted).build();\n }\n\n @Path(PATH_SEGMENT_PATTERN)\n @DELETE\n @Produces(\"application/json;charset=UTF-8\")\n public Response delete(@PathParam(\"segment\") PathSegment segment, @Context UriInfo uriInfo) throws RestDslException {\n ServiceQuery<K> query = getQueryFromRequest(segment, uriInfo);\n int deleted = serviceModel.delete(query);\n return Response.ok().entity(new BasicDBObject(\"deleted\", deleted).toString()).build();\n }\n\n protected void validatePostEntity(V entity) throws RestDslException {\n // override if you need extra validation\n }\n\n protected void validatePatchEntity(V entity) throws RestDslException {\n K val = entityInfo.getIdFieldValue(entity);\n if (val == null) {\n throw new RestDslException(\"Id must be provided when patching an entity, but was null\", RestDslException.Type.ENTITY_ERROR);\n }\n }\n\n protected void validatePut(K key, V entity) throws RestDslException {\n K val = entityInfo.getIdFieldValue(entity);\n if (val != null && !val.equals(key)) {\n throw new RestDslException(\"Id either should not be provided or be equal to the one in the entity, \" +\n \"but was: \" + val + \" vs \" + key, RestDslException.Type.ENTITY_ERROR);\n }\n }\n}", "@Entity(\"accounts\")\n @Indexes({\n @Index(fields = @Field(\"rating\")),\n// @Index(fields = @Field(\"deleted\")),\n @Index(fields = {@Field(\"stats.scoreBreakdown\"), @Field(value = \"rating\", type = IndexType.DESC)}),\n @Index(fields = @Field(\"nickname\"))\n })\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class Account {\n\n @Id\n @JsonSerialize(using = ObjectIdSerializer.class)\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonDeserialize(using = ObjectIdDeserializer.class)\n private ObjectId id;\n\n private List<Long> publicationUids;\n\n private Boolean deleted;\n\n private List<Publication> publications;\n\n @JsonSerialize(using = ObjectIdSerializer.class)\n @JsonDeserialize(using = ObjectIdDeserializer.class)\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private ObjectId mentorAccountId;\n\n private String newFiled;\n\n private String oldField;\n\n private Long rating;\n\n private AccountState state;\n\n @JsonSerialize(using = Rfc3339DateSerializer.class)\n @JsonDeserialize(using = Rfc3339DateDeserializer.class)\n @Property(\"cd\")\n private Date createdAt;\n\n @JsonSerialize(using = Rfc3339DateSerializer.class)\n @JsonDeserialize(using = Rfc3339DateDeserializer.class)\n @Property(\"ud\")\n private Date modifiedAt;\n\n private Date longDate;\n\n private AccountStats stats;\n\n private List<AccountStats> additionalStats;\n\n private String nickname;\n\n public ObjectId getId() {\n return id;\n }\n\n public void setId(ObjectId id) {\n this.id = id;\n }\n\n public List<Long> getPublicationUids() {\n return publicationUids;\n }\n\n public void setPublicationUids(List<Long> publicationUids) {\n this.publicationUids = publicationUids;\n }\n\n public ObjectId getMentorAccountId() {\n return mentorAccountId;\n }\n\n public void setMentorAccountId(ObjectId mentorAccountId) {\n this.mentorAccountId = mentorAccountId;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getModifiedAt() {\n return modifiedAt;\n }\n\n public void setModifiedAt(Date modifiedAt) {\n this.modifiedAt = modifiedAt;\n }\n\n public Long getRating() {\n return rating;\n }\n\n public void setRating(Long rating) {\n this.rating = rating;\n }\n\n public AccountStats getStats() {\n return stats;\n }\n\n public void setStats(AccountStats stats) {\n this.stats = stats;\n }\n\n public String getNickname() {\n return nickname;\n }\n\n public void setNickname(String nickname) {\n this.nickname = nickname;\n }\n\n public AccountState getState() {\n return state;\n }\n\n public void setState(AccountState state) {\n this.state = state;\n }\n\n public Date getLongDate() {\n return longDate;\n }\n\n public void setLongDate(Date longDate) {\n this.longDate = longDate;\n }\n\n public List<Publication> getPublications() {\n return publications;\n }\n\n public void setPublications(List<Publication> publications) {\n this.publications = publications;\n }\n\n public List<AccountStats> getAdditionalStats() {\n return additionalStats;\n }\n\n public void setAdditionalStats(List<AccountStats> additionalStats) {\n this.additionalStats = additionalStats;\n }\n\n public Boolean getDeleted() {\n return deleted;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Account account = (Account) o;\n\n if (id != null ? !id.equals(account.id) : account.id != null) return false;\n if (publicationUids != null ? !publicationUids.equals(account.publicationUids) : account.publicationUids != null)\n return false;\n if (publications != null ? !publications.equals(account.publications) : account.publications != null)\n return false;\n if (mentorAccountId != null ? !mentorAccountId.equals(account.mentorAccountId) : account.mentorAccountId != null)\n return false;\n if (rating != null ? !rating.equals(account.rating) : account.rating != null) return false;\n if (state != account.state) return false;\n if (createdAt != null ? !createdAt.equals(account.createdAt) : account.createdAt != null) return false;\n if (modifiedAt != null ? !modifiedAt.equals(account.modifiedAt) : account.modifiedAt != null) return false;\n if (stats != null ? !stats.equals(account.stats) : account.stats != null) return false;\n return nickname != null ? nickname.equals(account.nickname) : account.nickname == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = id != null ? id.hashCode() : 0;\n result = 31 * result + (publicationUids != null ? publicationUids.hashCode() : 0);\n result = 31 * result + (publications != null ? publications.hashCode() : 0);\n result = 31 * result + (mentorAccountId != null ? mentorAccountId.hashCode() : 0);\n result = 31 * result + (rating != null ? rating.hashCode() : 0);\n result = 31 * result + (state != null ? state.hashCode() : 0);\n result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0);\n result = 31 * result + (stats != null ? stats.hashCode() : 0);\n result = 31 * result + (nickname != null ? nickname.hashCode() : 0);\n return result;\n }\n}", "public class AccountStats {\n private Integer publicationCnt;\n private Integer followerCnt;\n private List<Long> scoreBreakdown;\n\n public AccountStats() {\n }\n\n public AccountStats(Integer publicationCnt, Integer followerCnt) {\n this.publicationCnt = publicationCnt;\n this.followerCnt = followerCnt;\n }\n\n public Integer getPublicationCnt() {\n return publicationCnt;\n }\n\n public void setPublicationCnt(Integer publicationCnt) {\n this.publicationCnt = publicationCnt;\n }\n\n public Integer getFollowerCnt() {\n return followerCnt;\n }\n\n public void setFollowerCnt(Integer followerCnt) {\n this.followerCnt = followerCnt;\n }\n\n public List<Long> getScoreBreakdown() {\n return scoreBreakdown;\n }\n\n public void setScoreBreakdown(List<Long> scoreBreakdown) {\n this.scoreBreakdown = scoreBreakdown;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AccountStats that = (AccountStats) o;\n\n if (publicationCnt != null ? !publicationCnt.equals(that.publicationCnt) : that.publicationCnt != null)\n return false;\n if (followerCnt != null ? !followerCnt.equals(that.followerCnt) : that.followerCnt != null) return false;\n return scoreBreakdown != null ? scoreBreakdown.equals(that.scoreBreakdown) : that.scoreBreakdown == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = publicationCnt != null ? publicationCnt.hashCode() : 0;\n result = 31 * result + (followerCnt != null ? followerCnt.hashCode() : 0);\n result = 31 * result + (scoreBreakdown != null ? scoreBreakdown.hashCode() : 0);\n return result;\n }\n}", "public class ServiceException extends RuntimeException {\n private static final long serialVersionUID = 3403608589330157070L;\n\n private Response.Status status = Response.Status.INTERNAL_SERVER_ERROR;\n\n public ServiceException(String message) {\n super(message);\n }\n\n public ServiceException(Throwable e) {\n super(e);\n }\n\n public ServiceException(String message, Throwable e) {\n super(message, e);\n }\n\n public ServiceException(String message, Response.Status status) {\n super(message);\n this.status = status;\n }\n\n public ServiceException(String message, Throwable cause, Response.Status status) {\n super(message, cause);\n this.status = status;\n }\n\n\n public Response.Status getStatus() {\n return status;\n }\n}", "@Singleton\npublic class AccountModel extends ServiceModel<Account, ObjectId> {\n private AccountDao accountDao;\n\n @Inject\n private PublicationModel publicationModel;\n\n\n @Inject\n public AccountModel(AccountDao accountDao) {\n super(accountDao);\n this.accountDao = accountDao;\n }\n\n public Account changeMentor(ObjectId accountId, ObjectId mentorId) throws RestDslException {\n ServiceQuery<ObjectId> q = ServiceQuery.byId(accountId);\n return accountDao.changeAccountMentor(q, mentorId);\n }\n\n public int deleteById(ObjectId id) throws RestDslException {\n Account account = getOne(id);\n if (account == null) {\n throw new ServiceException(\"Account with id '\" + id + \"' not found\", Response.Status.NOT_FOUND);\n }\n\n if (account.getPublicationUids() != null) {\n ServiceQuery<Long> pubsToDelete = ServiceQuery.byIds(account.getPublicationUids());\n publicationModel.delete(pubsToDelete);\n }\n return accountDao.delete(ServiceQuery.byId(id));\n }\n}" ]
import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import net.researchgate.restdsl.exceptions.RestDslException; import net.researchgate.restdsl.queries.ServiceQueryParams; import net.researchgate.restdsl.queries.ServiceQueryParamsImpl; import net.researchgate.restdsl.resources.ServiceResource; import net.researchgate.restler.domain.Account; import net.researchgate.restler.domain.AccountStats; import net.researchgate.restler.service.exceptions.ServiceException; import net.researchgate.restler.service.model.AccountModel; import org.bson.types.ObjectId; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;
package net.researchgate.restler.service.resources; /** * Account resource */ @Path("/accounts") @Singleton @Produces(MediaType.APPLICATION_JSON) public class AccountResource extends ServiceResource<Account, ObjectId> { private AccountModel accountModel; private static final ServiceQueryParams SERVICE_QUERY_PARAMS = ServiceQueryParamsImpl.builder() .defaultFields(Sets.newHashSet("id", "mentorAccountId", "publicationUids", "deleted")) // .addDefaultCriteriaItem("deleted", Collections.singletonList(false)) .defaultLimit(13) .build(); @Inject public AccountResource(AccountModel accountModel) throws RestDslException { super(accountModel, Account.class, ObjectId.class); this.accountModel = accountModel; } @GET @Path("/{id}/stats") public AccountStats getAccountStats(@PathParam("id") String id) { Account account = accountModel.getOne(getId(id)); if (account == null) {
throw new ServiceException("Account with id '" + id + "' not found", Response.Status.NOT_FOUND);
6
AstartesGuardian/WebDAV-Server
WebDAV-Server/src/webdav/server/virtual/entity/local/RsRoot.java
[ "public class FileSystemPath\r\n{\r\n public FileSystemPath(String fileName, FileSystemPath parent)\r\n {\r\n this.fileName = fileName;\r\n this.parent = parent;\r\n this.fileSystemPathManager = parent.fileSystemPathManager;\r\n }\r\n public FileSystemPath(String fileName, FileSystemPathManager fileSystemPathManager)\r\n {\r\n this.fileName = fileName;\r\n this.parent = null;\r\n this.fileSystemPathManager = fileSystemPathManager;\r\n }\r\n \r\n private final String fileName;\r\n private final FileSystemPath parent;\r\n private final FileSystemPathManager fileSystemPathManager;\r\n \r\n public String getName()\r\n {\r\n return fileName;\r\n }\r\n \r\n public FileSystemPath getParent()\r\n {\r\n return parent;\r\n }\r\n \r\n public boolean isRoot()\r\n {\r\n return parent == null;\r\n }\r\n \r\n public FileSystemPath createChild(String childName)\r\n {\r\n return new FileSystemPath(childName, this);\r\n }\r\n \r\n \r\n public LinkedList<FileSystemPath> toPaths()\r\n {\r\n LinkedList<FileSystemPath> paths = toReversePaths();\r\n Collections.reverse(paths);\r\n return paths;\r\n }\r\n public LinkedList<FileSystemPath> toReversePaths()\r\n {\r\n LinkedList<FileSystemPath> paths = new LinkedList<>();\r\n \r\n FileSystemPath path = this;\r\n do\r\n {\r\n paths.add(path);\r\n } while((path = path.getParent()) != null && !path.isRoot());\r\n \r\n return paths;\r\n }\r\n \r\n public String[] toStrings()\r\n {\r\n return toString().split(fileSystemPathManager.standardFileSeparator);\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n if(isRoot())\r\n return getName();\r\n \r\n String result = getParent() + fileSystemPathManager.standardFileSeparator + getName();\r\n if(result.startsWith(fileSystemPathManager.standardFileSeparator + fileSystemPathManager.standardFileSeparator))\r\n result = result.substring(1);\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object o)\r\n {\r\n return o instanceof FileSystemPath && o.hashCode() == this.hashCode();\r\n }\r\n @Override\r\n public int hashCode()\r\n {\r\n return toString().hashCode();\r\n }\r\n}\r", "public class UserRequiredException extends HTTPException\r\n{\r\n public UserRequiredException()\r\n {\r\n super(\"User required\");\r\n }\r\n}\r", "public class WrongResourceTypeException extends HTTPException\r\n{\r\n public WrongResourceTypeException()\r\n {\r\n super(\"This resource type can't call this method.\");\r\n }\r\n public WrongResourceTypeException(String description)\r\n {\r\n super(description);\r\n }\r\n}\r", "public class HTTPEnvRequest\r\n{\r\n public static Builder create()\r\n {\r\n return new Builder();\r\n }\r\n public static class Builder\r\n {\r\n public Builder()\r\n { }\r\n \r\n private HTTPRequest request;\r\n private HTTPCommand command;\r\n private HTTPServerSettings settings;\r\n private Collection<IResourceMutation> mutations = null;\r\n private byte[] bytesReceived = null;\r\n \r\n public Builder setRequest(HTTPRequest request)\r\n {\r\n this.request = request;\r\n return this;\r\n }\r\n \r\n public Builder setCommand(HTTPCommand command)\r\n {\r\n this.command = command;\r\n return this;\r\n }\r\n \r\n public Builder setBytesReceived(byte[] bytesReceived)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n return this;\r\n }\r\n \r\n public Builder setSettings(HTTPServerSettings settings)\r\n {\r\n this.settings = settings;\r\n return this;\r\n }\r\n \r\n public Builder setMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations = mutations;\r\n return this;\r\n }\r\n public Builder addMutations(IResourceMutation[] mutations)\r\n {\r\n this.mutations.addAll(Arrays.asList(mutations));\r\n return this;\r\n }\r\n public Builder addMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations.addAll(mutations);\r\n return this;\r\n }\r\n public Builder addMutation(IResourceMutation mutation)\r\n {\r\n this.mutations.add(mutation);\r\n return this;\r\n }\r\n \r\n public HTTPEnvRequest build()\r\n {\r\n if(mutations == null)\r\n mutations = Collections.EMPTY_LIST;\r\n \r\n return new HTTPEnvRequest(\r\n bytesReceived,\r\n request,\r\n command,\r\n settings.getAuthenticationManager().checkAuth(request),\r\n settings,\r\n settings.getFileManager().getResourceMutations());\r\n }\r\n }\r\n \r\n public HTTPEnvRequest(\r\n byte[] bytesReceived,\r\n HTTPRequest request,\r\n HTTPCommand command,\r\n HTTPUser user,\r\n HTTPServerSettings settings,\r\n Collection<IResourceMutation> mutations)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n this.request = request;\r\n this.command = command;\r\n this.user = user;\r\n this.settings = settings;\r\n this.mutations = mutations;\r\n }\r\n \r\n private byte[] bytesReceived;\r\n private FileSystemPath path = null;\r\n \r\n private final HTTPRequest request;\r\n private final HTTPCommand command;\r\n private final HTTPUser user;\r\n private final HTTPServerSettings settings;\r\n private final Collection<IResourceMutation> mutations;\r\n \r\n public FileSystemPath getPath()\r\n {\r\n if(path == null)\r\n path = settings.getFileSystemPathManager()\r\n .createFromString(request.getDecodedPath());\r\n \r\n return path;\r\n }\r\n \r\n public Collection<IResourceMutation> getMutations()\r\n {\r\n return mutations;\r\n }\r\n \r\n public byte[] getBytesReceived()\r\n {\r\n if(bytesReceived == null)\r\n bytesReceived = request.toBytes();\r\n return bytesReceived;\r\n }\r\n \r\n public HTTPRequest getRequest()\r\n {\r\n return request;\r\n }\r\n \r\n public HTTPCommand getCommand()\r\n {\r\n return command;\r\n }\r\n \r\n public HTTPUser getUser()\r\n {\r\n return user;\r\n }\r\n \r\n public HTTPServerSettings getSettings()\r\n {\r\n return settings;\r\n }\r\n}\r", "public interface IResource\r\n{\r\n /**\r\n * Get if the resource is visible.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean isVisible(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the type of the resource.\r\n * \r\n * @param env\r\n * @return ResourceType\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public ResourceType getResourceType(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the web name of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getWebName(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the resource name.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n //public FileSystemPath getPath(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the mime type of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getMimeType(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the size of the resource (byte).\r\n * \r\n * @param env\r\n * @return long\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public long getSize(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the creation time.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getCreationTime(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the last modified date.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getLastModified(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the list of the resources contained in this resource.\r\n * \r\n * @param env\r\n * @return Collection of IResource\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Collection<IResource> listResources(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the content of the resource.\r\n * \r\n * @param env\r\n * @return byte[]\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public byte[] getContent(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Set the content of the resource.\r\n * \r\n * @param content Content to put in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void setContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Append a content to the resource.\r\n * \r\n * @param content Content to append in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void appendContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Delete the resource.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean delete(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Rename or move a resource from the current path to 'resource' path.\r\n * \r\n * @param newPath\r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Define if the resource exists or not.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws UserRequiredException \r\n */\r\n public boolean exists(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException;\r\n public IResource creates(IResource resource, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean isOnTheSameFileSystemWith(IResource resource);\r\n \r\n public IResource getResource(LinkedList<FileSystemPath> reversedPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n \r\n public boolean equals(FileSystemPath path, HTTPEnvRequest env);\r\n \r\n \r\n public boolean addChild(IResource resource, HTTPEnvRequest env);\r\n public boolean removeChild(IResource resource, HTTPEnvRequest env);\r\n \r\n public boolean isInstanceOf(Class<?> c);\r\n \r\n \r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Properties\">\r\n public void setProperty(String namespace, String name, String value, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public Map<Pair<String, String>, String> getProperties(HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Locks\">\r\n public Collection<LockKind> getAvailableLocks() throws UserRequiredException;\r\n public List<Lock> getLocks(HTTPEnvRequest env) throws UserRequiredException;\r\n public List<Lock> getLocks(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(String uuid, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean canLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n}\r", "public enum ResourceType\r\n{\r\n File,\r\n Directory\r\n}\r" ]
import http.FileSystemPath; import http.server.exceptions.UserRequiredException; import http.server.exceptions.WrongResourceTypeException; import http.server.message.HTTPEnvRequest; import webdav.server.resource.IResource; import webdav.server.resource.ResourceType;
package webdav.server.virtual.entity.local; public class RsRoot extends RsLocalDirectory { public RsRoot() { super(""); } @Override public boolean delete(HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override
public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException
4
PathwayAndDataAnalysis/causalpath
src/main/java/org/panda/causalpath/run/CausalityAnalysisSingleMethodInterface.java
[ "public class CausalitySearcher implements Cloneable\n{\n\t/**\n\t * If that is false, then we are interested in conflicting relations.\n\t */\n\tprivate int causal;\n\n\t/**\n\t * If this is false, then we don't care if the target site of a relation and the site on the data matches.\n\t */\n\tprivate boolean forceSiteMatching;\n\n\t/**\n\t * When site matching is on, this parameter determines the largest value of the mismatch between relation and data\n\t * to consider it as a match. Set this to 0 for the most strict match.\n\t */\n\tprivate int siteProximityThreshold;\n\n\t/**\n\t * When this is true, the data whose effect is 0, but potentially can be part of the causal network if known, are\n\t * collected.\n\t */\n\tboolean collectDataWithMissingEffect;\n\n\t/**\n\t * The interesting subset of phosphorylation data with unknown effect.\n\t */\n\tprivate Set<SiteModProteinData> dataNeedsAnnotation;\n\n\t/**\n\t * When this is true, the data that are used for inference of causality or conflict are saved in a set.\n\t */\n\tboolean collectDataUsedForInference;\n\n\t/**\n\t * The set of data that is used during inference of causality.\n\t */\n\tprivate Map<Relation, Set<ExperimentData>> dataUsedForInference;\n\n\t/**\n\t * Set of pairs of data that contributed to inference.\n\t */\n\tprivate Map<Relation, Set<List<ExperimentData>>> pairsUsedForInference;\n\n\t/**\n\t * If true, then an expression relation has to have an Activity data at its source.\n\t */\n\tprotected boolean mandateActivityDataUpstreamOfExpression;\n\n\t/**\n\t * The data types that can be used for evidence of expression change. This is typically protein or rna or both.\n\t */\n\tprotected DataType[] expressionEvidence;\n\n\t/**\n\t * When true, this class uses only the strongest changing proteomic data with known effect as general activity\n\t * evidence.\n\t */\n\tprotected boolean useStrongestProteomicsDataForActivity;\n\n\t/**\n\t * When true, if a node has activity data, other data types are ignored for providing activity evidence.\n\t */\n\tprotected boolean prioritizeActivityData;\n\n\t/**\n\t * Data types that indicate activity change.\n\t */\n\tSet<DataType> generalActivityChangeIndicators;\n\n\t/**\n\t * A graph filter if needed to use at the end of network inference.\n\t */\n\tGraphFilter graphFilter;\n\n\tMap<Relation, Set<ExperimentData>> affectingSourceDataMap;\n\tMap<Relation, Set<ExperimentData>> explainableTargetDataMap;\n\n\t/**\n\t * Constructor with the reasoning type.\n\t * @param causal true:causal, false:conflicting\n\t */\n\tpublic CausalitySearcher(boolean causal)\n\t{\n\t\tsetCausal(causal);\n\t\tthis.forceSiteMatching = true;\n\t\tthis.siteProximityThreshold = 0;\n\t\tthis.collectDataWithMissingEffect = true;\n\t\tthis.collectDataUsedForInference = true;\n\t\tthis.mandateActivityDataUpstreamOfExpression = false;\n\t\tthis.useStrongestProteomicsDataForActivity = false;\n\n\t\tthis.generalActivityChangeIndicators = new HashSet<>(Arrays.asList(DataType.PROTEIN, DataType.PHOSPHOPROTEIN,\n\t\t\tDataType.ACETYLPROTEIN, DataType.METHYLPROTEIN, DataType.METABOLITE, DataType.ACTIVITY));\n\t}\n\n\tpublic void initRelationDataMappingMemory()\n\t{\n\t\tthis.affectingSourceDataMap = new HashMap<>();\n\t\tthis.explainableTargetDataMap = new HashMap<>();\n\t}\n\n\tpublic CausalitySearcher copy()\n\t{\n\t\ttry\n\t\t{\n\t\t\tCausalitySearcher cs = (CausalitySearcher) this.clone();\n\t\t\tcs.pairsUsedForInference = null;\n\t\t\tcs.dataUsedForInference = null;\n\t\t\tcs.dataNeedsAnnotation = null;\n\t\t\tcs.generalActivityChangeIndicators = new HashSet<>(generalActivityChangeIndicators);\n\t\t\tcs.setCollectDataUsedForInference(false);\n\t\t\tcs.setCollectDataWithMissingEffect(false);\n\t\t\treturn cs;\n\t\t}\n\t\tcatch (CloneNotSupportedException e)\n\t\t{\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Finds compatible or conflicting relations. The relations have to be associated with experiment data. Both the\n\t * experiment data and the relations have to be associated with related change detectors.\n\t */\n\tpublic Set<Relation> run(Set<Relation> relations)\n\t{\n//\t\tprintSizeOfRelationsBetweenSignificantData(relations);\n\n\t\t// Initialize collections\n\n\t\tif (collectDataWithMissingEffect)\n\t\t{\n\t\t\tif (dataNeedsAnnotation == null) dataNeedsAnnotation = new HashSet<>();\n\t\t\telse dataNeedsAnnotation.clear();\n\t\t}\n\t\tif (collectDataUsedForInference)\n\t\t{\n\t\t\tif (dataUsedForInference == null)\n\t\t\t{\n\t\t\t\tdataUsedForInference = new HashMap<>();\n\t\t\t\tpairsUsedForInference = new HashMap<>();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdataUsedForInference.clear();\n\t\t\t\tpairsUsedForInference.clear();\n\t\t\t}\n\t\t}\n\n\t\t// This is where magic happens\n\t\tSet<Relation> results = relations.stream().filter(this::satisfiesCriteria).collect(Collectors.toSet());\n\n\t\t// If a subset of the results is desired, trim it\n\t\tif (graphFilter != null)\n\t\t{\n\t\t\tresults = graphFilter.postAnalysisFilter(results);\n\n\t\t\t// remove unnecessary entries in the collected data\n\t\t\tif (collectDataUsedForInference)\n\t\t\t{\n\t\t\t\tSet<Relation> removedRels = new HashSet<>(dataUsedForInference.keySet());\n\t\t\t\tremovedRels.removeAll(results);\n\t\t\t\tremovedRels.forEach(r ->\n\t\t\t\t{\n\t\t\t\t\tdataUsedForInference.remove(r);\n\t\t\t\t\tpairsUsedForInference.remove(r);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Checks if the relation explains/conflicts the associated data.\n\t * @param relation relation to check\n\t * @return true if explanatory\n\t */\n\tpublic boolean satisfiesCriteria(Relation relation)\n\t{\n\t\t// Get data of target gene this relation can explain the change\n\t\tif (explainableTargetDataMap != null && !explainableTargetDataMap.containsKey(relation))\n\t\t\texplainableTargetDataMap.put(relation, getExplainableTargetDataWithSiteMatch(relation));\n\n\t\tSet<ExperimentData> td = explainableTargetDataMap == null ?\n\t\t\tgetExplainableTargetDataWithSiteMatch(relation) : explainableTargetDataMap.get(relation);\n\n\t\tif (!td.isEmpty())\n\t\t{\n\t\t\t// Get data of the source gene that can be cause of this relation\n\t\t\tif (affectingSourceDataMap != null && !affectingSourceDataMap.containsKey(relation))\n\t\t\t\taffectingSourceDataMap.put(relation, getAffectingSourceData(relation));\n\n\t\t\tSet<ExperimentData> sd = affectingSourceDataMap == null ?\n\t\t\t\tgetAffectingSourceData(relation) : affectingSourceDataMap.get(relation);\n\n\t\t\tif (!sd.isEmpty())\n\t\t\t{\n\t\t\t\treturn satisfiesCriteria(sd, relation, td);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if the relation has potential to explain/conflict with the associated data to source and targets, but\n\t * without evaluating data values.\n\t *\n\t * @param relation relation to check\n\t * @return true if the relation has considerable data at both sides\n\t */\n\tpublic boolean hasConsiderableDownstreamData(Relation relation)\n\t{\n\t\treturn !getExplainableTargetDataWithSiteMatch(relation).isEmpty();\n\t}\n\n\t/**\n\t * Checks if the relation has potential to explain/conflict with the associated data to source and targets, but\n\t * without evaluating data values.\n\t *\n\t * @param relation relation to check\n\t * @return true if the relation has considerable data at both sides\n\t */\n\tpublic boolean hasConsiderableData(Relation relation)\n\t{\n\t\tif (hasConsiderableDownstreamData(relation))\n\t\t{\n\t\t\t// Get data of the source gene that can be cause of this relation\n\t\t\tSet<ExperimentData> sd = getAffectingSourceData(relation);\n\t\t\treturn !sd.isEmpty();\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if any pair from the given source and target data can be explained by the given relation.\n\t * @param sd source data\n\t * @param rel the relation\n\t * @param td target data\n\t * @return true if any sd td pair is explained/conflicted by the given relation\n\t */\n\tprivate boolean satisfiesCriteria(Set<ExperimentData> sd, Relation rel, Set<ExperimentData> td)\n\t{\n\t\tboolean satisfies = false;\n\n\t\tfor (ExperimentData sourceData : sd)\n\t\t{\n\t\t\tfor (ExperimentData targetData : td)\n\t\t\t{\n\t\t\t\tif (satisfiesCriteria(rel, sourceData, targetData))\n\t\t\t\t{\n\t\t\t\t\tsatisfies = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn satisfies;\n\t}\n\n\t/**\n\t * Checks if the relation can explain/conflict the given source target data pair.\n\t * @param rel the relation\n\t * @param sourceData the source data\n\t * @param targetData the target data\n\t * @return true if the relation can explain/conflict the given data pair\n\t */\n\tprivate boolean satisfiesCriteria(Relation rel, ExperimentData sourceData, ExperimentData targetData)\n\t{\n\t\tint e = rel.chDet.getChangeSign(sourceData, targetData) * rel.getSign();\n\n\t\tif (e != 0 && collectDataWithMissingEffect && sourceData.getEffect() == 0)\n\t\t{\n\t\t\tdataNeedsAnnotation.add((SiteModProteinData) sourceData);\n\t\t}\n\t\telse if (sourceData.getEffect() * e == causal)\n\t\t{\n\t\t\tif (collectDataUsedForInference)\n\t\t\t{\n\t\t\t\tif (!dataUsedForInference.containsKey(rel))\n\t\t\t\t{\n\t\t\t\t\tdataUsedForInference.put(rel, new HashSet<>());\n\t\t\t\t\tpairsUsedForInference.put(rel, new HashSet<>());\n\t\t\t\t}\n\n\t\t\t\tdataUsedForInference.get(rel).add(sourceData);\n\t\t\t\tdataUsedForInference.get(rel).add(targetData);\n\t\t\t\tpairsUsedForInference.get(rel).add(Arrays.asList(sourceData, targetData));\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Gets the source data that match with the given relation and target data.\n\t * @param rel the relation\n\t * @param target target data\n\t * @return the set of matching source data\n\t */\n\tpublic Set<ExperimentData> getSatisfyingSourceData(Relation rel, ExperimentData target)\n\t{\n\t\treturn getAffectingSourceData(rel).stream()\n\t\t\t.filter(source -> satisfiesCriteria(rel, source, target))\n\t\t\t.collect(Collectors.toSet());\n\t}\n\n\t/**\n\t * Gets the set of target data that the given relation can potentially explain its change. but that is without\n\t * checking the value changes, only by data types.\n\t * @param rel the relation\n\t * @return the set of target data explainable by the relation\n\t */\n\tpublic Set<ExperimentData> getExplainableTargetData(Relation rel)\n\t{\n\t\tif (rel.type.affectsPhosphoSite)\n\t\t{\n\t\t\treturn getEvidenceForPhosphoChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsTotalProt)\n\t\t{\n\t\t\treturn getEvidenceForExpressionChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsGTPase)\n\t\t{\n\t\t\treturn getEvidenceForGTPaseChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsAcetylSite)\n\t\t{\n\t\t\treturn getEvidenceForAcetylChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsMethlSite)\n\t\t{\n\t\t\treturn getEvidenceForMethylChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsMetabolite)\n\t\t{\n\t\t\treturn getEvidenceForMetaboliteChange(rel.targetData);\n\t\t}\n\n\t\tthrow new RuntimeException(\"Code should not reach here. Is there a new relation type to handle?\");\n\t}\n\n\t/**\n\t * Gets the set of target data that the given relation can potentially explain its change. That is without\n\t * checking the value changes, but site matching (if relevant) is evaluated.\n\t * @param rel the relation\n\t * @return the set of target data explainable by the relation\n\t */\n\tpublic Set<ExperimentData> getExplainableTargetDataWithSiteMatch(Relation rel)\n\t{\n\t\tSet<ExperimentData> datas = getExplainableTargetData(rel);\n\n\t\treturn datas.stream().filter(d -> !(d instanceof SiteModProteinData) ||\n\t\t\tisTargetSiteCompatible(rel, (SiteModProteinData) d)).collect(Collectors.toSet());\n\t}\n\n\n\t/**\n\t * Checks if target sites match for the relation and the data.\n\t * @param rel the relation\n\t * @param target target data\n\t * @return true if there is a match or no match needed\n\t */\n\tpublic boolean isTargetSiteCompatible(Relation rel, SiteModProteinData target)\n\t{\n\t\treturn !forceSiteMatching || !CollectionUtil.intersectionEmpty(\n\t\t\t\trel.getTargetWithSites(siteProximityThreshold), target.getGenesWithSites());\n\t}\n\n\t/**\n\t * Gets the source data that can be cause of this relation. This is without checking any change in values, only by\n\t * data types.\n\t * @param rel the relation\n\t * @return the set of source data that can be affecting\n\t */\n\tpublic Set<ExperimentData> getAffectingSourceData(Relation rel)\n\t{\n\t\tif (rel.type.affectsPhosphoSite || rel.type.affectsAcetylSite || rel.type.affectsMethlSite)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForSiteSpecificChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsTotalProt)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForExpressionChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsGTPase)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForGTPaseChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsMetabolite)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForMetaboliteChange(rel.sourceData);\n\t\t}\n\n\t\tthrow new RuntimeException(\"Code should not reach here. There must be a new relation type to handle.\");\n\t}\n\n\t/**\n\t * Gets the evidence for activity change of a gene in terms of the associated data. This method does not evaluate a\n\t * change in values but only assesses the valid data types.\n\t * @param gene the gene\n\t * @return the data with potential to indicate activity change\n\t */\n\tpublic Set<ExperimentData> getGeneralActivationEvidence(GeneWithData gene)\n\t{\n\t\tSet<ExperimentData> set = new HashSet<>();\n\n\t\tfor (DataType type : generalActivityChangeIndicators)\n\t\t{\n\t\t\tset.addAll(gene.getData(type));\n\t\t}\n\n\t\tset = set.stream().filter(d -> d.getEffect() != 0).collect(Collectors.toSet());\n\n\t\tif (useStrongestProteomicsDataForActivity)\n\t\t{\n\t\t\tremoveShadowedProteomicData(set);\n\t\t}\n\n\t\tif (prioritizeActivityData)\n\t\t{\n\t\t\tremoveOtherDataIfActivityDataIsPresent(set);\n\t\t}\n\n\t\treturn set;\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForSiteSpecificChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForExpressionChange(GeneWithData gene)\n\t{\n\t\tif (mandateActivityDataUpstreamOfExpression) return gene.getData(DataType.ACTIVITY);\n\t\telse return getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForGTPaseChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForMetaboliteChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForPhosphoChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.PHOSPHOPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForExpressionChange(GeneWithData gene)\n\t{\n\t\tif (expressionEvidence != null) return gene.getData(expressionEvidence);\n\t\treturn gene.getData(DataType.PROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForGTPaseChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.ACTIVITY);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForAcetylChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.ACETYLPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForMethylChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.METHYLPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForMetaboliteChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.METABOLITE);\n\t}\n\n\n\t/**\n\t * This method iterates over total protein and phosphoprotein data that has a known effect, and leaves only the one\n\t * with the biggest change, removes others. This is sometimes useful for complexity management.\n\t * @param data data to select from\n\t */\n\tprotected void removeShadowedProteomicData(Set<ExperimentData> data)\n\t{\n\t\tif (data.size() > 1)\n\t\t{\n\t\t\tOptional<ProteinData> opt = data.stream().filter(d -> d instanceof ProteinData && d.getEffect() != 0)\n\t\t\t\t.map(d -> (ProteinData) d).sorted((d1, d2) ->\n\t\t\t\t\tDouble.compare(Math.abs(d2.getChangeValue()), Math.abs(d1.getChangeValue()))).findFirst();\n\n\t\t\tif (opt.isPresent())\n\t\t\t{\n\t\t\t\tExperimentData ed = opt.get();\n\t\t\t\tdata.removeIf(d -> d instanceof ProteinData && d != ed);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void removeOtherDataIfActivityDataIsPresent(Set<ExperimentData> data)\n\t{\n\t\tif (data.stream().anyMatch(d -> d instanceof ActivityData))\n\t\t{\n\t\t\tdata.retainAll(data.stream().filter(d -> d instanceof ActivityData).collect(Collectors.toSet()));\n\t\t}\n\t}\n\n\tpublic void writeResults(String filename) throws IOException\n\t{\n\t\tif (pairsUsedForInference.isEmpty()) return;\n\n\t\tTwoDataChangeDetector relDet = pairsUsedForInference.keySet().iterator().next().chDet;\n\t\tCorrelationDetector corDet = relDet instanceof CorrelationDetector ? (CorrelationDetector) relDet : null;\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(filename));\n\t\twriter.write(\"Source\\tRelation\\tTarget\\tSites\\t\");\n\t\tif (corDet != null) writer.write(\"Source data ID\\tTarget data ID\\tCorrelation\\tCorrelation pval\");\n\t\telse writer.write(\"Source data ID\\tSource change\\t Source change pval\\tTarget data ID\\tTarget change\\tTarget change pval\");\n\n\t\tpairsUsedForInference.keySet().stream().\n\t\t\tsorted(Comparator.comparing(this::getRelationScore).reversed()). // Sort relations to their significance\n\t\t\tforEach(r -> pairsUsedForInference.get(r).stream().forEach(pair ->\n\t\t{\n\t\t\tIterator<ExperimentData> iter = pair.iterator();\n\t\t\tExperimentData sourceData = iter.next();\n\t\t\tExperimentData targetData = iter.next();\n\n\t\t\tFileUtil.lnwrite(r.source + \"\\t\" + r.type.getName() + \"\\t\" + r.target + \"\\t\" + r.getSitesInString() + \"\\t\", writer);\n\n\t\t\tif (corDet != null)\n\t\t\t{\n\t\t\t\tTuple t = corDet.calcCorrelation(sourceData, targetData);\n\t\t\t\tFileUtil.write(sourceData.getId() + \"\\t\" + targetData.getId() + \"\\t\" + t.v + \"\\t\" + t.p, writer);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOneDataChangeDetector sDet = sourceData.getChDet();\n\t\t\t\tOneDataChangeDetector tDet = targetData.getChDet();\n\n\t\t\t\tFileUtil.write(sourceData.getId() + \"\\t\" + sourceData.getChangeValue() + \"\\t\" +\n\t\t\t\t\t(sDet instanceof SignificanceDetector ? ((SignificanceDetector) sDet).getPValue(sourceData) : \"\") + \"\\t\", writer);\n\n\t\t\t\tFileUtil.write(targetData.getId() + \"\\t\" + targetData.getChangeValue() + \"\\t\" +\n\t\t\t\t\t(tDet instanceof SignificanceDetector ? ((SignificanceDetector) tDet).getPValue(targetData) : \"\"), writer);\n\t\t\t}\n\t\t}));\n\t\twriter.close();\n\t}\n\n\t/**\n\t * We want to sort the result rows according the their significance. This method generates a score for each relation\n\t * so that we can sort them using that score.\n\t */\n\tprivate double getRelationScore(Relation r)\n\t{\n\t\tdouble max = -Double.MAX_VALUE;\n\t\tSet<List<ExperimentData>> pairs = pairsUsedForInference.get(r);\n\t\tfor (List<ExperimentData> pair : pairs)\n\t\t{\n\t\t\tExperimentData src = pair.get(0);\n\t\t\tExperimentData tgt = pair.get(1);\n\n\t\t\tdouble val;\n\n\t\t\tif (r.chDet instanceof CorrelationDetector)\n\t\t\t{\n\t\t\t\tval = -((CorrelationDetector) r.chDet).calcCorrelation(src, tgt).p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOneDataChangeDetector sDet = src.getChDet();\n\t\t\t\tOneDataChangeDetector tDet = tgt.getChDet();\n\n\t\t\t\tif (sDet instanceof SignificanceDetector || tDet instanceof SignificanceDetector)\n\t\t\t\t{\n\t\t\t\t\tdouble vS = sDet instanceof SignificanceDetector ? ((SignificanceDetector) sDet).getPValue(src) : 0;\n\t\t\t\t\tdouble vT = tDet instanceof SignificanceDetector ? ((SignificanceDetector) tDet).getPValue(tgt) : 0;\n\t\t\t\t\tval = -Math.max(vS, vT);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tval = Math.min(Math.abs(sDet.getChangeValue(src)), Math.abs(tDet.getChangeValue(tgt)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (val > max) max = val;\n\t\t}\n\t\treturn max;\n\t}\n\n\tpublic void setCausal(boolean causal)\n\t{\n\t\tthis.causal = causal ? 1 : -1;\n\t}\n\n\tpublic Set<SiteModProteinData> getDataNeedsAnnotation()\n\t{\n\t\treturn dataNeedsAnnotation;\n\t}\n\n\tpublic Set<ExperimentData> getDataUsedForInference()\n\t{\n\t\treturn dataUsedForInference.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());\n\t}\n\n\tpublic Set<List<ExperimentData>> getPairsUsedForInference()\n\t{\n\t\treturn pairsUsedForInference.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());\n\t}\n\n\t//--DEBUG----------\n\tpublic void writePairsUsedForInferenceWithCorrelations(String file)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(file));\n\t\t\tSet<List<ExperimentData>> pairs = getPairsUsedForInference();\n\n\t\t\tCorrelationDetector cd = new CorrelationDetector(-1, 1);\n\t\t\tMap<String, Double> pvals = new HashMap<>();\n\n\t\t\tfor (List<ExperimentData> pair : pairs)\n\t\t\t{\n\t\t\t\tIterator<ExperimentData> iter = pair.iterator();\n\t\t\t\tExperimentData data1 = iter.next();\n\t\t\t\tExperimentData data2 = iter.next();\n\n\t\t\t\tTuple corr = cd.calcCorrelation(data1, data2);\n\t\t\t\tif (!corr.isNaN())\n\t\t\t\t{\n\t\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\t\tpair.stream().sorted(Comparator.comparing(ExperimentData::getId))\n\t\t\t\t\t\t.forEach(e -> sb.append(e.getId()).append(\":\"));\n\t\t\t\t\tString id = sb.toString();\n\n\t\t\t\t\tpvals.put(id, corr.p);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpvals.forEach((s, p) -> FileUtil.writeln(s + \"\\t\" + p, writer));\n\n\t\t\twriter.close();\n\t\t}\n\t\tcatch (IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\tpublic void printSizeOfRelationsBetweenSignificantData(Set<Relation> relations)\n\t{\n\t\tSet<Relation> rels = relations.stream().filter(r -> r.sourceData.getDataStream().anyMatch(d -> d.getChangeSign() != 0) &&\n\t\t\tr.targetData.getDataStream().anyMatch(d -> d.getChangeSign() != 0)).collect(Collectors.toSet());\n\t\tSystem.out.println(\"rels between sig data = \" + rels.size());\n\t\tlong protCnt = rels.stream().map(r -> Arrays.asList(r.source, r.target)).flatMap(Collection::stream).distinct().count();\n\t\tSystem.out.println(\"protCnt = \" + protCnt);\n\t}\n\t//--DEBUG----------\n\n\tpublic Map<Relation, Set<ExperimentData>> getInferenceUnits()\n\t{\n\t\treturn dataUsedForInference;\n\t}\n\n\tpublic void setCollectDataUsedForInference(boolean collect)\n\t{\n\t\tthis.collectDataUsedForInference = collect;\n\t}\n\n\tpublic void setCollectDataWithMissingEffect(boolean collect)\n\t{\n\t\tthis.collectDataWithMissingEffect = collect;\n\t}\n\n\tpublic void setMandateActivityDataUpstreamOfExpression(boolean mandate)\n\t{\n\t\tthis.mandateActivityDataUpstreamOfExpression = mandate;\n\t}\n\n\tpublic void setUseStrongestProteomicsDataForActivity(boolean use)\n\t{\n\t\tthis.useStrongestProteomicsDataForActivity = use;\n\t}\n\n\tpublic void setPrioritizeActivityData(boolean prioritizeActivityData)\n\t{\n\t\tthis.prioritizeActivityData = prioritizeActivityData;\n\t}\n\n\tpublic void addDataTypeForGeneralActivity(DataType type)\n\t{\n\t\tgeneralActivityChangeIndicators.add(type);\n\t}\n\n\tpublic void setForceSiteMatching(boolean forceSiteMatching)\n\t{\n\t\tthis.forceSiteMatching = forceSiteMatching;\n\t}\n\n\tpublic void setSiteProximityThreshold(int siteProximityThreshold)\n\t{\n\t\tthis.siteProximityThreshold = siteProximityThreshold;\n\t}\n\n\tpublic void setGraphFilter(GraphFilter graphFilter)\n\t{\n\t\tthis.graphFilter = graphFilter;\n\t}\n\n\tpublic boolean hasNoGraphFilter()\n\t{\n\t\treturn graphFilter == null;\n\t}\n\n\tpublic GraphFilter getGraphFilter()\n\t{\n\t\treturn graphFilter;\n\t}\n\n\tpublic void setExpressionEvidence(DataType... types)\n\t{\n\t\texpressionEvidence = types;\n\t}\n\n\t/**\n\t * This method is experimental, only to test how good is RNA expression as a proxy to protein activity. It is not\n\t * meant to be used in a regular CausalPath analysis.\n\t */\n\tpublic void useExpressionForActivity()\n\t{\n\t\tthis.generalActivityChangeIndicators = new HashSet<>(Collections.singletonList(DataType.RNA));\n\t}\n}", "public class ThresholdDetector implements OneDataChangeDetector\n{\n\t/**\n\t * Threshold to use.\n\t */\n\tprotected double threshold;\n\n\t/**\n\t * Method to reduce multiple values into one value.\n\t */\n\tAveragingMethod avgMet;\n\n\tpublic ThresholdDetector(double threshold)\n\t{\n\t\tthis.threshold = threshold;\n\t}\n\n\tpublic ThresholdDetector(double threshold, AveragingMethod avgMet)\n\t{\n\t\tthis.threshold = threshold;\n\t\tthis.avgMet = avgMet;\n\t}\n\n\tpublic void setAveragingMethod(AveragingMethod method)\n\t{\n\t\tthis.avgMet = method;\n\t}\n\n\tpublic void setThreshold(double threshold)\n\t{\n\t\tthis.threshold = threshold;\n\t}\n\n\t@Override\n\tpublic int getChangeSign(ExperimentData data)\n\t{\n\t\tdouble v = getChangeValue(data);\n\t\tif (Math.abs(v) >= threshold) return v > 0 ? 1 : -1;\n\t\telse return 0;\n\t}\n\n\tpublic double getChangeValue(ExperimentData data)\n\t{\n\t\tif (data instanceof NumericData)\n\t\t{\n\t\t\tNumericData nd = (NumericData) data;\n\t\t\tswitch (avgMet)\n\t\t\t{\n\t\t\t\tcase FIRST_VALUE: return nd.vals[0];\n\t\t\t\tcase ARITHMETIC_MEAN: return ArrayUtil.mean(nd.vals);\n\t\t\t\tcase FOLD_CHANGE_MEAN: return foldChangeGeometricMean(nd.vals);\n\t\t\t\tcase MAX: return maxOfAbs(nd.vals);\n\t\t\t}\n\t\t}\n\t\telse if (data instanceof CategoricalData)\n\t\t{\n\t\t\tCategoricalData qd = (CategoricalData) data;\n\n\t\t\tswitch (avgMet)\n\t\t\t{\n\t\t\t\tcase FIRST_VALUE: return qd.getCategories()[0];\n\t\t\t\tcase ARITHMETIC_MEAN: return ArrayUtil.mean(qd.getCategories());\n\t\t\t\tcase FOLD_CHANGE_MEAN: throw new RuntimeException(\"Fold change averaging cannot be applied to categories.\");\n\t\t\t\tcase MAX: return maxOfAbs(qd.getCategories());\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic OneDataChangeDetector makeACopy()\n\t{\n\t\treturn new ThresholdDetector(this.threshold, this.avgMet);\n\t}\n\n\t/**\n\t * Gets the geometric mean of fold change values that is formatted to span the range (-inf, -1], [1, inf).\n\t */\n\tpublic double foldChangeGeometricMean(double[] vals)\n\t{\n\t\tdouble mult = 1;\n\t\tint cnt = 0;\n\t\tfor (double val : vals)\n\t\t{\n\t\t\tif (Double.isNaN(val)) continue;\n\t\t\tcnt++;\n\t\t\tmult *= val < 0 ? -1 / val : val;\n\t\t}\n\t\treturn Math.pow(mult, 1D / cnt);\n\t}\n\n\tpublic double maxOfAbs(double[] vals)\n\t{\n\t\tdouble max = 0;\n\t\tdouble v = 0;\n\n\t\tfor (double val : vals)\n\t\t{\n\t\t\tdouble abs = Math.abs(val);\n\t\t\tif (abs > max)\n\t\t\t{\n\t\t\t\tmax = abs;\n\t\t\t\tv = val;\n\t\t\t}\n\t\t}\n\n\t\treturn v;\n\t}\n\n\tpublic double maxOfAbs(int[] vals)\n\t{\n\t\tint max = 0;\n\t\tint v = 0;\n\n\t\tfor (int val : vals)\n\t\t{\n\t\t\tint abs = Math.abs(val);\n\t\t\tif (abs > max)\n\t\t\t{\n\t\t\t\tmax = abs;\n\t\t\t\tv = val;\n\t\t\t}\n\t\t}\n\n\t\treturn v;\n\t}\n\n\tpublic enum AveragingMethod\n\t{\n\t\tARITHMETIC_MEAN,\n\t\tFOLD_CHANGE_MEAN,\n\t\tMAX,\n\t\tFIRST_VALUE\n\t}\n}", "public class ActivityData extends CategoricalData\n{\n\tpublic ActivityData(String id, String symbol)\n\t{\n\t\tsuper(id, symbol);\n\t}\n\n\t/**\n\t * This constructor is for converting the activity-encoding RPPAData in the resource module to an activity data to\n\t * use in this project.\n\t */\n\tpublic ActivityData(ProteomicsFileRow rppa)\n\t{\n\t\tsuper(rppa.id, rppa.genes.iterator().next());\n\t\tdata = new SingleCategoricalData[rppa.vals.length];\n\t\tfor (int i = 0; i < data.length; i++)\n\t\t{\n\t\t\tdata[i] = new Activity((int) rppa.vals[i]);\n\t\t}\n\t}\n\n\t@Override\n\tpublic ExperimentData copy()\n\t{\n\t\treturn new ActivityData(id, getGeneSymbols().iterator().next());\n\t}\n\n\t@Override\n\tpublic DataType getType()\n\t{\n\t\treturn DataType.ACTIVITY;\n\t}\n}", "public class GraphWriter\n{\n\t/**\n\t * Border color of activating phosphorylations or mutations.\n\t */\n\tprivate Color activatingBorderColor;\n\t/**\n\t * Border color of inhibiting phosphorylations or mutations.\n\t */\n\tprivate Color inhibitingBorderColor;\n\n\t/**\n\t * This color is used when the downstream of a gene suggest it is activated and inhibited at the same time.\n\t */\n\tprivate Color doubleSignificanceBorderColor;\n\n\t/**\n\t * Border color of nodes and phosphosites when their activating/inactivating status is not known, or their\n\t * activated/inactivated status is not significant.\n\t */\n\tprivate Color defaultBorderColor;\n\n\t/**\n\t * Parameter to use gene background to display the total protein change. If false, then it is displayed on the gene\n\t * node as a separate feature.\n\t */\n\tprivate boolean useGeneBGForTotalProtein;\n\n\t/**\n\t * The most intense color to show downregulation.\n\t */\n\tprivate Color maxDownColor;\n\n\t/**\n\t * The most intense color to show upregulation.\n\t */\n\tprivate Color maxUpColor;\n\n\t/**\n\t * The value where the most intense colors are reached. If a value is more extreme than this value, it will be\n\t * shown with the most intense color, and would be considered \"saturated\".\n\t */\n\tprivate double colorSaturationValue;\n\n\t/**\n\t * An object that can produce a color for a given up/downregulation value.\n\t */\n\tprivate ValToColor vtc;\n\n\t/**\n\t * The set of relations with the associated data to draw.\n\t */\n\tprivate Set<Relation> relations;\n\n\tprivate NetworkSignificanceCalculator nsc;\n\n\tprivate Set<ExperimentData> experimentDataToDraw;\n\n\tprivate Set<GeneWithData> otherGenesToShow;\n\n\tprivate boolean showInsignificantData = false;\n\n\t/**\n\t * Constructor with the relations. Those relations are the result of the causality search.\n\t */\n\tpublic GraphWriter(Set<Relation> relations)\n\t{\n\t\tthis(relations, null);\n\t}\n\n\t/**\n\t * Constructor with the relations and significance calculation results.\n\t * Those relations are the result of the causality search.\n\t */\n\tpublic GraphWriter(Set<Relation> relations, NetworkSignificanceCalculator nsc)\n\t{\n\t\tthis.relations = relations;\n\t\tactivatingBorderColor = new Color(0, 180, 20);\n\t\tinhibitingBorderColor = new Color(180, 0, 20);\n\t\tdoubleSignificanceBorderColor = new Color(150, 150, 0);\n\t\tdefaultBorderColor = new Color(50, 50, 50);\n\n\t\tmaxDownColor = new Color(40, 80, 255);\n\t\tmaxUpColor = new Color(255, 80, 40);\n\t\tcolorSaturationValue = 1;\n\n\t\tinitColorMapper();\n\n\t\tuseGeneBGForTotalProtein = false;\n\n\t\tthis.nsc = nsc;\n\t}\n\n\t/**\n\t * Saturation color for downregulation.\n\t */\n\tpublic void setMaxDownColor(Color maxDownColor)\n\t{\n\t\tthis.maxDownColor = maxDownColor;\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * Saturation color for upregulation.\n\t */\n\tpublic void setMaxUpColor(Color maxUpColor)\n\t{\n\t\tthis.maxUpColor = maxUpColor;\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * The value where color saturation occurs. The parameter has to be a positive value. Negative saturation will be\n\t * symmetrical to positive saturation.\n\t */\n\tpublic void setColorSaturationValue(double colorSaturationValue)\n\t{\n\t\tthis.colorSaturationValue = Math.abs(colorSaturationValue);\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * Initializes the color mapping object.\n\t */\n\tprivate void initColorMapper()\n\t{\n\t\tvtc = new ValToColor(new double[]{-colorSaturationValue, 0, colorSaturationValue},\n\t\t\tnew Color[]{maxDownColor, Color.WHITE, maxUpColor});\n\t}\n\n\tpublic void setUseGeneBGForTotalProtein(boolean useGeneBGForTotalProtein)\n\t{\n\t\tthis.useGeneBGForTotalProtein = useGeneBGForTotalProtein;\n\t}\n\n\tpublic void setActivatingBorderColor(Color activatingBorderColor)\n\t{\n\t\tthis.activatingBorderColor = activatingBorderColor;\n\t}\n\n\tpublic void setInhibitingBorderColor(Color inhibitingBorderColor)\n\t{\n\t\tthis.inhibitingBorderColor = inhibitingBorderColor;\n\t}\n\n\tpublic void setExpColorSchema(ValToColor vtc)\n\t{\n\t\tthis.vtc = vtc;\n\t}\n\n\tpublic void setExperimentDataToDraw(Set<ExperimentData> experimentDataToDraw)\n\t{\n\t\tthis.experimentDataToDraw = experimentDataToDraw;\n\t}\n\n\tpublic void setOtherGenesToShow(Set<GeneWithData> set)\n\t{\n\t\tthis.otherGenesToShow = set;\n\t}\n\n\tpublic void setShowInsignificantData(boolean showInsignificantData)\n\t{\n\t\tthis.showInsignificantData = showInsignificantData;\n\t}\n\n\t/**\n\t * Produces a causality graph where each node corresponds to a gene. In this graph, data may be displayed more than\n\t * once if they map to more than one gene. The output .sif and .format files can be visualized using ChiBE. From\n\t * ChiBE, do SIF -> Load SIF File ... and select the output .sif file.\n\t */\n\tpublic void writeSIFGeneCentric(String filename) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".sif\")) filename += \".sif\";\n\n\t\t// write relations\n\t\tBufferedWriter writer1 = new BufferedWriter(new FileWriter(filename));\n\t\trelations.stream().distinct().forEach(r -> FileUtil.writeln(r.toString(), writer1));\n\t\tif (otherGenesToShow != null)\n\t\t{\n\t\t\tSet<String> genesInGraph = getGenesInGraph();\n\t\t\totherGenesToShow.stream().filter(g -> !genesInGraph.contains(g.getId())).forEach(g ->\n\t\t\t\tFileUtil.writeln(g.getId(), writer1));\n\t\t}\n\t\twriter1.close();\n\n\t\tSet<String> totalProtUsedUp = new HashSet<>();\n\n\t\tfilename = filename.substring(0, filename.lastIndexOf(\".\")) + \".format\";\n\t\tBufferedWriter writer2 = new BufferedWriter(new FileWriter(filename));\n\t\twriter2.write(\"node\\tall-nodes\\tcolor\\t255 255 255\\n\");\n\t\twriter2.write(\"node\\tall-nodes\\tbordercolor\\t\" + inString(defaultBorderColor) + \"\\n\");\n\n\t\tSet<ExperimentData> dataInGraph = getExperimentDataToDraw();\n\n\t\tdataInGraph.forEach(data ->\n\t\t{\n\t\t\tString colS = \"255 255 255\";\n\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tif (data.getChangeSign() != 0 || showInsignificantData)\n\t\t\t\t{\n\t\t\t\t\tcolS = vtc.getColorInString(data.getChangeValue());\n\t\t\t\t}\n\t\t\t\telse return;\n\t\t\t}\n\n\t\t\tString bor = inString(defaultBorderColor);\n\t\t\tString let = \"?\";\n\n\t\t\tif (data instanceof SiteModProteinData)\n\t\t\t{\n\t\t\t\tSiteModProteinData pd = (SiteModProteinData) data;\n\t\t\t\tif (pd.getEffect() > 0) bor = inString(activatingBorderColor);\n\t\t\t\telse if (pd.getEffect() < 0) bor = inString(inhibitingBorderColor);\n\n\t\t\t\tlet = pd.getModification().toString().substring(0, 1).toLowerCase();\n\t\t\t}\n\t\t\telse if (data instanceof ProteinData)\n\t\t\t{\n\t\t\t\tlet = \"t\";\n\t\t\t}\n\t\t\telse if (data instanceof MetaboliteData)\n\t\t\t{\n\t\t\t\tlet = \"c\";\n\t\t\t}\n\t\t\telse if (data instanceof MutationData)\n\t\t\t{\n\t\t\t\tlet = \"x\";\n\t\t\t\tif (data.getEffect() == 1)\n\t\t\t\t\tbor = inString(activatingBorderColor);\n\t\t\t\telse bor = inString(inhibitingBorderColor);\n\t\t\t}\n\t\t\telse if (data instanceof CNAData)\n\t\t\t{\n\t\t\t\tlet = \"d\";\n\t\t\t}\n\t\t\telse if (data instanceof RNAData)\n\t\t\t{\n\t\t\t\tlet = \"r\";\n\t\t\t}\n\t\t\telse if (data instanceof ActivityData)\n\t\t\t{\n\t\t\t\tlet = data.getChangeSign() > 0 ? \"!\" : \"i\";\n\t\t\t\tbor = inString(activatingBorderColor);\n\t\t\t}\n\n\t\t\tString siteID = data.id;\n\t\t\tString val = data.hasChangeDetector() ? data.getChangeValue() + \"\" : \"\";\n\n\t\t\tfor (String gene : data.getGeneSymbols())\n\t\t\t{\n\t\t\t\tif (nsc != null)\n\t\t\t\t{\n\t\t\t\t\tif (nsc.isDownstreamSignificant(gene))\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\tborderwidth\\t2\", writer2);\n\t\t\t\t\t}\n\t\t\t\t\tboolean act = false;\n\t\t\t\t\tboolean inh = false;\n\n\t\t\t\t\tif (nsc instanceof NSCForComparison)\n\t\t\t\t\t{\n\t\t\t\t\t\tact = ((NSCForComparison) nsc).isActivatingTargetsSignificant(gene);\n\t\t\t\t\t\tinh = ((NSCForComparison) nsc).isInhibitoryTargetsSignificant(gene);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (act && !inh) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(activatingBorderColor), writer2);\n\t\t\t\t\telse if (!act && inh) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(inhibitingBorderColor), writer2);\n\t\t\t\t\telse if (act /* && inh */) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(doubleSignificanceBorderColor), writer2);\n\t\t\t\t\t//else FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(defaultBorderColor), writer2);\n\t\t\t\t}\n\n\t\t\t\tif (useGeneBGForTotalProtein && (let.equals(\"t\") || let.equals(\"c\")) && !totalProtUsedUp.contains(gene))\n\t\t\t\t{\n\t\t\t\t\tif (let.equals(\"c\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + siteID + \"\\tcolor\\t\" + colS, writer2);\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + siteID + \"\\ttooltip\\t\" + gene + \", \" + val, writer2);\n\t\t\t\t\t\ttotalProtUsedUp.add(gene);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\tcolor\\t\" + colS, writer2);\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\ttooltip\\t\" + siteID + \", \" + val, writer2);\n\t\t\t\t\t\ttotalProtUsedUp.add(gene);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\trppasite\\t\" + siteID.replaceAll(\"\\\\|\", \"-\") + \"|\" + let + \"|\" + colS + \"|\" + bor +\n\t\t\t\t\t\t\"|\" + val, writer2);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\twriter2.close();\n\t}\n\n\t/**\n\t * Converts color to a string.\n\t */\n\tprivate String inString(Color c)\n\t{\n\t\treturn c.getRed() + \" \" + c.getGreen() + \" \" + c.getBlue();\n\t}\n\n\t/**\n\t * Converts color to a JSON string.\n\t */\n\tprivate String inJSONString(Color c)\n\t{\n\t\treturn \"rgb(\" + c.getRed() + \",\" + c.getGreen() + \",\" + c.getBlue() + \")\";\n\t}\n\n\t/**\n\t * Generates a causality graph where each node is a measurement. In this graph, pathway relations can be displayed\n\t * more than once if the same relation can explain more than one data pairs.\n\t *\n\t * @param filename name of the output sif file\n\t * @param unitsMap The map from the inferred relations to the data that helped the inference.\n\t */\n\tpublic void writeSIFDataCentric(String filename, Map<Relation, Set<ExperimentData>> unitsMap) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".sif\")) filename += \".sif\";\n\n\t\tSet<ExperimentData> used = new HashSet<>();\n\n\t\t// write relations\n\t\tBufferedWriter writer1 = new BufferedWriter(new FileWriter(filename));\n\t\tunitsMap.keySet().forEach(r ->\n\t\t{\n\t\t\tSet<ExperimentData> datas = unitsMap.get(r);\n\t\t\tSet<ExperimentData> sources = r.sourceData.getData().stream().filter(datas::contains)\n\t\t\t\t.collect(Collectors.toSet());\n\t\t\tSet<ExperimentData> targets = r.targetData.getData().stream().filter(datas::contains)\n\t\t\t\t.collect(Collectors.toSet());\n\n\t\t\tfor (ExperimentData source : sources)\n\t\t\t{\n\t\t\t\tfor (ExperimentData target : targets)\n\t\t\t\t{\n\t\t\t\t\tFileUtil.writeln(source.getId() + \"\\t\" + r.type.getName() + \"\\t\" + target.getId(), writer1);\n\t\t\t\t\tused.add(source);\n\t\t\t\t\tused.add(target);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\twriter1.close();\n\n\t\tfilename = filename.substring(0, filename.lastIndexOf(\".\")) + \".format\";\n\t\tBufferedWriter writer2 = new BufferedWriter(new FileWriter(filename));\n\t\twriter2.write(\"node\\tall-nodes\\tcolor\\t255 255 255\\n\");\n\t\tused.stream().forEach(data ->\n\t\t{\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tFileUtil.writeln(\"node\\t\" + data.getId() + \"\\tcolor\\t\" + vtc.getColorInString(data.getChangeValue()),\n\t\t\t\t\twriter2);\n\t\t\t}\n\t\t\tif (data.getType() == DataType.PHOSPHOPROTEIN && data.getEffect() != 0)\n\t\t\t{\n\t\t\t\tFileUtil.writeln(\"node\\t\" + data.getId() + \"\\tbordercolor\\t\" +\n\t\t\t\t\tinString(data.getEffect() == -1 ? inhibitingBorderColor : activatingBorderColor), writer2);\n\t\t\t}\n\t\t});\n\t\twriter2.close();\n\t}\n\n\t/**\n\t * Writes the graph in JSON format, which can be viewed using the web-based proteomics analysis tool.\n\t */\n\tpublic void writeJSON(String filename) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".json\")) filename += \".json\";\n\n\t\tMap<String, Object> map = new HashMap<>();\n\t\tList<Map> nodes = new ArrayList<>();\n\t\tList<Map> edges = new ArrayList<>();\n\t\tmap.put(\"nodes\", nodes);\n\t\tmap.put(\"edges\", edges);\n\n\t\tMap<String, Map> geneMap = new HashMap<>();\n\t\tSet<String> relMem = new HashSet<>();\n\n\t\trelations.forEach(rel ->\n\t\t{\n\t\t\tString src = rel.source.startsWith(\"CHEBI:\") ? rel.sourceData.getData().iterator().next().getId() : rel.source;\n\t\t\tString tgt = rel.target.startsWith(\"CHEBI:\") ? rel.targetData.getData().iterator().next().getId() : rel.target;\n\t\t\tString key = src + \"\\t\" + rel.type.getName() + \"\\t\" + tgt;\n\t\t\tif (relMem.contains(key)) return;\n\t\t\telse relMem.add(key);\n\n\t\t\tMap<String, Object> edge = new HashMap<>();\n\t\t\tedges.add(edge);\n\t\t\tMap<String, Object> dMap = new HashMap<>();\n\t\t\tedge.put(\"data\", dMap);\n\t\t\tdMap.put(\"source\", src);\n\t\t\tdMap.put(\"target\", tgt);\n\t\t\tdMap.put(\"edgeType\", rel.type.getName());\n\t\t\tdMap.put(\"tooltipText\", CollectionUtil.merge(rel.getTargetWithSites(0), \", \"));\n\n\t\t\tif (rel.getMediators() != null)\n\t\t\t{\n\t\t\t\tList<String> medList = Arrays.asList(rel.getMediators().split(\";| \"));\n\t\t\t\tif (!medList.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tdMap.put(\"pcLinks\", medList);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tSet<String> totalProtUsedUp = new HashSet<>();\n\n\t\tSet<ExperimentData> dataInGraph = getExperimentDataToDraw();\n\n\t\tdataInGraph.forEach(data ->\n\t\t{\n\t\t\tString colS = \"255 255 255\";\n\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tif (data.getChangeSign() != 0)\n\t\t\t\t{\n\t\t\t\t\tcolS = vtc.getColorInJSONString(data.getChangeValue());\n\t\t\t\t}\n\t\t\t\telse return;\n\t\t\t}\n\n\t\t\tString bor = inJSONString(defaultBorderColor);\n\t\t\tString let = \"?\";\n\n\t\t\tif (data instanceof SiteModProteinData)\n\t\t\t{\n\t\t\t\tSiteModProteinData pd = (SiteModProteinData) data;\n\t\t\t\tif (pd.getEffect() > 0) bor = inJSONString(activatingBorderColor);\n\t\t\t\telse if (pd.getEffect() < 0) bor = inJSONString(inhibitingBorderColor);\n\n\t\t\t\tlet = pd.getModification().toString().substring(0, 1).toLowerCase();\n\t\t\t}\n\t\t\telse if (data instanceof ProteinData)\n\t\t\t{\n\t\t\t\tlet = \"t\";\n\t\t\t}\n\t\t\telse if (data instanceof MetaboliteData)\n\t\t\t{\n\t\t\t\tlet = \"c\";\n\t\t\t}\n\t\t\telse if (data instanceof MutationData)\n\t\t\t{\n\t\t\t\tlet = \"x\";\n\t\t\t\tif (data.getEffect() == 1)\n\t\t\t\t\tbor = inJSONString(activatingBorderColor);\n\t\t\t\telse bor = inJSONString(inhibitingBorderColor);\n\t\t\t}\n\t\t\telse if (data instanceof CNAData)\n\t\t\t{\n\t\t\t\tlet = \"d\";\n\t\t\t}\n\t\t\telse if (data instanceof RNAData)\n\t\t\t{\n\t\t\t\tlet = \"r\";\n\t\t\t}\n\t\t\telse if (data instanceof ActivityData)\n\t\t\t{\n\t\t\t\tlet = data.getChangeSign() > 0 ? \"!\" : \"i\";\n\t\t\t\tbor = inJSONString(activatingBorderColor);\n\t\t\t}\n\n\t\t\tString siteID = data.id;\n\t\t\tString val = data.hasChangeDetector() ? data.getChangeValue() + \"\" : \"\";\n\n\t\t\tfor (String sym : data.getGeneSymbols())\n\t\t\t{\n\t\t\t\tString nodeText = let.equals(\"c\") ? siteID : sym;\n\t\t\t\tinitJsonNode(geneMap, nodes, nodeText);\n\n\t\t\t\tMap node = geneMap.get(nodeText);\n\n\t\t\t\tif (nsc != null)\n\t\t\t\t{\n\t\t\t\t\tif (nsc.isDownstreamSignificant(sym))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderWidth\", \"2px\");\n\t\t\t\t\t}\n\t\t\t\t\tboolean act = false;\n\t\t\t\t\tboolean inh = false;\n\n\t\t\t\t\tif (nsc instanceof NSCForComparison)\n\t\t\t\t\t{\n\t\t\t\t\t\tact = ((NSCForComparison) nsc).isActivatingTargetsSignificant(sym);\n\t\t\t\t\t\tinh = ((NSCForComparison) nsc).isInhibitoryTargetsSignificant(sym);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (act || inh && !node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\tif (act && !inh) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(activatingBorderColor));\n\t\t\t\t\telse if (!act && inh) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(inhibitingBorderColor));\n\t\t\t\t\telse if (act /** && inh **/) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(doubleSignificanceBorderColor));\n\t\t\t\t}\n\n\t\t\t\tif (useGeneBGForTotalProtein && (let.equals(\"t\") || let.equals(\"c\")) && !totalProtUsedUp.contains(nodeText))\n\t\t\t\t{\n\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\t\t\t\t\t((Map) node.get(\"css\")).put(\"backgroundColor\", colS);\n\t\t\t\t\tString tooltip = (let.equals(\"c\") ? sym : siteID) + (val.isEmpty() ? \"\" : \", \" + val);\n\t\t\t\t\t((Map) node.get(\"data\")).put(\"tooltipText\", tooltip);\n\t\t\t\t\ttotalProtUsedUp.add(nodeText);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMap site = new HashMap();\n\t\t\t\t\t((List) ((Map) node.get(\"data\")).get(\"sites\")).add(site);\n\n\t\t\t\t\tsite.put(\"siteText\", let);\n\t\t\t\t\tsite.put(\"siteInfo\", siteID);\n\t\t\t\t\tsite.put(\"siteBackgroundColor\", colS);\n\t\t\t\t\tsite.put(\"siteBorderColor\", bor);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(filename));\n\t\tJsonUtils.writePrettyPrint(writer, map);\n\t\twriter.close();\n\t}\n\n\t/**\n\t * This method takes in a SIF graph defined by two files (.sif and .format), and generates a corresponding .json\n\t * file that the webserver can display.\n\t *\n\t * @param sifFileanme SIF filename\n\t * @param formatFilename Format filename\n\t * @param outJasonFilename JASON filename to produce\n\t */\n\tpublic static void convertSIFToJSON(String sifFileanme, String formatFilename, String outJasonFilename) throws IOException\n\t{\n\t\tMap<String, Object> map = new HashMap<>();\n\t\tList<Map> nodes = new ArrayList<>();\n\t\tList<Map> edges = new ArrayList<>();\n\t\tmap.put(\"nodes\", nodes);\n\t\tmap.put(\"edges\", edges);\n\n\t\tMap<String, Map> nodeMap = new HashMap<>();\n\t\tSet<String> relMem = new HashSet<>();\n\n\t\tFiles.lines(Paths.get(sifFileanme)).map(l -> l.split(\"\\t\")).forEach(t ->\n\t\t{\n\t\t\tif (t.length > 2)\n\t\t\t{\n\t\t\t\tString key = t[0] + \"\\t\" + t[1] + \"\\t\" + t[2];\n\t\t\t\tif (relMem.contains(key)) return;\n\t\t\t\telse relMem.add(key);\n\n\t\t\t\tMap<String, Object> edge = new HashMap<>();\n\t\t\t\tedges.add(edge);\n\t\t\t\tMap<String, Object> dMap = new HashMap<>();\n\t\t\t\tedge.put(\"data\", dMap);\n\t\t\t\tdMap.put(\"source\", t[0]);\n\t\t\t\tdMap.put(\"target\", t[2]);\n\t\t\t\tdMap.put(\"edgeType\", t[1]);\n\t\t\t\tif (t.length > 4 && !t[4].trim().isEmpty())\n\t\t\t\t{\n\t\t\t\t\tdMap.put(\"tooltipText\", t[2] + \"-\" + CollectionUtil.merge(Arrays.asList(t[4].split(\";\")), \"-\"));\n\t\t\t\t}\n\n\t\t\t\tif (t.length > 3 && !t[3].trim().isEmpty())\n\t\t\t\t{\n\t\t\t\t\tList<String> medList = Arrays.asList(t[3].split(\";| \"));\n\t\t\t\t\tif (!medList.isEmpty())\n\t\t\t\t\t{\n\t\t\t\t\t\tdMap.put(\"pcLinks\", medList);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinitJsonNode(nodeMap, nodes, t[2]);\n\t\t\t}\n\n\t\t\tif (t.length > 0 && !t[0].isEmpty()) initJsonNode(nodeMap, nodes, t[0]);\n\t\t});\n\n\t\tMap<String, String> defaultColors = new HashMap<>();\n\t\tString defBGCKey = \"node BG color\";\n\t\tString defBorCKey = \"node border color\";\n\n\t\tFiles.lines(Paths.get(formatFilename)).map(l -> l.split(\"\\t\")).filter(t -> t.length > 3).forEach(t ->\n\t\t{\n\t\t\tif (t[1].equals(\"all-nodes\"))\n\t\t\t{\n\t\t\t\tif (t[2].equals(\"color\")) defaultColors.put(defBGCKey, jasonizeColor(t[3]));\n\t\t\t\telse if (t[2].equals(\"bordercolor\")) defaultColors.put(defBorCKey, jasonizeColor(t[3]));\n\t\t\t}\n\n\t\t\tif (t[0].equals(\"node\"))\n\t\t\t{\n\t\t\t\tString name = t[1];\n\t\t\t\tMap node = nodeMap.get(name);\n\t\t\t\tif (node != null)\n\t\t\t\t{\n\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\tswitch (t[2])\n\t\t\t\t\t{\n\t\t\t\t\t\tcase \"rppasite\":\n\t\t\t\t\t\t\tString[] x = t[3].split(\"\\\\|\");\n\t\t\t\t\t\t\tMap site = new HashMap();\n\t\t\t\t\t\t\t((List) ((Map) node.get(\"data\")).get(\"sites\")).add(site);\n\t\t\t\t\t\t\tsite.put(\"siteText\", x[1]);\n\t\t\t\t\t\t\tsite.put(\"siteInfo\", x[0] + (x.length > 4 ? (\" \" + x[4]) : \"\"));\n\t\t\t\t\t\t\tsite.put(\"siteBackgroundColor\", jasonizeColor(x[2]));\n\t\t\t\t\t\t\tsite.put(\"siteBorderColor\", jasonizeColor(x[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"color\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"backgroundColor\", jasonizeColor(t[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"bordercolor\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderColor\", jasonizeColor(t[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"borderwidth\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderWidth\", t[3] + \"px\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"tooltip\":\n\t\t\t\t\t\t\t((Map) node.get(\"data\")).put(\"tooltipText\", t[3]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(outJasonFilename));\n\t\tJsonUtils.writePrettyPrint(writer, map);\n\t\twriter.close();\n\t}\n\n\tprivate static void initJsonNode(Map<String, Map> nodeMap, List<Map> nodes, String name)\n\t{\n\t\tif (!nodeMap.containsKey(name))\n\t\t{\n\t\t\tHashMap<String, Object> node = new HashMap<>();\n\t\t\tnodeMap.put(name, node);\n\t\t\tnodes.add(node);\n\t\t\tMap<String, Object> d = new HashMap<>();\n\t\t\tnode.put(\"data\", d);\n\t\t\td.put(\"id\", name);\n\t\t\td.put(\"text\", name);\n\t\t\tList<Map> sites = new ArrayList<>();\n\t\t\td.put(\"sites\", sites);\n\t\t}\n\t}\n\n\tprivate static String jasonizeColor(String c)\n\t{\n\t\tString[] t = c.split(\" \");\n\t\treturn \"rgb(\" + ArrayUtil.getString(\",\", t[0], t[1], t[2]) + \")\";\n\t}\n\n\tprivate Set<ExperimentData> getExperimentDataToDraw()\n\t{\n\t\tif (experimentDataToDraw != null) return experimentDataToDraw;\n\n\t\tSet<ExperimentData> datas = Stream.concat(\n\t\t\trelations.stream().map(r -> r.sourceData.getChangedData().keySet()).flatMap(Collection::stream),\n\t\t\trelations.stream().map(r -> r.targetData.getChangedData().keySet()).flatMap(Collection::stream))\n\t\t\t.collect(Collectors.toSet());\n\n\t\tif (otherGenesToShow != null)\n\t\t{\n\t\t\tdatas.addAll(otherGenesToShow.stream().map(GeneWithData::getData).flatMap(Collection::stream)\n\t\t\t\t.collect(Collectors.toSet()));\n\t\t}\n\n\t\treturn datas;\n\t}\n\n\tprivate Set<String> getGenesInGraph()\n\t{\n\t\treturn relations.stream().map(r -> new String[]{r.source, r.target}).flatMap(Arrays::stream)\n\t\t\t.collect(Collectors.toSet());\n\t}\n}", "public class Relation\n{\n\t/**\n\t * Source gene.\n\t */\n\tpublic String source;\n\n\t/**\n\t * Target gene.\n\t */\n\tpublic String target;\n\n\t/**\n\t * The type of the relation.\n\t */\n\tpublic RelationType type;\n\n\t/**\n\t * Set of experiment data associated with source gene.\n\t */\n\tpublic GeneWithData sourceData;\n\n\t/**\n\t * Set of experiment data associated with target gene.\n\t */\n\tpublic GeneWithData targetData;\n\n\t/**\n\t * Pathway Commons IDs of the mediator objects for the relation.\n\t */\n\tprivate String mediators;\n\n\t/**\n\t * A change detector that can evaluate pairs of experiment data to see if this relation can explain the causality\n\t * between them.\n\t */\n\tpublic TwoDataChangeDetector chDet;\n\n\t/**\n\t * Sites for the target. Needed when the relation is a phosphorylation or dephosphorylation.\n\t */\n\tpublic Set<ProteinSite> sites;\n\n\t/**\n\t * For performance reasons. This design assumes the proximityThreshold will not change during execution of the\n\t * program.\n\t */\n\tprivate Set<String> targetWithSites;\n\n\tpublic Relation(String source, String target, RelationType type, String mediators)\n\t{\n\t\tthis.source = source;\n\t\tthis.target = target;\n\t\tthis.type = type;\n\t\tthis.mediators = mediators;\n\t}\n\n\tpublic Relation(String line)\n\t{\n\t\tString[] token = line.split(\"\\t\");\n\t\tthis.source = token[0];\n\t\tthis.target = token[2];\n\t\tthis.type = RelationType.getType(token[1]);\n\t\tif (token.length > 3) this.mediators = token[3];\n\t\tif (token.length > 4)\n\t\t{\n\t\t\tsites = Arrays.stream(token[4].split(\";\")).map(s -> new ProteinSite(Integer.valueOf(s.substring(1)),\n\t\t\t\tString.valueOf(s.charAt(0)), 0)).collect(Collectors.toSet());\n\t\t}\n\t}\n\n\t/**\n\t * Sign of the relation.\n\t */\n\tpublic int getSign()\n\t{\n\t\treturn type.sign;\n\t}\n\n\tpublic String toString()\n\t{\n\t\treturn source + \"\\t\" + type.getName() + \"\\t\" + target + \"\\t\" + mediators + \"\\t\" + getSitesInString();\n\t}\n\n\tpublic String getMediators()\n\t{\n\t\treturn mediators;\n\t}\n\n\tpublic Set<String> getTargetWithSites(int proximityThr)\n\t{\n\t\tif (targetWithSites == null)\n\t\t{\n\t\t\ttargetWithSites = new HashSet<>();\n\n\t\t\tif (sites != null)\n\t\t\t{\n\t\t\t\tfor (ProteinSite site : sites)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i <= proximityThr; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\ttargetWithSites.add(target + \"_\" + (site.getSite() + i));\n\t\t\t\t\t\ttargetWithSites.add(target + \"_\" + (site.getSite() - i));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn targetWithSites;\n\t}\n\n\tpublic String getSitesInString()\n\t{\n\t\treturn sites == null ? \"\" : CollectionUtil.merge(sites, \";\");\n\t}\n\n\tpublic Set<ExperimentData> getAllData()\n\t{\n\t\treturn CollectionUtil.getUnion(sourceData.getData(), targetData.getData());\n\t}\n\n\tpublic void setChDet(TwoDataChangeDetector chDet)\n\t{\n\t\tthis.chDet = chDet;\n\t}\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn source.hashCode() + target.hashCode() + type.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj)\n\t{\n\t\treturn obj instanceof Relation && ((Relation) obj).source.equals(source) &&\n\t\t\t((Relation) obj).target.equals(target) && ((Relation) obj).type.equals(type);\n\t}\n\n\tpublic Relation copy()\n\t{\n\t\tRelation cln = new Relation(source, target, type, mediators);\n\t\tcln.sites = sites;\n\t\treturn cln;\n\t}\n}", "public class NetworkLoader\n{\n\t/**\n\t * Reads 4 of the built-in resource networks.\n\t */\n\tpublic static Set<Relation> load()\n\t{\n\t\treturn load(new HashSet<>(Arrays.asList(ResourceType.PC, ResourceType.PhosphoSitePlus,\n\t\t\tResourceType.PhosphoNetworks, ResourceType.IPTMNet, ResourceType.TRRUST, ResourceType.TFactS, ResourceType.PCMetabolic)));\n\t}\n\n\t/**\n\t * Reads the selected built-in resource networks.\n\t */\n\tpublic static Set<Relation> load(Set<ResourceType> resourceTypes)\n\t{\n\t\tSet<Relation> relations = new HashSet<>();\n\n\t\tMap<SignedType, DirectedGraph> allGraphs = new HashMap<>();\n\n\t\t// Load signed directed graph from Pathway Commons\n\t\tif (resourceTypes.contains(ResourceType.PC))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, SignedPC.get().getAllGraphs());\n\t\t}\n\n\t\t// Add PhosphoSitePlus\n\t\tif (resourceTypes.contains(ResourceType.PhosphoSitePlus))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, PhosphoSitePlus.get().getAllGraphs());\n\t\t}\n\n\t\t// Add REACH\n\t\tif (resourceTypes.contains(ResourceType.REACH))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, SignedREACH.get().getAllGraphs());\n\t\t}\n\n\t\t// Add IPTMNet\n\t\tif (resourceTypes.contains(ResourceType.IPTMNet))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, IPTMNet.get().getAllGraphs());\n\t\t}\n\n\t\t// Add PhosphoNetworks\n\t\tif (resourceTypes.contains(ResourceType.PhosphoNetworks))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PHOSPHORYLATES, PhosphoNetworks.get().getGraph());\n\t\t}\n\n\t\t// Add NetworKIN\n\t\tif (resourceTypes.contains(ResourceType.NetworKIN))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PHOSPHORYLATES, NetworKIN.get().getGraph());\n\t\t}\n\n\t\t// Add Rho GEF\n\t\tif (resourceTypes.contains(ResourceType.RHOGEF))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.ACTIVATES_GTPASE, RhoGEF.get().getGraph());\n\t\t}\n\n\t\t// Experimental code!!!!!!!!!!!!!!!!!!!\n\t\tif (resourceTypes.contains(ResourceType.PCTCGAConsensus))\n\t\t{\n\t\t\tDirectedGraph posG = new DirectedGraph(\"Pos\", SignedType.UPREGULATES_EXPRESSION.getTag());\n\t\t\tDirectedGraph negG = new DirectedGraph(\"Neg\", SignedType.DOWNREGULATES_EXPRESSION.getTag());\n\t\t\tString file = \"/home/babur/Documents/PC/SignedByTCGAConsensusFiltered.sif\";\n\t\t\tposG.load(file, Collections.singleton(posG.getEdgeType()));\n\t\t\tnegG.load(file, Collections.singleton(negG.getEdgeType()));\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, posG);\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, negG);\n\t\t}\n\n\t\t// Add TRRUST\n\t\tif (resourceTypes.contains(ResourceType.TRRUST))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, TRRUST.get().getPositiveGraph());\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, TRRUST.get().getNegativeGraph());\n\t\t}\n\n\t\t// Add TFactS\n\t\tif (resourceTypes.contains(ResourceType.TFactS))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, TFactS.get().getPositiveGraph());\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, TFactS.get().getNegativeGraph());\n\t\t}\n\n\t\t// Add PC Metabolic\n\t\tif (resourceTypes.contains(ResourceType.PCMetabolic))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PRODUCES, SignedMetabolic.getGraph(SignedType.PRODUCES));\n\t\t\taddGraph(allGraphs, SignedType.CONSUMES, SignedMetabolic.getGraph(SignedType.CONSUMES));\n\t\t\taddGraph(allGraphs, SignedType.USED_TO_PRODUCE, SignedMetabolic.getGraph(SignedType.USED_TO_PRODUCE));\n\t\t}\n\n\t\t// Clean-up conflicts\n\t\tcleanUpConflicts(allGraphs);\n\n\t\t// Generate relations based on the network\n\n\t\tfor (SignedType signedType : allGraphs.keySet())\n\t\t{\n\t\t\tDirectedGraph graph = allGraphs.get(signedType);\n\t\t\tif (graph == null)\n\t\t\t{\n//\t\t\t\tSystem.out.println(\"Null graph for type: \" + signedType);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// take a subset of the network for debugging\n//\t\t\tgraph.crop(Arrays.asList(\"HCK\", \"CD247\"));\n\n\t\t\tfor (String source : graph.getOneSideSymbols(true))\n\t\t\t{\n\t\t\t\tfor (String target : graph.getDownstream(source))\n\t\t\t\t{\n\t\t\t\t\tRelationType type;\n\t\t\t\t\tswitch (signedType)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase PHOSPHORYLATES: type = RelationType.PHOSPHORYLATES; break;\n\t\t\t\t\t\tcase DEPHOSPHORYLATES: type = RelationType.DEPHOSPHORYLATES; break;\n\t\t\t\t\t\tcase UPREGULATES_EXPRESSION: type = RelationType.UPREGULATES_EXPRESSION; break;\n\t\t\t\t\t\tcase DOWNREGULATES_EXPRESSION: type = RelationType.DOWNREGULATES_EXPRESSION; break;\n\t\t\t\t\t\tcase ACTIVATES_GTPASE: type = RelationType.ACTIVATES_GTPASE; break;\n\t\t\t\t\t\tcase INHIBITS_GTPASE: type = RelationType.INHIBITS_GTPASE; break;\n\t\t\t\t\t\tcase ACETYLATES: type = RelationType.ACETYLATES; break;\n\t\t\t\t\t\tcase DEACETYLATES: type = RelationType.DEACETYLATES; break;\n\t\t\t\t\t\tcase DEMETHYLATES: type = RelationType.DEMETHYLATES; break;\n\t\t\t\t\t\tcase METHYLATES: type = RelationType.METHYLATES; break;\n\t\t\t\t\t\tcase PRODUCES: type = RelationType.PRODUCES; break;\n\t\t\t\t\t\tcase CONSUMES: type = RelationType.CONSUMES; break;\n\t\t\t\t\t\tcase USED_TO_PRODUCE: type = RelationType.USED_TO_PRODUCE; break;\n\t\t\t\t\t\tdefault: throw new RuntimeException(\"Is there a new type??\");\n\t\t\t\t\t}\n\t\t\t\t\tRelation rel = new Relation(source, target, type, graph.getMediatorsInString(source, target));\n\n\t\t\t\t\tif (graph instanceof SiteSpecificGraph)\n\t\t\t\t\t{\n\t\t\t\t\t\tSiteSpecificGraph pGraph = (SiteSpecificGraph) graph;\n\t\t\t\t\t\tSet<String> sites = pGraph.getSites(source, target);\n\t\t\t\t\t\tif (sites != null && !sites.isEmpty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trel.sites = new HashSet<>();\n\n\t\t\t\t\t\t\tfor (String site : sites)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!site.isEmpty())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\trel.sites.add(new ProteinSite(Integer.parseInt(site.substring(1)),\n\t\t\t\t\t\t\t\t\t\tsite.substring(0, 1), 0));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\trelations.add(rel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// clean from non-HGNC\n\n\t\trelations = relations.stream().filter(r -> (r.source.startsWith(\"CHEBI:\") || HGNC.get().getSymbol(r.source) != null) &&\n\t\t\t(r.target.startsWith(\"CHEBI:\") || HGNC.get().getSymbol(r.target) != null)).collect(Collectors.toSet());\n\n\t\t// initiate source and target data\n\n\t\tinitSourceTargetData(relations);\n\n\t\treturn relations;\n\t}\n\n\tprivate static void check(Map<SignedType, DirectedGraph> allGraphs)\n\t{\n\t\tDirectedGraph graph = allGraphs.get(SignedType.DEPHOSPHORYLATES);\n\t\tif (graph != null)\n\t\t{\n\t\t\tSet<String> dwns = graph.getDownstream(\"ABL1\");\n\t\t\tif (dwns.contains(\"RB1\"))\n\t\t\t{\n\t\t\t\tSystem.out.println(\"Here it is!!!\");\n\t\t\t}\n\t\t\telse System.out.println(\"Nope\");\n\t\t}\n\t\telse System.out.println(\"No graph\");\n\t}\n\n\tpublic static Set<Relation> load(String customFile) throws IOException\n\t{\n\t\tSet<Relation> relations = Files.lines(Paths.get(customFile)).filter(l -> !l.isEmpty() && !l.startsWith(\"#\")).map(Relation::new)\n\t\t\t.collect(Collectors.toSet());\n\n\t\tinitSourceTargetData(relations);\n\n\t\treturn relations;\n\t}\n\n\tprivate static void initSourceTargetData(Set<Relation> relations)\n\t{\n\t\tSet<String> genes = relations.stream().map(r -> r.source).collect(Collectors.toSet());\n\t\tgenes.addAll(relations.stream().map(r -> r.target).collect(Collectors.toSet()));\n\n\t\tMap<String, GeneWithData> map = new HashMap<>();\n\t\tgenes.forEach(g -> map.put(g, new GeneWithData(g)));\n\n\t\tfor (Relation relation : relations)\n\t\t{\n\t\t\trelation.sourceData = map.get(relation.source);\n\t\t\trelation.targetData = map.get(relation.target);\n\t\t}\n\t}\n\n\tprivate static void mergeSecondMapIntoFirst(Map<SignedType, DirectedGraph> allGraphs, Map<SignedType, DirectedGraph> graphs)\n\t{\n\t\tfor (SignedType type : graphs.keySet())\n\t\t{\n\t\t\tif (allGraphs.containsKey(type)) allGraphs.get(type).merge(graphs.get(type));\n\t\t\telse allGraphs.put(type, graphs.get(type));\n\t\t}\n\t}\n\n\tprivate static void addGraph(Map<SignedType, DirectedGraph> allGraphs, SignedType type, DirectedGraph graph)\n\t{\n\t\tif (allGraphs.containsKey(type)) allGraphs.get(type).merge(graph);\n\t\telse allGraphs.put(type, graph);\n\t}\n\n\tprivate static void cleanUpConflicts(Map<SignedType, DirectedGraph> graphs)\n\t{\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.PHOSPHORYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEPHOSPHORYLATES));\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.ACETYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEACETYLATES));\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.METHYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEMETHYLATES));\n\t\tcleanUpConflicts(graphs.get(SignedType.UPREGULATES_EXPRESSION), graphs.get(SignedType.DOWNREGULATES_EXPRESSION));\n\t\tcleanUpConflicts(graphs.get(SignedType.ACTIVATES_GTPASE), graphs.get(SignedType.INHIBITS_GTPASE));\n\t}\n\n\tprivate static void cleanUpConflicts(DirectedGraph graph1, DirectedGraph graph2)\n\t{\n\t\tSet<String[]> rem1 = new HashSet<>();\n\t\tSet<String[]> rem2 = new HashSet<>();\n\n\t\tfor (String source : graph1.getOneSideSymbols(true))\n\t\t{\n\t\t\tfor (String target : graph1.getDownstream(source))\n\t\t\t{\n\t\t\t\tif (graph2.hasRelation(source, target))\n\t\t\t\t{\n\t\t\t\t\tString[] rel = new String[]{source, target};\n\t\t\t\t\tlong c1 = paperCnt(graph1.getMediators(source, target));\n\t\t\t\t\tlong c2 = paperCnt(graph2.getMediators(source, target));\n\n\t\t\t\t\tif (c1 >= c2) rem2.add(rel);\n\t\t\t\t\tif (c2 >= c1) rem1.add(rel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trem1.forEach(rel -> graph1.removeRelation(rel[0], rel[1]));\n\t\trem2.forEach(rel -> graph2.removeRelation(rel[0], rel[1]));\n\t}\n\n\tprivate static void cleanUpConflicts(SiteSpecificGraph graph1, SiteSpecificGraph graph2)\n\t{\n\t\tfor (String source : graph1.getOneSideSymbols(true))\n\t\t{\n\t\t\tfor (String target : graph1.getDownstream(source))\n\t\t\t{\n\t\t\t\tif (graph2.hasRelation(source, target))\n\t\t\t\t{\n\t\t\t\t\tSet<String> s1 = graph1.getSites(source, target);\n\t\t\t\t\tSet<String> s2 = graph1.getSites(source, target);\n\n\t\t\t\t\tSet<String> common = CollectionUtil.getIntersection(s1, s2);\n\n\t\t\t\t\tif (!common.isEmpty())\n\t\t\t\t\t{\n\t\t\t\t\t\tlong c1 = paperCnt(graph1.getMediators(source, target));\n\t\t\t\t\t\tlong c2 = paperCnt(graph2.getMediators(source, target));\n\n\t\t\t\t\t\tfor (String site : common)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (c1 >= c2) graph2.removeSite(source, target, site);\n\t\t\t\t\t\t\tif (c2 >= c1) graph1.removeSite(source, target, site);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static long paperCnt(Set<String> mediators)\n\t{\n\t\treturn mediators.stream().filter(s -> s.startsWith(\"PMID:\")).distinct().count();\n\t}\n\n\tpublic enum ResourceType\n\t{\n\t\tPC(\"Pathway Commons v9 for all kinds of relations.\"),\n\t\tPhosphoSitePlus(\"PhosphoSitePlus database for (de)phosphorylations, (de)acetylations and (de)methylations.\"),\n\t\tREACH(\"Network derived from REACH NLP extraction results for phosphorylation relations.\"),\n\t\tPhosphoNetworks(\"The PhosphoNetworks database for phosphorylations.\"),\n\t\tIPTMNet(\"The IPTMNet database for phosphorylations.\"),\n\t\tRHOGEF(\"The experimental Rho - GEF relations.\"),\n\t\tPCTCGAConsensus(\"Unsigned PC relations whose signs are inferred by TCGA studies.\"),\n\t\tTRRUST(\"The TRRUST database for expression relations.\"),\n\t\tTFactS(\"The TFactS database for expression relations.\"),\n\t\tNetworKIN(\"The NetworKIN database for phosphorylation relations.\"),\n\t\tPCMetabolic(\"Relations involving chemicals in PC\"),\n\t\t;\n\n\t\tString description;\n\n\t\tResourceType(String description)\n\t\t{\n\t\t\tthis.description = description;\n\t\t}\n\n\t\tpublic static Set<ResourceType> getSelectedResources(Set<String> names)\n\t\t{\n\t\t\tSet<ResourceType> set = new HashSet<>();\n\t\t\tfor (String res : names)\n\t\t\t{\n\t\t\t\tres = res.trim();\n\n\t\t\t\tif (!res.isEmpty())\n\t\t\t\t{\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tResourceType type = valueOf(res);\n\t\t\t\t\t\tset.add(type);\n\t\t\t\t\t} catch (IllegalArgumentException e)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new RuntimeException(\"Network resource not recognized: \" + res);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn set;\n\t\t}\n\n\t\tpublic static String getUsageInfo()\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tfor (ResourceType type : values())\n\t\t\t{\n\t\t\t\tsb.append(\"\\t\").append(type.name()).append(\": \").append(type.description).append(\"\\n\");\n\t\t\t}\n\t\t\treturn sb.toString();\n\t\t}\n\n\t\tpublic static Map getValuesAsJson()\n\t\t{\n\t\t\tList list = new ArrayList<>();\n\t\t\tfor (ResourceType type : values())\n\t\t\t{\n\t\t\t\tlist.add(type.toString());\n\t\t\t}\n\n\t\t\tMap map = new LinkedHashMap<>();\n\t\t\tmap.put(\"name\", \"ResourceType\");\n\t\t\tmap.put(\"values\", list);\n\t\t\treturn map;\n\t\t}\n\n\t}\n\n\n\tpublic static void main(String[] args) throws IOException\n\t{\n//\t\twriteSitesWithUpstream();\n\t\twriteRelations();\n\t}\n\n\tprivate static void writeRelations() throws IOException\n\t{\n\t\tSet<Relation> rels = NetworkLoader.load();\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(\"/Users/ozgun/Documents/Temp/causal-priors.txt\"));\n\n\t\tfor (Relation rel : rels)\n\t\t{\n\t\t\twriter.write(rel.toString() + \"\\n\");\n\t\t}\n\n\t\twriter.close();\n\t}\n\n\tpublic static void writeSitesWithUpstream() throws IOException\n\t{\n\t\tSet<Relation> rels = NetworkLoader.load(new HashSet<>(Arrays.asList(ResourceType.PC, ResourceType.PhosphoNetworks)));\n\t\tMap<String, Set<ProteinSite>> map = new HashMap<>();\n\t\tfor (Relation rel : rels)\n\t\t{\n\t\t\tif (rel.sites != null)\n\t\t\t{\n\t\t\t\tif (!map.containsKey(rel.target)) map.put(rel.target, new HashSet<>());\n\t\t\t\tmap.get(rel.target).addAll(rel.sites);\n\t\t\t}\n\t\t}\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(\"/home/ozgun/Documents/Temp/gene-to-sites.txt\"));\n\n\t\tfor (String gene : map.keySet())\n\t\t{\n\t\t\tSet<ProteinSite> sites = map.get(gene);\n\t\t\twriter.write(\"\\n\" + gene + \"\\t\");\n\t\t\twriter.write(CollectionUtil.merge(sites, \" \"));\n\t\t}\n\n\t\twriter.close();\n\t}\n\n}", "public class ProteomicsFileReader\n{\n\tprotected final static double LOG2 = Math.log(2);\n\n\t/**\n\t * Reads the annotation in a given proteomics file.\n\t *\n\t * @param filename name of the file\n\t * @param idCol name of the ID column\n\t * @param symbolCol name of the symbols column\n\t * @param siteCol name of the sites column\n\t * @param effectCol name of the effect column\n\t */\n\tpublic static List<ProteomicsFileRow> readAnnotation(String filename, String idCol, String symbolCol,\n\t\tString siteCol, String modCol, String effectCol) throws FileNotFoundException\n\t{\n\t\tList<ProteomicsFileRow> datas = new ArrayList<>();\n\n\t\tScanner sc = new Scanner(new File(filename));\n\t\tString s = sc.nextLine();\n\t\tList<String> cols = Arrays.asList(s.split(\"\\t\"));\n\n\t\tint colInd = cols.indexOf(idCol);\n\t\tint symbolInd = cols.indexOf(symbolCol);\n\t\tint siteInd = cols.indexOf(siteCol);\n\t\tint modInd = modCol == null ? -1 : cols.indexOf(modCol);\n\t\tint effectInd = effectCol == null ? -1 : cols.indexOf(effectCol);\n\n\t\twhile (sc.hasNextLine())\n\t\t{\n\t\t\tString[] row = sc.nextLine().split(\"\\t\");\n\t\t\tString id = row[colInd];\n\t\t\tString syms = row[symbolInd];\n\t\t\tString sites = row.length > siteInd ? row[siteInd] : \"\";\n\t\t\tFeature feature = modInd >= 0 && row.length > modInd ? Feature.getFeat(row[modInd]) : null;\n\t\t\tString effect = effectInd >= 0 && row.length > effectInd ? row[effectInd] : null;\n\n\t\t\tList<String> genes = Arrays.asList(syms.split(\"\\\\s+\"));\n\t\t\tMap<String, List<String>> siteMap = sites.isEmpty() ? null : new HashMap<>();\n\t\t\tif (!sites.isEmpty())\n\t\t\t{\n\t\t\t\tString[] perGene = sites.split(\"\\\\s+\");\n\t\t\t\tfor (int i = 0; i < perGene.length; i++)\n\t\t\t\t{\n\t\t\t\t\tsiteMap.put(genes.get(i), Arrays.asList(perGene[i].split(\"\\\\|\")));\n\t\t\t\t}\n\t\t\t\tif (siteMap.size() < genes.size())\n\t\t\t\t{\n\t\t\t\t\tfor (int i = siteMap.size(); i < genes.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tsiteMap.put(genes.get(i), siteMap.get(genes.get(0)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tProteomicsFileRow data = new ProteomicsFileRow(id, null, genes, siteMap, feature);\n\n\t\t\tif (effect != null)\n\t\t\t{\n\t\t\t\tdata.effect = effect.equals(\"c\") ? ProteomicsFileRow.SiteEffect.COMPLEX :\n\t\t\t\t\teffect.equals(\"a\") ? ProteomicsFileRow.SiteEffect.ACTIVATING : effect.equals(\"i\") ?\n\t\t\t\t\t\tProteomicsFileRow.SiteEffect.INHIBITING : null;\n\t\t\t}\n\n\t\t\tdatas.add(data);\n\t\t}\n\t\treturn datas;\n\t}\n\n\t/**\n\t * Reads the measurement values in the given proteomics file.\n\t *\n\t * @param filename File name\n\t * @param idName Name of the ID column\n\t * @param colname Array of the names of the value columns\n\t * @return Array of values for each row ID\n\t */\n\tpublic static Map<String, Double>[] readVals(String filename, String idName, String... colname)\n\t{\n\t\ttry\n\t\t{\n\t\t\tMap<String, Double>[] valMaps = new Map[colname.length];\n\t\t\tfor (int i = 0; i < valMaps.length; i++)\n\t\t\t{\n\t\t\t\tvalMaps[i] = new HashMap<>();\n\t\t\t}\n\n\t\t\tScanner sc = new Scanner(new File(filename));\n\t\t\tList<String> header = Arrays.asList(sc.nextLine().split(\"\\t\"));\n\n\t\t\tint idInd = header.indexOf(idName);\n\n\t\t\tif (idInd < 0) throw new RuntimeException(\"Cannot find \\\"\" + idName + \"\\\" column in values file.\");\n\n\t\t\tint[] valInd = new int[colname.length];\n\t\t\tfor (int i = 0; i < colname.length; i++)\n\t\t\t{\n\t\t\t\tvalInd[i] = header.indexOf(colname[i]);\n\t\t\t\tif (valInd[i] == -1) throw new RuntimeException(\"Cannot find the column \\\"\" + colname[i] + \"\\\"\");\n\t\t\t}\n\n\t\t\twhile (sc.hasNextLine())\n\t\t\t{\n\t\t\t\tString[] row = sc.nextLine().split(\"\\t\");\n\n\t\t\t\tfor (int i = 0; i < colname.length; i++)\n\t\t\t\t{\n\t\t\t\t\tdouble val;\n\t\t\t\t\ttry { val = Double.parseDouble(row[valInd[i]]); }\n\t\t\t\t\tcatch (NumberFormatException e){val = Double.NaN;}\n\n\t\t\t\t\tvalMaps[i].put(row[idInd], val);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn valMaps;\n\t\t}\n\t\tcatch (FileNotFoundException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * After reading the annotations from a proteomics file, this method is used to fill in the measurement values.\n\t * These two methods are not in the same method because annotation can be in a separate file or it can appear in\n\t * with the values. Presence of two methods satisfies this flexibility.\n\t * @param datas rows with annotations\n\t * @param filename file name\n\t * @param idColName name of the id column\n\t * @param vals list of value columns\n\t * @param missingVal what to use if a value is missing\n\t */\n\tpublic static void addValues(List<ProteomicsFileRow> datas, String filename, String idColName,\n\t\tList<String> vals, Double missingVal, boolean logTransform)\n\t{\n\t\tMap<String, Double>[] v = readVals(\n\t\t\tfilename, idColName, vals.toArray(new String[vals.size()]));\n\n\t\tfor (ProteomicsFileRow data : datas)\n\t\t{\n\t\t\tdata.vals = new double[v.length];\n\t\t\tfor (int i = 0; i < v.length; i++)\n\t\t\t{\n\t\t\t\tDouble doubVal = v[i].get(data.id);\n\t\t\t\tif (doubVal != null)\n\t\t\t\t{\n\t\t\t\t\tdata.vals[i] = logTransform ? Math.log(doubVal) / LOG2 : doubVal;\n\t\t\t\t}\n\t\t\t\telse if (missingVal == null) data.vals[i] = Double.NaN;\n\t\t\t\telse data.vals[i] = missingVal;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static int getPotentialIDColIndex(String[] header)\n\t{\n\t\treturn getPotentialColIndex(header, \"id\");\n\t}\n\n\tpublic static int getPotentialSymbolColIndex(String[] header)\n\t{\n\t\treturn getPotentialColIndex(header, \"symbol\");\n\t}\n\n\tpublic static int getPotentialSiteColIndex(String[] header)\n\t{\n\t\treturn getPotentialColIndex(header, \"site\");\n\t}\n\n\tpublic static int getPotentialEffectColIndex(String[] header)\n\t{\n\t\treturn getPotentialColIndex(header, \"effect\");\n\t}\n\n\t/**\n\t * Searches certain words in column headers to infer which column contains which type of information.\n\t */\n\tprivate static int getPotentialColIndex(String[] header, String find)\n\t{\n\t\tfor (int i = 0; i < header.length; i++)\n\t\t{\n\t\t\tif (header[i].toLowerCase().contains(find)) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Checks which columns contain numbers to infer value columns.\n\t */\n\tpublic static List<String> getNamesOfNumberColumns(String filename)\n\t{\n\t\tString[] header = getARow(filename, 1);\n\t\tString[] row = getARow(filename, 2);\n\n\t\tList<String> names = new ArrayList<>();\n\n\t\tfor (int i = 0; i < row.length; i++)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tDouble.parseDouble(row[i]);\n\t\t\t\tnames.add(header[i]);\n\t\t\t}\n\t\t\tcatch (NumberFormatException e){}\n\t\t}\n\n\t\treturn names;\n\t}\n\n\t/**\n\t * Reads the requested row from the file.\n\t */\n\tpublic static String[] getARow(String filename, int rowNum)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn Files.lines(Paths.get(filename)).skip(rowNum - 1).findFirst().get().split(\"\\t\");\n\t\t}\n\t\tcatch (IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public class ProteomicsLoader\n{\n\t/**\n\t * Map from genes to related data.\n\t */\n\tMap<String, Set<ExperimentData>> dataMap;\n\n\t/**\n\t * Set of all data. This collection supposed to hold everything in the dataMap's values.\n\t */\n\tSet<ExperimentData> datas;\n\n\t/**\n\t * Initializes self using a set of RPPAData.\n\t */\n\tpublic ProteomicsLoader(Collection<ProteomicsFileRow> rows, Map<DataType, Double> stdevThresholds)\n\t{\n\t\tdataMap = new HashMap<>();\n\t\tdatas = new HashSet<>();\n\t\trows.stream().distinct().forEach(r ->\n\t\t{\n\t\t\tExperimentData ed = r.isActivity() ? new ActivityData(r) :\n\t\t\t\tr.isSiteSpecific() ? new SiteModProteinData(r) :\n\t\t\t\tr.isRNA() ? new RNAData(r) :\n\t\t\t\tr.isMetabolite() ? new MetaboliteData(r) :\n\t\t\t\t\tnew ProteinData(r);\n\n\t\t\tif (stdevThresholds != null && ed instanceof NumericData)\n\t\t\t{\n\t\t\t\tDataType type = ed.getType();\n\t\t\t\tDouble thr = stdevThresholds.get(type);\n\t\t\t\tif (thr != null)\n\t\t\t\t{\n\t\t\t\t\tdouble sd = Summary.stdev(((NumericData) ed).vals);\n\t\t\t\t\tif (Double.isNaN(sd) || sd < thr) return;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (String sym : ed.getGeneSymbols())\n\t\t\t{\n\t\t\t\tif (!dataMap.containsKey(sym)) dataMap.put(sym, new HashSet<>());\n\n\t\t\t\t// check if there is already some data with the same ID\n\t\t\t\tfor (ExperimentData data : dataMap.get(sym))\n\t\t\t\t{\n\t\t\t\t\tif (data.getId().equals(ed.getId()))\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new RuntimeException(\"Proteomic data has non-unique IDs: \" + ed.getId());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdataMap.get(sym).add(ed);\n\t\t\t\tdatas.add(ed);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void addRepeatData(Collection<ProteomicsFileRow> rows, Map<DataType, Double> stdevThresholds)\n\t{\n\t\trows.stream().distinct().forEach(r ->\n\t\t{\n\t\t\tExperimentData ed = r.isActivity() ? new ActivityData(r) :\n\t\t\t\tr.isSiteSpecific() ? new SiteModProteinData(r) : new ProteinData(r);\n\n\t\t\tif (stdevThresholds != null && ed instanceof NumericData)\n\t\t\t{\n\t\t\t\tDataType type = ed.getType();\n\t\t\t\tDouble thr = stdevThresholds.get(type);\n\t\t\t\tif (thr != null)\n\t\t\t\t{\n\t\t\t\t\tdouble sd = Summary.stdev(((NumericData) ed).vals);\n\t\t\t\t\tif (Double.isNaN(sd) || sd < thr) return;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (String sym : ed.getGeneSymbols())\n\t\t\t{\n\t\t\t\tif (!dataMap.containsKey(sym)) dataMap.put(sym, new HashSet<>());\n\n\t\t\t\tExperimentData orig = null;\n\t\t\t\tfor (ExperimentData data : dataMap.get(sym))\n\t\t\t\t{\n\t\t\t\t\tif (data.getId().equals(ed.getId()))\n\t\t\t\t\t{\n\t\t\t\t\t\torig = data;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (orig != null)\n\t\t\t\t{\n\t\t\t\t\torig.addRepeatData(ed);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdataMap.get(sym).add(ed);\n\t\t\t\t\tdatas.add(ed);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void printStDevHistograms()\n\t{\n\t\tprintStDevHistograms(datas);\n\t}\n\tpublic void printStDevHistograms(Set<ExperimentData> datas)\n\t{\n\t\tSystem.out.println(\"\\nSt-dev histograms:\");\n\t\tMap<DataType, Histogram> hMap = new HashMap<>();\n\t\tdatas.stream().filter(d -> d instanceof NumericData).map(d -> (NumericData) d).forEach(d ->\n\t\t{\n\t\t\tDataType type = d.getType();\n\t\t\tif (!hMap.containsKey(type))\n\t\t\t{\n\t\t\t\tHistogram h = new Histogram(0.05);\n\t\t\t\th.setBorderAtZero(true);\n\t\t\t\thMap.put(type, h);\n\t\t\t}\n\t\t\thMap.get(type).count(Summary.stdev(d.vals));\n\t\t});\n\t\thMap.keySet().forEach(k ->\n\t\t{\n\t\t\tSystem.out.println(\"type = \" + k);\n\t\t\thMap.get(k).print();\n\t\t});\n\t}\n\n\t/**\n\t * Adds the related data to the given relations.\n\t */\n\tpublic void decorateRelations(Set<Relation> relations)\n\t{\n\t\tMap<String, GeneWithData> map = collectExistingData(relations);\n\t\tCausalityHelper ch = new CausalityHelper();\n\t\tfor (Relation rel : relations)\n\t\t{\n\t\t\tif (rel.sourceData == null)\n\t\t\t{\n\t\t\t\tif (map.containsKey(rel.source))\n\t\t\t\t{\n\t\t\t\t\trel.sourceData = map.get(rel.source);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tGeneWithData gwd = new GeneWithData(rel.source);\n\t\t\t\t\tgwd.addAll(dataMap.get(rel.source));\n\t\t\t\t\tmap.put(gwd.getId(), gwd);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse rel.sourceData.addAll(dataMap.get(rel.source));\n\n\t\t\tif (rel.targetData == null)\n\t\t\t{\n\t\t\t\tif (map.containsKey(rel.target))\n\t\t\t\t{\n\t\t\t\t\trel.targetData = map.get(rel.target);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tGeneWithData gwd = new GeneWithData(rel.target);\n\t\t\t\t\tgwd.addAll(dataMap.get(rel.target));\n\t\t\t\t\tmap.put(gwd.getId(), gwd);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse rel.targetData.addAll(dataMap.get(rel.target));\n\n\t\t\trel.chDet = ch;\n\t\t}\n\t}\n\n\tprivate Map<String, GeneWithData> collectExistingData(Set<Relation> relations)\n\t{\n\t\tMap<String, GeneWithData> map = new HashMap<>();\n\n\t\tfor (Relation rel : relations)\n\t\t{\n\t\t\tif (rel.sourceData != null) map.put(rel.sourceData.getId(), rel.sourceData);\n\t\t\tif (rel.targetData != null) map.put(rel.targetData.getId(), rel.targetData);\n\t\t}\n\n\t\treturn map;\n\t}\n\n\t/**\n\t * Puts the given change detector to the data that is filtered by the given selector.\n\t */\n\tpublic void associateChangeDetector(OneDataChangeDetector chDet, DataSelector selector)\n\t{\n\t\tdatas.stream().filter(selector::select).forEach(d -> d.setChDet(chDet));\n\t}\n\n\tpublic void initMissingDataForProteins()\n\t{\n\t\tOptional<ProteinData> opt = datas.stream().filter(d -> d instanceof ProteinData)\n\t\t\t.map(d -> (ProteinData) d).findAny();\n\n\t\tif (!opt.isPresent()) return;\n\n\t\tint size = opt.get().vals.length;\n\n//\t\tint[] totalProtCnt = new int[size];\n//\t\tint[] phospProtCnt = new int[size];\n\n\t\tboolean[] hasTotalProt = new boolean[size];\n\t\tboolean[] hasPhospProt = new boolean[size];\n\n\t\tArrays.fill(hasTotalProt, false);\n\t\tArrays.fill(hasPhospProt, false);\n\n\t\tdatas.stream().filter(d -> d instanceof ProteinData).map(d -> (ProteinData) d).forEach(d ->\n\t\t{\n\t\t\tif (d.getType() == DataType.PROTEIN)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < size; i++)\n\t\t\t\t{\n\t\t\t\t\tif (!Double.isNaN(d.vals[i]))\n\t\t\t\t\t{\n\t\t\t\t\t\thasTotalProt[i] = true;\n//\t\t\t\t\t\ttotalProtCnt[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (d.getType() == DataType.PHOSPHOPROTEIN)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < size; i++)\n\t\t\t\t{\n\t\t\t\t\tif (!Double.isNaN(d.vals[i]))\n\t\t\t\t\t{\n\t\t\t\t\t\thasPhospProt[i] = true;\n//\t\t\t\t\t\tphospProtCnt[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tdatas.stream().filter(d -> d instanceof ProteinData).map(d -> (ProteinData) d)\n\t\t\t.forEach(d -> d.initPresenceData(d.getType() == DataType.PHOSPHOPROTEIN ? hasPhospProt : hasTotalProt));\n\n//\t\tSystem.out.println(\"Total protein counts\");\n//\t\tHistogram h = new Histogram(100, ArrayUtil.toDouble(totalProtCnt));\n//\t\th.print();\n//\n//\t\tSystem.out.println(\"\\nPhosphoprotein counts\");\n//\t\th = new Histogram(100, ArrayUtil.toDouble(phospProtCnt));\n//\t\th.print();\n\t}\n\n\t/**\n\t * Function to filter experiment data.\n\t */\n\tpublic interface DataSelector\n\t{\n\t\tboolean select(ExperimentData data);\n\t}\n}" ]
import org.panda.causalpath.analyzer.CausalitySearcher; import org.panda.causalpath.analyzer.ThresholdDetector; import org.panda.causalpath.data.ActivityData; import org.panda.causalpath.data.ProteinData; import org.panda.causalpath.network.GraphWriter; import org.panda.causalpath.network.Relation; import org.panda.causalpath.resource.NetworkLoader; import org.panda.causalpath.resource.ProteomicsFileReader; import org.panda.causalpath.resource.ProteomicsLoader; import org.panda.resource.ResourceDirectory; import org.panda.resource.siteeffect.SiteEffectCollective; import org.panda.resource.tcga.ProteomicsFileRow; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set;
package org.panda.causalpath.run; /** * This class provides a single basic method interface to the causality analysis, which is specifically designed to be * used by tools in other programming languages, such as R. * * @author Ozgun Babur */ public class CausalityAnalysisSingleMethodInterface { /** * Reads the proteomics platform and data files, and generates a ChiBE SIF graph. * * @param platformFile Name of the antibody reference file * @param idColumn Column name of IDs * @param symbolsColumn Column name of gene symbols * @param sitesColumn Column name for phosphorylation sites * @param effectColumn Column name for effect of the site on activity * @param valuesFile Name of the measurements file * @param valueColumn Name of the values column in the measurements file * @param valueThreshold The value threshold to be considered as significant * @param graphType Either "compatible" or "conflicting" * @param doSiteMatch option to enforce matching a phosphorylation site in the network with * the annotation of antibody * @param siteMatchProximityThreshold when site matching is on, this parameter sets the proxomity threshold for a * site number in the relation to match the site whose change is observed in the data * @param siteEffectProximityThreshold when the site effect is not known, we can approximate it with the known * effect of proximate sites. This parameter sets the proximity threshold for using the proximate sites for that * prediction. * @param geneCentric Option to produce a gene-centric or an antibody-centric graph * @param colorSaturationValue The value that maps to the most saturated color * @param outputFilePrefix If the user provides xxx, then xxx.sif and xxx.format are generated * @param customNetworkDirectory The directory that the network will be downloaded and SignedPC * directory will be created in. Pass null to use default * @throws IOException */ public static void generateCausalityGraph(String platformFile, String idColumn, String symbolsColumn, String sitesColumn, String modificationColumn, String effectColumn, String valuesFile, String valueColumn, double valueThreshold, String graphType, boolean doSiteMatch, int siteMatchProximityThreshold, int siteEffectProximityThreshold, boolean geneCentric, double colorSaturationValue, String outputFilePrefix, String customNetworkDirectory) throws IOException { if (customNetworkDirectory != null) ResourceDirectory.set(customNetworkDirectory); // Read platform file List<ProteomicsFileRow> rows = ProteomicsFileReader.readAnnotation(platformFile, idColumn, symbolsColumn, sitesColumn, modificationColumn, effectColumn); // Read values List<String> vals = Collections.singletonList(valueColumn); ProteomicsFileReader.addValues(rows, valuesFile, idColumn, vals, 0D, false); // Fill-in missing effect SiteEffectCollective sec = new SiteEffectCollective(); sec.fillInMissingEffect(rows, siteEffectProximityThreshold); generateCausalityGraph(rows, valueThreshold, graphType, doSiteMatch, siteMatchProximityThreshold, geneCentric, colorSaturationValue, outputFilePrefix); } /** * For the given proteomics data, generates a ChiBE SIF graph. * * @param rows The proteomics data rows that are read from an external source * @param valueThreshold The value threshold to be considered as significant * @param graphType Either "compatible" or "conflicting" * @param doSiteMatch option to enforce matching a phosphorylation site in the network with * the annotation of antibody * @param geneCentric Option to produce a gene-centric or an antibody-centric graph * @param colorSaturationValue The value that maps to the most saturated color * @param outputFilePrefix If the user provides xxx, then xxx.sif and xxx.format are generated * @throws IOException */ public static void generateCausalityGraph(Collection<ProteomicsFileRow> rows, double valueThreshold, String graphType, boolean doSiteMatch, int siteMatchProximityThreshold, boolean geneCentric, double colorSaturationValue, String outputFilePrefix) throws IOException { ProteomicsLoader loader = new ProteomicsLoader(rows, null); // Associate change detectors loader.associateChangeDetector(new ThresholdDetector(valueThreshold, ThresholdDetector.AveragingMethod.ARITHMETIC_MEAN), data -> data instanceof ProteinData); loader.associateChangeDetector(new ThresholdDetector(0.1, ThresholdDetector.AveragingMethod.ARITHMETIC_MEAN), data -> data instanceof ActivityData); // Load signed relations Set<Relation> relations = NetworkLoader.load(); loader.decorateRelations(relations); // Prepare causality searcher
CausalitySearcher cs = new CausalitySearcher(!graphType.toLowerCase().startsWith("conflict"));
0
Meituan-Dianping/walle
plugin/src/main/java/com/android/apksigner/core/DefaultApkSignerEngine.java
[ "public enum DigestAlgorithm {\n /** SHA-1 */\n SHA1(\"SHA-1\"),\n\n /** SHA2-256 */\n SHA256(\"SHA-256\");\n\n private final String mJcaMessageDigestAlgorithm;\n\n private DigestAlgorithm(String jcaMessageDigestAlgoritm) {\n mJcaMessageDigestAlgorithm = jcaMessageDigestAlgoritm;\n }\n\n /**\n * Returns the {@link java.security.MessageDigest} algorithm represented by this digest\n * algorithm.\n */\n String getJcaMessageDigestAlgorithm() {\n return mJcaMessageDigestAlgorithm;\n }\n}", "public abstract class V1SchemeSigner {\n\n public static final String MANIFEST_ENTRY_NAME = \"META-INF/MANIFEST.MF\";\n\n private static final Attributes.Name ATTRIBUTE_NAME_CREATED_BY =\n new Attributes.Name(\"Created-By\");\n private static final String ATTRIBUTE_DEFALT_VALUE_CREATED_BY = \"1.0 (Android apksigner)\";\n private static final String ATTRIBUTE_VALUE_MANIFEST_VERSION = \"1.0\";\n private static final String ATTRIBUTE_VALUE_SIGNATURE_VERSION = \"1.0\";\n\n private static final Attributes.Name SF_ATTRIBUTE_NAME_ANDROID_APK_SIGNED_NAME =\n new Attributes.Name(\"X-Android-APK-Signed\");\n\n /**\n * Signer configuration.\n */\n public static class SignerConfig {\n /** Name. */\n public String name;\n\n /** Private key. */\n public PrivateKey privateKey;\n\n /**\n * Certificates, with the first certificate containing the public key corresponding to\n * {@link #privateKey}.\n */\n public List<X509Certificate> certificates;\n\n /**\n * Digest algorithm used for the signature.\n */\n public DigestAlgorithm signatureDigestAlgorithm;\n\n /**\n * Digest algorithm used for digests of JAR entries and MANIFEST.MF.\n */\n public DigestAlgorithm contentDigestAlgorithm;\n }\n\n /** Hidden constructor to prevent instantiation. */\n private V1SchemeSigner() {}\n\n /**\n * Gets the JAR signing digest algorithm to be used for signing an APK using the provided key.\n *\n * @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see\n * AndroidManifest.xml minSdkVersion attribute)\n *\n * @throws InvalidKeyException if the provided key is not suitable for signing APKs using\n * JAR signing (aka v1 signature scheme)\n */\n public static DigestAlgorithm getSuggestedSignatureDigestAlgorithm(\n PublicKey signingKey, int minSdkVersion) throws InvalidKeyException {\n String keyAlgorithm = signingKey.getAlgorithm();\n if (\"RSA\".equalsIgnoreCase(keyAlgorithm)) {\n // Prior to API Level 18, only SHA-1 can be used with RSA.\n if (minSdkVersion < 18) {\n return DigestAlgorithm.SHA1;\n }\n return DigestAlgorithm.SHA256;\n } else if (\"DSA\".equalsIgnoreCase(keyAlgorithm)) {\n // Prior to API Level 21, only SHA-1 can be used with DSA\n if (minSdkVersion < 21) {\n return DigestAlgorithm.SHA1;\n } else {\n return DigestAlgorithm.SHA256;\n }\n } else if (\"EC\".equalsIgnoreCase(keyAlgorithm)) {\n if (minSdkVersion < 18) {\n throw new InvalidKeyException(\n \"ECDSA signatures only supported for minSdkVersion 18 and higher\");\n }\n // Prior to API Level 21, only SHA-1 can be used with ECDSA\n if (minSdkVersion < 21) {\n return DigestAlgorithm.SHA1;\n } else {\n return DigestAlgorithm.SHA256;\n }\n } else {\n throw new InvalidKeyException(\"Unsupported key algorithm: \" + keyAlgorithm);\n }\n }\n\n /**\n * Returns the JAR signing digest algorithm to be used for JAR entry digests.\n *\n * @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see\n * AndroidManifest.xml minSdkVersion attribute)\n */\n public static DigestAlgorithm getSuggestedContentDigestAlgorithm(int minSdkVersion) {\n return (minSdkVersion >= 18) ? DigestAlgorithm.SHA256 : DigestAlgorithm.SHA1;\n }\n\n /**\n * Returns a new {@link MessageDigest} instance corresponding to the provided digest algorithm.\n */\n public static MessageDigest getMessageDigestInstance(DigestAlgorithm digestAlgorithm) {\n String jcaAlgorithm = digestAlgorithm.getJcaMessageDigestAlgorithm();\n try {\n return MessageDigest.getInstance(jcaAlgorithm);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"Failed to obtain \" + jcaAlgorithm + \" MessageDigest\", e);\n }\n }\n\n /**\n * Returns the JCA {@link MessageDigest} algorithm corresponding to the provided digest\n * algorithm.\n */\n public static String getJcaMessageDigestAlgorithm(DigestAlgorithm digestAlgorithm) {\n return digestAlgorithm.getJcaMessageDigestAlgorithm();\n }\n\n /**\n * Returns {@code true} if the provided JAR entry must be mentioned in signed JAR archive's\n * manifest.\n */\n public static boolean isJarEntryDigestNeededInManifest(String entryName) {\n // See https://docs.oracle.com/javase/8/docs/technotes/guides/jar/jar.html#Signed_JAR_File\n\n // Entries outside of META-INF must be listed in the manifest.\n if (!entryName.startsWith(\"META-INF/\")) {\n return true;\n }\n // Entries in subdirectories of META-INF must be listed in the manifest.\n if (entryName.indexOf('/', \"META-INF/\".length()) != -1) {\n return true;\n }\n\n // Ignored file names (case-insensitive) in META-INF directory:\n // MANIFEST.MF\n // *.SF\n // *.RSA\n // *.DSA\n // *.EC\n // SIG-*\n String fileNameLowerCase =\n entryName.substring(\"META-INF/\".length()).toLowerCase(Locale.US);\n if ((\"manifest.mf\".equals(fileNameLowerCase))\n || (fileNameLowerCase.endsWith(\".sf\"))\n || (fileNameLowerCase.endsWith(\".rsa\"))\n || (fileNameLowerCase.endsWith(\".dsa\"))\n || (fileNameLowerCase.endsWith(\".ec\"))\n || (fileNameLowerCase.startsWith(\"sig-\"))) {\n return false;\n }\n return true;\n }\n\n /**\n * Signs the provided APK using JAR signing (aka v1 signature scheme) and returns the list of\n * JAR entries which need to be added to the APK as part of the signature.\n *\n * @param signerConfigs signer configurations, one for each signer. At least one signer config\n * must be provided.\n *\n * @throws InvalidKeyException if a signing key is not suitable for this signature scheme or\n * cannot be used in general\n * @throws SignatureException if an error occurs when computing digests of generating\n * signatures\n */\n public static List<Pair<String, byte[]>> sign(\n List<SignerConfig> signerConfigs,\n DigestAlgorithm jarEntryDigestAlgorithm,\n Map<String, byte[]> jarEntryDigests,\n List<Integer> apkSigningSchemeIds,\n byte[] sourceManifestBytes)\n throws InvalidKeyException, CertificateEncodingException, SignatureException {\n if (signerConfigs.isEmpty()) {\n throw new IllegalArgumentException(\"At least one signer config must be provided\");\n }\n OutputManifestFile manifest =\n generateManifestFile(jarEntryDigestAlgorithm, jarEntryDigests, sourceManifestBytes);\n\n return signManifest(signerConfigs, jarEntryDigestAlgorithm, apkSigningSchemeIds, manifest);\n }\n\n /**\n * Signs the provided APK using JAR signing (aka v1 signature scheme) and returns the list of\n * JAR entries which need to be added to the APK as part of the signature.\n *\n * @param signerConfigs signer configurations, one for each signer. At least one signer config\n * must be provided.\n *\n * @throws InvalidKeyException if a signing key is not suitable for this signature scheme or\n * cannot be used in general\n * @throws SignatureException if an error occurs when computing digests of generating\n * signatures\n */\n public static List<Pair<String, byte[]>> signManifest(\n List<SignerConfig> signerConfigs,\n DigestAlgorithm digestAlgorithm,\n List<Integer> apkSigningSchemeIds,\n OutputManifestFile manifest)\n throws InvalidKeyException, CertificateEncodingException, SignatureException {\n if (signerConfigs.isEmpty()) {\n throw new IllegalArgumentException(\"At least one signer config must be provided\");\n }\n\n // For each signer output .SF and .(RSA|DSA|EC) file, then output MANIFEST.MF.\n List<Pair<String, byte[]>> signatureJarEntries =\n new ArrayList<>(2 * signerConfigs.size() + 1);\n byte[] sfBytes =\n generateSignatureFile(apkSigningSchemeIds, digestAlgorithm, manifest);\n for (SignerConfig signerConfig : signerConfigs) {\n String signerName = signerConfig.name;\n byte[] signatureBlock;\n try {\n signatureBlock = generateSignatureBlock(signerConfig, sfBytes);\n } catch (InvalidKeyException e) {\n throw new InvalidKeyException(\n \"Failed to sign using signer \\\"\" + signerName + \"\\\"\", e);\n } catch (CertificateEncodingException e) {\n throw new CertificateEncodingException(\n \"Failed to sign using signer \\\"\" + signerName + \"\\\"\", e);\n } catch (SignatureException e) {\n throw new SignatureException(\n \"Failed to sign using signer \\\"\" + signerName + \"\\\"\", e);\n }\n signatureJarEntries.add(Pair.of(\"META-INF/\" + signerName + \".SF\", sfBytes));\n PublicKey publicKey = signerConfig.certificates.get(0).getPublicKey();\n String signatureBlockFileName =\n \"META-INF/\" + signerName + \".\"\n + publicKey.getAlgorithm().toUpperCase(Locale.US);\n signatureJarEntries.add(\n Pair.of(signatureBlockFileName, signatureBlock));\n }\n signatureJarEntries.add(Pair.of(MANIFEST_ENTRY_NAME, manifest.contents));\n return signatureJarEntries;\n }\n\n /**\n * Returns the names of JAR entries which this signer will produce as part of v1 signature.\n */\n public static Set<String> getOutputEntryNames(List<SignerConfig> signerConfigs) {\n Set<String> result = new HashSet<>(2 * signerConfigs.size() + 1);\n for (SignerConfig signerConfig : signerConfigs) {\n String signerName = signerConfig.name;\n result.add(\"META-INF/\" + signerName + \".SF\");\n PublicKey publicKey = signerConfig.certificates.get(0).getPublicKey();\n String signatureBlockFileName =\n \"META-INF/\" + signerName + \".\"\n + publicKey.getAlgorithm().toUpperCase(Locale.US);\n result.add(signatureBlockFileName);\n }\n result.add(MANIFEST_ENTRY_NAME);\n return result;\n }\n\n /**\n * Generated and returns the {@code META-INF/MANIFEST.MF} file based on the provided (optional)\n * input {@code MANIFEST.MF} and digests of JAR entries covered by the manifest.\n */\n public static OutputManifestFile generateManifestFile(\n DigestAlgorithm jarEntryDigestAlgorithm,\n Map<String, byte[]> jarEntryDigests,\n byte[] sourceManifestBytes) {\n Manifest sourceManifest = null;\n if (sourceManifestBytes != null) {\n try {\n sourceManifest = new Manifest(new ByteArrayInputStream(sourceManifestBytes));\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Failed to parse source MANIFEST.MF\", e);\n }\n }\n ByteArrayOutputStream manifestOut = new ByteArrayOutputStream();\n Attributes mainAttrs = new Attributes();\n // Copy the main section from the source manifest (if provided). Otherwise use defaults.\n if (sourceManifest != null) {\n mainAttrs.putAll(sourceManifest.getMainAttributes());\n } else {\n mainAttrs.put(Attributes.Name.MANIFEST_VERSION, ATTRIBUTE_VALUE_MANIFEST_VERSION);\n mainAttrs.put(ATTRIBUTE_NAME_CREATED_BY, ATTRIBUTE_DEFALT_VALUE_CREATED_BY);\n }\n\n try {\n ManifestWriter.writeMainSection(manifestOut, mainAttrs);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to write in-memory MANIFEST.MF\", e);\n }\n\n List<String> sortedEntryNames = new ArrayList<>(jarEntryDigests.keySet());\n Collections.sort(sortedEntryNames);\n SortedMap<String, byte[]> invidualSectionsContents = new TreeMap<>();\n String entryDigestAttributeName = getEntryDigestAttributeName(jarEntryDigestAlgorithm);\n for (String entryName : sortedEntryNames) {\n byte[] entryDigest = jarEntryDigests.get(entryName);\n Attributes entryAttrs = new Attributes();\n entryAttrs.putValue(\n entryDigestAttributeName,\n Base64.getEncoder().encodeToString(entryDigest));\n ByteArrayOutputStream sectionOut = new ByteArrayOutputStream();\n byte[] sectionBytes;\n try {\n ManifestWriter.writeIndividualSection(sectionOut, entryName, entryAttrs);\n sectionBytes = sectionOut.toByteArray();\n manifestOut.write(sectionBytes);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to write in-memory MANIFEST.MF\", e);\n }\n invidualSectionsContents.put(entryName, sectionBytes);\n }\n\n OutputManifestFile result = new OutputManifestFile();\n result.contents = manifestOut.toByteArray();\n result.mainSectionAttributes = mainAttrs;\n result.individualSectionsContents = invidualSectionsContents;\n return result;\n }\n\n public static class OutputManifestFile {\n public byte[] contents;\n public SortedMap<String, byte[]> individualSectionsContents;\n public Attributes mainSectionAttributes;\n }\n\n private static byte[] generateSignatureFile(\n List<Integer> apkSignatureSchemeIds,\n DigestAlgorithm manifestDigestAlgorithm,\n OutputManifestFile manifest) {\n Manifest sf = new Manifest();\n Attributes mainAttrs = sf.getMainAttributes();\n mainAttrs.put(Attributes.Name.SIGNATURE_VERSION, ATTRIBUTE_VALUE_SIGNATURE_VERSION);\n mainAttrs.put(ATTRIBUTE_NAME_CREATED_BY, ATTRIBUTE_DEFALT_VALUE_CREATED_BY);\n if (!apkSignatureSchemeIds.isEmpty()) {\n // Add APK Signature Scheme v2 (and newer) signature stripping protection.\n // This attribute indicates that this APK is supposed to have been signed using one or\n // more APK-specific signature schemes in addition to the standard JAR signature scheme\n // used by this code. APK signature verifier should reject the APK if it does not\n // contain a signature for the signature scheme the verifier prefers out of this set.\n StringBuilder attrValue = new StringBuilder();\n for (int id : apkSignatureSchemeIds) {\n if (attrValue.length() > 0) {\n attrValue.append(\", \");\n }\n attrValue.append(String.valueOf(id));\n }\n mainAttrs.put(\n SF_ATTRIBUTE_NAME_ANDROID_APK_SIGNED_NAME,\n attrValue.toString());\n }\n\n // Add main attribute containing the digest of MANIFEST.MF.\n MessageDigest md = getMessageDigestInstance(manifestDigestAlgorithm);\n mainAttrs.putValue(\n getManifestDigestAttributeName(manifestDigestAlgorithm),\n Base64.getEncoder().encodeToString(md.digest(manifest.contents)));\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n try {\n SignatureFileWriter.writeMainSection(out, mainAttrs);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to write in-memory .SF file\", e);\n }\n String entryDigestAttributeName = getEntryDigestAttributeName(manifestDigestAlgorithm);\n for (Map.Entry<String, byte[]> manifestSection\n : manifest.individualSectionsContents.entrySet()) {\n String sectionName = manifestSection.getKey();\n byte[] sectionContents = manifestSection.getValue();\n byte[] sectionDigest = md.digest(sectionContents);\n Attributes attrs = new Attributes();\n attrs.putValue(\n entryDigestAttributeName,\n Base64.getEncoder().encodeToString(sectionDigest));\n\n try {\n SignatureFileWriter.writeIndividualSection(out, sectionName, attrs);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to write in-memory .SF file\", e);\n }\n }\n\n // A bug in the java.util.jar implementation of Android platforms up to version 1.6 will\n // cause a spurious IOException to be thrown if the length of the signature file is a\n // multiple of 1024 bytes. As a workaround, add an extra CRLF in this case.\n if ((out.size() > 0) && ((out.size() % 1024) == 0)) {\n try {\n SignatureFileWriter.writeSectionDelimiter(out);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to write to ByteArrayOutputStream\", e);\n }\n }\n\n return out.toByteArray();\n }\n\n private static byte[] generateSignatureBlock(\n SignerConfig signerConfig, byte[] signatureFileBytes)\n throws InvalidKeyException, CertificateEncodingException, SignatureException {\n JcaCertStore certs = new JcaCertStore(signerConfig.certificates);\n X509Certificate signerCert = signerConfig.certificates.get(0);\n String jcaSignatureAlgorithm =\n getJcaSignatureAlgorithm(\n signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm);\n try {\n ContentSigner signer =\n new JcaContentSignerBuilder(jcaSignatureAlgorithm)\n .build(signerConfig.privateKey);\n CMSSignedDataGenerator gen = new CMSSignedDataGenerator();\n gen.addSignerInfoGenerator(\n new SignerInfoGeneratorBuilder(\n new JcaDigestCalculatorProviderBuilder().build(),\n SignerInfoSignatureAlgorithmFinder.INSTANCE)\n .setDirectSignature(true)\n .build(signer, new JcaX509CertificateHolder(signerCert)));\n gen.addCertificates(certs);\n\n CMSSignedData sigData =\n gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {\n DEROutputStream dos = new DEROutputStream(out);\n dos.writeObject(asn1.readObject());\n }\n return out.toByteArray();\n } catch (OperatorCreationException | CMSException | IOException e) {\n throw new SignatureException(\"Failed to generate signature\", e);\n }\n }\n\n /**\n * Chooser of SignatureAlgorithm for PKCS #7 CMS SignerInfo.\n */\n private static class SignerInfoSignatureAlgorithmFinder\n implements CMSSignatureEncryptionAlgorithmFinder {\n private static final SignerInfoSignatureAlgorithmFinder INSTANCE =\n new SignerInfoSignatureAlgorithmFinder();\n\n private static final AlgorithmIdentifier DSA =\n new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, DERNull.INSTANCE);\n\n private final CMSSignatureEncryptionAlgorithmFinder mDefault =\n new DefaultCMSSignatureEncryptionAlgorithmFinder();\n\n @Override\n public AlgorithmIdentifier findEncryptionAlgorithm(AlgorithmIdentifier id) {\n // Use the default chooser, but replace dsaWithSha1 with dsa. This is because \"dsa\" is\n // accepted by any Android platform whereas \"dsaWithSha1\" is accepted only since\n // API Level 9.\n id = mDefault.findEncryptionAlgorithm(id);\n if (id != null) {\n ASN1ObjectIdentifier oid = id.getAlgorithm();\n if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(oid)) {\n return DSA;\n }\n }\n\n return id;\n }\n }\n\n private static String getEntryDigestAttributeName(DigestAlgorithm digestAlgorithm) {\n switch (digestAlgorithm) {\n case SHA1:\n return \"SHA1-Digest\";\n case SHA256:\n return \"SHA-256-Digest\";\n default:\n throw new IllegalArgumentException(\n \"Unexpected content digest algorithm: \" + digestAlgorithm);\n }\n }\n\n private static String getManifestDigestAttributeName(DigestAlgorithm digestAlgorithm) {\n switch (digestAlgorithm) {\n case SHA1:\n return \"SHA1-Digest-Manifest\";\n case SHA256:\n return \"SHA-256-Digest-Manifest\";\n default:\n throw new IllegalArgumentException(\n \"Unexpected content digest algorithm: \" + digestAlgorithm);\n }\n }\n\n private static String getJcaSignatureAlgorithm(\n PublicKey publicKey, DigestAlgorithm digestAlgorithm) throws InvalidKeyException {\n String keyAlgorithm = publicKey.getAlgorithm();\n String digestPrefixForSigAlg;\n switch (digestAlgorithm) {\n case SHA1:\n digestPrefixForSigAlg = \"SHA1\";\n break;\n case SHA256:\n digestPrefixForSigAlg = \"SHA256\";\n break;\n default:\n throw new IllegalArgumentException(\n \"Unexpected digest algorithm: \" + digestAlgorithm);\n }\n if (\"RSA\".equalsIgnoreCase(keyAlgorithm)) {\n return digestPrefixForSigAlg + \"withRSA\";\n } else if (\"DSA\".equalsIgnoreCase(keyAlgorithm)) {\n return digestPrefixForSigAlg + \"withDSA\";\n } else if (\"EC\".equalsIgnoreCase(keyAlgorithm)) {\n return digestPrefixForSigAlg + \"withECDSA\";\n } else {\n throw new InvalidKeyException(\"Unsupported key algorithm: \" + keyAlgorithm);\n }\n }\n}", "public abstract class V2SchemeSigner {\n /*\n * The two main goals of APK Signature Scheme v2 are:\n * 1. Detect any unauthorized modifications to the APK. This is achieved by making the signature\n * cover every byte of the APK being signed.\n * 2. Enable much faster signature and integrity verification. This is achieved by requiring\n * only a minimal amount of APK parsing before the signature is verified, thus completely\n * bypassing ZIP entry decompression and by making integrity verification parallelizable by\n * employing a hash tree.\n *\n * The generated signature block is wrapped into an APK Signing Block and inserted into the\n * original APK immediately before the start of ZIP Central Directory. This is to ensure that\n * JAR and ZIP parsers continue to work on the signed APK. The APK Signing Block is designed for\n * extensibility. For example, a future signature scheme could insert its signatures there as\n * well. The contract of the APK Signing Block is that all contents outside of the block must be\n * protected by signatures inside the block.\n */\n\n private static final int CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES = 1024 * 1024;\n\n private static final byte[] APK_SIGNING_BLOCK_MAGIC =\n new byte[] {\n 0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20,\n 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32,\n };\n private static final int APK_SIGNATURE_SCHEME_V2_BLOCK_ID = 0x7109871a;\n\n /**\n * Signer configuration.\n */\n public static class SignerConfig {\n /** Private key. */\n public PrivateKey privateKey;\n\n /**\n * Certificates, with the first certificate containing the public key corresponding to\n * {@link #privateKey}.\n */\n public List<X509Certificate> certificates;\n\n /**\n * List of signature algorithms with which to sign.\n */\n public List<SignatureAlgorithm> signatureAlgorithms;\n }\n\n /** Hidden constructor to prevent instantiation. */\n private V2SchemeSigner() {}\n\n /**\n * Gets the APK Signature Scheme v2 signature algorithms to be used for signing an APK using the\n * provided key.\n *\n * @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see\n * AndroidManifest.xml minSdkVersion attribute).\n *\n * @throws InvalidKeyException if the provided key is not suitable for signing APKs using\n * APK Signature Scheme v2\n */\n public static List<SignatureAlgorithm> getSuggestedSignatureAlgorithms(\n PublicKey signingKey, int minSdkVersion) throws InvalidKeyException {\n String keyAlgorithm = signingKey.getAlgorithm();\n if (\"RSA\".equalsIgnoreCase(keyAlgorithm)) {\n // Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee\n // deterministic signatures which make life easier for OTA updates (fewer files\n // changed when deterministic signature schemes are used).\n\n // Pick a digest which is no weaker than the key.\n int modulusLengthBits = ((RSAKey) signingKey).getModulus().bitLength();\n if (modulusLengthBits <= 3072) {\n // 3072-bit RSA is roughly 128-bit strong, meaning SHA-256 is a good fit.\n return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA256);\n } else {\n // Keys longer than 3072 bit need to be paired with a stronger digest to avoid the\n // digest being the weak link. SHA-512 is the next strongest supported digest.\n return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA512);\n }\n } else if (\"DSA\".equalsIgnoreCase(keyAlgorithm)) {\n // DSA is supported only with SHA-256.\n return Collections.singletonList(SignatureAlgorithm.DSA_WITH_SHA256);\n } else if (\"EC\".equalsIgnoreCase(keyAlgorithm)) {\n // Pick a digest which is no weaker than the key.\n int keySizeBits = ((ECKey) signingKey).getParams().getOrder().bitLength();\n if (keySizeBits <= 256) {\n // 256-bit Elliptic Curve is roughly 128-bit strong, meaning SHA-256 is a good fit.\n return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA256);\n } else {\n // Keys longer than 256 bit need to be paired with a stronger digest to avoid the\n // digest being the weak link. SHA-512 is the next strongest supported digest.\n return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA512);\n }\n } else {\n throw new InvalidKeyException(\"Unsupported key algorithm: \" + keyAlgorithm);\n }\n }\n\n /**\n * Signs the provided APK using APK Signature Scheme v2 and returns the APK Signing Block\n * containing the signature.\n *\n * @param signerConfigs signer configurations, one for each signer At least one signer config\n * must be provided.\n *\n * @throws IOException if an I/O error occurs\n * @throws InvalidKeyException if a signing key is not suitable for this signature scheme or\n * cannot be used in general\n * @throws SignatureException if an error occurs when computing digests of generating\n * signatures\n */\n public static byte[] generateApkSigningBlock(\n DataSource beforeCentralDir,\n DataSource centralDir,\n DataSource eocd,\n List<SignerConfig> signerConfigs)\n throws IOException, InvalidKeyException, SignatureException {\n if (signerConfigs.isEmpty()) {\n throw new IllegalArgumentException(\n \"No signer configs provided. At least one is required\");\n }\n\n // Figure out which digest(s) to use for APK contents.\n Set<ContentDigestAlgorithm> contentDigestAlgorithms = new HashSet<>(1);\n for (SignerConfig signerConfig : signerConfigs) {\n for (SignatureAlgorithm signatureAlgorithm : signerConfig.signatureAlgorithms) {\n contentDigestAlgorithms.add(signatureAlgorithm.getContentDigestAlgorithm());\n }\n }\n\n // Ensure that, when digesting, ZIP End of Central Directory record's Central Directory\n // offset field is treated as pointing to the offset at which the APK Signing Block will\n // start.\n long centralDirOffsetForDigesting = beforeCentralDir.size();\n ByteBuffer eocdBuf = ByteBuffer.allocate((int) eocd.size());\n eocdBuf.order(ByteOrder.LITTLE_ENDIAN);\n eocd.copyTo(0, (int) eocd.size(), eocdBuf);\n eocdBuf.flip();\n ZipUtils.setZipEocdCentralDirectoryOffset(eocdBuf, centralDirOffsetForDigesting);\n\n // Compute digests of APK contents.\n Map<ContentDigestAlgorithm, byte[]> contentDigests; // digest algorithm ID -> digest\n try {\n contentDigests =\n computeContentDigests(\n contentDigestAlgorithms,\n new DataSource[] {\n beforeCentralDir,\n centralDir,\n DataSources.asDataSource(eocdBuf)});\n } catch (IOException e) {\n throw new IOException(\"Failed to read APK being signed\", e);\n } catch (DigestException e) {\n throw new SignatureException(\"Failed to compute digests of APK\", e);\n }\n\n // Sign the digests and wrap the signatures and signer info into an APK Signing Block.\n return generateApkSigningBlock(signerConfigs, contentDigests);\n }\n\n static Map<ContentDigestAlgorithm, byte[]> computeContentDigests(\n Set<ContentDigestAlgorithm> digestAlgorithms,\n DataSource[] contents) throws IOException, DigestException {\n // For each digest algorithm the result is computed as follows:\n // 1. Each segment of contents is split into consecutive chunks of 1 MB in size.\n // The final chunk will be shorter iff the length of segment is not a multiple of 1 MB.\n // No chunks are produced for empty (zero length) segments.\n // 2. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk's\n // length in bytes (uint32 little-endian) and the chunk's contents.\n // 3. The output digest is computed over the concatenation of the byte 0x5a, the number of\n // chunks (uint32 little-endian) and the concatenation of digests of chunks of all\n // segments in-order.\n\n long chunkCountLong = 0;\n for (DataSource input : contents) {\n chunkCountLong +=\n getChunkCount(input.size(), CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);\n }\n if (chunkCountLong > Integer.MAX_VALUE) {\n throw new DigestException(\"Input too long: \" + chunkCountLong + \" chunks\");\n }\n int chunkCount = (int) chunkCountLong;\n\n ContentDigestAlgorithm[] digestAlgorithmsArray =\n digestAlgorithms.toArray(new ContentDigestAlgorithm[digestAlgorithms.size()]);\n MessageDigest[] mds = new MessageDigest[digestAlgorithmsArray.length];\n byte[][] digestsOfChunks = new byte[digestAlgorithmsArray.length][];\n int[] digestOutputSizes = new int[digestAlgorithmsArray.length];\n for (int i = 0; i < digestAlgorithmsArray.length; i++) {\n ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];\n int digestOutputSizeBytes = digestAlgorithm.getChunkDigestOutputSizeBytes();\n digestOutputSizes[i] = digestOutputSizeBytes;\n byte[] concatenationOfChunkCountAndChunkDigests =\n new byte[5 + chunkCount * digestOutputSizeBytes];\n concatenationOfChunkCountAndChunkDigests[0] = 0x5a;\n setUnsignedInt32LittleEndian(\n chunkCount, concatenationOfChunkCountAndChunkDigests, 1);\n digestsOfChunks[i] = concatenationOfChunkCountAndChunkDigests;\n String jcaAlgorithm = digestAlgorithm.getJcaMessageDigestAlgorithm();\n try {\n mds[i] = MessageDigest.getInstance(jcaAlgorithm);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(jcaAlgorithm + \" MessageDigest not supported\", e);\n }\n }\n\n MessageDigestSink mdSink = new MessageDigestSink(mds);\n byte[] chunkContentPrefix = new byte[5];\n chunkContentPrefix[0] = (byte) 0xa5;\n int chunkIndex = 0;\n // Optimization opportunity: digests of chunks can be computed in parallel. However,\n // determining the number of computations to be performed in parallel is non-trivial. This\n // depends on a wide range of factors, such as data source type (e.g., in-memory or fetched\n // from file), CPU/memory/disk cache bandwidth and latency, interconnect architecture of CPU\n // cores, load on the system from other threads of execution and other processes, size of\n // input.\n // For now, we compute these digests sequentially and thus have the luxury of improving\n // performance by writing the digest of each chunk into a pre-allocated buffer at exactly\n // the right position. This avoids unnecessary allocations, copying, and enables the final\n // digest to be more efficient because it's presented with all of its input in one go.\n for (DataSource input : contents) {\n long inputOffset = 0;\n long inputRemaining = input.size();\n while (inputRemaining > 0) {\n int chunkSize =\n (int) Math.min(inputRemaining, CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);\n setUnsignedInt32LittleEndian(chunkSize, chunkContentPrefix, 1);\n for (int i = 0; i < mds.length; i++) {\n mds[i].update(chunkContentPrefix);\n }\n try {\n input.feed(inputOffset, chunkSize, mdSink);\n } catch (IOException e) {\n throw new IOException(\"Failed to read chunk #\" + chunkIndex, e);\n }\n for (int i = 0; i < digestAlgorithmsArray.length; i++) {\n MessageDigest md = mds[i];\n byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];\n int expectedDigestSizeBytes = digestOutputSizes[i];\n int actualDigestSizeBytes =\n md.digest(\n concatenationOfChunkCountAndChunkDigests,\n 5 + chunkIndex * expectedDigestSizeBytes,\n expectedDigestSizeBytes);\n if (actualDigestSizeBytes != expectedDigestSizeBytes) {\n throw new RuntimeException(\n \"Unexpected output size of \" + md.getAlgorithm()\n + \" digest: \" + actualDigestSizeBytes);\n }\n }\n inputOffset += chunkSize;\n inputRemaining -= chunkSize;\n chunkIndex++;\n }\n }\n\n Map<ContentDigestAlgorithm, byte[]> result = new HashMap<>(digestAlgorithmsArray.length);\n for (int i = 0; i < digestAlgorithmsArray.length; i++) {\n ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];\n byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];\n MessageDigest md = mds[i];\n byte[] digest = md.digest(concatenationOfChunkCountAndChunkDigests);\n result.put(digestAlgorithm, digest);\n }\n return result;\n }\n\n private static final long getChunkCount(long inputSize, int chunkSize) {\n return (inputSize + chunkSize - 1) / chunkSize;\n }\n\n private static void setUnsignedInt32LittleEndian(int value, byte[] result, int offset) {\n result[offset] = (byte) (value & 0xff);\n result[offset + 1] = (byte) ((value >> 8) & 0xff);\n result[offset + 2] = (byte) ((value >> 16) & 0xff);\n result[offset + 3] = (byte) ((value >> 24) & 0xff);\n }\n\n private static byte[] generateApkSigningBlock(\n List<SignerConfig> signerConfigs,\n Map<ContentDigestAlgorithm, byte[]> contentDigests)\n throws InvalidKeyException, SignatureException {\n byte[] apkSignatureSchemeV2Block =\n generateApkSignatureSchemeV2Block(signerConfigs, contentDigests);\n return generateApkSigningBlock(apkSignatureSchemeV2Block);\n }\n\n private static byte[] generateApkSigningBlock(byte[] apkSignatureSchemeV2Block) {\n // FORMAT:\n // uint64: size (excluding this field)\n // repeated ID-value pairs:\n // uint64: size (excluding this field)\n // uint32: ID\n // (size - 4) bytes: value\n // uint64: size (same as the one above)\n // uint128: magic\n\n int resultSize =\n 8 // size\n + 8 + 4 + apkSignatureSchemeV2Block.length // v2Block as ID-value pair\n + 8 // size\n + 16 // magic\n ;\n ByteBuffer result = ByteBuffer.allocate(resultSize);\n result.order(ByteOrder.LITTLE_ENDIAN);\n long blockSizeFieldValue = resultSize - 8;\n result.putLong(blockSizeFieldValue);\n\n long pairSizeFieldValue = 4 + apkSignatureSchemeV2Block.length;\n result.putLong(pairSizeFieldValue);\n result.putInt(APK_SIGNATURE_SCHEME_V2_BLOCK_ID);\n result.put(apkSignatureSchemeV2Block);\n\n result.putLong(blockSizeFieldValue);\n result.put(APK_SIGNING_BLOCK_MAGIC);\n\n return result.array();\n }\n\n private static byte[] generateApkSignatureSchemeV2Block(\n List<SignerConfig> signerConfigs,\n Map<ContentDigestAlgorithm, byte[]> contentDigests)\n throws InvalidKeyException, SignatureException {\n // FORMAT:\n // * length-prefixed sequence of length-prefixed signer blocks.\n\n List<byte[]> signerBlocks = new ArrayList<>(signerConfigs.size());\n int signerNumber = 0;\n for (SignerConfig signerConfig : signerConfigs) {\n signerNumber++;\n byte[] signerBlock;\n try {\n signerBlock = generateSignerBlock(signerConfig, contentDigests);\n } catch (InvalidKeyException e) {\n throw new InvalidKeyException(\"Signer #\" + signerNumber + \" failed\", e);\n } catch (SignatureException e) {\n throw new SignatureException(\"Signer #\" + signerNumber + \" failed\", e);\n }\n signerBlocks.add(signerBlock);\n }\n\n return encodeAsSequenceOfLengthPrefixedElements(\n new byte[][] {\n encodeAsSequenceOfLengthPrefixedElements(signerBlocks),\n });\n }\n\n private static byte[] generateSignerBlock(\n SignerConfig signerConfig,\n Map<ContentDigestAlgorithm, byte[]> contentDigests)\n throws InvalidKeyException, SignatureException {\n if (signerConfig.certificates.isEmpty()) {\n throw new SignatureException(\"No certificates configured for signer\");\n }\n PublicKey publicKey = signerConfig.certificates.get(0).getPublicKey();\n\n byte[] encodedPublicKey = encodePublicKey(publicKey);\n\n V2SignatureSchemeBlock.SignedData signedData = new V2SignatureSchemeBlock.SignedData();\n try {\n signedData.certificates = encodeCertificates(signerConfig.certificates);\n } catch (CertificateEncodingException e) {\n throw new SignatureException(\"Failed to encode certificates\", e);\n }\n\n List<Pair<Integer, byte[]>> digests =\n new ArrayList<>(signerConfig.signatureAlgorithms.size());\n for (SignatureAlgorithm signatureAlgorithm : signerConfig.signatureAlgorithms) {\n ContentDigestAlgorithm contentDigestAlgorithm =\n signatureAlgorithm.getContentDigestAlgorithm();\n byte[] contentDigest = contentDigests.get(contentDigestAlgorithm);\n if (contentDigest == null) {\n throw new RuntimeException(\n contentDigestAlgorithm + \" content digest for \" + signatureAlgorithm\n + \" not computed\");\n }\n digests.add(Pair.of(signatureAlgorithm.getId(), contentDigest));\n }\n signedData.digests = digests;\n\n V2SignatureSchemeBlock.Signer signer = new V2SignatureSchemeBlock.Signer();\n // FORMAT:\n // * length-prefixed sequence of length-prefixed digests:\n // * uint32: signature algorithm ID\n // * length-prefixed bytes: digest of contents\n // * length-prefixed sequence of certificates:\n // * length-prefixed bytes: X.509 certificate (ASN.1 DER encoded).\n // * length-prefixed sequence of length-prefixed additional attributes:\n // * uint32: ID\n // * (length - 4) bytes: value\n signer.signedData = encodeAsSequenceOfLengthPrefixedElements(new byte[][] {\n encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes(signedData.digests),\n encodeAsSequenceOfLengthPrefixedElements(signedData.certificates),\n // additional attributes\n new byte[0],\n });\n signer.publicKey = encodedPublicKey;\n signer.signatures = new ArrayList<>(signerConfig.signatureAlgorithms.size());\n for (SignatureAlgorithm signatureAlgorithm : signerConfig.signatureAlgorithms) {\n Pair<String, ? extends AlgorithmParameterSpec> sigAlgAndParams =\n signatureAlgorithm.getJcaSignatureAlgorithmAndParams();\n String jcaSignatureAlgorithm = sigAlgAndParams.getFirst();\n AlgorithmParameterSpec jcaSignatureAlgorithmParams = sigAlgAndParams.getSecond();\n byte[] signatureBytes;\n try {\n Signature signature = Signature.getInstance(jcaSignatureAlgorithm);\n signature.initSign(signerConfig.privateKey);\n if (jcaSignatureAlgorithmParams != null) {\n signature.setParameter(jcaSignatureAlgorithmParams);\n }\n signature.update(signer.signedData);\n signatureBytes = signature.sign();\n } catch (InvalidKeyException e) {\n throw new InvalidKeyException(\"Failed sign using \" + jcaSignatureAlgorithm, e);\n } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException\n | SignatureException e) {\n throw new SignatureException(\"Failed sign using \" + jcaSignatureAlgorithm, e);\n }\n\n try {\n Signature signature = Signature.getInstance(jcaSignatureAlgorithm);\n signature.initVerify(publicKey);\n if (jcaSignatureAlgorithmParams != null) {\n signature.setParameter(jcaSignatureAlgorithmParams);\n }\n signature.update(signer.signedData);\n if (!signature.verify(signatureBytes)) {\n throw new SignatureException(\"Signature did not verify\");\n }\n } catch (InvalidKeyException e) {\n throw new InvalidKeyException(\"Failed to verify generated \" + jcaSignatureAlgorithm\n + \" signature using public key from certificate\", e);\n } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException\n | SignatureException e) {\n throw new SignatureException(\"Failed to verify generated \" + jcaSignatureAlgorithm\n + \" signature using public key from certificate\", e);\n }\n\n signer.signatures.add(Pair.of(signatureAlgorithm.getId(), signatureBytes));\n }\n\n // FORMAT:\n // * length-prefixed signed data\n // * length-prefixed sequence of length-prefixed signatures:\n // * uint32: signature algorithm ID\n // * length-prefixed bytes: signature of signed data\n // * length-prefixed bytes: public key (X.509 SubjectPublicKeyInfo, ASN.1 DER encoded)\n return encodeAsSequenceOfLengthPrefixedElements(\n new byte[][] {\n signer.signedData,\n encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes(\n signer.signatures),\n signer.publicKey,\n });\n }\n\n private static final class V2SignatureSchemeBlock {\n private static final class Signer {\n public byte[] signedData;\n public List<Pair<Integer, byte[]>> signatures;\n public byte[] publicKey;\n }\n\n private static final class SignedData {\n public List<Pair<Integer, byte[]>> digests;\n public List<byte[]> certificates;\n }\n }\n\n private static byte[] encodePublicKey(PublicKey publicKey) throws InvalidKeyException {\n byte[] encodedPublicKey = null;\n if (\"X.509\".equals(publicKey.getFormat())) {\n encodedPublicKey = publicKey.getEncoded();\n }\n if (encodedPublicKey == null) {\n try {\n encodedPublicKey =\n KeyFactory.getInstance(publicKey.getAlgorithm())\n .getKeySpec(publicKey, X509EncodedKeySpec.class)\n .getEncoded();\n } catch (NoSuchAlgorithmException e) {\n throw new InvalidKeyException(\n \"Failed to obtain X.509 encoded form of public key \" + publicKey\n + \" of class \" + publicKey.getClass().getName(),\n e);\n } catch (InvalidKeySpecException e) {\n throw new InvalidKeyException(\n \"Failed to obtain X.509 encoded form of public key \" + publicKey\n + \" of class \" + publicKey.getClass().getName(),\n e);\n }\n }\n if ((encodedPublicKey == null) || (encodedPublicKey.length == 0)) {\n throw new InvalidKeyException(\n \"Failed to obtain X.509 encoded form of public key \" + publicKey\n + \" of class \" + publicKey.getClass().getName());\n }\n return encodedPublicKey;\n }\n\n private static List<byte[]> encodeCertificates(List<X509Certificate> certificates)\n throws CertificateEncodingException {\n List<byte[]> result = new ArrayList<>(certificates.size());\n for (X509Certificate certificate : certificates) {\n result.add(certificate.getEncoded());\n }\n return result;\n }\n\n private static byte[] encodeAsSequenceOfLengthPrefixedElements(List<byte[]> sequence) {\n return encodeAsSequenceOfLengthPrefixedElements(\n sequence.toArray(new byte[sequence.size()][]));\n }\n\n private static byte[] encodeAsSequenceOfLengthPrefixedElements(byte[][] sequence) {\n int payloadSize = 0;\n for (byte[] element : sequence) {\n payloadSize += 4 + element.length;\n }\n ByteBuffer result = ByteBuffer.allocate(payloadSize);\n result.order(ByteOrder.LITTLE_ENDIAN);\n for (byte[] element : sequence) {\n result.putInt(element.length);\n result.put(element);\n }\n return result.array();\n }\n\n private static byte[] encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes(\n List<Pair<Integer, byte[]>> sequence) {\n int resultSize = 0;\n for (Pair<Integer, byte[]> element : sequence) {\n resultSize += 12 + element.getSecond().length;\n }\n ByteBuffer result = ByteBuffer.allocate(resultSize);\n result.order(ByteOrder.LITTLE_ENDIAN);\n for (Pair<Integer, byte[]> element : sequence) {\n byte[] second = element.getSecond();\n result.putInt(8 + second.length);\n result.putInt(element.getFirst());\n result.putInt(second.length);\n result.put(second);\n }\n return result.array();\n }\n}", "public class ByteArrayOutputStreamSink implements DataSink {\n\n private final ByteArrayOutputStream mBuf = new ByteArrayOutputStream();\n\n @Override\n public void consume(byte[] buf, int offset, int length) {\n mBuf.write(buf, offset, length);\n }\n\n @Override\n public void consume(ByteBuffer buf) {\n if (!buf.hasRemaining()) {\n return;\n }\n\n if (buf.hasArray()) {\n mBuf.write(\n buf.array(),\n buf.arrayOffset() + buf.position(),\n buf.remaining());\n buf.position(buf.limit());\n } else {\n byte[] tmp = new byte[buf.remaining()];\n buf.get(tmp);\n mBuf.write(tmp, 0, tmp.length);\n }\n }\n\n /**\n * Returns the data received so far.\n */\n public byte[] getData() {\n return mBuf.toByteArray();\n }\n}", "public class MessageDigestSink implements DataSink {\n\n private final MessageDigest[] mMessageDigests;\n\n public MessageDigestSink(MessageDigest[] digests) {\n mMessageDigests = digests;\n }\n\n @Override\n public void consume(byte[] buf, int offset, int length) {\n for (MessageDigest md : mMessageDigests) {\n md.update(buf, offset, length);\n }\n }\n\n @Override\n public void consume(ByteBuffer buf) {\n int originalPosition = buf.position();\n for (MessageDigest md : mMessageDigests) {\n // Reset the position back to the original because the previous iteration's\n // MessageDigest.update set the buffer's position to the buffer's limit.\n buf.position(originalPosition);\n md.update(buf);\n }\n }\n}", "public final class Pair<A, B> {\n private final A mFirst;\n private final B mSecond;\n\n private Pair(A first, B second) {\n mFirst = first;\n mSecond = second;\n }\n\n public static <A, B> Pair<A, B> of(A first, B second) {\n return new Pair<A, B>(first, second);\n }\n\n public A getFirst() {\n return mFirst;\n }\n\n public B getSecond() {\n return mSecond;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());\n result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n @SuppressWarnings(\"rawtypes\")\n Pair other = (Pair) obj;\n if (mFirst == null) {\n if (other.mFirst != null) {\n return false;\n }\n } else if (!mFirst.equals(other.mFirst)) {\n return false;\n }\n if (mSecond == null) {\n if (other.mSecond != null) {\n return false;\n }\n } else if (!mSecond.equals(other.mSecond)) {\n return false;\n }\n return true;\n }\n}", "public interface DataSink {\n\n /**\n * Consumes the provided chunk of data.\n *\n * <p>This data sink guarantees to not hold references to the provided buffer after this method\n * terminates.\n */\n void consume(byte[] buf, int offset, int length) throws IOException;\n\n /**\n * Consumes all remaining data in the provided buffer and advances the buffer's position\n * to the buffer's limit.\n *\n * <p>This data sink guarantees to not hold references to the provided buffer after this method\n * terminates.\n */\n void consume(ByteBuffer buf) throws IOException;\n}", "public interface DataSource {\n\n /**\n * Returns the amount of data (in bytes) contained in this data source.\n */\n long size();\n\n /**\n * Feeds the specified chunk from this data source into the provided sink.\n *\n * @param offset index (in bytes) at which the chunk starts inside data source\n * @param size size (in bytes) of the chunk\n */\n void feed(long offset, long size, DataSink sink) throws IOException;\n\n /**\n * Returns a buffer holding the contents of the specified chunk of data from this data source.\n * Changes to the data source are not guaranteed to be reflected in the returned buffer.\n * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.\n *\n * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is\n * {@code size}.\n *\n * @param offset index (in bytes) at which the chunk starts inside data source\n * @param size size (in bytes) of the chunk\n */\n ByteBuffer getByteBuffer(long offset, int size) throws IOException;\n\n /**\n * Copies the specified chunk from this data source into the provided destination buffer,\n * advancing the destination buffer's position by {@code size}.\n *\n * @param offset index (in bytes) at which the chunk starts inside data source\n * @param size size (in bytes) of the chunk\n */\n void copyTo(long offset, int size, ByteBuffer dest) throws IOException;\n\n /**\n * Returns a data source representing the specified region of data of this data source. Changes\n * to data represented by this data source will also be visible in the returned data source.\n *\n * @param offset index (in bytes) at which the region starts inside data source\n * @param size size (in bytes) of the region\n */\n DataSource slice(long offset, long size);\n}" ]
import com.android.apksigner.core.internal.apk.v1.DigestAlgorithm; import com.android.apksigner.core.internal.apk.v1.V1SchemeSigner; import com.android.apksigner.core.internal.apk.v2.V2SchemeSigner; import com.android.apksigner.core.internal.util.ByteArrayOutputStreamSink; import com.android.apksigner.core.internal.util.MessageDigestSink; import com.android.apksigner.core.internal.util.Pair; import com.android.apksigner.core.util.DataSink; import com.android.apksigner.core.util.DataSource; import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;
private boolean isDone() { return mDone; } } private static class OutputApkSigningBlockRequestImpl implements OutputApkSigningBlockRequest { private final byte[] mApkSigningBlock; private volatile boolean mDone; private OutputApkSigningBlockRequestImpl(byte[] apkSigingBlock) { mApkSigningBlock = apkSigingBlock.clone(); } @Override public byte[] getApkSigningBlock() { return mApkSigningBlock.clone(); } @Override public void done() { mDone = true; } private boolean isDone() { return mDone; } } /** * JAR entry inspection request which obtain the entry's uncompressed data. */ private static class GetJarEntryDataRequest implements InspectJarEntryRequest { private final String mEntryName; private final Object mLock = new Object(); private boolean mDone; private ByteArrayOutputStreamSink mBuf; private GetJarEntryDataRequest(String entryName) { mEntryName = entryName; } @Override public String getEntryName() { return mEntryName; } @Override public DataSink getDataSink() { synchronized (mLock) { checkNotDone(); if (mBuf == null) { mBuf = new ByteArrayOutputStreamSink(); } return mBuf; } } @Override public void done() { synchronized (mLock) { if (mDone) { return; } mDone = true; } } private boolean isDone() { synchronized (mLock) { return mDone; } } private void checkNotDone() throws IllegalStateException { synchronized (mLock) { if (mDone) { throw new IllegalStateException("Already done"); } } } private byte[] getData() { synchronized (mLock) { if (!mDone) { throw new IllegalStateException("Not yet done"); } return (mBuf != null) ? mBuf.getData() : new byte[0]; } } } /** * JAR entry inspection request which obtains the digest of the entry's uncompressed data. */ private static class GetJarEntryDataDigestRequest implements InspectJarEntryRequest { private final String mEntryName; private final String mJcaDigestAlgorithm; private final Object mLock = new Object(); private boolean mDone; private DataSink mDataSink; private MessageDigest mMessageDigest; private byte[] mDigest; private GetJarEntryDataDigestRequest(String entryName, String jcaDigestAlgorithm) { mEntryName = entryName; mJcaDigestAlgorithm = jcaDigestAlgorithm; } @Override public String getEntryName() { return mEntryName; } @Override public DataSink getDataSink() { synchronized (mLock) { checkNotDone(); if (mDataSink == null) {
mDataSink = new MessageDigestSink(new MessageDigest[] {getMessageDigest()});
4
junjunguo/PocketMaps
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/activities/Analytics.java
[ "public class SportCategory {\n private String text;\n private Integer imageId;\n private Calorie.Type sportMET;\n\n public SportCategory(String text, Integer imageId, Calorie.Type activityMET) {\n this.text = text;\n this.imageId = imageId;\n this.sportMET = activityMET;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public Integer getImageId() {\n return imageId;\n }\n\n public void setImageId(Integer imageId) {\n this.imageId = imageId;\n }\n\n public Calorie.Type getSportMET() {\n return sportMET;\n }\n}", "public interface TrackingListener {\n /**\n * @param distance new distance passed in m\n */\n void updateDistance(Double distance);\n\n /**\n * @param avgSpeed new avg speed in km/h\n */\n void updateAvgSpeed(Double avgSpeed);\n\n /**\n * @param maxSpeed new max speed in km/h\n */\n void updateMaxSpeed(Double maxSpeed);\n\n /**\n * return data when {@link Tracking#requestDistanceGraphSeries()} called\n *\n * @param dataPoints\n */\n void updateDistanceGraphSeries(DataPoint[][] dataPoints);\n\n /**\n * used to set the flag for updating\n */\n void setUpdateNewPoint();\n}", "public class Tracking {\n private static Tracking tracking;\n private double avgSpeed, maxSpeed, distance;\n private Location startLocation;\n private long timeStart, timeEnd;\n\n private boolean isOnTracking;\n private DBtrackingPoints dBtrackingPoints;\n private List<TrackingListener> listeners;\n\n private Tracking(Context applicationContext) {\n isOnTracking = false;\n dBtrackingPoints = new DBtrackingPoints(applicationContext);\n listeners = new ArrayList<>();\n }\n\n public static Tracking getTracking(Context applicationContext) {\n if (tracking == null) {\n tracking = new Tracking(applicationContext);\n }\n return tracking;\n }\n\n /**\n * stop Tracking: is on tracking false\n */\n public void stopTracking(AppSettings appSettings) {\n isOnTracking = false;\n initAnalytics();\n appSettings.updateAnalytics(0, 0);\n }\n\n /**\n * set avg speed & distance to 0 & start location = null;\n */\n private void initAnalytics() {\n avgSpeed = 0; // km/h\n maxSpeed = 0; // km/h\n distance = 0; // meter\n timeStart = System.currentTimeMillis();\n startLocation = null;\n }\n\n /**\n * init and start tracking\n */\n public void startTracking(Activity activity) {\n init();\n initAnalytics();\n MapHandler.getMapHandler().startTrack(activity);\n isOnTracking = true;\n }\n\n public void init() {\n dBtrackingPoints.open();\n dBtrackingPoints.deleteAllRows();\n dBtrackingPoints.close();\n isOnTracking = false;\n }\n \n public void loadData(Activity activity, File gpxFile, AppSettings appSettings) {\n try\n {\n isOnTracking = false;\n initAnalytics();\n init();\n appSettings.openAnalyticsActivity(false);\n MapHandler.getMapHandler().startTrack(activity);\n ArrayList<Location> posList = new GenerateGPX().readGpxFile(gpxFile);\n boolean first = true;\n for (Location pos : posList)\n {\n if (first)\n { // Center on map.\n GeoPoint firstP = new GeoPoint(pos.getLatitude(), pos.getLongitude());\n MapHandler.getMapHandler().centerPointOnMap(firstP, 0, 0, 0);\n setTimeStart(pos.getTime());\n first = false;\n }\n MapHandler.getMapHandler().addTrackPoint(activity, new GeoPoint(pos.getLatitude(), pos.getLongitude()));\n addPoint(pos, appSettings);\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n /**\n * @return average speed in km/h\n */\n public double getAvgSpeed() {\n return avgSpeed;\n }\n\n /**\n * @return max speed in km/h\n */\n public double getMaxSpeed() {\n return maxSpeed;\n }\n\n public void setMaxSpeed(double maxSpeed) {\n this.maxSpeed = maxSpeed;\n }\n\n /**\n * @return total distance through in meters\n */\n public double getDistance() {\n return distance;\n }\n\n /**\n * @return total distance through in km\n */\n public double getDistanceKm() {\n return distance / 1000.0;\n }\n\n /**\n * @return tracking start time in milliseconds\n */\n public long getTimeStart() {\n return timeStart;\n }\n \n /**\n * @return tracking end time in milliseconds, only used for loading old TrackingData\n */\n public long getTimeEnd() {\n return timeEnd;\n }\n \n /**\n * Tracking start time in milliseconds.\n * This function is used for loading old TrackingData.\n */\n public void setTimeStart(long timeStart) {\n this.timeStart = timeStart;\n }\n \n /**\n * Tracking end time in milliseconds.\n * This function is used for loading old TrackingData.\n */\n public void setTimeEnd(long timeEnd) {\n this.timeEnd = timeEnd;\n }\n \n /**\n * @return total points recorded --> database row count\n */\n public int getTotalPoints() {\n dBtrackingPoints.open();\n int p = dBtrackingPoints.getRowCount();\n dBtrackingPoints.close();\n return p;\n }\n\n /**\n * @return true if is on tracking\n */\n public boolean isTracking() {\n return isOnTracking;\n }\n\n /**\n * add a location point to points list\n *\n * @param location\n */\n public void addPoint(Location location, AppSettings appSettings) {\n dBtrackingPoints.open();\n dBtrackingPoints.addLocation(location);\n dBtrackingPoints.close();\n updateDisSpeed(location, appSettings);// update first\n updateMaxSpeed(location);// update after updateDisSpeed\n startLocation = location;\n }\n\n /**\n * distance DataPoint series DataPoint (x, y) x = increased time, y = increased distance\n * <p/>\n * Listener will handler the return data\n */\n public void requestDistanceGraphSeries() {\n new AsyncTask<URL, Integer, DataPoint[][]>() {\n protected DataPoint[][] doInBackground(URL... params) {\n try {\n dBtrackingPoints.open();\n DataPoint[][] dp = dBtrackingPoints.readGraphSeries();\n dBtrackingPoints.close();\n return dp;\n } catch (Exception e) {e.printStackTrace();}\n return null;\n }\n\n protected void onPostExecute(DataPoint[][] dataPoints) {\n super.onPostExecute(dataPoints);\n broadcast(null, null, null, dataPoints);\n }\n }.execute();\n }\n\n /**\n * update distance and speed\n *\n * @param location\n */\n private void updateDisSpeed(Location location, AppSettings appSettings) {\n if (startLocation != null) {\n float disPoints = startLocation.distanceTo(location);\n distance += disPoints;\n long duration = getDurationInMilliS(location.getTime());\n avgSpeed = (distance) / (duration / (60 * 60));\n if (appSettings.getAppSettingsVP().getVisibility() == View.VISIBLE) {\n appSettings.updateAnalytics(avgSpeed, distance);\n }\n broadcast(avgSpeed, null, distance, null);\n }\n }\n\n /**\n * @return duration in milli second\n */\n public long getDurationInMilliS() {\n long now = System.currentTimeMillis();\n return (now - timeStart);\n }\n \n /**\n * @return duration in milli second\n */\n public long getDurationInMilliS(long endTime) {\n return endTime - timeStart;\n }\n\n /**\n * @return duration in hours\n */\n public double getDurationInHours() {\n return (getDurationInMilliS() / (60 * 60 * 1000.0));\n }\n \n /**\n * @return duration in hours, but with different endTime\n */\n public double getDurationInHours(long endTime) {\n return getDurationInMilliS(endTime) / (60 * 60 * 1000.0);\n }\n \n /**\n * update max speed and broadcast DataPoint for speeds and distances\n *\n * @param location\n */\n private void updateMaxSpeed(Location location) {\n if (startLocation != null) {\n // velocity: m/s\n double velocity =\n (startLocation.distanceTo(location)) / ((location.getTime() - startLocation.getTime()) / (1000.0));\n broadcastNewPoint();\n // TODO: improve noise reduce (Kalman filter)\n // TODO: http://dsp.stackexchange.com/questions/8860/more-on-kalman-filter-for-position-and-velocity\n velocity = velocity * (6 * 6 / 10);// velocity: km/h\n // if (maxSpeed < velocity && velocity < (maxSpeed + 32) * 10) {\n if (maxSpeed < velocity) {\n maxSpeed = (float) velocity;\n broadcast(null, maxSpeed, null, null);\n }\n }\n }\n\n\n private void broadcastNewPoint() {\n for (TrackingListener tl : listeners) {\n tl.setUpdateNewPoint();\n }\n }\n\n /**\n * set null if do not need to update\n *\n * @param avgSpeed in km/h\n * @param maxSpeed in km/h\n * @param distance in m\n */\n\n private void broadcast(Double avgSpeed, Double maxSpeed, Double distance, DataPoint[][] dataPoints) {\n for (TrackingListener tl : listeners) {\n if (avgSpeed != null) {\n tl.updateAvgSpeed(avgSpeed);\n }\n if (maxSpeed != null) {\n tl.updateMaxSpeed(maxSpeed);\n }\n if (distance != null) {\n tl.updateDistance(distance);\n }\n if (dataPoints != null) {\n tl.updateDistanceGraphSeries(dataPoints);\n }\n }\n }\n\n /**\n * remove from listeners list\n *\n * @param listener\n */\n public void removeListener(TrackingListener listener) {\n listeners.remove(listener);\n }\n\n /**\n * add to listeners list\n *\n * @param listener\n */\n public void addListener(TrackingListener listener) {\n listeners.add(listener);\n }\n\n /**\n * export location data from database to GPX file\n *\n * @param name folder name\n */\n public void saveAsGPX(final String name) {\n final File trackFolder = new File(Variable.getVariable().getTrackingFolder().getAbsolutePath());\n trackFolder.mkdirs();\n final File gpxFile = new File(trackFolder, name);\n if (!gpxFile.exists()) {\n try {\n gpxFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n new AsyncTask<Object, Object, Object>() {\n protected Object doInBackground(Object... params) {\n try {\n new GenerateGPX().writeGpxFile(name, dBtrackingPoints, gpxFile);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n protected void onPostExecute(Object o) {\n super.onPostExecute(o);\n if (gpxFile.exists()) {\n gpxFile.renameTo(new File(trackFolder, name + \".gpx\"));\n }\n }\n }.execute();\n }\n}", "public class Calorie {\n /*\n * sport category, which defines the MET value\n */\n \n /** Slow with bike 10mph or 16kmh **/\n public final static double BIKE_SLOW = 4.0;\n /** Normal with bike 13mph or 20kmh **/\n public final static double BIKE_MID = 8.0;\n /** Fast with bike 15mph or 24kmh **/\n public final static double BIKE_FAST = 10.0;\n /** Slow walk 3mph or 5kmh **/\n public final static double WALK_SLOW = 3.0;\n /** Slow running 5mph or 8kmh **/\n public final static double RUN_SLOW = 8.0;\n /** Normal running 8mph or 12kmh **/\n public final static double RUN_MID = 13.5;\n /** Fast running 10mph or 16kmh **/\n public final static double RUN_FAST = 16.0;\n /** General driving with car **/\n public final static double CAR_DRIVE = 2.0;\n \n public enum Type {Bike, Car, Run};\n \n /**\n * default body weight by kg if not defined by user\n */\n public final static double weightKg = 77.0;\n\n public static double getMET(double speedKmh, Type type)\n {\n if (type == Type.Run)\n {\n if (speedKmh<6.5) { return WALK_SLOW; }\n if (speedKmh<10) { return RUN_SLOW; }\n if (speedKmh<14) { return RUN_MID; }\n return RUN_FAST;\n }\n else if (type == Type.Bike)\n {\n if (speedKmh<18) { return BIKE_SLOW; }\n if (speedKmh<22) { return BIKE_MID; }\n return BIKE_FAST;\n }\n return CAR_DRIVE;\n }\n \n \n /**\n * weightKg = 77.0\n *\n * @param activity: bicycling, running, walking\n * @param timeHour: hours\n * @return calorie burned (activity * weightKg * timeHour)\n */\n public static double calorieBurned(double activity, double timeHour) {\n return calorieBurned(activity, weightKg, timeHour);\n }\n\n /**\n * @param activity: bicycling, running, walking\n * @param weightKg: in kg\n * @param timeHour: hours\n * @return calorie burned (activity * weightKg * timeHour)\n */\n public static double calorieBurned(double activity, double weightKg, double timeHour) {\n return activity * weightKg * timeHour;\n }\n\n /**\n * use The Harris–Benedict equations revised by Roza and Shizgal in 1984. BMR\n *\n * @param activity: bicycling, running, walking\n * @param weightKg: in kg\n * @param timeHour: hours\n * @param heightCm: height in cm\n * @param age: age in years\n * @param men: true -> men ; false -> women\n * @return calorie burned (BMR * activity * timeHour)\n */\n public static double calorieBurned(double activity, double weightKg, double timeHour, double heightCm, double age,\n boolean men) {\n if (men) {\n return (88.362 + (13.397 * weightKg) + (4.799 * heightCm) - (5.677 * age)) * activity * timeHour;\n }\n return (447.593 + (9.247 * weightKg) + (3.098 * heightCm) - (4.330 * age)) * activity * timeHour;\n }\n}", "public class SetStatusBarColor {\n\n public SetStatusBarColor() {\n }\n\n /**\n * set (statusBar: systemBar + actionBar) View to (color) with given (activity)\n *\n * @param statusBar View\n * @param color int\n * @param activity FragmentActivity\n */\n public void setStatusBarColor(View statusBar, int color, Activity activity) {\n // System.out.println(\"------------------\" + statusBar + \"--\" + color + \"--\" + activity);\n try {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n Window w = activity.getWindow();\n w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,\n WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n //status bar height\n int actionBarHeight = getActionBarHeight(activity);\n int statusBarHeight = getStatusBarHeight(activity);\n //action bar height\n statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;\n statusBar.setBackgroundColor(color);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * set (systemBar only) View to (color) with given (activity)\n *\n * @param statusBar View\n * @param color int\n * @param activity FragmentActivity\n */\n public void setSystemBarColor(View statusBar, int color, Activity activity) {\n try {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n Window w = activity.getWindow();\n w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,\n WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n statusBar.getLayoutParams().height = getStatusBarHeight(activity);\n statusBar.setBackgroundColor(color);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param activity\n * @return action bar height\n */\n public int getActionBarHeight(Activity activity) {\n int actionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {\n actionBarHeight =\n TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());\n }\n return actionBarHeight;\n }\n\n /**\n * @param activity\n * @return status bar height\n */\n public int getStatusBarHeight(Activity activity) {\n int result = 0;\n int resourceId = activity.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = activity.getResources().getDimensionPixelSize(resourceId);\n }\n return result;\n }\n}", "public class UnitCalculator\n{\n public static final double METERS_OF_FEET = 0.3048;\n public static final double METERS_OF_MILE = 1609.344;\n public static final double METERS_OF_KM = 1000.0;\n public static final double FEETS_OF_MILE = 5280.0;\n \n public static String getString(double m)\n {\n if (!Variable.getVariable().isImperalUnit())\n {\n if (m < METERS_OF_KM) return Math.round(m) + \" meter\";\n return (((int) (m / 100)) / 10f) + \" km\";\n }\n if (m < METERS_OF_MILE) return toImperalFeet(m) + \" feet\";\n return toImperalMiles(m, 1) + \" mi\";\n }\n \n public static String getUnit(boolean big)\n {\n if (!Variable.getVariable().isImperalUnit())\n {\n if (big) { return \"km\"; }\n return \"m\";\n }\n if (big) { return \"mi\"; }\n return \"ft\";\n }\n \n /** How many meters for switch to Big unit **/\n public static double getMultValue()\n {\n if (!Variable.getVariable().isImperalUnit()) { return METERS_OF_KM; }\n return METERS_OF_MILE;\n }\n \n /** Returns a rounded Value of KM or MI.\n * @param pdp Post decimal positions. **/\n public static String getBigDistance(double m, int pdp)\n {\n if (Variable.getVariable().isImperalUnit()) { m = toImperalMiles(m); }\n else { m = m / METERS_OF_KM; }\n return String.format(Locale.getDefault(), \"%.\" + pdp + \"f\", m);\n }\n \n /** Returns the value in KM or MI. **/\n public static double getBigDistanceValue(double km)\n {\n if (!Variable.getVariable().isImperalUnit()) { return km; }\n return toImperalMiles(km * METERS_OF_KM);\n }\n \n /** Returns a rounded Value of M or FT. **/\n public static String getShortDistance(double m)\n {\n if (Variable.getVariable().isImperalUnit()) { m = toImperalFeet(m); }\n return \"\" + Math.round(m);\n }\n// \n// /** Get KM or MI **/\n// public static double getCorrectValueFromKm(double km)\n// {\n// if (!Variable.getVariable().isImperalUnit()) { return km; }\n// return toImperalMiles(km * 1000);\n// }\n//\n// /** Get M or FT **/\n// public static double getCorrectValueFromM(double m)\n// {\n// if (!Variable.getVariable().isImperalUnit()) { return m; }\n// return toImperalFeet(m);\n// }\n \n private static long toImperalFeet(double m)\n {\n m = m / METERS_OF_FEET;\n return Math.round(m);\n }\n\n /** Returns the Value of MI. **/\n private static double toImperalMiles(double m)\n {\n return m / METERS_OF_MILE;\n }\n \n /** Returns a rounded Value of MI.\n * @param pdp Post decimal positions. **/\n private static float toImperalMiles(double m, int pdp)\n {\n m = toImperalMiles(m);\n float mult = 10 * pdp;\n return (((int) (m * mult)) / mult);\n }\n}", "public class SpinnerAdapter extends ArrayAdapter<SportCategory> {\n private int resource;\n private ArrayList<SportCategory> list;\n LayoutInflater inflater;\n\n /**\n * @param context\n * @param resource single item layout to be inflated\n * @param list\n */\n public SpinnerAdapter(Context context, int resource, ArrayList<SportCategory> list) {\n super(context, resource, list);\n this.list = list;\n this.resource = resource;\n inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n }\n\n /**\n * @param position\n * @param convertView\n * @param parent\n * @return an item view with text + img\n */\n public View getView(int position, View convertView, ViewGroup parent) {\n View itemView = inflater.inflate(resource, parent, false);\n ImageView imageView = (ImageView) itemView.findViewById(R.id.analytics_activity_type_img);\n imageView.setImageResource(list.get(position).getImageId());\n TextView textView = (TextView) itemView.findViewById(R.id.analytics_activity_type_txt);\n textView.setText(list.get(position).getText());\n return itemView;\n }\n\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n return getView(position, convertView, parent);\n }\n}", "public class Variable {\n public enum TravelMode{Foot, Bike, Car};\n public enum VarType{Base, Geocode};\n private TravelMode travelMode;\n private HashMap<VarType, Boolean> loadStatus = new HashMap<VarType, Boolean>();\n /**\n * fastest, shortest (route)\n */\n private String weighting;\n /**\n * Bidirectional Dijkstra: DIJKSTRA_BI = \"dijkstrabi\"\n * <p/>\n * Unidirectional Dijkstra: DIJKSTRA = \"dijkstra\"\n * <p/>\n * one to many Dijkstra: DIJKSTRA_ONE_TO_MANY = \"dijkstraOneToMany\"\n * <p/>\n * Unidirectional A* : ASTAR = \"astar\"\n * <p/>\n * Bidirectional A* : ASTAR_BI = \"astarbi\"\n */\n private String routingAlgorithms;\n /**\n * instructions on or off; default true (on)\n */\n private boolean directionsON;\n /**\n * Show a sign while navigating, that indicates max speed\n */\n private boolean showSpeedLimits;\n /**\n * Warn the user if current speed is more than max allowed speed\n */\n private boolean speakSpeedLimits;\n /**\n * users current / last used zoom level\n */\n private int lastZoomLevel;\n\n /**\n * users last browsed screen center location\n */\n private GeoPoint lastLocation;\n /**\n * map directory name: pocketmaps/maps/\n */\n private String mapDirectory;\n /**\n * download directory name: pocketmaps/downloads/\n */\n private String dlDirectory;\n /**\n * map directory name: pocketmaps/tracking/\n */\n private String trackingDirectory;\n\n /**\n * The default map to startup.\n */\n private boolean autoSelectMap;\n \n /**\n * The selected speech engine, null for AndroidTTS.\n */\n private String ttsEngine;\n private String ttsWantedVoice;\n\n /**\n * area or country name (need to be loaded)\n * <p/>\n * example: /storage/emulated/0/Download/(mapDirectory)/(country)-gh\n */\n private String country;\n /**\n * a File where all Areas or counties are in\n * <p/>\n * example:\n * <p/>\n * <li>mapsFolder.getAbsolutePath() = /storage/emulated/0/Download/pocketmaps/maps </li>\n * <p/>\n * <li> mapsFolder = new File(\"/storage/emulated/0/Download/pocketmaps/maps\")</li>\n */\n private File mapsFolder;\n\n /**\n * Server for download JSON list of maps\n */\n private String mapUrlJSON;\n /**\n * prepare to load the map\n */\n private volatile boolean prepareInProgress;\n \n private boolean bImperalUnit = false;\n\n /**\n * list of downloaded maps in local storage; check and init when app started; used to avoid recheck local files\n */\n private List<MyMap> localMaps;\n /**\n * temporary memorialize recent downloaded maps from DownloadMapActivity\n */\n private List<MyMap> recentDownloadedMaps;\n\n /**\n * temporary memorialize download list of cloud maps from DownloadMapActivity\n */\n private List<MyMap> cloudMaps;\n \n /**\n * sport category spinner index at {@link Analytics#spinner}\n */\n private int sportCategoryIndex;\n\n private boolean lightSensorON;\n private boolean voiceON;\n private boolean smoothON;\n \n private int offlineSearchBits = GeocoderLocal.BIT_CITY + GeocoderLocal.BIT_STREET;\n private int geocodeSearchEngine = 0;\n private String geocodeSearchTextList = \"\";\n \n public static final int DEF_ZOOM = 8;\n public static final String DEF_WIGHTING = \"fastest\";\n public static final String DEF_ALG = \"astarbi\";\n\n /**\n * application context\n */\n private Context context;\n\n private static Variable variable;\n\n private Variable() {\n this.travelMode = TravelMode.Foot;\n this.weighting = DEF_WIGHTING;\n this.routingAlgorithms = DEF_ALG;\n this.autoSelectMap = false;\n this.ttsEngine = null;\n this.ttsWantedVoice = null;\n this.lastZoomLevel = DEF_ZOOM;\n this.lastLocation = null;\n this.country = null;\n this.mapsFolder = null;\n this.context = null;\n this.directionsON = true;\n this.showSpeedLimits = false;\n this.speakSpeedLimits = false;\n this.voiceON = true;\n this.lightSensorON = true;\n this.smoothON = false;\n this.mapDirectory = \"pocketmaps/maps/\";\n this.dlDirectory = \"pocketmaps/downloads/\";\n this.trackingDirectory = \"pocketmaps/tracking/\";\n this.mapUrlJSON = \"http://vsrv15044.customer.xenway.de/maps\";\n this.localMaps = new ArrayList<>();\n this.recentDownloadedMaps = new ArrayList<>();\n this.cloudMaps = new ArrayList<>();\n this.sportCategoryIndex = 0;\n }\n\n public static Variable getVariable() {\n if (variable == null) {\n variable = new Variable();\n }\n return variable;\n }\n \n public boolean isLoaded(VarType type)\n {\n if (loadStatus.containsKey(type)) { return true; }\n return false;\n }\n\n public String getMapUrlJSON() {\n return mapUrlJSON;\n }\n\n public TravelMode getTravelMode() {\n return travelMode;\n }\n\n public void setTravelMode(TravelMode travelMode) {\n this.travelMode = travelMode;\n }\n \n public boolean getAutoSelectMap()\n {\n return autoSelectMap;\n }\n \n public void setAutoSelectMap(boolean autoSelectMap)\n {\n this.autoSelectMap = autoSelectMap;\n }\n \n public String getTtsEngine()\n {\n return ttsEngine;\n }\n \n public void setTtsEngine(String ttsEngine)\n {\n this.ttsEngine = ttsEngine;\n }\n \n public String getTtsWantedVoice()\n {\n return ttsWantedVoice;\n }\n \n public void setTtsWantedVoice(String ttsWantedVoice)\n {\n this.ttsWantedVoice = ttsWantedVoice;\n }\n \n public int getGeocodeSearchEngine()\n {\n return geocodeSearchEngine;\n }\n \n public boolean setGeocodeSearchEngine(int geocodeSearchEngine)\n {\n if (this.geocodeSearchEngine == geocodeSearchEngine) { return false; }\n this.geocodeSearchEngine = geocodeSearchEngine;\n return true;\n }\n \n public int getOfflineSearchBits()\n {\n return offlineSearchBits;\n }\n \n public void setOfflineSearchBits(int offlineSearchBits)\n {\n this.offlineSearchBits = offlineSearchBits;\n }\n \n public String[] getGeocodeSearchTextList()\n {\n if (geocodeSearchTextList.isEmpty()) { return new String[0]; }\n return geocodeSearchTextList.trim().split(\"\\n\");\n }\n \n public boolean addGeocodeSearchText(String text)\n {\n if (text.isEmpty()) { return false; }\n text = text.toLowerCase();\n for (String curTxt : getGeocodeSearchTextList())\n {\n if (curTxt.contains(text)) { return false; }\n }\n geocodeSearchTextList = geocodeSearchTextList + \"\\n\" + text;\n return true;\n }\n\n public String getWeighting() {\n return weighting;\n }\n\n public void setWeighting(String weighting) {\n this.weighting = weighting;\n }\n\n public String getRoutingAlgorithms() {\n return routingAlgorithms;\n }\n\n public void setRoutingAlgorithms(String routingAlgorithms) {\n this.routingAlgorithms = routingAlgorithms;\n }\n\n public boolean isDirectionsON() {\n return directionsON;\n }\n\n public void setDirectionsON(boolean directionsON) {\n this.directionsON = directionsON;\n }\n\n public boolean isShowingSpeedLimits() {\n return showSpeedLimits;\n }\n\n public void setShowSpeedLimits(boolean showSpeedLimits) {\n this.showSpeedLimits = showSpeedLimits;\n }\n\n public boolean isSpeakingSpeedLimits() {\n return speakSpeedLimits;\n }\n\n public void setSpeakSpeedLimits(boolean speakSpeedLimits) {\n this.speakSpeedLimits = speakSpeedLimits;\n }\n \n public boolean isVoiceON()\n {\n return voiceON;\n }\n \n public void setVoiceON(boolean voiceON)\n {\n this.voiceON = voiceON;\n }\n \n public boolean isLightSensorON()\n {\n return lightSensorON;\n }\n \n public void setLightSensorON(boolean lightSensorON)\n {\n this.lightSensorON = lightSensorON;\n }\n\n public boolean isSmoothON()\n {\n return smoothON;\n }\n\n public void setSmoothON(boolean smoothON)\n {\n this.smoothON = smoothON;\n }\n\n /**\n * @return is DirectionsON as string : \"true or false\"\n */\n public String getDirectionsON() {\n return isDirectionsON() ? \"true\" : \"false\";\n }\n\n public int getLastZoomLevel() {\n return lastZoomLevel;\n }\n\n public void setLastZoomLevel(int lastZoomLevel) {\n this.lastZoomLevel = lastZoomLevel;\n }\n \n public boolean isImperalUnit() {\n return bImperalUnit;\n }\n \n public void setImperalUnit(boolean bImperalUnit) {\n this.bImperalUnit = bImperalUnit;\n }\n\n public GeoPoint getLastLocation() {\n return lastLocation;\n }\n\n public void setLastLocation(GeoPoint lastLocation) {\n this.lastLocation = lastLocation;\n }\n\n /** Returns the last selected country, or an empty String. **/\n public String getCountry() {\n if (country==null) { return \"\"; }\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public File getMapsFolder() {\n return mapsFolder;\n }\n \n public File getDownloadsFolder() {\n File dlFolder = new File(mapsFolder.getParentFile().getParent(), dlDirectory);\n if (!dlFolder.exists()) { dlFolder.mkdirs(); }\n return IO.getDownloadDirectory(dlFolder, context);\n }\n\n public void setBaseFolder(String baseFolder) {\n this.mapsFolder = new File(baseFolder, mapDirectory);\n }\n\n public File getTrackingFolder() {\n return new File(mapsFolder.getParentFile().getParent(), trackingDirectory);\n }\n\n public Context getContext() {\n return context;\n }\n\n public void setContext(Context context) {\n this.context = context;\n }\n\n public boolean isPrepareInProgress() {\n return prepareInProgress;\n }\n\n public void setPrepareInProgress(boolean prepareInProgress) {\n this.prepareInProgress = prepareInProgress;\n }\n\n public List<MyMap> getLocalMaps() {\n return localMaps;\n }\n\n /**\n * add a list of maps to localMaps\n *\n * @param localMaps list of maps\n */\n public void addLocalMaps(List<MyMap> localMaps) {\n this.localMaps.addAll(localMaps);\n }\n\n /**\n * add a map to local map list\n *\n * @param localMap MyMap\n */\n public void addLocalMap(MyMap localMap) {\n if (!getLocalMapNameList().contains(localMap.getMapName())) {\n this.localMaps.add(localMap);\n }\n }\n\n public void removeLocalMap(MyMap localMap) {\n this.localMaps.remove(localMap);\n }\n\n public void setLocalMaps(List<MyMap> localMaps) {\n this.localMaps = localMaps;\n }\n\n /**\n * @return a string list of local map names (continent_country)\n */\n public List<String> getLocalMapNameList() {\n ArrayList<String> al = new ArrayList<String>();\n for (MyMap mm : getLocalMaps()) {\n al.add(mm.getMapName());\n }\n return al;\n }\n\n public List<MyMap> getRecentDownloadedMaps() {\n return recentDownloadedMaps;\n }\n\n public List<MyMap> getCloudMaps() {\n return cloudMaps;\n }\n\n public void updateCloudMaps(List<MyMap> cloudMaps) {\n ArrayList<MyMap> newList = new ArrayList<MyMap>();\n for (MyMap oldMap : this.cloudMaps)\n {\n for (MyMap newMap : cloudMaps)\n {\n if (newMap.getUrl().equals(oldMap.getUrl()))\n {\n newMap.setStatus(oldMap.getStatus());\n break;\n }\n }\n }\n // Find same Map from CloudMaps\n for (MyMap newMap : cloudMaps)\n {\n int myIndex = Variable.getVariable().getCloudMaps().indexOf(newMap);\n if (myIndex < 0) { newList.add(newMap); continue; }\n MyMap sameMap = Variable.getVariable().getCloudMaps().get(myIndex);\n sameMap.set(newMap);\n newList.add(sameMap);\n }\n this.cloudMaps = newList;\n }\n\n /** Similar as getTravelMode() but used for spinner. **/\n public int getSportCategoryIndex() {\n return sportCategoryIndex;\n }\n\n /** Similar as setTravelMode() but used for spinner. **/\n public void setSportCategoryIndex(int sportCategoryIndex) {\n this.sportCategoryIndex = sportCategoryIndex;\n }\n\n /**\n * run when app open at run time\n * <p/>\n * load variables from saved file\n *\n * @return true if load succeed, false if nothing to load or load fail\n */\n public boolean loadVariables(VarType varType)\n {\n String content;\n if (varType == VarType.Base)\n {\n content = readFile(\"pocketmapssavedfile.txt\");\n loadStatus.put(VarType.Base, Boolean.TRUE);\n }\n else\n {\n content = readFile(\"pocketmapssavedfile_\" + varType + \".txt\");\n loadStatus.put(VarType.Geocode, Boolean.TRUE);\n }\n if (content == null)\n {\n return false;\n }\n JsonWrapper jo;\n try\n {\n jo = new JsonWrapper(content);\n if (varType == VarType.Base)\n {\n setTravelMode(TravelMode.valueOf(toUpperFirst(jo.getStr(\"travelMode\", TravelMode.Foot.toString()))));\n setWeighting(jo.getStr(\"weighting\", DEF_WIGHTING));\n setRoutingAlgorithms(jo.getStr(\"routingAlgorithms\", DEF_ALG));\n setDirectionsON(jo.getBool(\"directionsON\", true));\n setSpeakSpeedLimits(jo.getBool(\"speakSpeedLimits\", false));\n setShowSpeedLimits(jo.getBool(\"showSpeedLimits\", false));\n setVoiceON(jo.getBool(\"voiceON\", true));\n setLightSensorON(jo.getBool(\"lightSensorON\", true));\n setAutoSelectMap(jo.getBool(\"autoSelectMap\", false));\n setTtsEngine(jo.getStr(\"ttsEngine\", null));\n setTtsWantedVoice(jo.getStr(\"ttsWantedVoice\", null));\n setLastZoomLevel(jo.getInt(\"lastZoomLevel\", DEF_ZOOM));\n setImperalUnit(jo.getBool(\"isImperalUnit\", false));\n setSmoothON(jo.getBool(\"smoothON\", false));\n double la = jo.getDouble(\"latitude\", 0);\n double lo = jo.getDouble(\"longitude\", 0);\n if (la != 0 && lo != 0) {\n setLastLocation(new GeoPoint(la, lo));\n }\n String coun = jo.getStr(\"country\", \"\");\n if (!coun.isEmpty()) {\n setCountry(coun);\n }\n String mapsFolderAbsStr = jo.getStr(\"mapsFolderAbsPath\", \"/x/y/z\");\n File mapsFolderAbsPath = new File(mapsFolderAbsStr);\n if (mapsFolderAbsPath.exists() && !mapsFolderAbsStr.equals(\"/x/y/z\"))\n {\n setBaseFolder(mapsFolderAbsPath.getParentFile().getParent());\n }\n setSportCategoryIndex(jo.getInt(\"sportCategoryIndex\", 0));\n }\n else if (varType == VarType.Geocode)\n {\n setGeocodeSearchEngine(jo.getInt(\"geocodeSearchEngine\", 0));\n geocodeSearchTextList = jo.getStr(\"geocodeSearchTextList\", \"\");\n offlineSearchBits = jo.getInt(\"offlineSearchBits\", GeocoderLocal.BIT_CITY + GeocoderLocal.BIT_STREET);\n }\n }\n catch (JSONException e)\n {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n\n private static String toUpperFirst(String string)\n {\n // TODO This is just a workaround, because of incompatiblity from older versions.\n // This workaround will ensure to override the fault data.\n // Can be deleted later, maybe in year 2022\n if (string == null) { return \"Car\"; }\n String first = string.substring(0,1).toUpperCase();\n String rest = string.substring(1);\n return first + rest;\n }\n\n /**\n * run before app destroyed at run time\n * <p/>\n * save variables to local file (json) @return true is succeed, false otherwise\n */\n public boolean saveVariables(VarType varType) {\n JsonWrapper jo = new JsonWrapper();\n try\n {\n if (varType == VarType.Base)\n {\n jo.put(\"travelMode\", getTravelMode().toString());\n jo.put(\"weighting\", getWeighting());\n jo.put(\"routingAlgorithms\", getRoutingAlgorithms());\n jo.put(\"directionsON\", isDirectionsON());\n jo.put(\"showSpeedLimits\", isShowingSpeedLimits());\n jo.put(\"speakSpeedLimits\", isSpeakingSpeedLimits());\n jo.put(\"voiceON\", isVoiceON());\n jo.put(\"lightSensorON\", isLightSensorON());\n jo.put(\"autoSelectMap\", autoSelectMap);\n jo.put(\"ttsEngine\", ttsEngine);\n jo.put(\"ttsWantedVoice\", ttsWantedVoice);\n jo.put(\"lastZoomLevel\", getLastZoomLevel());\n if (getLastLocation() != null) {\n jo.put(\"latitude\", getLastLocation().getLatitude());\n jo.put(\"longitude\", getLastLocation().getLongitude());\n } else {\n jo.put(\"latitude\", 0);\n jo.put(\"longitude\", 0);\n }\n jo.put(\"isImperalUnit\", bImperalUnit);\n jo.put(\"country\", getCountry());\n jo.put(\"smoothON\", smoothON);\n jo.put(\"mapsFolderAbsPath\", getMapsFolder().getAbsolutePath());\n jo.put(\"sportCategoryIndex\", getSportCategoryIndex());\n }\n else if (varType == VarType.Geocode)\n {\n jo.put(\"geocodeSearchEngine\", geocodeSearchEngine);\n jo.put(\"geocodeSearchTextList\", geocodeSearchTextList);\n jo.put(\"offlineSearchBits\", offlineSearchBits);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n return false;\n }\n if (varType == VarType.Base)\n {\n return saveStringToFile(\"pocketmapssavedfile.txt\", jo.toString());\n }\n else\n {\n return saveStringToFile(\"pocketmapssavedfile_\" + varType + \".txt\", jo.toString());\n }\n }\n \n /** Return existing files, where settings are saved. **/\n public ArrayList<String> getSavingFiles()\n {\n ArrayList<String> list = new ArrayList<String>();\n for (String f : context.fileList())\n {\n if (isSavingFile(f)) { list.add(f); }\n }\n return list;\n }\n \n public static boolean isSavingFile(String f)\n {\n return f.startsWith(\"pocketmapssavedfile\") && f.endsWith(\".txt\");\n }\n\n /**\n * @return read saved file and return it as a string\n */\n private String readFile(String file) {\n try(FileInputStream fis = context.openFileInput(file);\n InputStreamReader isr = new InputStreamReader(fis);\n BufferedReader bufferedReader = new BufferedReader(isr))\n {\n StringBuilder sb = new StringBuilder();\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n sb.append(line);\n }\n return sb.toString();\n } catch (IOException e) {\n log(\"Cant load savingfile, maybe the first time since app installed.\");\n e.printStackTrace();\n return null;\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * @param file a string need to be saved\n * @return\n */\n private boolean saveStringToFile(String file, String content) {\n try(FileOutputStream fos = context.openFileOutput(file, Context.MODE_PRIVATE))\n {\n fos.write(content.getBytes());\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n \n private void log(String s) {\n Log.i(Variable.class.getName(), s);\n }\n\n}" ]
import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.TextView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.LegendRenderer; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.junjunguo.pocketmaps.R; import com.junjunguo.pocketmaps.model.SportCategory; import com.junjunguo.pocketmaps.model.listeners.TrackingListener; import com.junjunguo.pocketmaps.map.Tracking; import com.junjunguo.pocketmaps.util.Calorie; import com.junjunguo.pocketmaps.util.SetStatusBarColor; import com.junjunguo.pocketmaps.util.UnitCalculator; import com.junjunguo.pocketmaps.fragments.SpinnerAdapter; import com.junjunguo.pocketmaps.util.Variable; import java.util.ArrayList; import java.util.Locale;
package com.junjunguo.pocketmaps.activities; /** * This file is part of PocketMaps * <p> * Created by GuoJunjun <junjunguo.com> on July 04, 2015. */ public class Analytics extends AppCompatActivity implements TrackingListener { // status ----------------- public static boolean startTimer = true; /** * a sport category spinner: to choose with type of sport which also has MET value in its adapter */ private Spinner spinner; private TextView durationTV, avgSpeedTV, maxSpeedTV, distanceTV, distanceUnitTV, caloriesTV, maxSpeedUnitTV, avgSpeedUnitTV; // duration private Handler durationHandler; private Handler calorieUpdateHandler; // graph ----------------- /** * max value for it's axis (minimum 0) * <p/> * <li>X axis: time - hours</li> <li>Y1 (left) axis: speed - km/h</li> <li>Y2 (right) axis: distance - km</li> */ private double maxXaxis, maxY1axis, maxY2axis; /** * has a new point needed to update to graph view */ private boolean hasNewPoint; private GraphView graph; private LineGraphSeries<DataPoint> speedGraphSeries; private LineGraphSeries<DataPoint> distanceGraphSeries; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_analytics); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // set status bar new SetStatusBarColor().setStatusBarColor(findViewById(R.id.statusBarBackgroundDownload), getResources().getColor(R.color.my_primary), this); // status initSpinner(); initStatus(); durationHandler = new Handler(); calorieUpdateHandler = new Handler(); // graph initGraph(); } // ---------- status --------------- private void initSpinner() { spinner = (Spinner) findViewById(R.id.activity_analytics_spinner); ArrayList<SportCategory> spinnerList = new ArrayList<>(); spinnerList.add(new SportCategory("walk/run", R.drawable.ic_directions_run_white_24dp, Calorie.Type.Run)); spinnerList.add(new SportCategory("bike", R.drawable.ic_directions_bike_white_24dp, Calorie.Type.Bike)); spinnerList.add(new SportCategory("car", R.drawable.ic_directions_car_white_24dp, Calorie.Type.Car));
SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.analytics_activity_type, spinnerList);
6
cattaka/AdapterToolbox
example/src/androidTest/java/net/cattaka/android/adaptertoolbox/example/TreeItemAdapterExampleActivityTest.java
[ "public class MyTreeItemAdapter extends AbsChoosableTreeItemAdapter<\n MyTreeItemAdapter,\n MyTreeItemAdapter.ViewHolder,\n MyTreeItem,\n MyTreeItemAdapter.WrappedItem\n > {\n public static ITreeItemAdapterRef<MyTreeItemAdapter, ViewHolder, MyTreeItem, WrappedItem> REF = new ITreeItemAdapterRef<MyTreeItemAdapter, ViewHolder, MyTreeItem, WrappedItem>() {\n @NonNull\n @Override\n public Class<MyTreeItem> getItemClass() {\n return MyTreeItem.class;\n }\n\n @NonNull\n @Override\n public MyTreeItemAdapter createAdapter(@NonNull Context context, @NonNull List<MyTreeItem> items) {\n return new MyTreeItemAdapter(context, items);\n }\n\n @NonNull\n @Override\n public WrappedItem createWrappedItem(int level, MyTreeItem item, WrappedItem parent) {\n return new WrappedItem(level, item, parent);\n }\n };\n\n private View.OnClickListener createOnClickListener(View parent) {\n final IForwardingListener.IProvider provider = getProvider(parent);\n return new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n RecyclerView recyclerView = provider.getAttachedRecyclerView();\n ViewHolder vh = (ViewHolder) (recyclerView != null ? recyclerView.findContainingViewHolder(view) : null);\n if (vh != null) {\n int position = vh.getAdapterPosition();\n WrappedItem item = getItemAt(position);\n switch (view.getId()) {\n case R.id.check_opened: {\n doOpen(item, !item.isOpened());\n break;\n }\n default: {\n toggleCheck(item);\n break;\n }\n }\n }\n }\n };\n }\n\n public MyTreeItemAdapter(Context context, List<MyTreeItem> items) {\n super(context, items, REF);\n }\n\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(getContext()).inflate(R.layout.item_my_tree_item, parent, false);\n ViewHolder holder = new ViewHolder(view);\n\n holder.openedCheck.setOnClickListener(createOnClickListener(parent));\n\n holder.itemView.setOnClickListener(getForwardingListener(parent));\n holder.itemView.setOnLongClickListener(getForwardingListener(parent));\n\n return holder;\n }\n\n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n WrappedItem wrappedItem = getItemAt(position);\n MyTreeItem item = wrappedItem.getItem();\n\n {\n ViewGroup.LayoutParams params = holder.levelSpace.getLayoutParams();\n params.width = wrappedItem.level * getContext().getResources().getDimensionPixelSize(R.dimen.element_spacing_large);\n holder.levelSpace.setLayoutParams(params);\n }\n {\n boolean hasChildren = (wrappedItem.children != null && wrappedItem.children.size() > 0);\n holder.openedCheck.setVisibility(hasChildren ? View.VISIBLE : View.INVISIBLE);\n }\n\n holder.openedCheck.setChecked(wrappedItem.isOpened());\n holder.labelText.setText(item.getText());\n }\n\n public static class WrappedItem extends AbsChoosableTreeItemAdapter.WrappedItem<WrappedItem, MyTreeItem> {\n public WrappedItem(int level, MyTreeItem item, WrappedItem parent) {\n super(level, item, parent);\n }\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n Space levelSpace;\n CompoundButton openedCheck;\n TextView labelText;\n\n public ViewHolder(View itemView) {\n super(itemView);\n levelSpace = (Space) itemView.findViewById(R.id.space_level);\n openedCheck = (CompoundButton) itemView.findViewById(R.id.check_opened);\n labelText = (TextView) itemView.findViewById(R.id.text_label);\n }\n }\n}", "public class MyTreeItem implements ITreeItem<MyTreeItem> {\n private String text;\n private List<MyTreeItem> children;\n\n public MyTreeItem() {\n }\n\n public MyTreeItem(String text, List<MyTreeItem> children) {\n this.text = text;\n this.children = children;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n @Override\n public List<MyTreeItem> getChildren() {\n return children;\n }\n\n public void setChildren(List<MyTreeItem> children) {\n this.children = children;\n }\n}", "public class MockSnackbarLogic extends SnackbarLogic {\n @NonNull\n @Override\n public ISnackbarWrapper make(@NonNull View view, @NonNull CharSequence text, int duration) {\n return new MockSnackbarWrapper();\n }\n\n @NonNull\n @Override\n public ISnackbarWrapper make(@NonNull View view, int resId, int duration) {\n return new MockSnackbarWrapper();\n }\n\n public static class MockSnackbarWrapper implements ISnackbarWrapper {\n @Override\n public void show() {\n // no-op\n }\n }\n}", "public class RecyclerViewAnimatingIdlingResource implements IdlingResource {\n RecyclerView mRecyclerView;\n ResourceCallback mCallback;\n\n public RecyclerViewAnimatingIdlingResource(RecyclerView recyclerView) {\n mRecyclerView = recyclerView;\n }\n\n @Override\n public void registerIdleTransitionCallback(ResourceCallback callback) {\n mCallback = callback;\n }\n\n @Override\n public boolean isIdleNow() {\n if (!mRecyclerView.isAnimating()) {\n if (mCallback != null) {\n mCallback.onTransitionToIdle();\n }\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public String getName() {\n return \"RecyclerViewAnimatingIdlingResource\";\n }\n}", "public class TestUtils {\n @SuppressWarnings(\"unchecked\")\n public static <T extends Activity> T monitorActivity(@NonNull Class<T> activityClass, int timeOut, @NonNull Runnable runnable) {\n Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(activityClass.getCanonicalName(), null, false);\n try {\n InstrumentationRegistry.getInstrumentation().addMonitor(monitor);\n runnable.run();\n return (T) monitor.waitForActivityWithTimeout(timeOut);\n } finally {\n InstrumentationRegistry.getInstrumentation().removeMonitor(monitor);\n }\n }\n\n public static Matcher<View> withIdInRecyclerView(int id, int recyclerViewId, int position) {\n return allOf(withId(id), isDescendantOfRecyclerView(recyclerViewId, position));\n }\n\n public static Matcher<View> isDescendantOfRecyclerView(final int recyclerViewId, final int position) {\n return new BaseMatcher<View>() {\n @Override\n public boolean matches(Object arg) {\n if (arg instanceof View) {\n View v = (View) arg;\n View parent = v;\n while (parent.getParent() != null && parent.getParent() instanceof View) {\n if ((recyclerViewId == -1 || parent.getId() == recyclerViewId)\n && parent instanceof RecyclerView) {\n RecyclerView.ViewHolder holder = findContainingViewHolder((RecyclerView) parent, v);\n if (holder != null && holder.getAdapterPosition() == position) {\n return true;\n }\n }\n parent = (View) parent.getParent();\n }\n }\n return false;\n }\n\n @Override\n public void describeTo(Description description) {\n String resName = String.valueOf(recyclerViewId);\n try {\n resName = InstrumentationRegistry.getTargetContext().getResources().getResourceEntryName(recyclerViewId);\n } catch (Resources.NotFoundException e) {\n // ignore\n }\n description.appendText(\"isDescendantOfRecyclerView(\")\n .appendValue(resName)\n .appendText(\",\")\n .appendValue(position)\n .appendText(\")\");\n }\n };\n }\n\n public static Matcher<View> withIdInAdapterView(int id, int adapterViewId, int position) {\n return allOf(withId(id), isDescendantOfAdapterView(adapterViewId, position));\n }\n\n public static Matcher<View> isDescendantOfAdapterView(final int adapterViewId, final int position) {\n return new BaseMatcher<View>() {\n @Override\n public boolean matches(Object arg) {\n if (arg instanceof View) {\n View view = (View) arg;\n while (view.getParent() != null && view.getParent() instanceof View) {\n View parent = (View) view.getParent();\n if ((adapterViewId == -1 || parent.getId() == adapterViewId)\n && parent instanceof AdapterView) {\n AdapterView adapterView = ((AdapterView) parent);\n int offsetPosition = position - adapterView.getFirstVisiblePosition();\n if (0 <= offsetPosition && offsetPosition < adapterView.getChildCount()\n && adapterView.getChildAt(offsetPosition) == view) {\n return true;\n }\n }\n view = parent;\n }\n }\n return false;\n }\n\n @Override\n public void describeTo(Description description) {\n String resName = String.valueOf(adapterViewId);\n try {\n resName = InstrumentationRegistry.getTargetContext().getResources().getResourceEntryName(adapterViewId);\n } catch (Resources.NotFoundException e) {\n // ignore\n }\n description.appendText(\"isDescendantOfAdapterView(\")\n .appendValue(resName)\n .appendText(\",\")\n .appendValue(position)\n .appendText(\")\");\n }\n };\n }\n\n /* This method is implemented in newer RecyclerView. */\n @Nullable\n public static RecyclerView.ViewHolder findContainingViewHolder(RecyclerView recyclerView, View view) {\n View v = view;\n while (v != null && v.getParent() instanceof View) {\n if (v.getParent() == recyclerView) {\n return recyclerView.getChildViewHolder(v);\n }\n v = (View) v.getParent();\n }\n return null;\n }\n\n public static ViewAction setProgress(final int progress) {\n return new ViewAction() {\n @Override\n public void perform(UiController uiController, View view) {\n ((SeekBar) view).setProgress(progress);\n }\n\n @Override\n public String getDescription() {\n return \"Set a progress\";\n }\n\n @Override\n public Matcher<View> getConstraints() {\n return ViewMatchers.isAssignableFrom(SeekBar.class);\n }\n };\n }\n\n public static ViewAssertion hasProgress(final Matcher<Integer> progress) {\n return new ViewAssertion() {\n @Override\n public void check(View view, NoMatchingViewException noViewFoundException) {\n if (view instanceof ProgressBar) {\n if (progress.matches(((ProgressBar) view).getProgress())) {\n return;\n }\n }\n throw noViewFoundException;\n }\n };\n }\n\n public static ViewAssertion hasSelectedItem(final Matcher<? extends Object> item) {\n return new ViewAssertion() {\n @Override\n public void check(View view, NoMatchingViewException noViewFoundException) {\n if (view instanceof AdapterView) {\n if (item.matches(((AdapterView) view).getSelectedItem())) {\n return;\n }\n }\n throw noViewFoundException;\n }\n };\n }\n\n /**\n * To be truthful, We should use Espresso#registerIdlingResource.\n * But sometime it become too slow.\n */\n public static void waitForIdlingResource(IdlingResource idlingResource, int timeout) {\n long l = SystemClock.elapsedRealtime();\n do {\n if (idlingResource.isIdleNow()) {\n break;\n }\n SystemClock.sleep(100);\n } while (SystemClock.elapsedRealtime() - l > timeout);\n }\n\n public static int calcPositionOffset(MergeRecyclerAdapter mergeRecyclerAdapter, RecyclerView.Adapter adapter) {\n int offset = 0;\n for (int i = 0; i < mergeRecyclerAdapter.getSubAdapterCount(); i++) {\n RecyclerView.Adapter a = mergeRecyclerAdapter.getSubAdapter(i);\n if (a == adapter) {\n break;\n }\n offset += a.getItemCount();\n }\n return offset;\n }\n\n\n @SuppressWarnings(\"unchecked\")\n public static <T extends RecyclerView.Adapter> T find(@Nullable MergeRecyclerAdapter mergeRecyclerAdapter, @NonNull Class<T> clazz, int position) {\n if (mergeRecyclerAdapter == null) {\n return null;\n }\n int count = 0;\n for (int i = 0; i < mergeRecyclerAdapter.getSubAdapterCount(); i++) {\n RecyclerView.Adapter item = mergeRecyclerAdapter.getSubAdapter(i);\n if (clazz.isInstance(item)) {\n if (count == position) {\n return (T) item;\n }\n count++;\n }\n }\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> Entry<T> find(@Nullable List<?> items, @NonNull Class<T> clazz, int position) {\n if (items == null) {\n return null;\n }\n int count = 0;\n for (int i = 0; i < items.size(); i++) {\n Object item = items.get(i);\n if (clazz.isInstance(item)) {\n if (count == position) {\n return new Entry<>(i, (T) item);\n }\n count++;\n }\n }\n return null;\n }\n\n public static class Entry<T> {\n public final int index;\n public final T object;\n\n public Entry(int index, T object) {\n this.index = index;\n this.object = object;\n }\n }\n}", "@SuppressWarnings(\"unchecked\")\npublic static <T extends RecyclerView.Adapter> T find(@Nullable MergeRecyclerAdapter mergeRecyclerAdapter, @NonNull Class<T> clazz, int position) {\n if (mergeRecyclerAdapter == null) {\n return null;\n }\n int count = 0;\n for (int i = 0; i < mergeRecyclerAdapter.getSubAdapterCount(); i++) {\n RecyclerView.Adapter item = mergeRecyclerAdapter.getSubAdapter(i);\n if (clazz.isInstance(item)) {\n if (count == position) {\n return (T) item;\n }\n count++;\n }\n }\n return null;\n}", "public static void waitForIdlingResource(IdlingResource idlingResource, int timeout) {\n long l = SystemClock.elapsedRealtime();\n do {\n if (idlingResource.isIdleNow()) {\n break;\n }\n SystemClock.sleep(100);\n } while (SystemClock.elapsedRealtime() - l > timeout);\n}", "public static Matcher<View> withIdInRecyclerView(int id, int recyclerViewId, int position) {\n return allOf(withId(id), isDescendantOfRecyclerView(recyclerViewId, position));\n}" ]
import android.support.test.rule.ActivityTestRule; import android.view.View; import net.cattaka.android.adaptertoolbox.example.adapter.MyTreeItemAdapter; import net.cattaka.android.adaptertoolbox.example.data.MyTreeItem; import net.cattaka.android.adaptertoolbox.example.test.MockSnackbarLogic; import net.cattaka.android.adaptertoolbox.example.test.RecyclerViewAnimatingIdlingResource; import net.cattaka.android.adaptertoolbox.example.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.contrib.RecyclerViewActions.scrollToPosition; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.find; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.waitForIdlingResource; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.withIdInRecyclerView; import static org.hamcrest.Matchers.containsString; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify;
package net.cattaka.android.adaptertoolbox.example; /** * Created by cattaka on 16/06/05. */ public class TreeItemAdapterExampleActivityTest { @Rule public ActivityTestRule<TreeItemAdapterExampleActivity> mActivityTestRule = new ActivityTestRule<>(TreeItemAdapterExampleActivity.class, false, true); RecyclerViewAnimatingIdlingResource mRecyclerViewAnimatingIdlingResource; @Before public void before() { mRecyclerViewAnimatingIdlingResource = new RecyclerViewAnimatingIdlingResource(mActivityTestRule.getActivity().mRecyclerView); // registerIdlingResources(mRecyclerViewAnimatingIdlingResource); } @After public void after() { // unregisterIdlingResources(mRecyclerViewAnimatingIdlingResource); } @Test public void openCloseAll() { TreeItemAdapterExampleActivity activity = mActivityTestRule.getActivity();
MyTreeItemAdapter adapter = (MyTreeItemAdapter) activity.mRecyclerView.getAdapter();
0
zerg000000/mario-ai
src/main/java/ch/idsia/scenarios/test/EvaluateJLink.java
[ "public class LargeSRNAgent extends BasicMarioAIAgent implements Agent, Evolvable\n{\n\nprivate SRN srn;\nfinal int numberOfOutputs = Environment.numberOfKeys;\nfinal int numberOfInputs = 101;\nstatic private final String name = \"LargeSRNAgent\";\n\npublic LargeSRNAgent()\n{\n super(name);\n srn = new SRN(numberOfInputs, 10, numberOfOutputs);\n}\n\npublic LargeSRNAgent(SRN srn)\n{\n super(name);\n this.srn = srn;\n}\n\npublic Evolvable getNewInstance()\n{\n return new LargeSRNAgent(srn.getNewInstance());\n}\n\npublic Evolvable copy()\n{\n return new LargeSRNAgent(srn.copy());\n}\n\npublic void reset()\n{\n srn.reset();\n}\n\npublic void mutate()\n{\n srn.mutate();\n}\n\npublic boolean[] getAction()\n{\n double[] inputs;// = new double[numberOfInputs];\n// byte[][] scene = observation.getLevelSceneObservation(/*1*/);\n// byte[][] enemies = observation.getEnemiesObservation(/*0*/);\n inputs = new double[numberOfInputs];\n int which = 0;\n for (int i = -3; i < 4; i++)\n {\n for (int j = -3; j < 4; j++)\n {\n inputs[which++] = probe(i, j, levelScene);\n }\n }\n for (int i = -3; i < 4; i++)\n {\n for (int j = -3; j < 4; j++)\n {\n inputs[which++] = probe(i, j, enemies);\n }\n }\n inputs[inputs.length - 3] = isMarioOnGround ? 1 : 0;\n inputs[inputs.length - 2] = isMarioAbleToJump ? 1 : 0;\n inputs[inputs.length - 1] = 1;\n double[] outputs = srn.propagate(inputs);\n boolean[] action = new boolean[numberOfOutputs];\n for (int i = 0; i < action.length; i++)\n {\n action[i] = outputs[i] > 0;\n }\n return action;\n}\n\npublic String getName()\n{\n return name;\n}\n\npublic void setName(String name)\n{\n}\n\nprivate double probe(int x, int y, byte[][] scene)\n{\n int realX = x + 11;\n int realY = y + 11;\n return (scene[realX][realY] != 0) ? 1 : 0;\n}\n}", "public abstract class GlobalOptions\n{\npublic static final int primaryVerionUID = 0;\npublic static final int minorVerionUID = 1;\npublic static final int minorSubVerionID = 9;\n\npublic static boolean areLabels = false;\npublic static boolean isCameraCenteredOnMario = false;\npublic static Integer FPS = 24;\npublic static int MaxFPS = 100;\npublic static boolean areFrozenCreatures = false;\n\npublic static boolean isVisualization = true;\npublic static boolean isGameplayStopped = false;\npublic static boolean isFly = false;\n\nprivate static GameViewer GameViewer = null;\n// public static boolean isTimer = true;\n\npublic static int mariosecondMultiplier = 15;\n\npublic static boolean isPowerRestoration;\n\n// required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java\npublic static int receptiveFieldWidth = 19;\npublic static int receptiveFieldHeight = 19;\npublic static int marioEgoCol = 9;\npublic static int marioEgoRow = 9;\n\nprivate static MarioVisualComponent marioVisualComponent;\npublic static int VISUAL_COMPONENT_WIDTH = 320;\npublic static int VISUAL_COMPONENT_HEIGHT = 240;\n\npublic static boolean isShowReceptiveField = false;\npublic static boolean isScale2x = false;\npublic static boolean isRecording = false;\npublic static boolean isReplaying = false;\n\npublic static int getPrimaryVersionUID()\n{\n return primaryVerionUID;\n}\n\npublic static int getMinorVersionUID()\n{\n return minorVerionUID;\n}\n\npublic static int getMinorSubVersionID()\n{\n return minorSubVerionID;\n}\n\npublic static String getBenchmarkName()\n{\n return \"[~ Mario AI Benchmark ~\" + GlobalOptions.getVersionUID() + \"]\";\n}\n\npublic static String getVersionUID()\n{\n return \" \" + getPrimaryVersionUID() + \".\" + getMinorVersionUID() + \".\" + getMinorSubVersionID();\n}\n\npublic static void registerMarioVisualComponent(MarioVisualComponent mc)\n{\n marioVisualComponent = mc;\n}\n\npublic static void registerGameViewer(GameViewer gv)\n{\n GameViewer = gv;\n}\n\npublic static void AdjustMarioVisualComponentFPS()\n{\n if (marioVisualComponent != null)\n marioVisualComponent.adjustFPS();\n}\n\npublic static void gameViewerTick()\n{\n if (GameViewer != null)\n GameViewer.tick();\n}\n\npublic static String getDateTime(Long d)\n{\n final DateFormat dateFormat = (d == null) ? new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss:ms\") :\n new SimpleDateFormat(\"HH:mm:ss:ms\");\n if (d != null)\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n final Date date = (d == null) ? new Date() : new Date(d);\n return dateFormat.format(date);\n}\n\nfinal static private DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd_HH-mm-ss\");\n\npublic static String getTimeStamp()\n{\n return dateFormat.format(new Date());\n}\n\npublic static void changeScale2x()\n{\n if (marioVisualComponent == null)\n return;\n\n isScale2x = !isScale2x;\n marioVisualComponent.width *= isScale2x ? 2 : 0.5;\n marioVisualComponent.height *= isScale2x ? 2 : 0.5;\n marioVisualComponent.changeScale2x();\n}\n}", "public class SimulationOptions extends ParameterContainer\n{\nfinal Point viewLocation = new Point(42, 42);\nprotected Agent agent;\n// protected MarioComponent marioComponent = null;\n\nprotected SimulationOptions()\n{\n super();\n}\n\npublic void setUpOptions(String[] args)\n{\n if (args != null)\n for (int i = 0; i < args.length - 1; i += 2)\n try\n {\n setParameterValue(args[i], args[i + 1]);\n\n if (args[i].equals(\"-lf\") && args[i + 1].equals(\"on\"))\n {\n setBlocksCount(false);\n setCoinsCount(false);\n setTubesCount(false);\n setGapsCount(false);\n setDeadEndsCount(false);\n setCannonsCount(false);\n setEnemies(\"off\");\n }\n }\n catch (ArrayIndexOutOfBoundsException e)\n {\n // Basically we can push the red button to explaud the computer, since this case must happen never.\n System.err.println(\"Error: Wrong number of input parameters\");\n// System.err.println(\"It is a perfect day to kill yourself with the yellow wall\");\n }\n GlobalOptions.isVisualization = isVisualization();\n GlobalOptions.FPS = getFPS() /*GlobalOptions.FPS*/;\n// GlobalOptions.isPauseWorld = isPauseWorld();\n GlobalOptions.isPowerRestoration = isPowerRestoration();\n// GlobalOptions.isTimer = isTimer();\n}\n\npublic boolean isExitProgramWhenFinished()\n{\n return b(getParameterValue(\"-ewf\"));\n}\n\npublic void setExitProgramWhenFinished(boolean exitProgramWhenFinished)\n{\n setParameterValue(\"-ewf\", s(exitProgramWhenFinished));\n}\n\npublic Point getViewLocation()\n{\n viewLocation.x = i(getParameterValue(\"-vlx\"));\n viewLocation.y = i(getParameterValue(\"-vly\"));\n return viewLocation;\n}\n\npublic boolean isViewAlwaysOnTop()\n{\n return b(getParameterValue(\"-vaot\"));\n}\n\npublic void setViewerAlwaysOnTop(boolean vaot)\n{\n setParameterValue(\"-vaot\", s(vaot));\n}\n\npublic void setFPS(int fps)\n{\n setParameterValue(\"-fps\", s(fps));\n GlobalOptions.FPS = getFPS();\n}\n\npublic int getFPS()\n{\n return i(getParameterValue(\"-fps\"));\n}\n\npublic String getAgentFullLoadName()\n{\n return getParameterValue(\"-ag\");\n}\n\npublic String getLevelFileName()\n{\n return getParameterValue(\"-s\");\n}\n\n// Agent\n\npublic Agent getAgent()\n{\n// return a(getParameterValue(\"-ag\")); }\n if (agent == null)\n {\n agent = AgentsPool.loadAgent(getParameterValue(\"-ag\"), isPunj());\n// System.out.println(\"Info: Agent not specified. Default \" + agent.getName() + \" has been used instead\");\n }\n return agent;\n}\n\npublic void setAgent(Agent agent)\n{\n// setParameterValue(\"-ag\", s(agent));\n this.agent = agent;\n}\n\npublic void setAgent(String agentWOXorClassName)\n{\n this.agent = AgentsPool.loadAgent(agentWOXorClassName, isPunj());\n}\n\n// LevelType\n\npublic int getLevelType()\n{\n return i(getParameterValue(\"-lt\"));\n}\n\npublic void setLevelType(int levelType)\n{\n setParameterValue(\"-lt\", s(levelType));\n}\n\n// LevelDifficulty\n\npublic int getLevelDifficulty()\n{\n return i(getParameterValue(\"-ld\"));\n}\n\npublic void setLevelDifficulty(int levelDifficulty)\n{\n setParameterValue(\"-ld\", s(levelDifficulty));\n}\n\n//LevelLength\n\npublic int getLevelLength()\n{\n return i(getParameterValue(\"-ll\"));\n}\n\npublic void setLevelLength(int levelLength)\n{\n setParameterValue(\"-ll\", s(levelLength));\n}\n\n//LevelHeight\n\npublic int getLevelHeight()\n{\n return i(getParameterValue(\"-lh\"));\n}\n\npublic void setLevelHeight(int levelHeight)\n{\n setParameterValue(\"-lh\", s(levelHeight));\n}\n\n//LevelRandSeed\n\npublic int getLevelRandSeed() throws NumberFormatException\n{\n return i(getParameterValue(\"-ls\"));\n}\n\npublic void setLevelRandSeed(int levelRandSeed)\n{\n setParameterValue(\"-ls\", s(levelRandSeed));\n}\n\n//Visualization\n\npublic boolean isVisualization()\n{\n return b(getParameterValue(\"-vis\"));\n}\n\npublic void setVisualization(boolean visualization)\n{\n setParameterValue(\"-vis\", s(visualization));\n}\n\n//isPowerRestoration\n\npublic void setFrozenCreatures(boolean frozenCreatures)\n{\n setParameterValue(\"-fc\", s(frozenCreatures));\n}\n\npublic boolean isFrozenCreatures()\n{\n return b(getParameterValue(\"-fc\"));\n}\n\n\npublic boolean isPowerRestoration()\n{\n return b(getParameterValue(\"-pr\"));\n}\n\npublic void setPowerRestoration(boolean powerRestoration)\n{\n setParameterValue(\"-pr\", s(powerRestoration));\n}\n\n//MarioMode\n\npublic int getMarioMode()\n{\n return i(getParameterValue(\"-mm\"));\n}\n\npublic void setMarioMode(int marioMode)\n{ setParameterValue(\"-mm\", s(marioMode)); }\n\n//ZLevelScene\n\npublic int getZLevelScene()\n{\n return i(getParameterValue(\"-zs\"));\n}\n\npublic void setZLevelScene(int zLevelMap)\n{\n setParameterValue(\"-zs\", s(zLevelMap));\n}\n\n//ZLevelEnemies\n\npublic int getZLevelEnemies()\n{\n return i(getParameterValue(\"-ze\"));\n}\n\npublic void setZLevelEnemies(int zLevelEnemies)\n{\n setParameterValue(\"-ze\", s(zLevelEnemies));\n}\n\n// TimeLimit\n\npublic int getTimeLimit()\n{\n return i(getParameterValue(\"-tl\"));\n}\n\npublic void setTimeLimit(int timeLimit)\n{\n setParameterValue(\"-tl\", s(timeLimit));\n}\n\n// Invulnerability\n\npublic boolean isMarioInvulnerable()\n{\n return b(getParameterValue(\"-i\"));\n}\n\npublic void setMarioInvulnerable(boolean invulnerable)\n{ setParameterValue(\"-i\", s(invulnerable)); }\n\n// Level: dead ends count\n\npublic boolean getDeadEndsCount()\n{\n return b(getParameterValue(\"-lde\"));\n}\n\npublic void setDeadEndsCount(boolean var)\n{\n setParameterValue(\"-lde\", s(var));\n}\n\n// Level: cannons count\n\npublic boolean getCannonsCount()\n{\n return b(getParameterValue(\"-lca\"));\n}\n\npublic void setCannonsCount(boolean var)\n{\n setParameterValue(\"-lca\", s(var));\n}\n\n// Level: HillStraight count\n\npublic boolean getHillStraightCount()\n{\n return b(getParameterValue(\"-lhs\"));\n}\n\npublic void setHillStraightCount(boolean var)\n{\n setParameterValue(\"-lhs\", s(var));\n}\n\n// Level: Tubes count\n\npublic boolean getTubesCount()\n{\n return b(getParameterValue(\"-ltb\"));\n}\n\npublic void setTubesCount(boolean var)\n{\n setParameterValue(\"-ltb\", s(var));\n}\n\n// Level: blocks count\n\npublic boolean getBlocksCount()\n{\n return b(getParameterValue(\"-lb\"));\n}\n\npublic void setBlocksCount(boolean var)\n{\n setParameterValue(\"-lb\", s(var));\n}\n\n// Level: coins count\n\npublic boolean getCoinsCount()\n{\n return b(getParameterValue(\"-lco\"));\n}\n\npublic void setCoinsCount(boolean var)\n{\n setParameterValue(\"-lco\", s(var));\n}\n\n// Level: gaps count\n\npublic boolean getGapsCount()\n{\n return b(getParameterValue(\"-lg\"));\n}\n\npublic void setGapsCount(boolean var)\n{\n setParameterValue(\"-lg\", s(var));\n}\n\n// Level: hidden blocks count\n\npublic boolean getHiddenBlocksCount()\n{\n return b(getParameterValue(\"-lhb\"));\n}\n\npublic void setHiddenBlocksCount(boolean var)\n{\n setParameterValue(\"-lhb\", s(var));\n}\n\n// Level: enemies mask\n\npublic String getEnemies()\n{\n return getParameterValue(\"-le\");\n}\n\npublic void setEnemies(String var)\n{\n setParameterValue(\"-le\", var);\n}\n\n// Level: flat level\n\npublic boolean isFlatLevel()\n{\n return b(getParameterValue(\"-lf\"));\n}\n\npublic void setFlatLevel(boolean var)\n{\n setParameterValue(\"-lf\", s(var));\n}\n\npublic boolean isTrace()\n{\n String s = getParameterValue(\"-trace\");\n boolean f = false;\n\n if (!s.equals(\"off\") && !s.equals(\"\"))\n f = true;\n\n return f;\n}\n\npublic String getTraceFileName()\n{\n String s = getParameterValue(\"-trace\");\n String res = \"\";\n\n if (!s.equals(\"off\") && !s.equals(\"\"))\n {\n if (s.equals(\"on\"))\n res = \"[MarioAI]-MarioTrace.txt\";\n else\n res = s;\n }\n\n return res;\n}\n\npublic String getRecordingFileName()\n{\n return getParameterValue(\"-rec\");\n}\n\npublic void setRecordFile(String var)\n{\n setParameterValue(\"-rec\", var);\n}\n\npublic boolean isScale2X()\n{\n return b(getParameterValue(\"-z\"));\n}\n\npublic void setScale2X(boolean z)\n{\n setParameterValue(\"-z\", s(z));\n}\n\npublic void setGreenMushroomMode(int mode)\n{\n setParameterValue(\"-gmm\", s(mode));\n}\n\npublic int getGreenMushroomMode()\n{\n return i(getParameterValue(\"-gmm\"));\n}\n\npublic boolean isLevelLadder()\n{\n return b(getParameterValue(\"-lla\"));\n}\n\npublic void setLevelLadder(boolean ladder)\n{\n setParameterValue(\"-lla\", s(ladder));\n}\n\npublic void setPunj(boolean punj)\n{\n setParameterValue(\"-punj\", s(punj));\n}\n\npublic boolean isPunj()\n{\n return b(getParameterValue(\"-punj\"));\n}\n}", "public class SRN implements FA<double[], double[]>, Evolvable\n{\n\nprotected double[][] firstConnectionLayer;\nprotected double[][] recurrentConnectionLayer;\nprotected double[][] secondConnectionLayer;\nprotected double[] hiddenNeurons;\nprotected double[] hiddenNeuronsCopy;\nprotected double[] outputs;\nprotected double mutationMagnitude = 0.1;\n\nprivate final Random random = new Random();\n\npublic SRN(int numberOfInputs, int numberOfHidden, int numberOfOutputs)\n{\n firstConnectionLayer = new double[numberOfInputs][numberOfHidden];\n recurrentConnectionLayer = new double[numberOfHidden][numberOfHidden];\n secondConnectionLayer = new double[numberOfHidden][numberOfOutputs];\n hiddenNeurons = new double[numberOfHidden];\n hiddenNeuronsCopy = new double[numberOfHidden];\n outputs = new double[numberOfOutputs];\n mutate();\n}\n\npublic SRN(double[][] firstConnectionLayer, double[][] recurrentConnectionLayer,\n double[][] secondConnectionLayer, int numberOfHidden,\n int numberOfOutputs)\n{\n this.firstConnectionLayer = firstConnectionLayer;\n this.recurrentConnectionLayer = recurrentConnectionLayer;\n this.secondConnectionLayer = secondConnectionLayer;\n hiddenNeurons = new double[numberOfHidden];\n hiddenNeuronsCopy = new double[numberOfHidden];\n outputs = new double[numberOfOutputs];\n}\n\npublic double[] propagate(double[] inputs)\n{\n\n if (inputs.length != firstConnectionLayer.length)\n System.out.println(\"NOTE: only \" + inputs.length + \" inputs out of \" + firstConnectionLayer.length + \" are used in the network\");\n\n System.arraycopy(hiddenNeurons, 0, hiddenNeuronsCopy, 0, hiddenNeurons.length);\n clear(hiddenNeurons);\n clear(outputs);\n propagateOneStep(inputs, hiddenNeurons, firstConnectionLayer);\n propagateOneStep(hiddenNeuronsCopy, hiddenNeurons, recurrentConnectionLayer);\n tanh(hiddenNeurons);\n propagateOneStep(hiddenNeurons, outputs, secondConnectionLayer);\n tanh(outputs);\n return outputs;\n}\n\npublic SRN getNewInstance()\n{\n return new SRN(firstConnectionLayer.length, secondConnectionLayer.length, outputs.length);\n}\n\npublic SRN copy()\n{\n return new SRN(copy(firstConnectionLayer), copy(recurrentConnectionLayer),\n copy(secondConnectionLayer), hiddenNeurons.length, outputs.length);\n}\n\npublic void mutate()\n{\n mutate(firstConnectionLayer);\n mutate(recurrentConnectionLayer);\n mutate(secondConnectionLayer);\n}\n\npublic void reset()\n{\n clear(hiddenNeurons);\n clear(hiddenNeuronsCopy);\n}\n\npublic double[] approximate(double[] doubles)\n{\n return propagate(doubles);\n}\n\nprotected double[][] copy(double[][] original)\n{\n double[][] copy = new double[original.length][original[0].length];\n for (int i = 0; i < original.length; i++)\n {\n System.arraycopy(original[i], 0, copy[i], 0, original[i].length);\n }\n return copy;\n}\n\nprotected void mutate(double[] array)\n{\n for (int i = 0; i < array.length; i++)\n {\n array[i] += random.nextGaussian() * mutationMagnitude;\n }\n}\n\nprotected void mutate(double[][] array)\n{\n for (double[] anArray : array)\n {\n mutate(anArray);\n }\n}\n\nprotected void propagateOneStep(double[] fromLayer, double[] toLayer, double[][] connections)\n{\n for (int from = 0; from < fromLayer.length; from++)\n {\n for (int to = 0; to < toLayer.length; to++)\n {\n toLayer[to] += fromLayer[from] * connections[from][to];\n }\n }\n}\n\nprotected void clear(double[] array)\n{\n for (int i = 0; i < array.length; i++)\n {\n array[i] = 0;\n }\n}\n\nprotected void tanh(double[] array)\n{\n for (int i = 0; i < array.length; i++)\n {\n array[i] = Math.tanh(array[i]);\n }\n}\n\n\npublic String toString()\n{\n return \"RecurrentMLP:\" + firstConnectionLayer.length + \"/\" + secondConnectionLayer.length + \"/\" + outputs.length;\n}\n\npublic void setMutationMagnitude(double mutationMagnitude)\n{\n this.mutationMagnitude = mutationMagnitude;\n}\n\n}", "public final class MarioAIOptions extends SimulationOptions\n{\nprivate static final HashMap<String, MarioAIOptions> CmdLineOptionsMapString = new HashMap<String, MarioAIOptions>();\nprivate String optionsAsString = \"\";\n\nfinal private Point marioInitialPos = new Point();\n\npublic MarioAIOptions(String[] args)\n{\n super();\n this.setArgs(args);\n}\n\n// @Deprecated\n\npublic MarioAIOptions(String args)\n{\n //USE MarioAIOptions.getCmdLineOptionsClassByString(String args) method\n super();\n this.setArgs(args);\n}\n\npublic MarioAIOptions()\n{\n super();\n this.setArgs(\"\");\n}\n\npublic void setArgs(String argString)\n{\n if (!\"\".equals(argString))\n this.setArgs(argString.trim().split(\"\\\\s+\"));\n else\n this.setArgs((String[]) null);\n}\n\npublic String asString()\n{\n return optionsAsString;\n}\n\npublic void setArgs(String[] args)\n{\n// if (args.length > 0 && !args[0].startsWith(\"-\") /*starts with a path to agent then*/)\n// {\n// this.setAgent(args[0]);\n//\n// String[] shiftedargs = new String[args.length - 1];\n// System.arraycopy(args, 1, shiftedargs, 0, args.length - 1);\n// this.setUpOptions(shiftedargs);\n// }\n// else\n if (args != null)\n for (String s : args)\n optionsAsString += s + \" \";\n\n this.setUpOptions(args);\n\n if (isEcho())\n {\n this.printOptions(false);\n }\n GlobalOptions.receptiveFieldWidth = getReceptiveFieldWidth();\n GlobalOptions.receptiveFieldHeight = getReceptiveFieldHeight();\n if (getMarioEgoPosCol() == 9 && GlobalOptions.receptiveFieldWidth != 19)\n GlobalOptions.marioEgoCol = GlobalOptions.receptiveFieldWidth / 2;\n else\n GlobalOptions.marioEgoCol = getMarioEgoPosCol();\n if (getMarioEgoPosRow() == 9 && GlobalOptions.receptiveFieldHeight != 19)\n GlobalOptions.marioEgoRow = GlobalOptions.receptiveFieldHeight / 2;\n else\n GlobalOptions.marioEgoRow = getMarioEgoPosRow();\n\n GlobalOptions.VISUAL_COMPONENT_HEIGHT = getViewHeight();\n GlobalOptions.VISUAL_COMPONENT_WIDTH = getViewWidth();\n// Environment.ObsWidth = GlobalOptions.receptiveFieldWidth/2;\n// Environment.ObsHeight = GlobalOptions.receptiveFieldHeight/2;\n GlobalOptions.isShowReceptiveField = isReceptiveFieldVisualized();\n GlobalOptions.isGameplayStopped = isStopGamePlay();\n}\n\npublic float getMarioGravity()\n{\n // TODO: getMarioGravity, doublecheck if unit test is present and remove if fixed\n return f(getParameterValue(\"-mgr\"));\n}\n\npublic void setMarioGravity(float mgr)\n{\n setParameterValue(\"-mgr\", s(mgr));\n}\n\npublic float getWind()\n{\n return f(getParameterValue(\"-w\"));\n}\n\npublic void setWind(float wind)\n{\n setParameterValue(\"-w\", s(wind));\n}\n\npublic float getIce()\n{\n return f(getParameterValue(\"-ice\"));\n}\n\npublic void setIce(float ice)\n{\n setParameterValue(\"-ice\", s(ice));\n}\n\npublic float getCreaturesGravity()\n{\n // TODO: getCreaturesGravity, same as for mgr\n return f(getParameterValue(\"-cgr\"));\n}\n\npublic int getViewWidth()\n{\n return i(getParameterValue(\"-vw\"));\n}\n\npublic void setViewWidth(int width)\n{\n setParameterValue(\"-vw\", s(width));\n}\n\npublic int getViewHeight()\n{\n return i(getParameterValue(\"-vh\"));\n}\n\npublic void setViewHeight(int height)\n{\n setParameterValue(\"-vh\", s(height));\n}\n\npublic void printOptions(boolean singleLine)\n{\n System.out.println(\"\\n[MarioAI] : Options have been set to:\");\n for (Map.Entry<String, String> el : optionsHashMap.entrySet())\n if (singleLine)\n System.out.print(el.getKey() + \" \" + el.getValue() + \" \");\n else\n System.out.println(el.getKey() + \" \" + el.getValue() + \" \");\n}\n\npublic static MarioAIOptions getOptionsByString(String argString)\n{\n // TODO: verify validity of this method, add unit tests\n if (CmdLineOptionsMapString.get(argString) == null)\n {\n final MarioAIOptions value = new MarioAIOptions(argString.trim().split(\"\\\\s+\"));\n CmdLineOptionsMapString.put(argString, value);\n return value;\n }\n return CmdLineOptionsMapString.get(argString);\n}\n\npublic static MarioAIOptions getDefaultOptions()\n{\n return getOptionsByString(\"\");\n}\n\npublic boolean isToolsConfigurator()\n{\n return b(getParameterValue(\"-tc\"));\n}\n\npublic boolean isGameViewer()\n{\n return b(getParameterValue(\"-gv\"));\n}\n\npublic void setGameViewer(boolean gv)\n{\n setParameterValue(\"-gv\", s(gv));\n}\n\npublic boolean isGameViewerContinuousUpdates()\n{\n return b(getParameterValue(\"-gvc\"));\n}\n\npublic void setGameViewerContinuousUpdates(boolean gvc)\n{\n setParameterValue(\"-gvc\", s(gvc));\n}\n\npublic boolean isEcho()\n{\n return b(getParameterValue(\"-echo\"));\n}\n\npublic void setEcho(boolean echo)\n{\n setParameterValue(\"-echo\", s(echo));\n}\n\npublic boolean isStopGamePlay()\n{\n return b(getParameterValue(\"-stop\"));\n}\n\npublic void setStopGamePlay(boolean stop)\n{\n setParameterValue(\"-stop\", s(stop));\n}\n\npublic float getJumpPower()\n{\n return f(getParameterValue(\"-jp\"));\n}\n\npublic void setJumpPower(float jp)\n{\n setParameterValue(\"-jp\", s(jp));\n}\n\npublic int getReceptiveFieldWidth()\n{\n int ret = i(getParameterValue(\"-rfw\"));\n//\n// if (ret % 2 == 0)\n// {\n// System.err.println(\"\\n[MarioAI WARNING] : Wrong value for receptive field width: \" + ret++ +\n// \" ; receptive field width set to \" + ret);\n// setParameterValue(\"-rfw\", s(ret));\n// }\n return ret;\n}\n\npublic void setReceptiveFieldWidth(int rfw)\n{\n setParameterValue(\"-rfw\", s(rfw));\n}\n\npublic int getReceptiveFieldHeight()\n{\n int ret = i(getParameterValue(\"-rfh\"));\n// if (ret % 2 == 0)\n// {\n// System.err.println(\"\\n[MarioAI WARNING] : Wrong value for receptive field height: \" + ret++ +\n// \" ; receptive field height set to \" + ret);\n// setParameterValue(\"-rfh\", s(ret));\n// }\n return ret;\n}\n\npublic void setReceptiveFieldHeight(int rfh)\n{\n setParameterValue(\"-rfh\", s(rfh));\n}\n\npublic boolean isReceptiveFieldVisualized()\n{\n return b(getParameterValue(\"-srf\"));\n}\n\npublic void setReceptiveFieldVisualized(boolean srf)\n{\n setParameterValue(\"-srf\", s(srf));\n}\n\npublic Point getMarioInitialPos()\n{\n marioInitialPos.x = i(getParameterValue(\"-mix\"));\n marioInitialPos.y = i(getParameterValue(\"-miy\"));\n return marioInitialPos;\n}\n\npublic void reset()\n{\n optionsHashMap.clear();\n}\n\npublic int getMarioEgoPosRow()\n{\n return i(getParameterValue(\"-mer\"));\n}\n\npublic int getMarioEgoPosCol()\n{\n return i(getParameterValue(\"-mec\"));\n}\n\npublic int getExitX()\n{\n return i(getParameterValue(\"-ex\"));\n}\n\npublic int getExitY()\n{\n return i(getParameterValue(\"-ey\"));\n}\n\npublic void setExitX(int x)\n{\n setParameterValue(\"-ex\", s(x));\n}\n\npublic void setExitY(int y)\n{\n setParameterValue(\"-ey\", s(y));\n}\n}" ]
import ch.idsia.benchmark.mario.simulation.SimulationOptions; import ch.idsia.evolution.SRN; import ch.idsia.tools.MarioAIOptions; import ch.idsia.agents.Agent; import ch.idsia.agents.learning.LargeSRNAgent; import ch.idsia.benchmark.mario.engine.GlobalOptions;
/* * Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the Mario AI nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ch.idsia.scenarios.test; /** * Created by IntelliJ IDEA. * User: koutnij * Date: Jul 27, 2009 * Time: 4:34:37 PM */ public class EvaluateJLink { /** * returns {in, rec, out} array. Just to make math and java codes fully independent. */ public static int[] getDimension() { return new int[]{getInputSize() * getInputSize() * 2 + 3, 6, 6}; } /** * returns length of an edge of the input window square */ public static int getInputSize() { return 7; } public double evaluateLargeSRN(double[][] inputs, double[][] recurrent, double[][] output, int level, int seed) { // System.out.println(inputs.length+" "+inputs[0].length); // System.out.println(recurrent.length+" "+recurrent[0].length); // System.out.println(output.length+" "+output[0].length);
SRN srn = new SRN(inputs, recurrent, output, recurrent.length, output[0].length);
3
ajonkisz/TraVis
src/travis/view/project/graph/connection/ConnectionPainter.java
[ "public class UIHelper {\n\n private static final UIHelper INSTANCE = new UIHelper();\n\n public enum MessageType {\n INFORMATION, WARNING, ERROR\n }\n\n public enum Mode {\n ATTACH, PLAYBACK\n }\n\n private Mode mode;\n\n private final JFileChooser fc;\n private volatile File currentDirectory;\n\n private final Vector<Attacher> attachers;\n\n private final MainFrame frame;\n private final TreePanel treePanel;\n private final AttacherPanel attacherPanel;\n private final ConsolePanel consolePanel;\n private final GraphPanel graph;\n private final GraphTooltip tooltip;\n private final GraphLayeredPane graphLayeredPane;\n private final SettingsPane settingsPane;\n private final PlaybackPanel playbackPanel;\n\n private final ExecutorService dispatcher;\n\n private UIHelper() {\n dispatcher = Executors.newFixedThreadPool(2);\n\n fc = new JFileChooser();\n fc.setAcceptAllFileFilterUsed(false);\n\n attachers = new Vector<Attacher>();\n\n frame = new MainFrame();\n treePanel = new TreePanel();\n attacherPanel = new AttacherPanel();\n consolePanel = new ConsolePanel();\n graph = new GraphPanel();\n tooltip = new GraphTooltip();\n graphLayeredPane = new GraphLayeredPane(graph, tooltip);\n settingsPane = new SettingsPane();\n playbackPanel = new PlaybackPanel();\n\n mode = Mode.ATTACH;\n }\n\n public static UIHelper getInstance() {\n return INSTANCE;\n }\n\n public void populateFrame() {\n fc.setCurrentDirectory(new File(System.getProperty(\"user.dir\")));\n currentDirectory = fc.getCurrentDirectory();\n frame.populateFrame();\n changeMode(Mode.ATTACH);\n }\n\n private void changeMode(Mode mode) {\n this.mode = mode;\n if (mode == Mode.ATTACH) {\n frame.setAttachMode();\n } else if (mode == Mode.PLAYBACK) {\n frame.setPlaybackMode();\n }\n }\n\n public Mode getMode() {\n return mode;\n }\n\n public Vector<Attacher> getAttachers() {\n return new Vector<Attacher>(attachers);\n }\n\n public void killAllAttachers() {\n synchronized (attachers) {\n for (Attacher attacher : attachers) {\n attacher.detach();\n }\n attachers.clear();\n }\n repaintAttachersTable();\n }\n\n public void startAttacher(Attacher attacher) {\n getProjectTree().setupScriptGenerator();\n\n try {\n attacher.start();\n } catch (IOException e) {\n displayException(e);\n }\n }\n\n public void addAndStartAttacher(final Attacher attacher) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"attaching\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n attachers.add(attacher);\n getProjectTree().generateScript();\n\n try {\n attacher.start();\n } catch (IOException e) {\n displayException(e);\n }\n repaintAttachersTable();\n\n dialog.setVisible(false);\n }\n });\n }\n\n public void removeAndKillAttacher(Attacher attacher) {\n attacher.detach();\n attachers.remove(attacher);\n repaintAttachersTable();\n }\n\n public ConsolePanel getConsolePanel() {\n return consolePanel;\n }\n\n public File getCurrentDirectory() {\n return currentDirectory;\n }\n\n public void setCurrentDirectory(File currentDirectory) {\n this.currentDirectory = currentDirectory;\n }\n\n public void updatePlaybackMode() {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n playbackPanel.updatePlaybackMode();\n }\n });\n }\n\n public void updatePlaybackSpeed() {\n playbackPanel.updatePlaybackSpeed();\n }\n\n public TreePanel getTreePanel() {\n return treePanel;\n }\n\n public ProjectTree getProjectTree() {\n return treePanel.getTree();\n }\n\n public AttacherPanel getAttacherPanel() {\n return attacherPanel;\n }\n\n public GraphPanel getGraph() {\n return graph;\n }\n\n public GraphTooltip getTooltip() {\n return tooltip;\n }\n\n public GraphLayeredPane getGraphLayeredPane() {\n return graphLayeredPane;\n }\n\n public SettingsPane getSettingsPane() {\n return settingsPane;\n }\n\n public PlaybackPanel getPlaybackPanel() {\n return playbackPanel;\n }\n\n public MainFrame getMainFrame() {\n return frame;\n }\n\n public void openClasspath() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForDirs();\n if (checkClassPath()) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.classpath\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n treePanel.buildTree(fc.getSelectedFile());\n UIGraphicsHelper.getInstance()\n .resetConnectionsAndRepaintTree();\n dialog.setVisible(false);\n }\n });\n }\n }\n\n public void attachClasspath() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForDirs();\n if (checkClassPath()) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.classpath\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n treePanel.attachTree(fc.getSelectedFile());\n UIGraphicsHelper.getInstance()\n .resetConnectionsAndRepaintTree();\n dialog.setVisible(false);\n }\n });\n }\n }\n\n private boolean checkClassPath() {\n if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)\n return false;\n\n changeMode(Mode.ATTACH);\n currentDirectory = fc.getSelectedFile();\n File f = fc.getSelectedFile();\n if (!isClasspathValid(f)) {\n displayMessage(Messages.get(\"file.not.valid\"), MessageType.ERROR);\n return false;\n }\n return true;\n }\n\n private boolean isClasspathValid(File f) {\n return f.isDirectory() && f.canRead();\n }\n\n private void setupFilechooserForDirs() {\n fc.setCurrentDirectory(getCurrentDirectory());\n fc.resetChoosableFileFilters();\n fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n fc.setFileFilter(new FileFilter() {\n @Override\n public String getDescription() {\n return Messages.get(\"directories.only\");\n }\n\n @Override\n public boolean accept(File f) {\n return f.isDirectory();\n }\n });\n }\n\n public void openFile() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForFiles();\n if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.file\"));\n changeMode(Mode.PLAYBACK);\n currentDirectory = fc.getCurrentDirectory();\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n try {\n final FileParser fp = new FileParser(fc.getSelectedFile());\n UIGraphicsHelper.getInstance().resetConnections();\n getProjectTree().setRoot(fp);\n playbackPanel.setFileParser(fp);\n\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n dialog.setVisible(false);\n }\n });\n } catch (IOException e) {\n displayException(e);\n } catch (ClassNotFoundException e) {\n displayException(e);\n }\n }\n });\n }\n\n public JDialog getAndShowProgressBarWindow(String text) {\n JPanel panel = new JPanel(new BorderLayout());\n JLabel label = new JLabel(text);\n label.setHorizontalAlignment(SwingConstants.CENTER);\n JProgressBar progressBar = new JProgressBar();\n progressBar.setIndeterminate(true);\n\n panel.add(label, BorderLayout.CENTER);\n panel.add(progressBar, BorderLayout.PAGE_END);\n\n final JOptionPane optionPane = new JOptionPane(panel,\n JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null,\n new Object[]{}, null);\n final JDialog dialog = optionPane.createDialog(frame,\n Messages.get(\"work.in.progress\"));\n dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n dialog.pack();\n dialog.setResizable(false);\n dialog.setVisible(true);\n }\n });\n\n return dialog;\n }\n\n public void saveFileAs() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForFiles();\n if (fc.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n currentDirectory = fc.getCurrentDirectory();\n File f = fc.getSelectedFile();\n if (!f.getName().matches(\".*\\\\.vis\")) {\n f = new File(f.getAbsolutePath() + \".vis\");\n }\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"saving.file\"));\n final File fFinal = f;\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n getProjectTree().setupScriptGenerator();\n try {\n ScriptHandler.getInstance().saveToFile(fFinal,\n getProjectTree().getCheckedPaths());\n } catch (IOException e) {\n displayException(e);\n }\n dialog.setVisible(false);\n }\n });\n }\n\n public void saveSubtrace() {\n if (mode != Mode.PLAYBACK)\n return;\n\n playbackPanel.pause();\n\n // Ensure subtrace is selected\n PlaybackProgress progress = playbackPanel.getPlaybackProgress();\n double start = progress.getPlaybackStart();\n double end = progress.getPlaybackEnd();\n if (start == 0d && end == 1d) {\n displayMessage(Messages.get(\"no.subtrace\"), MessageType.INFORMATION);\n return;\n }\n\n // Ensure playback attacher\n Playback playback = playbackPanel.getPlayback();\n if (playback == null) {\n displayMessage(Messages.get(\"no.playback\"), MessageType.ERROR);\n return;\n }\n\n setupFilechooserForFiles();\n if (fc.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n currentDirectory = fc.getCurrentDirectory();\n File selectedFile = fc.getSelectedFile();\n final File f = selectedFile.getName().matches(\".*\\\\.vis\") ? selectedFile\n : new File(selectedFile.getAbsolutePath() + \".vis\");\n\n // Ensure saving to a different file\n final File scriptFile = playback.getScript();\n if (f.equals(scriptFile)) {\n displayMessage(Messages.get(\"subtrace.to.trace\"), MessageType.ERROR);\n saveSubtrace();\n return;\n }\n\n final long from = (long) (playback.getTracesStart() + (double) playback\n .getTracesLength() * start);\n final long to = (long) (playback.getTracesStart() + (double) playback\n .getTracesLength() * end);\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"saving.subtrace\"));\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n getProjectTree().generateScript();\n try {\n ScriptHandler.getInstance().saveToFile(f,\n getProjectTree().getCheckedPaths());\n ScriptHandler.copyLines(scriptFile, f, from, to);\n } catch (IOException e) {\n displayException(e);\n }\n dialog.setVisible(false);\n }\n });\n\n }\n\n private void setupFilechooserForFiles() {\n fc.setCurrentDirectory(getCurrentDirectory());\n fc.resetChoosableFileFilters();\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fc.setFileFilter(new FileFilter() {\n @Override\n public String getDescription() {\n return \".vis\";\n }\n\n @Override\n public boolean accept(File f) {\n return f.isDirectory() || f.getName().matches(\".*\\\\.vis\");\n }\n });\n }\n\n /**\n * Asks user, in form of a dialog window, if he wants to disconnect from\n * attached processes if connected to any.\n *\n * @return true if disconnected from attached processes, false otherwise.\n */\n public boolean askToKillAllIfConnected() {\n if (mode == Mode.PLAYBACK) {\n Playback p = playbackPanel.getPlayback();\n if (p != null) {\n p.pause();\n }\n return true;\n }\n if (attachers.isEmpty()) {\n return true;\n }\n if (displayConfirmation(Messages.get(\"disconnect.confirm\"))) {\n killAllAttachers();\n return true;\n }\n return false;\n }\n\n public void repaintAttachersTable() {\n attacherPanel.getAttachersTable().repaintTable();\n }\n\n public void displayMessage(String msg, MessageType type) {\n String title;\n int messageType;\n switch (type) {\n case ERROR:\n title = Messages.get(\"error\");\n messageType = JOptionPane.ERROR_MESSAGE;\n break;\n case INFORMATION:\n title = Messages.get(\"information\");\n messageType = JOptionPane.INFORMATION_MESSAGE;\n break;\n case WARNING:\n title = Messages.get(\"warning\");\n messageType = JOptionPane.WARNING_MESSAGE;\n break;\n default:\n return;\n }\n JOptionPane.showMessageDialog(frame, msg, title, messageType);\n }\n\n public boolean displayConfirmation(String msg) {\n JPanel panel = new JPanel();\n panel.add(new JLabel(msg));\n int status = JOptionPane.showConfirmDialog(frame, panel,\n Messages.get(\"confirm\"), JOptionPane.OK_CANCEL_OPTION,\n JOptionPane.PLAIN_MESSAGE, null);\n return status == JOptionPane.OK_OPTION;\n }\n\n public void displayException(Exception e) {\n killAllAttachers();\n e.printStackTrace();\n\n StringBuilder sb = new StringBuilder(e.toString());\n for (StackTraceElement trace : e.getStackTrace()) {\n sb.append(\"\\n at \");\n sb.append(trace);\n }\n JTextArea textArea = new JTextArea(sb.toString());\n textArea.setEditable(false);\n JScrollPane scrollPane = new JScrollPane(textArea);\n scrollPane.setPreferredSize(new Dimension(500, 250));\n\n JOptionPane.showMessageDialog(frame, scrollPane,\n Messages.get(\"exception\"), JOptionPane.ERROR_MESSAGE);\n }\n\n}", "public class TraceInfo {\n\n private final int methodId;\n private final boolean returnCall;\n private final long callTime;\n private final long threadId;\n\n public TraceInfo(int methodId, boolean returnCall, long callTime,\n long threadId) {\n this.methodId = methodId;\n this.returnCall = returnCall;\n this.callTime = callTime;\n this.threadId = threadId;\n }\n\n public int getMethodId() {\n return methodId;\n }\n\n public boolean isReturnCall() {\n return returnCall;\n }\n\n public long getCallTime() {\n return callTime;\n }\n\n public long getThreadId() {\n return threadId;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(returnCall ? \"<-- \" : \"--> \");\n sb.append(methodId);\n sb.append(' ');\n sb.append(callTime);\n sb.append(' ');\n sb.append(threadId);\n return sb.toString();\n }\n}", "public class Util {\n\n public static final RenderingHints HINTS;\n\n static {\n HINTS = new RenderingHints(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n HINTS.put(RenderingHints.KEY_TEXT_ANTIALIASING,\n RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n }\n\n public static JButton getButtonWithIcon(String name) {\n JButton b = new JButton(IconFactory.createImageIcon(name + \".png\"));\n b.setPressedIcon(IconFactory.createImageIcon(name + \"_pressed.png\"));\n return b;\n }\n\n public static int pow(int num, int power) {\n if (power < 1) {\n return 1;\n }\n return num * pow(num, --power);\n }\n\n public static boolean containsFlag(int flags, int flag) {\n return (flags & flag) == flag;\n }\n\n public static int toggleFlag(int flags, int flag, boolean enabled) {\n if (enabled) {\n flags |= flag;\n } else {\n flags &= ~flag;\n }\n return flags;\n }\n\n public static JSlider createSlider(int min, int max, int init,\n int majorTick, int minorTick) {\n JSlider slider = new JSlider(SwingConstants.HORIZONTAL, min, max, init);\n slider.setMajorTickSpacing(majorTick);\n slider.setMinorTickSpacing(minorTick);\n slider.setPaintLabels(true);\n slider.setPaintTicks(true);\n return slider;\n }\n\n public static JPanel createBorderedPanel(String title,\n Component... components) {\n return createBorderedPanel(title, \"\", components);\n }\n\n public static JPanel createBorderedPanel(String title, String constraints,\n Component... components) {\n JPanel panel = new JPanel(new MigLayout(\"fillx, insets 0, gap 0, \"\n + constraints));\n if (components == null || components.length == 0) {\n return panel;\n }\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createLineBorder(Color.BLACK), title,\n TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION));\n for (Component component : components) {\n panel.add(component, \"grow\");\n }\n return panel;\n }\n\n}", "public class ComponentData implements Comparable<ComponentData> {\n\n private final Settings sets = Settings.getInstance();\n\n private final ProjectTreeNode node;\n private final StructComponent comp;\n private final ComponentData parent;\n private final Set<ComponentData> children;\n private final int totalSelectedMethods;\n\n private ArcRectangle arcRect;\n private double startAngle;\n private double degreesWidth;\n\n // This point is used for inner radial layout\n private ControlPoint controlPoint;\n\n public ComponentData(ProjectTreeNode node, ComponentData parent,\n int totalSelectedMethods) {\n this.node = node;\n this.parent = parent;\n this.totalSelectedMethods = totalSelectedMethods;\n comp = node.getUserObject();\n children = new TreeSet<ComponentData>();\n }\n\n public int getMaximumPackageDepth() {\n int max = 0;\n boolean morePackages = false;\n for (ComponentData child : children) {\n if (child.getComp() instanceof StructPackage) {\n morePackages = true;\n max = Math.max(max, child.getMaximumPackageDepth());\n }\n }\n if (!morePackages)\n return Math.max(max, getDepth());\n return max;\n }\n\n public int getDepth() {\n if (parent == null)\n return 0;\n return 1 + parent.getDepth();\n }\n\n public int getMaxDepth() {\n int max = 1;\n for (ComponentData child : children) {\n max = Math.max(max, child.getMaxDepth() + 1);\n }\n return max;\n }\n\n public boolean addChild(ComponentData child) {\n return children.add(child);\n }\n\n public boolean removeChild(ComponentData child) {\n return children.remove(child);\n }\n\n public Set<ComponentData> getChildren() {\n return children;\n }\n\n public int getTotalSelectedMethods() {\n return totalSelectedMethods;\n }\n\n public ProjectTreeNode getNode() {\n return node;\n }\n\n public StructComponent getComp() {\n return comp;\n }\n\n public ComponentData getFirstVisibleParent() {\n if (parent == null)\n return null;\n return parent.isVisible() ? parent : parent.getFirstVisibleParent();\n }\n\n public ComponentData getParent() {\n return parent;\n }\n\n public ControlPoint getControlPoint() {\n return controlPoint;\n }\n\n public void setControlPoint(ControlPoint controlPoint) {\n this.controlPoint = controlPoint;\n }\n\n /**\n * @return ArcRectangle belonging to this ComponentData or if not visible\n * then return ArcRectangle of a parent.\n */\n public ArcRectangle getArcRect() {\n return isVisible() ? arcRect : (parent == null ? null : parent\n .getArcRect());\n }\n\n public double getCenterAngleForPackage() {\n return arcRect.getCenterAngle();\n }\n\n public double getCenterAngle() {\n if (comp instanceof StructPackage && comp.containsAnyClasses()) {\n return calculateCenterAngleForPackageWithClasses();\n }\n\n return arcRect.getCenterAngle();\n }\n\n private double calculateCenterAngleForPackageWithClasses() {\n double startAngle = 0;\n double endAngle = 0;\n\n boolean first = true;\n for (ComponentData child : children) {\n if (child.comp instanceof StructClass) {\n if (first) {\n startAngle = child.arcRect.getStartAngle();\n first = false;\n }\n endAngle = child.arcRect.getStartAngle()\n + child.arcRect.getDegreesWidth();\n }\n }\n\n double diff = (endAngle - startAngle) / 2;\n return startAngle + diff;\n }\n\n public Point2D getInnerCenterPoint() {\n return arcRect.getInnerCenter();\n }\n\n public void setArcRect(ArcRectangle arcRect) {\n this.arcRect = arcRect;\n startAngle = arcRect.getActualStartAngle();\n degreesWidth = -arcRect.getDegreesWidth();\n }\n\n public double getStartAngle() {\n return startAngle;\n }\n\n public double getDegreesWidth() {\n return degreesWidth;\n }\n\n public boolean isVisible() {\n if (comp instanceof StructPackage) {\n if (getDepth() < sets.getGraphPackageLayersToHide()\n && (sets.isDrawingStruct(Settings.STRUCT_CLASS) || sets\n .isDrawingStruct(Settings.STRUCT_METHOD)))\n return false;\n else\n return sets.isDrawingStruct(Settings.STRUCT_PACKAGE);\n }\n return sets.isDrawingStruct(comp);\n }\n\n public int getPercentHeight() {\n if (comp instanceof StructPackage) {\n return isVisible() ? sets.getPackageHeightPercent() : 0;\n } else if (comp instanceof StructClass) {\n return isVisible() ? sets.getClassHeightPercent() : 0;\n } else {\n return isVisible() ? sets.getMethodHeightPercent() : 0;\n }\n }\n\n public int getGap() {\n if (comp instanceof StructPackage) {\n return isVisible() ? sets.getPackageGap() : 0;\n } else if (comp instanceof StructClass) {\n return isVisible() ? sets.getClassGap() : 0;\n } else {\n return 0;\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof ComponentData) {\n return compareTo((ComponentData) obj) == 0;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return node.hashCode();\n }\n\n @Override\n public int compareTo(ComponentData o) {\n return node.compareTo(o.getNode());\n }\n\n}", "public class ControlPoint extends Point {\n\n private static final long serialVersionUID = 2985196999770983254L;\n\n private ControlPoint parentPoint;\n\n public ControlPoint(int x, int y) {\n super(x, y);\n }\n\n public ControlPoint getParentPoint() {\n return parentPoint;\n }\n\n public void setParentPoint(ControlPoint parentPoint) {\n this.parentPoint = parentPoint;\n }\n\n public int getDepth() {\n if (parentPoint == null)\n return 1;\n return 1 + parentPoint.getDepth();\n }\n\n public Point[] getPathTo(ControlPoint cp) {\n int depth = cp.getDepth();\n Point[] path1 = new Point[depth * 2];\n Point[] path2 = new Point[depth];\n populatePath(path1, this, 0);\n populatePath(path2, cp, 0);\n\n boolean foundCommonAncestor = false;\n int i = 0;\n for (Point p : path1) {\n if (path1[i] == null)\n break;\n if (path2[i] == null) {\n i++;\n break;\n }\n if (p.equals(path2[i])) {\n int length = addInReverse(path1, i + 1, i, path2);\n path1 = Arrays.copyOf(path1, length);\n foundCommonAncestor = true;\n break;\n }\n i++;\n }\n\n if (!foundCommonAncestor) {\n int length = addInReverse(path1, i, path2.length, path2);\n path1 = Arrays.copyOf(path1, length);\n }\n\n return path1;\n }\n\n private int addInReverse(Point[] dest, int offset, int beforeIndex, Point[] source) {\n beforeIndex--;\n for (; beforeIndex >= 0; beforeIndex--, offset++) {\n dest[offset] = source[beforeIndex];\n }\n return offset;\n }\n\n private void populatePath(Point[] path, ControlPoint cp, int i) {\n if (cp == null)\n return;\n path[i] = cp;\n populatePath(path, cp.getParentPoint(), ++i);\n }\n\n}", "public class TreeRepresentation {\n\n private static final int INNER_CIRCLES_NO = 3;\n private static final int CENTER_MIN_RADIUS = 50;\n\n private final Settings sets = Settings.getInstance();\n\n private volatile BufferedImage image;\n\n private final Set<ComponentData> roots;\n private ComponentData[] methods;\n\n private Ellipse2D methodCircle;\n private Ellipse2D latestInnerCircle;\n private Ellipse2D[] innerCircles;\n\n private int maxHeight;\n\n public TreeRepresentation() {\n this.roots = new TreeSet<ComponentData>();\n }\n\n public ComponentData[] getMethods() {\n return methods == null ? new ComponentData[]{} : methods;\n }\n\n private void configureRepresentaion() {\n ProjectTree tree = UIHelper.getInstance().getProjectTree();\n\n if (!tree.isChanged())\n return;\n\n tree.consumeChenge();\n roots.clear();\n\n ProjectTreeNode root = tree.getRootNode();\n if (root == null) {\n return;\n }\n findSelectedRoots(root);\n\n Map<StructMethod, Integer> structMethods = tree.getStructMethods();\n if (structMethods == null) {\n methods = new ComponentData[]{};\n } else {\n methods = new ComponentData[structMethods.size()];\n }\n for (ComponentData cd : roots) {\n populateRoots(cd, structMethods);\n }\n }\n\n private void populateRoots(ComponentData parent,\n Map<StructMethod, Integer> structMethods) {\n ProjectTree tree = UIHelper.getInstance().getProjectTree();\n ProjectTreeNode node = parent.getNode();\n Enumeration<ProjectTreeNode> children = node.children();\n\n while (children.hasMoreElements()) {\n ProjectTreeNode child = children.nextElement();\n if (tree.isSelected(child)\n && child.getUserObject().isPartOfClassPath()) {\n StructComponent comp = child.getUserObject();\n if (!sets.isDrawingClass(comp))\n continue;\n int selectedMethods = tree.getNumberOfSelectedMethods(child);\n if (selectedMethods <= 0)\n continue;\n ComponentData newChild = new ComponentData(child, parent,\n selectedMethods);\n parent.addChild(newChild);\n if (child.getUserObject() instanceof StructMethod\n && sets.isDrawingMethod(child.getUserObject())) {\n int i = structMethods.get(child.getUserObject());\n methods[i] = newChild;\n }\n populateRoots(newChild, structMethods);\n }\n }\n }\n\n private void findSelectedRoots(ProjectTreeNode root) {\n ProjectTree tree = UIHelper.getInstance().getProjectTree();\n Enumeration<ProjectTreeNode> children = root.children();\n\n while (children.hasMoreElements()) {\n ProjectTreeNode child = children.nextElement();\n if (tree.isSelected(child)\n && child.getUserObject().isPartOfClassPath()) {\n roots.add(new ComponentData(child, null, tree\n .getNumberOfSelectedMethods(child)));\n }\n }\n\n if (roots.isEmpty()) {\n children = root.children();\n while (children.hasMoreElements()) {\n ProjectTreeNode child = children.nextElement();\n if (tree.isSelected(child))\n findSelectedRoots(child);\n }\n }\n }\n\n public BufferedImage getImage() {\n return image;\n }\n\n public void createImage(int radius, double rotate) {\n maxHeight = radius;\n latestInnerCircle = null;\n\n BufferedImage newGraph = new BufferedImage(radius * 2 + 2,\n radius * 2 + 2, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = (Graphics2D) newGraph.getGraphics();\n g2.setRenderingHints(Util.HINTS);\n\n configureRepresentaion();\n if (roots.size() == 0) {\n g2.dispose();\n image = newGraph;\n return;\n }\n\n Ellipse2D circle = new Ellipse2D.Double(1, 1, radius * 2, radius * 2);\n setMethodCircle(circle);\n int totalMethods = 0;\n int depth = 0;\n for (ComponentData cd : roots) {\n depth = Math.max(depth, cd.getMaximumPackageDepth());\n totalMethods += cd.getTotalSelectedMethods();\n }\n if (sets.isPackageEnabled() != depth > 0)\n sets.setPackageEnabled(depth > 0);\n\n drawData(circle, rotate, g2, roots, 0, totalMethods);\n\n // Deal with radial layout and control points\n int innerCirclesNo = sets.isMinDepth() ? INNER_CIRCLES_NO - 1\n : INNER_CIRCLES_NO;\n boolean hiddenAll = depth - sets.getGraphPackageLayersToHide() <= 0;\n if (!sets.isDrawingStruct(Settings.STRUCT_PACKAGE) || hiddenAll)\n innerCirclesNo -= 1;\n createInnerCircles(innerCirclesNo);\n createInnerLayout(innerCirclesNo);\n\n boolean drawInnerLayout = sets.isDrawingInnerLayout();\n if (drawInnerLayout) {\n g2.setPaint(Color.YELLOW);\n for (Ellipse2D c : innerCircles) {\n g2.draw(c);\n }\n g2.setPaint(Color.BLUE);\n drawInnerLayout(g2);\n boolean drawInnerStruct = false;\n if (drawInnerStruct) {\n for (ComponentData cd : roots) {\n drawStructInnerLayout(cd, g2);\n }\n }\n }\n\n g2.dispose();\n image = newGraph;\n }\n\n private void createInnerCircles(int innerCirclesNo) {\n innerCircles = new Ellipse2D[innerCirclesNo];\n double innerRadius = latestInnerCircle.getWidth() / 2;\n\n for (int i = 1; i <= innerCircles.length; i++) {\n double newRadius = innerRadius\n * ((double) i / (innerCircles.length + 1));\n double diff = innerRadius - newRadius;\n innerCircles[i - 1] = new Ellipse2D.Double(latestInnerCircle.getX()\n + diff, latestInnerCircle.getY() + diff, newRadius * 2,\n newRadius * 2);\n }\n }\n\n private void createInnerLayout(int innerCirclesNo) {\n for (ComponentData cd : methods) {\n // This one could be skipped as the method wasn't selected.\n if (cd == null) {\n continue;\n }\n\n ControlPoint cpRoot = new ControlPoint((int) cd.getArcRect()\n .getInnerCenterX(), (int) cd.getArcRect().getInnerCenterY());\n cd.setControlPoint(cpRoot);\n\n Point2D p;\n if (cd.getFirstVisibleParent() == null) {\n p = ArcRectangle.calculatePointOnCircle(\n innerCircles[innerCirclesNo - 1], cd.getCenterAngle());\n } else {\n if (cd.getFirstVisibleParent().getComp() instanceof StructPackage\n && !sets.isDrawingStruct(Settings.STRUCT_METHOD)) {\n ComponentData parent = cd.getFirstVisibleParent();\n Point2D p2 = ArcRectangle.calculatePointOnCircle(\n cd.getFirstVisibleParent().getArcRect()\n .getInnerArc(), parent.getCenterAngle());\n cpRoot = new ControlPoint((int) p2.getX(), (int) p2.getY());\n cd.setControlPoint(cpRoot);\n }\n p = ArcRectangle.calculatePointOnCircle(\n innerCircles[innerCirclesNo - 1], cd\n .getFirstVisibleParent().getCenterAngle());\n }\n\n ControlPoint cp = new ControlPoint((int) p.getX(), (int) p.getY());\n cpRoot.setParentPoint(cp);\n\n createRemainingLevelsOfInnerLayout(innerCirclesNo - 1,\n cd.getParent(), cp);\n }\n }\n\n private void createRemainingLevelsOfInnerLayout(int depth,\n ComponentData cd, ControlPoint cp) {\n if (depth < 1)\n return;\n\n boolean cannotPassOnControl = cd.getParent() == null\n || !cd.getParent().isVisible()\n || cd.getComp() instanceof StructPackage;\n\n Point2D p;\n if (cannotPassOnControl) {\n p = ArcRectangle.calculatePointOnCircle(innerCircles[depth - 1],\n cd.getCenterAngle());\n } else {\n p = ArcRectangle.calculatePointOnCircle(innerCircles[depth - 1], cd\n .getParent().getCenterAngle());\n }\n ControlPoint cpChild = new ControlPoint((int) p.getX(), (int) p.getY());\n cp.setParentPoint(cpChild);\n\n if (cannotPassOnControl) {\n createRemainingLevelsOfInnerLayout(depth - 1, cd, cpChild);\n } else {\n createRemainingLevelsOfInnerLayout(depth - 1, cd.getParent(),\n cpChild);\n }\n }\n\n private void drawInnerLayout(Graphics2D g2) {\n for (ComponentData cd : methods) {\n // This one could be skipped as the method wasn't selected.\n if (cd == null)\n continue;\n ControlPoint p = cd.getControlPoint();\n drawPoint(p, g2);\n drawControlPoint(p, g2);\n }\n }\n\n private void drawControlPoint(ControlPoint p, Graphics2D g2) {\n if (p.getParentPoint() == null)\n return;\n\n g2.setPaint(Color.BLUE);\n g2.drawLine((int) p.getParentPoint().getX(), (int) p.getParentPoint()\n .getY(), (int) p.getX(), (int) p.getY());\n drawPoint(p.getParentPoint(), g2);\n drawControlPoint(p.getParentPoint(), g2);\n }\n\n private void drawPoint(ControlPoint p, Graphics2D g2) {\n g2.setPaint(Color.MAGENTA);\n g2.fillRect((int) p.getX() - 2, (int) p.getY() - 2, 4, 4);\n }\n\n private void drawStructInnerLayout(ComponentData parent, Graphics2D g2) {\n Point2D center = parent.getInnerCenterPoint();\n int x1 = (int) center.getX();\n int y1 = (int) center.getY();\n for (ComponentData child : parent.getChildren()) {\n center = parent.getInnerCenterPoint();\n int x2 = (int) center.getX();\n int y2 = (int) center.getY();\n g2.setPaint(Color.BLUE);\n g2.drawLine(x1, y1, x2, y2);\n drawStructInnerLayout(child, g2);\n }\n }\n\n private void drawData(Ellipse2D circle, double rotate, Graphics2D g2,\n Set<ComponentData> children, double startAngle, int totalMethods) {\n double radius = circle.getWidth() / 2;\n int i = 0;\n for (ComponentData cd : children) {\n i++;\n double gapSizeAngle = ArcRectangle.calculateAngle(cd.getGap(),\n radius);\n double maxAngle = cd.getParent() == null ? 360d : cd.getParent()\n .getDegreesWidth();\n double degreeWidth = (maxAngle * cd.getTotalSelectedMethods())\n / totalMethods - gapSizeAngle;\n // If a package and not drawing a first layer use up the available\n // space to not leave a gap.\n if (i == children.size() && cd.getComp() instanceof StructPackage\n && cd.getParent() != null && cd.getParent().isVisible())\n degreeWidth += gapSizeAngle;\n\n double height = determineHeight(cd, radius);\n\n String name = getUndotedName(cd);\n double rotateFix = cd.getParent() != null ? rotate : 0;\n LabelledArcRectangle arcRect = new LabelledArcRectangle(circle,\n rotate + startAngle - rotateFix, degreeWidth < 0.1 ? 0.1\n : degreeWidth, height, name);\n\n arcRect.setFillColor(sets.getColors().getColorForComp(cd.getComp()));\n cd.setArcRect(arcRect);\n if (cd.isVisible())\n arcRect.draw(g2);\n\n startAngle += degreeWidth + gapSizeAngle;\n\n calculateDifferenceAndDrawChildren(height, cd, radius, circle,\n rotate, g2);\n }\n }\n\n private void calculateDifferenceAndDrawChildren(double height,\n ComponentData cd, double radius, Ellipse2D circle, double rotate,\n Graphics2D g2) {\n double diff = height + sets.getLayerGap();\n // If element is not visible do not add layer gap to maintain the\n // level how classes are drawn.\n if (!cd.isVisible())\n diff -= sets.getLayerGap();\n diff = getMaxRadiusForLength(radius, diff);\n double newRadius = radius - diff;\n Ellipse2D newCircle = new Ellipse2D.Double(circle.getX() + diff,\n circle.getY() + diff, newRadius * 2, newRadius * 2);\n\n if (latestInnerCircle == null\n || latestInnerCircle.getWidth() > newCircle.getWidth())\n latestInnerCircle = newCircle;\n\n drawData(newCircle, rotate, g2, cd.getChildren(), cd.getStartAngle(),\n cd.getTotalSelectedMethods());\n }\n\n private double determineHeight(ComponentData cd, double radius) {\n double height;\n if (cd.getComp() instanceof StructClass && cd.isVisible()) {\n height = radius - methodCircle.getWidth() / 2;\n } else if (cd.getComp() instanceof StructMethod && cd.isVisible()\n && !cd.getParent().isVisible()\n && sets.isDrawingStruct(Settings.STRUCT_PACKAGE)) {\n height = radius - methodCircle.getWidth() / 2;\n height += getHeightPercent(cd.getPercentHeight());\n } else {\n height = getHeightPercent(cd.getPercentHeight());\n }\n height = getMaxRadiusForLength(radius, height);\n return height;\n }\n\n private void setMethodCircle(Ellipse2D circle) {\n double diff = 0;\n\n if (sets.isDrawingStruct(Settings.STRUCT_PACKAGE)) {\n int depth = 0;\n for (ComponentData cd : roots) {\n depth = Math.max(depth, cd.getMaximumPackageDepth());\n }\n int maxPackageDepth = depth;\n if (depth > 0)\n depth++;\n if (sets.isDrawingStruct(Settings.STRUCT_CLASS)\n || sets.isDrawingStruct(Settings.STRUCT_METHOD)) {\n int min = Math.min(sets.getGraphPackageLayersToHide(),\n maxPackageDepth + 1);\n depth -= min;\n }\n // Packages and Layers offset\n diff = depth\n * (getHeightPercent(sets.getPackageHeightPercent()) + sets\n .getLayerGap());\n }\n\n // Class offset\n if (sets.isDrawingStruct(Settings.STRUCT_CLASS)) {\n diff += getHeightPercent(sets.getClassHeightPercent());\n }\n\n double r = circle.getWidth() / 2 - diff;\n methodCircle = new Ellipse2D.Double(circle.getX() + diff, circle.getY()\n + diff, r * 2, r * 2);\n }\n\n public double getHeightPercent(int percent) {\n return maxHeight * 0.01 * percent;\n }\n\n private double getMaxRadiusForLength(double radius, double length) {\n return radius - CENTER_MIN_RADIUS > length ? length : radius\n - CENTER_MIN_RADIUS;\n }\n\n private String getUndotedName(ComponentData data) {\n String name = data.getComp().getName();\n int dotIndex = name.lastIndexOf('.');\n name = dotIndex == -1 ? name : name.substring(dotIndex + 1);\n return name;\n }\n\n public ComponentData getElementForCoord(Point p) {\n return getElementForCoord(p, roots);\n }\n\n private ComponentData getElementForCoord(Point p,\n Set<ComponentData> children) {\n for (ComponentData cd : children) {\n if (cd.getArcRect() != null && cd.isVisible()\n && cd.getArcRect().contains(p))\n return cd;\n }\n for (ComponentData cd : children) {\n ComponentData c = getElementForCoord(p, cd.getChildren());\n if (c != null)\n return c;\n }\n return null;\n }\n\n}", "public class Settings extends Observable {\n\n private static final Settings INSTANCE = new Settings();\n\n public enum Type {\n GRAPH, GRAPH_CONNECTION, PLAYBACK_SPEED, PLAYBACK_MODE\n }\n\n public static final int STRUCT_PACKAGE = 1;\n public static final int STRUCT_CLASS = 1 << 1;\n public static final int STRUCT_METHOD = 1 << 2;\n public static final int STRUCT_ORDINARY_CLASS = 1 << 3;\n public static final int STRUCT_ABSTRACT_CLASS = 1 << 4;\n public static final int STRUCT_INTERFACE = 1 << 5;\n public static final int STRUCT_ENUM = 1 << 6;\n public static final int STRUCT_PUBLIC_METHOD = 1 << 7;\n public static final int STRUCT_PRIVATE_METHOD = 1 << 8;\n public static final int STRUCT_PROTECTED_METHOD = 1 << 9;\n public static final int STRUCT_DEFAULT_METHOD = 1 << 10;\n private int structsToDraw;\n\n private int graphRotate;\n private int graphPackageLayersToHide;\n private boolean packageEnabled;\n\n private int packageGap;\n private int classGap;\n private int layerGap;\n\n private int packageHeightPercent;\n private int classHeightPercent;\n private int methodHeightPercent;\n\n private double curveBundlingStrength;\n\n private int cachedTracesNo;\n private int maxCurvesNo;\n private int curvesPerSec;\n\n private boolean minDepth;\n private boolean drawingInnerLayout;\n\n private final ModifiableColor colors;\n\n private int executionPointSize;\n\n private boolean drawingUniqueTraces;\n\n private Settings() {\n structsToDraw = STRUCT_PACKAGE | STRUCT_CLASS | STRUCT_METHOD\n | STRUCT_ORDINARY_CLASS | STRUCT_ABSTRACT_CLASS\n | STRUCT_INTERFACE | STRUCT_ENUM | STRUCT_PUBLIC_METHOD\n | STRUCT_PRIVATE_METHOD | STRUCT_PROTECTED_METHOD\n | STRUCT_DEFAULT_METHOD;\n\n graphRotate = 0;\n graphPackageLayersToHide = 0;\n packageEnabled = true;\n\n packageGap = 6;\n classGap = 3;\n layerGap = 5;\n\n packageHeightPercent = 5;\n classHeightPercent = 10;\n methodHeightPercent = 15;\n\n curveBundlingStrength = 0.75;\n\n cachedTracesNo = 50000;\n maxCurvesNo = 100;\n curvesPerSec = 1;\n\n minDepth = false;\n drawingInnerLayout = false;\n\n colors = new ModifiableColor();\n\n executionPointSize = 3;\n\n drawingUniqueTraces = true;\n }\n\n public int getExecutionPointSize() {\n return executionPointSize;\n }\n\n public void setExecutionPointSize(int executionPointSize) {\n this.executionPointSize = executionPointSize;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public ModifiableColor getColors() {\n return colors;\n }\n\n public void setColors(StructColor colors) {\n this.colors.setColors(colors);\n setChanged(Type.GRAPH);\n }\n\n public boolean isDrawingClass(StructComponent comp) {\n if (!(comp instanceof StructClass)) return true;\n\n if (comp.isOrdinaryClass()\n && isDrawingStruct(STRUCT_ORDINARY_CLASS)) {\n return true;\n }\n else if (comp.isInterface() && isDrawingStruct(STRUCT_INTERFACE)) {\n return true;\n }\n // This extra check must be here as according to ASM and interface\n // is also an abstract class.\n else if (comp.isInterface() && !isDrawingStruct(STRUCT_INTERFACE)) {\n return false;\n }\n else if (comp.isAbstract() && isDrawingStruct(STRUCT_ABSTRACT_CLASS)) {\n return true;\n }\n else return comp.isEnum() && isDrawingStruct(STRUCT_ENUM);\n }\n\n public boolean isDrawingMethod(StructComponent comp) {\n if (!(comp instanceof StructMethod)) return true;\n\n if (comp.getVisibility() == Visibility.PUBLIC\n && isDrawingStruct(STRUCT_PUBLIC_METHOD)) {\n return true;\n }\n else if (comp.getVisibility() == Visibility.PRIVATE\n && isDrawingStruct(STRUCT_PRIVATE_METHOD)) {\n return true;\n }\n else if (comp.getVisibility() == Visibility.PROTECTED\n && isDrawingStruct(STRUCT_PROTECTED_METHOD)) {\n return true;\n }\n else return comp.getVisibility() == Visibility.DEFAULT\n && isDrawingStruct(STRUCT_DEFAULT_METHOD);\n }\n\n public boolean isDrawingStruct(StructComponent comp) {\n if (comp instanceof StructPackage) {\n return isDrawingStruct(STRUCT_PACKAGE);\n } else if (comp instanceof StructClass) {\n if (!isDrawingStruct(STRUCT_CLASS)) {\n return false;\n }\n if (comp.isOrdinaryClass()\n && isDrawingStruct(STRUCT_ORDINARY_CLASS)) {\n return true;\n }\n if (comp.isAbstract() && isDrawingStruct(STRUCT_ABSTRACT_CLASS)) {\n return true;\n }\n if (comp.isInterface() && isDrawingStruct(STRUCT_INTERFACE)) {\n return true;\n }\n return comp.isEnum() && isDrawingStruct(STRUCT_ENUM);\n } else if (comp instanceof StructMethod) {\n if (!isDrawingStruct(STRUCT_METHOD)) {\n return false;\n }\n if (comp.getVisibility() == Visibility.PUBLIC\n && isDrawingStruct(STRUCT_PUBLIC_METHOD)) {\n return true;\n }\n if (comp.getVisibility() == Visibility.PRIVATE\n && isDrawingStruct(STRUCT_PRIVATE_METHOD)) {\n return true;\n }\n if (comp.getVisibility() == Visibility.PROTECTED\n && isDrawingStruct(STRUCT_PROTECTED_METHOD)) {\n return true;\n }\n return comp.getVisibility() == Visibility.DEFAULT\n && isDrawingStruct(STRUCT_DEFAULT_METHOD);\n } else {\n return true;\n }\n }\n\n public boolean isDrawingStruct(int struct) {\n return Util.containsFlag(structsToDraw, struct);\n }\n\n public boolean isMinDepth() {\n return minDepth;\n }\n\n public void setMinDepth(boolean minDepth) {\n this.minDepth = minDepth;\n setChanged(Type.GRAPH);\n }\n\n public boolean isDrawingInnerLayout() {\n return drawingInnerLayout;\n }\n\n public void setDrawingInnerLayout(boolean drawInnerLayout) {\n this.drawingInnerLayout = drawInnerLayout;\n setChanged(Type.GRAPH);\n }\n\n public int getMaxCurvesNo() {\n return maxCurvesNo;\n }\n\n public void setMaxCurvesNo(int maxCurvesNo) {\n if (maxCurvesNo < 1)\n maxCurvesNo = 1;\n this.maxCurvesNo = maxCurvesNo;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public boolean isDrawingUniqueTraces() {\n return drawingUniqueTraces;\n }\n\n public void setDrawingUniqueTraces(boolean drawingUniqueTraces) {\n this.drawingUniqueTraces = drawingUniqueTraces;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public int getCurvesPerSec() {\n return curvesPerSec;\n }\n\n public void setCurvesPerSec(int curvesPerSec) {\n if (curvesPerSec < 1)\n curvesPerSec = 1;\n this.curvesPerSec = curvesPerSec;\n setChanged(Type.PLAYBACK_SPEED);\n }\n\n public int getCachedTracesNo() {\n return cachedTracesNo;\n }\n\n public void setCachedTracesNo(int cachedTracesNo) {\n this.cachedTracesNo = cachedTracesNo;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public double getCurveBundlingStrength() {\n return curveBundlingStrength;\n }\n\n public void setCurveBundlingStrength(double curveBundlingStrength) {\n if (curveBundlingStrength < 0 || curveBundlingStrength > 1)\n throw new IllegalArgumentException(\n Messages.get(\"bundling.strength.exception\"));\n this.curveBundlingStrength = curveBundlingStrength;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public static Settings getInstance() {\n return INSTANCE;\n }\n\n public void setChanged(Type type) {\n setChanged();\n notifyObservers(type);\n }\n\n public void drawStruct(int struct, boolean enabled) {\n int oldStruct = structsToDraw;\n structsToDraw = Util.toggleFlag(structsToDraw, struct, enabled);\n if (oldStruct != structsToDraw) {\n UIHelper.getInstance().getProjectTree().setChanged(true);\n setChanged(Type.GRAPH);\n setChanged(Type.PLAYBACK_MODE);\n }\n }\n\n public int getGraphRotate() {\n return graphRotate;\n }\n\n public void setGraphRotate(int graphRotate) {\n this.graphRotate = graphRotate;\n setChanged(Type.GRAPH);\n }\n\n public int getGraphPackageLayersToHide() {\n return graphPackageLayersToHide;\n }\n\n public void setGraphPackageLayersToHide(int graphLayersToHide) {\n this.graphPackageLayersToHide = graphLayersToHide;\n setChanged(Type.GRAPH);\n }\n\n public boolean isPackageEnabled() {\n return packageEnabled;\n }\n\n public void setPackageEnabled(boolean packageEnabled) {\n this.packageEnabled = packageEnabled;\n setChanged(Type.GRAPH);\n }\n\n public int getPackageGap() {\n return packageGap;\n }\n\n public void setPackageGap(int packageGap) {\n this.packageGap = packageGap;\n setChanged(Type.GRAPH);\n }\n\n public int getClassGap() {\n return classGap;\n }\n\n public void setClassGap(int classGap) {\n this.classGap = classGap;\n setChanged(Type.GRAPH);\n }\n\n public int getLayerGap() {\n return layerGap;\n }\n\n public void setLayerGap(int layerGap) {\n this.layerGap = layerGap;\n setChanged(Type.GRAPH);\n }\n\n public int getPackageHeightPercent() {\n return packageHeightPercent;\n }\n\n public void setPackageHeightPercent(int packageHeightPercent) {\n this.packageHeightPercent = packageHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n public int getClassHeightPercent() {\n return classHeightPercent;\n }\n\n public void setClassHeightPercent(int classHeightPercent) {\n this.classHeightPercent = classHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n public int getMethodHeightPercent() {\n return methodHeightPercent;\n }\n\n public void setMethodHeightPercent(int methodHeightPercent) {\n this.methodHeightPercent = methodHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n}" ]
import travis.controller.UIHelper; import travis.model.script.TraceInfo; import travis.view.Util; import travis.view.project.graph.ComponentData; import travis.view.project.graph.ControlPoint; import travis.view.project.graph.TreeRepresentation; import travis.view.settings.Settings; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.LinkedBlockingDeque;
/* * ConnectionPainter.java * * Copyright (C) 2011-2012, Artur Jonkisz, <[email protected]> * * This file is part of TraVis. * See https://github.com/ajonkisz/TraVis for more info. * * TraVis is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TraVis is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with TraVis. If not, see <http://www.gnu.org/licenses/>. */ package travis.view.project.graph.connection; public class ConnectionPainter { private static final float MIN_ALPHA = 0.1f; private static final float MAX_ALPHA = 0.6f; private final TreeRepresentation treeRep; private final LinkedBlockingDeque<TraceInfo> traces; private Collection<GraphBspline> oldSplines; private volatile ExecutionPoint execPoint; private volatile BufferedImage image; private volatile boolean needRepaint; public ConnectionPainter(TreeRepresentation treeRep) { this.treeRep = treeRep; traces = new LinkedBlockingDeque<TraceInfo>(); oldSplines = new LinkedHashSet<GraphBspline>(); needRepaint = true; } public ExecutionPoint getExecutionPoint() { return execPoint; } public void reset() { traces.clear(); oldSplines.clear(); needRepaint = true; } public void setNeedRepaint(boolean needRepaint) { this.needRepaint = needRepaint; } public Collection<GraphBspline> getSplines() { return oldSplines; } public void lineTo(TraceInfo trace) { needRepaint = true; traces.addFirst(trace); while (traces.size() > Settings.getInstance().getCachedTracesNo()) { traces.removeLast(); } } public void createConnections(ControlPoint cpStart, TraceInfo previousTrace, Iterator<TraceInfo> it, ConnectionData data, boolean isFirst) { for (; it.hasNext(); ) { TraceInfo trace = it.next();
ComponentData cd = treeRep.getMethods()[trace.getMethodId()];
3
6thsolution/EasyMVP
easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/BaseDecorator.java
[ "public class DelegateClassGenerator extends ClassGenerator {\n private final ClassName viewClass;\n private ClassName presenterClass;\n private ViewType viewType;\n private int resourceID = -1;\n private String presenterFieldNameInView = \"\";\n private String presenterViewQualifiedName;\n private boolean injectablePresenterInView = false;\n private ClassName presenterTypeInView;\n private BaseDecorator decorator;\n\n private String presenterId = \"\";\n\n public String getPresenterId() {\n return presenterId;\n }\n\n public DelegateClassGenerator(String packageName, String className, ClassName viewClass) {\n super(packageName, className);\n this.viewClass = viewClass;\n }\n\n public ClassName getViewClass() {\n return viewClass;\n }\n\n public String getPresenterViewQualifiedName() {\n return presenterViewQualifiedName;\n }\n\n public void setPresenterViewQualifiedName(String presenterViewQualifiedName) {\n this.presenterViewQualifiedName = presenterViewQualifiedName;\n }\n\n public void setViewType(ViewType viewType) {\n this.viewType = viewType;\n switch (viewType) {\n case ACTIVITY:\n decorator = new ActivityDecorator(this);\n break;\n case SUPPORT_ACTIVITY:\n decorator = new SupportActivityDecorator(this);\n break;\n case FRAGMENT:\n decorator = new FragmentDecorator(this);\n break;\n case SUPPORT_FRAGMENT:\n decorator = new SupportFragmentDecorator(this);\n break;\n case CUSTOM_VIEW:\n decorator = new CustomViewDecorator(this);\n break;\n case CONDUCTOR_CONTROLLER:\n decorator = new ConductorControllerDecorator(this);\n break;\n }\n }\n\n public void setResourceID(int resourceID) {\n this.resourceID = resourceID;\n }\n\n public void setPresenter(ClassName presenter) {\n this.presenterClass = presenter;\n }\n\n public void setViewPresenterField(String fieldName) {\n presenterFieldNameInView = fieldName;\n }\n\n @Override\n public JavaFile build() {\n TypeSpec.Builder result =\n TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(\n ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,\n getPresenterFactoryTypeName()));\n decorator.build(result);\n return JavaFile.builder(getPackageName(), result.build())\n .addFileComment(\"Generated class from EasyMVP. Do not modify!\").build();\n }\n\n\n public void injectablePresenterInView(boolean injectable) {\n this.injectablePresenterInView = injectable;\n }\n\n private TypeName getPresenterFactoryTypeName() {\n return ParameterizedTypeName.get(PROVIDER, presenterClass);\n }\n\n public ClassName getPresenterClass() {\n return presenterClass;\n }\n\n public boolean isInjectablePresenterInView() {\n return injectablePresenterInView;\n }\n\n public ClassName getPresenterTypeInView() {\n return presenterTypeInView;\n }\n\n public void setPresenterTypeInView(String presenterTypeInView) {\n this.presenterTypeInView = ClassName.bestGuess(presenterTypeInView);\n }\n\n public String getPresenterFieldNameInView() {\n return presenterFieldNameInView;\n }\n\n public int getResourceID() {\n return resourceID;\n }\n\n public void setPresenterId(String presenterId) {\n this.presenterId = presenterId;\n }\n}", "public static final ClassName BUNDLE = ClassName.get(\"android.os\", \"Bundle\");", "public static final ClassName CONTEXT = ClassName.get(\"android.content\", \"Context\");", "public static final ClassName PROVIDER = ClassName.get(\"javax.inject\", \"Provider\");", "public static final ClassName WEAK_REFERENCE = ClassName.get(\"java.lang.ref\", \"WeakReference\");" ]
import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import easymvp.compiler.generator.DelegateClassGenerator; import java.util.concurrent.atomic.AtomicInteger; import javax.lang.model.element.Modifier; import static easymvp.compiler.util.ClassNames.BUNDLE; import static easymvp.compiler.util.ClassNames.CONTEXT; import static easymvp.compiler.util.ClassNames.PROVIDER; import static easymvp.compiler.util.ClassNames.WEAK_REFERENCE;
package easymvp.compiler.generator.decorator; /** * @author Saeed Masoumi ([email protected]) */ public abstract class BaseDecorator { protected static final String FIELD_PRESENTER = "presenter"; protected static final String METHOD_ON_LOADER_RESET = "onLoaderReset"; private static final String METHOD_INITIALIZE = "initialize"; private static final String METHOD_ATTACH_VIEW = "attachView"; private static final String METHOD_DETACH_VIEW = "detachView"; private static final String METHOD_DESTROY = "destroy"; private static final String METHOD_GET_LOADER_MANAGER = "getLoaderManager"; private static final String CLASS_PRESENTER_FACTORY = "PresenterFactory"; private static final String CLASS_PRESENTER_LOADER_CALLBACKS = "PresenterLoaderCallbacks"; private static final String METHOD_ON_CREATE_LOADER = "onCreateLoader"; private static final String METHOD_ON_LOAD_FINISHED = "onLoadFinished"; private static final String FIELD_PRESENTER_DELIVERED = "presenterDelivered"; private static final AtomicInteger LOADER_ID = new AtomicInteger(500);
protected DelegateClassGenerator delegateClassGenerator;
0
aleven/jpec-server
src/test/java/TestRegolaPec.java
[ "public class RegolaPecBL {\n\n\tprotected static final Logger logger = LoggerFactory.getLogger(RegolaPecBL.class);\n\n\tpublic static synchronized List<RegolaPec> regole(EntityManagerFactory emf, RegolaPecEventoEnum evento) throws Exception {\n\t\tRegolaPecFilter filtro = new RegolaPecFilter();\n\t\tfiltro.setEvento(evento);\n\n\t\tList<RegolaPec> res = JpaController.callFind(emf, RegolaPec.class, filtro);\n\n//\t\tif (res == null || res.size() == 0) {\n//\t\t\tlogger.warn(\"nessuna regola configurata per evento {}\", evento);\n//\t\t}\n\n\t\treturn res;\n\t}\n\n\tpublic static synchronized AzioneEsito applicaRegole(EntityManagerFactory emf, RegolaPecEventoEnum evento, AzioneContext contesto) throws Exception {\n\t\tList<RegolaPec> regoleDaApplicare = regole(emf, evento);\n\t\tAzioneEsito tutteLeRegoleVerificate = AzioneEsito.errore(\"\", null);\n\t\tif (regoleDaApplicare != null && regoleDaApplicare.size() > 0) {\n\t\t\t// tutteLeRegoleVerificate = applicaRegole(emf, regoleDaApplicare, email, messaggioPec, mailboxName);\n\t\t\ttutteLeRegoleVerificate = applicaRegole(emf, regoleDaApplicare, contesto);\n\t\t} else {\n\t\t\tlogger.warn(\"nessuna regola configurata per evento {}\", evento);\n\t\t\ttutteLeRegoleVerificate = AzioneEsito.ok(\"\", \"\");\n\t\t}\n\t\treturn tutteLeRegoleVerificate;\n\t}\n\n\t// Message email, MessaggioPec messaggioPec, String mailboxName\n\tpublic static synchronized AzioneEsito applicaRegole(EntityManagerFactory emf, List<RegolaPec> regoleDaApplicare, AzioneContext contesto) throws Exception {\n\t\t// default true\n\t\tAzioneEsito res = AzioneEsito.errore(\"\", null);\n\t\t// boolean tutteLeRegoleVerificate = true;\n\t\t\n\t\tif (regoleDaApplicare != null && regoleDaApplicare.size() > 0) {\n\t\t\t\t\t\t\t\t\t\n\t\t\tfor (RegolaPec regola : regoleDaApplicare) {\n\t\t\t\t\n\t\t\t\tMap<String, Object> regolaContext = new HashMap<String, Object>();\n\t\t\t\tString classe = regola.getClasse();\n\t\t\t\tAzioneGenerica istanzaAzione = null;\n\t\t\t\tif (StringUtils.isNotBlank(classe)) {\n\t\t\t\t\t// istanzaAzione = AzioneBL.creaIstanzaAzione(emf, email, messaggioPec, mailboxName, classe);\n\t\t\t\t\tistanzaAzione = AzioneBL.creaIstanzaAzione(emf, classe, contesto);\n\t\t\t\t\tregolaContext.put(\"azione\", istanzaAzione);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(\"nessuna implementazione configurata per questa regola\");\n\t\t\t\t}\n\n\t\t\t\tBinding binding = new Binding();\n\t\t\t\tbinding.setVariable(\"email\", contesto.getEmail());\n\t\t\t\tbinding.setVariable(\"helper\", new RegolaPecHelper(regola, contesto.getEmail()));\n\t\t\t\tif (regolaContext != null && !regolaContext.isEmpty()) {\n\t\t\t\t\tfor (String key : regolaContext.keySet()) {\n\t\t\t\t\t\tbinding.setVariable(key, regolaContext.get(key));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// String grrovyBody = groovyCode.trim();\n\t\t\t\t// if (!grrovyBody.startsWith(\"{\")) {\n\t\t\t\t// groovyCode = \"{\" + grrovyBody + \"}(email, helper)\";\n\t\t\t\t// } else {\n\t\t\t\t// groovyCode = \"\" + grrovyBody + \"(email, helper)\";\n\t\t\t\t// }\n\t\t\t\tGroovyShell shell = new GroovyShell(binding);\n\t\t\t\t\n\t\t\t\tlogger.debug(\"regola: \\\"{}\\\"\", regola.getNome());\n\t\t\t\tString criterioGroovy = regola.getCriterio();\n\t\t\t\tboolean criterioRegolaSoddisfatto = false;\n\t\t\t\tif (StringUtils.isNotBlank(criterioGroovy)) {\n\t\t\t\t\tlogger.debug(\"criterio: \\\"{}\\\"\", criterioGroovy);\n\t\t\t\t\tObject criterioGroovyResult = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcriterioGroovyResult = shell.evaluate(criterioGroovy);\n\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\tlogger.error(\"errore valutazione script groovy.\", ex);\n\t\t\t\t\t}\n\t\t\t\t\tif (criterioGroovyResult != null && criterioGroovyResult instanceof Boolean) {\n\t\t\t\t\t\tcriterioRegolaSoddisfatto = (Boolean) criterioGroovyResult;\n\t\t\t\t\t\tlogger.debug(\"risultato: {}\", criterioRegolaSoddisfatto);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error(\"impossibile verificare come risultato boolean il criterio groovy applicato\");\n\t\t\t\t\t\tcriterioRegolaSoddisfatto = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(\"la regola non contiene criteri groovy da valutare\");\n\t\t\t\t\tcriterioRegolaSoddisfatto = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t/* se i criteri sono verificati (o vuoti) applico le azioni e poi istanzio la classe da eseguire */\n\t\t\t\tif (criterioRegolaSoddisfatto) {\n\t\t\t\t\t\n\t\t\t\t\tString azioneGroovy = regola.getAzione();\n\t\t\t\t\tif (StringUtils.isNotBlank(azioneGroovy)) {\n\t\t\t\t\t\tlogger.debug(\"azione: \\\"{}\\\"\", azioneGroovy);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tObject azioneResult = shell.evaluate(azioneGroovy);\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tlogger.error(\"errore valutazione criterio groovy.\", ex);\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (istanzaAzione != null) {\n\t\t\t\t\t\tres = AzioneBL.eseguiIstanza(istanzaAzione);\n\t\t\t\t\t\tif (res.stato != AzioneEsitoStato.OK) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.warn(\"nessuna azione da eseguire\");\n\t\t\t\t\t\tres = AzioneEsito.ok(\"\", \"\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tres = AzioneEsito.regolaNonApplicabile(\"criterio di Applicazione Regola Non Soddisfatto\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// tutteLeRegoleVerificate = tutteLeRegoleVerificate && criterioRegolaVerificato;\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tlogger.warn(\"nessuna regola da applicare specificata\");\n\t\t\tres = AzioneEsito.ok(\"\", \"\");\n\t\t}\n\t\t\t\t\n\t\treturn res;\n\t}\n\t\t\n//\tpublic static synchronized boolean applicaRegole(EntityManagerFactory emf, List<RegolaPec> regoleDaApplicare, Message email, MessaggioPec messaggioPec, String mailboxName) throws Exception {\n////\t\tMap<String, Object> regolaContext = new HashMap<String, Object>();\n////\t\tregolaContext.put(\"protocollo\", istanzaProtocollo);\n//\t\t\n//\t\treturn applicaRegole(emf, regoleDaApplicare, email, messaggioPec, mailboxName);\n//\t}\n}", "public enum RegolaPecEventoEnum {\r\n\r\n\tIMPORTA_MESSAGGIO,\r\n\tPROTOCOLLA_MESSAGGIO,\r\n\tAGGIORNA_STATO,\r\n\tAGGIORNA_SEGNATURA,\r\n\tNOTIFICA\r\n\r\n}\r", "@Entity\r\n@Table(schema = \"\", name = \"pec06_regole\")\r\npublic class RegolaPec extends AbstractEntityMarksWithIdLong<RegolaPec> {\r\n\r\n\tprotected static final Logger logger = Logger.getLogger(RegolaPec.class.getName());\r\n\r\n\t/**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.AUTO)\r\n\t@Column(name = \"pec06_id\")\r\n\tprivate long id;\r\n\r\n\t@Column(name = \"pec06_nome\")\r\n\tprivate String nome;\r\n\r\n\t@Column(name = \"pec06_note\")\r\n\t@Lob\r\n\tprivate String note;\r\n\r\n\t@Column(name = \"pec06_evento\")\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate RegolaPecEventoEnum evento;\r\n\r\n\t@Column(name = \"pec06_criterio\")\r\n\t@Lob\r\n\tprivate String criterio;\r\n\r\n\t@Column(name = \"pec06_azione\")\r\n\t@Lob\r\n\tprivate String azione;\r\n\r\n\t@Column(name = \"pec06_classe\")\r\n\tprivate String classe;\r\n\r\n\t@Column(name = \"pec06_ordine\")\r\n\tprivate Integer ordine;\r\n\r\n\t@Embedded\r\n\t@AttributeOverrides({ @AttributeOverride(name = \"dataCreazione\", column = @Column(name = \"pec06_dt_creazione\")), @AttributeOverride(name = \"dataModifica\", column = @Column(name = \"pec06_ts_modifica\")), @AttributeOverride(name = \"dataCancellazione\", column = @Column(name = \"pec06_dt_cancellazione\")), @AttributeOverride(name = \"utenteCreazioneId\", column = @Column(name = \"pec06_id_utente_creazione\")), @AttributeOverride(name = \"utenteModificaId\", column = @Column(name = \"pec06_id_utente_modifica\")), @AttributeOverride(name = \"utenteCancellazioneId\", column = @Column(name = \"pec06_id_utente_cancellazione\")) })\r\n\tprivate EntityMarks entityMarks;\r\n\r\n\t@Override\r\n\tpublic EntityMarks getEntityMarks() {\r\n\t\treturn entityMarks;\r\n\t}\r\n\r\n\tpublic void setEntityMarks(EntityMarks entityMarks) {\r\n\t\tthis.entityMarks = entityMarks;\r\n\t}\r\n\r\n\tpublic long getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(long id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n\tpublic void setNome(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNote() {\r\n\t\treturn note;\r\n\t}\r\n\r\n\tpublic void setNote(String note) {\r\n\t\tthis.note = note;\r\n\t}\r\n\r\n\tpublic RegolaPecEventoEnum getEvento() {\r\n\t\treturn evento;\r\n\t}\r\n\r\n\tpublic void setEvento(RegolaPecEventoEnum evento) {\r\n\t\tthis.evento = evento;\r\n\t}\r\n\r\n\tpublic String getCriterio() {\r\n\t\treturn criterio;\r\n\t}\r\n\r\n\tpublic void setCriterio(String criterio) {\r\n\t\tthis.criterio = criterio;\r\n\t}\r\n\r\n\tpublic String getAzione() {\r\n\t\treturn azione;\r\n\t}\r\n\r\n\tpublic void setAzione(String azione) {\r\n\t\tthis.azione = azione;\r\n\t}\r\n\r\n\tpublic Integer getOrdine() {\r\n\t\treturn ordine;\r\n\t}\r\n\r\n\tpublic void setOrdine(Integer ordine) {\r\n\t\tthis.ordine = ordine;\r\n\t}\r\n\r\n\tpublic String getClasse() {\r\n\t\treturn classe;\r\n\t}\r\n\r\n\tpublic void setClasse(String classe) {\r\n\t\tthis.classe = classe;\r\n\t}\r\n\r\n}\r", "public class AzioneContext {\n\n\tprotected static final Logger logger = LoggerFactory.getLogger(AzioneContext.class);\n\n\tprivate EntityManagerFactory emf;\n\tprivate Message email;\n\tprivate MessaggioPec pec;\n\tprivate RegolaPec regola;\n\n\tprivate Properties configurazioneMailbox;\n\tprivate String mailboxName;\n\n\tprivate MessaggioPec ricevuta;\n\tprivate MessaggioPec messaggioInviato;\n\n\tprivate AzioneContext() {\n\t\tsuper();\n\t}\n\n\tpublic static AzioneContext buildContextMessaggi(EntityManagerFactory emf, Message email, MessaggioPec pec, String mailboxName) {\n\t\tAzioneContext res = new AzioneContext();\n\t\tres.emf = emf;\n\t\tres.email = email;\n\t\tres.pec = pec;\n\t\tres.mailboxName = mailboxName;\n\t\tlogger.debug(\"buildContextMessaggi\");\n\t\tlogger.debug(\"email={}\", email);\n\t\tlogger.debug(\"pec={}\", pec);\n\t\tlogger.debug(\"configurazioneMailbox={}\", mailboxName);\n\n\t\treturn res;\n\t}\n\n\tpublic static AzioneContext buildContextMessaggi(EntityManagerFactory emf, Message email, MessaggioPec pec, Properties configurazioneMailbox) {\n\t\tAzioneContext res = new AzioneContext();\n\t\tres.emf = emf;\n\t\tres.email = email;\n\t\tres.pec = pec;\n\t\tres.configurazioneMailbox = configurazioneMailbox;\n\t\tlogger.debug(\"buildContextRicevute\");\n\t\tlogger.debug(\"email={}\", email);\n\t\tlogger.debug(\"pec={}\", pec);\n\t\tlogger.debug(\"configurazioneMailbox={}\", configurazioneMailbox);\n\t\treturn res;\n\t}\n\n\tpublic static AzioneContext buildContextRicevute(EntityManagerFactory emf, MessaggioPec ricevuta, MessaggioPec messaggioInviato) {\n\t\tAzioneContext res = new AzioneContext();\n\t\tres.emf = emf;\n\t\tres.ricevuta = ricevuta;\n\t\tres.messaggioInviato = messaggioInviato;\n\t\tlogger.debug(\"buildContextRicevute\");\n\t\tlogger.debug(\"ricevuta={}\", ricevuta);\n\t\tlogger.debug(\"messaggioInviato={}\", messaggioInviato);\n\t\treturn res;\n\t}\n\n\tpublic EntityManagerFactory getEmf() {\n\t\treturn emf;\n\t}\n\n\tpublic Message getMessaggioEmail() {\n\t\treturn email;\n\t}\n\n\tpublic RegolaPec getRegola() {\n\t\treturn regola;\n\t}\n\n\tpublic Properties getConfigurazioneMailbox() {\n\t\treturn configurazioneMailbox;\n\t}\n\n\tpublic MessaggioPec getPec() {\n\t\treturn pec;\n\t}\n\n\tpublic Message getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(Message email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getMailboxName() {\n\t\treturn mailboxName;\n\t}\n\n\tpublic void setMailboxName(String mailboxName) {\n\t\tthis.mailboxName = mailboxName;\n\t}\n\n\tpublic MessaggioPec getRicevuta() {\n\t\treturn ricevuta;\n\t}\n\n\tpublic void setRicevuta(MessaggioPec ricevuta) {\n\t\tthis.ricevuta = ricevuta;\n\t}\n\n\tpublic MessaggioPec getMessaggioInviato() {\n\t\treturn messaggioInviato;\n\t}\n\n\tpublic void setMessaggioInviato(MessaggioPec messaggioInviato) {\n\t\tthis.messaggioInviato = messaggioInviato;\n\t}\n\n\tpublic void setEmf(EntityManagerFactory emf) {\n\t\tthis.emf = emf;\n\t}\n\n\tpublic void setPec(MessaggioPec pec) {\n\t\tthis.pec = pec;\n\t}\n\n\tpublic void setRegola(RegolaPec regola) {\n\t\tthis.regola = regola;\n\t}\n\n\tpublic void setConfigurazioneMailbox(Properties configurazioneMailbox) {\n\t\tthis.configurazioneMailbox = configurazioneMailbox;\n\t}\n}", "public class AzioneEsito {\n\t\n\tpublic enum AzioneEsitoStato {\n\t\tOK,\n\t\tREGOLA_NON_APPLICABILE,\n\t\tNOTIFICA,\n\t\tERRORE\n\t}\n\n\tprivate AzioneEsito() {\n\t\tthis.stato = AzioneEsitoStato.ERRORE;\n\t}\n\n\tpublic static AzioneEsito ok(String protocollo, String urlDocumentale) {\n\t\tAzioneEsito esitoOk = new AzioneEsito();\n\t\tesitoOk.stato = AzioneEsitoStato.OK;\n\t\tesitoOk.protocollo = protocollo;\n\t\tesitoOk.urlDocumentale = urlDocumentale;\n\t\treturn esitoOk;\n\t}\n\t\n\tpublic static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {\n\t\tAzioneEsito esitoOk = ok(protocollo, urlDocumentale);\n\t\tesitoOk.errore = nota;\n\t\treturn esitoOk;\n\t}\n\t\n\tpublic static AzioneEsito notifica(String messaggio, Throwable ex) {\n\t\tAzioneEsito esitoErrore = new AzioneEsito();\n\t\tesitoErrore.stato = AzioneEsitoStato.NOTIFICA;\n\t\tesitoErrore.errore = messaggio;\n\t\tesitoErrore.eccezione = ex;\n\t\treturn esitoErrore;\n\t}\n\t\n\tpublic static AzioneEsito errore(String messaggio, Throwable ex) {\n\t\tAzioneEsito esitoErrore = new AzioneEsito();\n\t\tesitoErrore.errore = messaggio;\n\t\tesitoErrore.eccezione = ex;\n\t\treturn esitoErrore;\n\t}\n\t\n\tpublic static AzioneEsito regolaNonApplicabile(String messaggio) {\n\t\tAzioneEsito esito = new AzioneEsito();\n\t\tesito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;\n\t\tesito.errore = messaggio;\n\t\treturn esito;\n\t}\t\n\t\n\tpublic AzioneEsitoStato stato;\n\tpublic String protocollo;\n\tpublic String urlDocumentale;\n\tpublic String errore;\n\tpublic Throwable eccezione;\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ProtocolloEsito [stato=\" + stato + \", protocollo=\" + protocollo + \", errore=\" + errore + \"]\";\n\t}\n\t\n\tprivate StringBuffer sb = new StringBuffer();\n\t\n\tpublic void logAndBuffer(Logger logger, String message, Object... argArray) {\n\t\tsb.append(MessageFormatter.format(message, argArray).getMessage());\n\t\tsb.append(System.getProperty(\"line.separator\"));\n\t\t// aggiungi al log \n\t\tlogger.info(message, argArray);\n\t}\n\t\n\tpublic String getBufferedLog() {\n\t\treturn sb.toString();\n\t}\n}", "public enum AzioneEsitoStato {\n\tOK,\n\tREGOLA_NON_APPLICABILE,\n\tNOTIFICA,\n\tERRORE\n}" ]
import it.attocchi.jpec.server.bl.RegolaPecBL; import it.attocchi.jpec.server.bl.RegolaPecEventoEnum; import it.attocchi.jpec.server.entities.RegolaPec; import it.attocchi.jpec.server.protocollo.AzioneContext; import it.attocchi.jpec.server.protocollo.AzioneEsito; import it.attocchi.jpec.server.protocollo.AzioneEsito.AzioneEsitoStato; import java.util.List; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
public class TestRegolaPec { protected final Logger logger = LoggerFactory.getLogger(TestRegolaPec.class); @Test public void test() throws Exception { logger.info(this.getClass().getName()); try { EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpec-server-pu_TEST");
List<RegolaPec> regoleImporta = RegolaPecBL.regole(emf, RegolaPecEventoEnum.IMPORTA_MESSAGGIO);
2
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/fonts/GlyphSubstitutionTable.java
[ "public class AdvancedTypographicTableFormatException extends RuntimeException {\n\n /**\n * Instantiate ATT format exception.\n */\n public AdvancedTypographicTableFormatException() {\n super();\n }\n\n /**\n * Instantiate ATT format exception.\n *\n * @param message\n * a message string\n */\n public AdvancedTypographicTableFormatException(String message) {\n super(message);\n }\n\n /**\n * Instantiate ATT format exception.\n *\n * @param message\n * a message string\n * @param cause\n * a <code>Throwable</code> that caused this exception\n */\n public AdvancedTypographicTableFormatException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public final class GlyphClassTable extends GlyphMappingTable implements GlyphClassMapping {\n\n /** empty mapping table */\n public static final int GLYPH_CLASS_TYPE_EMPTY = GLYPH_MAPPING_TYPE_EMPTY;\n\n /** mapped mapping table */\n public static final int GLYPH_CLASS_TYPE_MAPPED = GLYPH_MAPPING_TYPE_MAPPED;\n\n /** range based mapping table */\n public static final int GLYPH_CLASS_TYPE_RANGE = GLYPH_MAPPING_TYPE_RANGE;\n\n /** empty mapping table */\n public static final int GLYPH_CLASS_TYPE_COVERAGE_SET = 3;\n\n private GlyphClassMapping cm;\n\n private GlyphClassTable(GlyphClassMapping cm) {\n assert cm != null;\n assert cm instanceof GlyphMappingTable;\n this.cm = cm;\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return ((GlyphMappingTable) cm).getType();\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return ((GlyphMappingTable) cm).getEntries();\n }\n\n /** {@inheritDoc} */\n public int getClassSize(int set) {\n return cm.getClassSize(set);\n }\n\n /** {@inheritDoc} */\n public int getClassIndex(int gid, int set) {\n return cm.getClassIndex(gid, set);\n }\n\n /**\n * Create glyph class table.\n *\n * @param entries\n * list of mapped or ranged class entries, or null or empty list\n * @return a new covera table instance\n */\n public static GlyphClassTable createClassTable(List entries) {\n GlyphClassMapping cm;\n if ((entries == null) || (entries.size() == 0)) {\n cm = new EmptyClassTable(entries);\n } else if (isMappedClass(entries)) {\n cm = new MappedClassTable(entries);\n } else if (isRangeClass(entries)) {\n cm = new RangeClassTable(entries);\n } else if (isCoverageSetClass(entries)) {\n cm = new CoverageSetClassTable(entries);\n } else {\n cm = null;\n }\n assert cm != null : \"unknown class type\";\n return new GlyphClassTable(cm);\n }\n\n private static boolean isMappedClass(List entries) {\n if ((entries == null) || (entries.size() == 0)) {\n return false;\n } else {\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (!(o instanceof Integer)) {\n return false;\n }\n }\n return true;\n }\n }\n\n private static boolean isRangeClass(List entries) {\n if ((entries == null) || (entries.size() == 0)) {\n return false;\n } else {\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (!(o instanceof MappingRange)) {\n return false;\n }\n }\n return true;\n }\n }\n\n private static boolean isCoverageSetClass(List entries) {\n if ((entries == null) || (entries.size() == 0)) {\n return false;\n } else {\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (!(o instanceof GlyphCoverageTable)) {\n return false;\n }\n }\n return true;\n }\n }\n\n private static class EmptyClassTable extends GlyphMappingTable.EmptyMappingTable implements GlyphClassMapping {\n\n public EmptyClassTable(List entries) {\n super(entries);\n }\n\n /** {@inheritDoc} */\n public int getClassSize(int set) {\n return 0;\n }\n\n /** {@inheritDoc} */\n public int getClassIndex(int gid, int set) {\n return -1;\n }\n }\n\n private static class MappedClassTable extends GlyphMappingTable.MappedMappingTable implements GlyphClassMapping {\n\n private int firstGlyph;\n private int[] gca;\n private int gcMax = -1;\n\n public MappedClassTable(List entries) {\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new java.util.ArrayList();\n entries.add(Integer.valueOf(firstGlyph));\n if (gca != null) {\n for (int i = 0, n = gca.length; i < n; i++) {\n entries.add(Integer.valueOf(gca[i]));\n }\n }\n return entries;\n }\n\n /** {@inheritDoc} */\n public int getMappingSize() {\n return gcMax + 1;\n }\n\n /** {@inheritDoc} */\n public int getMappedIndex(int gid) {\n int i = gid - firstGlyph;\n if ((i >= 0) && (i < gca.length)) {\n return gca[i];\n } else {\n return -1;\n }\n }\n\n /** {@inheritDoc} */\n public int getClassSize(int set) {\n return getMappingSize();\n }\n\n /** {@inheritDoc} */\n public int getClassIndex(int gid, int set) {\n return getMappedIndex(gid);\n }\n\n private void populate(List entries) {\n // obtain entries iterator\n Iterator it = entries.iterator();\n // extract first glyph\n int firstGlyph = 0;\n if (it.hasNext()) {\n Object o = it.next();\n if (o instanceof Integer) {\n firstGlyph = ((Integer) o).intValue();\n } else {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entry, first entry must be Integer denoting first glyph value, but is: \" + o);\n }\n }\n // extract glyph class array\n int i = 0;\n int n = entries.size() - 1;\n int gcMax = -1;\n int[] gca = new int[n];\n while (it.hasNext()) {\n Object o = it.next();\n if (o instanceof Integer) {\n int gc = ((Integer) o).intValue();\n gca[i++] = gc;\n if (gc > gcMax) {\n gcMax = gc;\n }\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal mapping entry, must be Integer: \" + o);\n }\n }\n assert i == n;\n assert this.gca == null;\n this.firstGlyph = firstGlyph;\n this.gca = gca;\n this.gcMax = gcMax;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ firstGlyph = \" + firstGlyph + \", classes = {\");\n for (int i = 0, n = gca.length; i < n; i++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(Integer.toString(gca[i]));\n }\n sb.append(\"} }\");\n return sb.toString();\n }\n }\n\n private static class RangeClassTable extends GlyphMappingTable.RangeMappingTable implements GlyphClassMapping {\n\n public RangeClassTable(List entries) {\n super(entries);\n }\n\n /** {@inheritDoc} */\n public int getMappedIndex(int gid, int s, int m) {\n return m;\n }\n\n /** {@inheritDoc} */\n public int getClassSize(int set) {\n return getMappingSize();\n }\n\n /** {@inheritDoc} */\n public int getClassIndex(int gid, int set) {\n return getMappedIndex(gid);\n }\n }\n\n private static class CoverageSetClassTable extends GlyphMappingTable.EmptyMappingTable implements GlyphClassMapping {\n\n public CoverageSetClassTable(List entries) {\n throw new UnsupportedOperationException(\"coverage set class table not yet supported\");\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GLYPH_CLASS_TYPE_COVERAGE_SET;\n }\n\n /** {@inheritDoc} */\n public int getClassSize(int set) {\n return 0;\n }\n\n /** {@inheritDoc} */\n public int getClassIndex(int gid, int set) {\n return -1;\n }\n }\n\n}", "public final class GlyphCoverageTable extends GlyphMappingTable implements GlyphCoverageMapping {\n\n /** empty mapping table */\n public static final int GLYPH_COVERAGE_TYPE_EMPTY = GLYPH_MAPPING_TYPE_EMPTY;\n\n /** mapped mapping table */\n public static final int GLYPH_COVERAGE_TYPE_MAPPED = GLYPH_MAPPING_TYPE_MAPPED;\n\n /** range based mapping table */\n public static final int GLYPH_COVERAGE_TYPE_RANGE = GLYPH_MAPPING_TYPE_RANGE;\n\n private GlyphCoverageMapping cm;\n\n private GlyphCoverageTable(GlyphCoverageMapping cm) {\n this.cm = cm;\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return ((GlyphMappingTable) cm).getType();\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return ((GlyphMappingTable) cm).getEntries();\n }\n\n /** {@inheritDoc} */\n public int getCoverageSize() {\n return cm.getCoverageSize();\n }\n\n /** {@inheritDoc} */\n public int getCoverageIndex(int gid) {\n return cm.getCoverageIndex(gid);\n }\n\n /**\n * Create glyph coverage table.\n *\n * @param entries\n * list of mapped or ranged coverage entries, or null or empty list\n * @return a new covera table instance\n */\n public static GlyphCoverageTable createCoverageTable(List entries) {\n GlyphCoverageMapping cm;\n if ((entries == null) || (entries.size() == 0)) {\n cm = new EmptyCoverageTable(entries);\n } else if (isMappedCoverage(entries)) {\n cm = new MappedCoverageTable(entries);\n } else if (isRangeCoverage(entries)) {\n cm = new RangeCoverageTable(entries);\n } else {\n cm = null;\n }\n assert cm != null : \"unknown coverage type\";\n return new GlyphCoverageTable(cm);\n }\n\n private static boolean isMappedCoverage(List entries) {\n if ((entries == null) || (entries.size() == 0)) {\n return false;\n } else {\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (!(o instanceof Integer)) {\n return false;\n }\n }\n return true;\n }\n }\n\n private static boolean isRangeCoverage(List entries) {\n if ((entries == null) || (entries.size() == 0)) {\n return false;\n } else {\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (!(o instanceof MappingRange)) {\n return false;\n }\n }\n return true;\n }\n }\n\n private static class EmptyCoverageTable extends GlyphMappingTable.EmptyMappingTable implements GlyphCoverageMapping {\n\n public EmptyCoverageTable(List entries) {\n super(entries);\n }\n\n /** {@inheritDoc} */\n public int getCoverageSize() {\n return 0;\n }\n\n /** {@inheritDoc} */\n public int getCoverageIndex(int gid) {\n return -1;\n }\n }\n\n private static class MappedCoverageTable extends GlyphMappingTable.MappedMappingTable\n implements GlyphCoverageMapping {\n\n private int[] map;\n\n public MappedCoverageTable(List entries) {\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new java.util.ArrayList();\n if (map != null) {\n for (int i = 0, n = map.length; i < n; i++) {\n entries.add(Integer.valueOf(map[i]));\n }\n }\n return entries;\n }\n\n /** {@inheritDoc} */\n public int getMappingSize() {\n return (map != null) ? map.length : 0;\n }\n\n public int getMappedIndex(int gid) {\n int i;\n if ((i = Arrays.binarySearch(map, gid)) >= 0) {\n return i;\n } else {\n return -1;\n }\n }\n\n /** {@inheritDoc} */\n public int getCoverageSize() {\n return getMappingSize();\n }\n\n /** {@inheritDoc} */\n public int getCoverageIndex(int gid) {\n return getMappedIndex(gid);\n }\n\n private void populate(List entries) {\n int i = 0;\n int skipped = 0;\n int n = entries.size();\n int gidMax = -1;\n int[] map = new int[n];\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof Integer) {\n int gid = ((Integer) o).intValue();\n if ((gid >= 0) && (gid < 65536)) {\n if (gid > gidMax) {\n map[i++] = gidMax = gid;\n } else {\n skipped++;\n }\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal glyph index: \" + gid);\n }\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal coverage entry, must be Integer: \" + o);\n }\n }\n assert (i + skipped) == n;\n assert this.map == null;\n this.map = map;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append('{');\n for (int i = 0, n = map.length; i < n; i++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(Integer.toString(map[i]));\n }\n sb.append('}');\n return sb.toString();\n }\n }\n\n private static class RangeCoverageTable extends GlyphMappingTable.RangeMappingTable implements GlyphCoverageMapping {\n\n public RangeCoverageTable(List entries) {\n super(entries);\n }\n\n /** {@inheritDoc} */\n public int getMappedIndex(int gid, int s, int m) {\n return m + gid - s;\n }\n\n /** {@inheritDoc} */\n public int getCoverageSize() {\n return getMappingSize();\n }\n\n /** {@inheritDoc} */\n public int getCoverageIndex(int gid) {\n return getMappedIndex(gid);\n }\n }\n\n}", "public class GlyphDefinitionTable extends GlyphTable {\n\n /** glyph class subtable type */\n public static final int GDEF_LOOKUP_TYPE_GLYPH_CLASS = 1;\n /** attachment point subtable type */\n public static final int GDEF_LOOKUP_TYPE_ATTACHMENT_POINT = 2;\n /** ligature caret subtable type */\n public static final int GDEF_LOOKUP_TYPE_LIGATURE_CARET = 3;\n /** mark attachment subtable type */\n public static final int GDEF_LOOKUP_TYPE_MARK_ATTACHMENT = 4;\n\n /** pre-defined glyph class - base glyph */\n public static final int GLYPH_CLASS_BASE = 1;\n /** pre-defined glyph class - ligature glyph */\n public static final int GLYPH_CLASS_LIGATURE = 2;\n /** pre-defined glyph class - mark glyph */\n public static final int GLYPH_CLASS_MARK = 3;\n /** pre-defined glyph class - component glyph */\n public static final int GLYPH_CLASS_COMPONENT = 4;\n\n /** singleton glyph class table */\n private GlyphClassSubtable gct;\n /** singleton attachment point table */\n // private AttachmentPointSubtable apt; // NOT YET USED\n /** singleton ligature caret table */\n // private LigatureCaretSubtable lct; // NOT YET USED\n /** singleton mark attachment table */\n private MarkAttachmentSubtable mat;\n\n /**\n * Instantiate a <code>GlyphDefinitionTable</code> object using the specified subtables.\n *\n * @param subtables\n * a list of identified subtables\n */\n public GlyphDefinitionTable(List subtables) {\n super(null, new HashMap(0));\n if ((subtables == null) || (subtables.size() == 0)) {\n throw new AdvancedTypographicTableFormatException(\"subtables must be non-empty\");\n } else {\n for (Iterator it = subtables.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof GlyphDefinitionSubtable) {\n addSubtable((GlyphSubtable) o);\n } else {\n throw new AdvancedTypographicTableFormatException(\"subtable must be a glyph definition subtable\");\n }\n }\n freezeSubtables();\n }\n }\n\n /**\n * Reorder combining marks in glyph sequence so that they precede (within the sequence) the base\n * character to which they are applied. N.B. In the case of LTR segments, marks are not reordered by this,\n * method since when the segment is reversed by BIDI processing, marks are automatically reordered to precede\n * their base glyph.\n *\n * @param gs\n * an input glyph sequence\n * @param widths\n * associated advance widths (also reordered)\n * @param gpa\n * associated glyph position adjustments (also reordered)\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @return the reordered (output) glyph sequence\n */\n public GlyphSequence reorderCombiningMarks(GlyphSequence gs, int[] widths, int[][] gpa, String script,\n String language) {\n ScriptProcessor sp = ScriptProcessor.getInstance(script);\n return sp.reorderCombiningMarks(this, gs, widths, gpa, script, language);\n }\n\n /** {@inheritDoc} */\n protected void addSubtable(GlyphSubtable subtable) {\n if (subtable instanceof GlyphClassSubtable) {\n this.gct = (GlyphClassSubtable) subtable;\n } else if (subtable instanceof AttachmentPointSubtable) {\n // TODO - not yet used\n // this.apt = (AttachmentPointSubtable) subtable;\n } else if (subtable instanceof LigatureCaretSubtable) {\n // TODO - not yet used\n // this.lct = (LigatureCaretSubtable) subtable;\n } else if (subtable instanceof MarkAttachmentSubtable) {\n this.mat = (MarkAttachmentSubtable) subtable;\n } else {\n throw new UnsupportedOperationException(\"unsupported glyph definition subtable type: \" + subtable);\n }\n }\n\n /**\n * Determine if glyph belongs to pre-defined glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param gc\n * a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n * @return true if glyph belongs to specified glyph class\n */\n public boolean isGlyphClass(int gid, int gc) {\n if (gct != null) {\n return gct.isGlyphClass(gid, gc);\n } else {\n return false;\n }\n }\n\n /**\n * Determine glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n */\n public int getGlyphClass(int gid) {\n if (gct != null) {\n return gct.getGlyphClass(gid);\n } else {\n return -1;\n }\n }\n\n /**\n * Determine if glyph belongs to (font specific) mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param mac\n * a (font specific) mark attachment class\n * @return true if glyph belongs to specified mark attachment class\n */\n public boolean isMarkAttachClass(int gid, int mac) {\n if (mat != null) {\n return mat.isMarkAttachClass(gid, mac);\n } else {\n return false;\n }\n }\n\n /**\n * Determine mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a non-negative mark attachment class, or -1 if no class defined\n */\n public int getMarkAttachClass(int gid) {\n if (mat != null) {\n return mat.getMarkAttachClass(gid);\n } else {\n return -1;\n }\n }\n\n /**\n * Map a lookup type name to its constant (integer) value.\n *\n * @param name\n * lookup type name\n * @return lookup type\n */\n public static int getLookupTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"glyphclass\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_GLYPH_CLASS;\n } else if (\"attachmentpoint\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_ATTACHMENT_POINT;\n } else if (\"ligaturecaret\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_LIGATURE_CARET;\n } else if (\"markattachment\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_MARK_ATTACHMENT;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Map a lookup type constant (integer) value to its name.\n *\n * @param type\n * lookup type\n * @return lookup type name\n */\n public static String getLookupTypeName(int type) {\n String tn = null;\n switch (type) {\n case GDEF_LOOKUP_TYPE_GLYPH_CLASS:\n tn = \"glyphclass\";\n break;\n case GDEF_LOOKUP_TYPE_ATTACHMENT_POINT:\n tn = \"attachmentpoint\";\n break;\n case GDEF_LOOKUP_TYPE_LIGATURE_CARET:\n tn = \"ligaturecaret\";\n break;\n case GDEF_LOOKUP_TYPE_MARK_ATTACHMENT:\n tn = \"markattachment\";\n break;\n default:\n tn = \"unknown\";\n break;\n }\n return tn;\n }\n\n /**\n * Create a definition subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags (must be zero)\n * @param format\n * subtable format\n * @param mapping\n * subtable mapping table\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format,\n GlyphMappingTable mapping, List entries) {\n GlyphSubtable st = null;\n switch (type) {\n case GDEF_LOOKUP_TYPE_GLYPH_CLASS:\n st = GlyphClassSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_ATTACHMENT_POINT:\n st = AttachmentPointSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_LIGATURE_CARET:\n st = LigatureCaretSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_MARK_ATTACHMENT:\n st = MarkAttachmentSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n default:\n break;\n }\n return st;\n }\n\n private abstract static class GlyphClassSubtable extends GlyphDefinitionSubtable {\n\n GlyphClassSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_GLYPH_CLASS;\n }\n\n /**\n * Determine if glyph belongs to pre-defined glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param gc\n * a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n * @return true if glyph belongs to specified glyph class\n */\n public abstract boolean isGlyphClass(int gid, int gc);\n\n /**\n * Determine glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n */\n public abstract int getGlyphClass(int gid);\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new GlyphClassSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class GlyphClassSubtableFormat1 extends GlyphClassSubtable {\n\n GlyphClassSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof GlyphClassSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean isGlyphClass(int gid, int gc) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0) == gc;\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int getGlyphClass(int gid) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0);\n } else {\n return -1;\n }\n }\n }\n\n private abstract static class AttachmentPointSubtable extends GlyphDefinitionSubtable {\n\n AttachmentPointSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_ATTACHMENT_POINT;\n }\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new AttachmentPointSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class AttachmentPointSubtableFormat1 extends AttachmentPointSubtable {\n\n AttachmentPointSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof AttachmentPointSubtable;\n }\n }\n\n private abstract static class LigatureCaretSubtable extends GlyphDefinitionSubtable {\n\n LigatureCaretSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_LIGATURE_CARET;\n }\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new LigatureCaretSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class LigatureCaretSubtableFormat1 extends LigatureCaretSubtable {\n\n LigatureCaretSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof LigatureCaretSubtable;\n }\n }\n\n private abstract static class MarkAttachmentSubtable extends GlyphDefinitionSubtable {\n\n MarkAttachmentSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_MARK_ATTACHMENT;\n }\n\n /**\n * Determine if glyph belongs to (font specific) mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param mac\n * a (font specific) mark attachment class\n * @return true if glyph belongs to specified mark attachment class\n */\n public abstract boolean isMarkAttachClass(int gid, int mac);\n\n /**\n * Determine mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a non-negative mark attachment class, or -1 if no class defined\n */\n public abstract int getMarkAttachClass(int gid);\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new MarkAttachmentSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MarkAttachmentSubtableFormat1 extends MarkAttachmentSubtable {\n\n MarkAttachmentSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MarkAttachmentSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean isMarkAttachClass(int gid, int mac) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0) == mac;\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int getMarkAttachClass(int gid) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0);\n } else {\n return -1;\n }\n }\n }\n\n}", "public abstract class ScriptProcessor {\n\n private final String script;\n\n private final Map<AssembledLookupsKey, GlyphTable.UseSpec[]> assembledLookups;\n\n private static Map<String, ScriptProcessor> processors = new HashMap<String, ScriptProcessor>();\n\n /**\n * Instantiate a script processor.\n *\n * @param script\n * a script identifier\n */\n protected ScriptProcessor(String script) {\n if ((script == null) || (script.length() == 0)) {\n throw new IllegalArgumentException(\"script must be non-empty string\");\n } else {\n this.script = script;\n this.assembledLookups = new HashMap<>();\n }\n }\n\n /** @return script identifier */\n public final String getScript() {\n return script;\n }\n\n /**\n * Obtain script specific required substitution features.\n *\n * @return array of suppported substitution features or null\n */\n public abstract String[] getSubstitutionFeatures();\n\n /**\n * Obtain script specific optional substitution features.\n *\n * @return array of suppported substitution features or null\n */\n public String[] getOptionalSubstitutionFeatures() {\n return new String[0];\n }\n\n /**\n * Obtain script specific substitution context tester.\n *\n * @return substitution context tester or null\n */\n public abstract ScriptContextTester getSubstitutionContextTester();\n\n /**\n * Perform substitution processing using a specific set of lookup tables.\n *\n * @param gsub\n * the glyph substitution table that applies\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param lookups\n * a mapping from lookup specifications to glyph subtables to use for substitution processing\n * @return the substituted (output) glyph sequence\n */\n public final GlyphSequence substitute(GlyphSubstitutionTable gsub, GlyphSequence gs, String script, String language,\n Map/*<LookupSpec,List<LookupTable>>>*/ lookups) {\n return substitute(gs, script, language, assembleLookups(gsub, getSubstitutionFeatures(), lookups),\n getSubstitutionContextTester());\n }\n\n /**\n * Perform substitution processing using a specific set of ordered glyph table use specifications.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param usa\n * an ordered array of glyph table use specs\n * @param sct\n * a script specific context tester (or null)\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language, GlyphTable.UseSpec[] usa,\n ScriptContextTester sct) {\n assert usa != null;\n for (int i = 0, n = usa.length; i < n; i++) {\n GlyphTable.UseSpec us = usa[i];\n gs = us.substitute(gs, script, language, sct);\n }\n return gs;\n }\n\n /**\n * Reorder combining marks in glyph sequence so that they precede (within the sequence) the base\n * character to which they are applied. N.B. In the case of RTL segments, marks are not reordered by this,\n * method since when the segment is reversed by BIDI processing, marks are automatically reordered to precede\n * their base glyph.\n *\n * @param gdef\n * the glyph definition table that applies\n * @param gs\n * an input glyph sequence\n * @param unscaledWidths\n * associated unscaled advance widths (also reordered)\n * @param gpa\n * associated glyph position adjustments (also reordered)\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @return the reordered (output) glyph sequence\n */\n public GlyphSequence reorderCombiningMarks(GlyphDefinitionTable gdef, GlyphSequence gs, int[] unscaledWidths,\n int[][] gpa, String script, String language) {\n return gs;\n }\n\n /**\n * Obtain script specific required positioning features.\n *\n * @return array of suppported positioning features or null\n */\n public abstract String[] getPositioningFeatures();\n\n /**\n * Obtain script specific optional positioning features.\n *\n * @return array of suppported positioning features or null\n */\n public String[] getOptionalPositioningFeatures() {\n return new String[0];\n }\n\n /**\n * Obtain script specific positioning context tester.\n *\n * @return positioning context tester or null\n */\n public abstract ScriptContextTester getPositioningContextTester();\n\n /**\n * Perform positioning processing using a specific set of lookup tables.\n *\n * @param gpos\n * the glyph positioning table that applies\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param fontSize\n * size in device units\n * @param lookups\n * a mapping from lookup specifications to glyph subtables to use for positioning processing\n * @param widths\n * array of default advancements for each glyph\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @return true if some adjustment is not zero; otherwise, false\n */\n public final boolean position(GlyphPositioningTable gpos, GlyphSequence gs, String script, String language,\n int fontSize, Map/*<LookupSpec,List<LookupTable>>*/ lookups, int[] widths,\n int[][] adjustments) {\n return position(gs, script, language, fontSize, assembleLookups(gpos, getPositioningFeatures(), lookups), widths,\n adjustments, getPositioningContextTester());\n }\n\n /**\n * Perform positioning processing using a specific set of ordered glyph table use specifications.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param fontSize\n * size in device units\n * @param usa\n * an ordered array of glyph table use specs\n * @param widths\n * array of default advancements for each glyph in font\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @param sct\n * a script specific context tester (or null)\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, int fontSize, GlyphTable.UseSpec[] usa,\n int[] widths, int[][] adjustments, ScriptContextTester sct) {\n assert usa != null;\n boolean adjusted = false;\n for (int i = 0, n = usa.length; i < n; i++) {\n GlyphTable.UseSpec us = usa[i];\n if (us.position(gs, script, language, fontSize, widths, adjustments, sct)) {\n adjusted = true;\n }\n }\n return adjusted;\n }\n\n /**\n * Assemble ordered array of lookup table use specifications according to the specified features and candidate\n * lookups,\n * where the order of the array is in accordance to the order of the applicable lookup list.\n *\n * @param table\n * the governing glyph table\n * @param features\n * array of feature identifiers to apply\n * @param lookups\n * a mapping from lookup specifications to lists of look tables from which to select lookup tables according to\n * the specified features\n * @return ordered array of assembled lookup table use specifications\n */\n public final GlyphTable.UseSpec[] assembleLookups(GlyphTable table, String[] features,\n Map/*<LookupSpec,List<LookupTable>>*/ lookups) {\n AssembledLookupsKey key = new AssembledLookupsKey(table, features, lookups);\n GlyphTable.UseSpec[] usa;\n if ((usa = assembledLookupsGet(key)) != null) {\n return usa;\n } else {\n return assembledLookupsPut(key, table.assembleLookups(features, lookups));\n }\n }\n\n private GlyphTable.UseSpec[] assembledLookupsGet(AssembledLookupsKey key) {\n return (GlyphTable.UseSpec[]) assembledLookups.get(key);\n }\n\n private GlyphTable.UseSpec[] assembledLookupsPut(AssembledLookupsKey key, GlyphTable.UseSpec[] usa) {\n assembledLookups.put(key, usa);\n return usa;\n }\n\n /**\n * Obtain script processor instance associated with specified script.\n *\n * @param script\n * a script identifier\n * @return a script processor instance or null if none found\n */\n public static synchronized ScriptProcessor getInstance(String script) {\n ScriptProcessor sp = null;\n assert processors != null;\n if ((sp = processors.get(script)) == null) {\n processors.put(script, sp = createProcessor(script));\n }\n return sp;\n }\n\n // [TBD] - rework to provide more configurable binding between script name and script processor constructor\n private static ScriptProcessor createProcessor(String script) {\n ScriptProcessor sp = null;\n int sc = CharScript.scriptCodeFromTag(script);\n if (sc == CharScript.SCRIPT_ARABIC) {\n sp = new ArabicScriptProcessor(script);\n } else if (CharScript.isIndicScript(sc)) {\n sp = IndicScriptProcessor.makeProcessor(script);\n } else {\n sp = new DefaultScriptProcessor(script);\n }\n return sp;\n }\n\n private static class AssembledLookupsKey {\n\n private final GlyphTable table;\n private final String[] features;\n private final Map/*<LookupSpec,List<LookupTable>>*/ lookups;\n\n AssembledLookupsKey(GlyphTable table, String[] features, Map/*<LookupSpec,List<LookupTable>>*/ lookups) {\n this.table = table;\n this.features = features;\n this.lookups = lookups;\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n int hc = 0;\n hc = 7 * hc + (hc ^ table.hashCode());\n hc = 11 * hc + (hc ^ Arrays.hashCode(features));\n hc = 17 * hc + (hc ^ lookups.hashCode());\n return hc;\n }\n\n /** {@inheritDoc} */\n public boolean equals(Object o) {\n if (o instanceof AssembledLookupsKey) {\n AssembledLookupsKey k = (AssembledLookupsKey) o;\n if (!table.equals(k.table)) {\n return false;\n } else if (!Arrays.equals(features, k.features)) {\n return false;\n } else {\n return lookups.equals(k.lookups);\n }\n } else {\n return false;\n }\n }\n\n }\n\n}", "public class CharAssociation implements Cloneable {\n\n // instance state\n private final int offset;\n private final int count;\n private final int[] subIntervals;\n private Map<String, Object> predications;\n\n // class state\n private static volatile Map<String, PredicationMerger> predicationMergers;\n\n interface PredicationMerger {\n\n Object merge(String key, Object v1, Object v2);\n }\n\n /**\n * Instantiate a character association.\n *\n * @param offset\n * into array of Unicode scalar values (in associated IntBuffer)\n * @param count\n * of Unicode scalar values (in associated IntBuffer)\n * @param subIntervals\n * if disjoint, then array of sub-intervals, otherwise null; even\n * members of array are sub-interval starts, and odd members are sub-interval\n * ends (exclusive)\n */\n public CharAssociation(int offset, int count, int[] subIntervals) {\n this.offset = offset;\n this.count = count;\n this.subIntervals = ((subIntervals != null) && (subIntervals.length > 2)) ? subIntervals : null;\n }\n\n /**\n * Instantiate a non-disjoint character association.\n *\n * @param offset\n * into array of UTF-16 code elements (in associated CharSequence)\n * @param count\n * of UTF-16 character code elements (in associated CharSequence)\n */\n public CharAssociation(int offset, int count) {\n this(offset, count, null);\n }\n\n /**\n * Instantiate a non-disjoint character association.\n *\n * @param subIntervals\n * if disjoint, then array of sub-intervals, otherwise null; even\n * members of array are sub-interval starts, and odd members are sub-interval\n * ends (exclusive)\n */\n public CharAssociation(int[] subIntervals) {\n this(getSubIntervalsStart(subIntervals), getSubIntervalsLength(subIntervals), subIntervals);\n }\n\n /** @return offset (start of association interval) */\n public int getOffset() {\n return offset;\n }\n\n /** @return count (number of characer codes in association) */\n public int getCount() {\n return count;\n }\n\n /** @return start of association interval */\n public int getStart() {\n return getOffset();\n }\n\n /** @return end of association interval */\n public int getEnd() {\n return getOffset() + getCount();\n }\n\n /** @return true if association is disjoint */\n public boolean isDisjoint() {\n return subIntervals != null;\n }\n\n /** @return subintervals of disjoint association */\n public int[] getSubIntervals() {\n return subIntervals;\n }\n\n /** @return count of subintervals of disjoint association */\n public int getSubIntervalCount() {\n return (subIntervals != null) ? (subIntervals.length / 2) : 0;\n }\n\n /**\n * @param offset\n * of interval in sequence\n * @param count\n * length of interval\n * @return true if this association is contained within [offset,offset+count)\n */\n public boolean contained(int offset, int count) {\n int s = offset;\n int e = offset + count;\n if (!isDisjoint()) {\n int s0 = getStart();\n int e0 = getEnd();\n return (s0 >= s) && (e0 <= e);\n } else {\n int ns = getSubIntervalCount();\n for (int i = 0; i < ns; i++) {\n int s0 = subIntervals[2 * i + 0];\n int e0 = subIntervals[2 * i + 1];\n if ((s0 >= s) && (e0 <= e)) {\n return true;\n }\n }\n return false;\n }\n }\n\n /**\n * Set predication <KEY,VALUE>.\n *\n * @param key\n * predication key\n * @param value\n * predication value\n */\n public void setPredication(String key, Object value) {\n if (predications == null) {\n predications = new HashMap<String, Object>();\n }\n if (predications != null) {\n predications.put(key, value);\n }\n }\n\n /**\n * Get predication KEY.\n *\n * @param key\n * predication key\n * @return predication KEY at OFFSET or null if none exists\n */\n public Object getPredication(String key) {\n if (predications != null) {\n return predications.get(key);\n } else {\n return null;\n }\n }\n\n /**\n * Merge predication <KEY,VALUE>.\n *\n * @param key\n * predication key\n * @param value\n * predication value\n */\n public void mergePredication(String key, Object value) {\n if (predications == null) {\n predications = new HashMap<String, Object>();\n }\n if (predications != null) {\n if (predications.containsKey(key)) {\n Object v1 = predications.get(key);\n Object v2 = value;\n predications.put(key, mergePredicationValues(key, v1, v2));\n } else {\n predications.put(key, value);\n }\n }\n }\n\n /**\n * Merge predication values V1 and V2 on KEY. Uses registered <code>PredicationMerger</code>\n * if one exists, otherwise uses V2 if non-null, otherwise uses V1.\n *\n * @param key\n * predication key\n * @param v1\n * first (original) predication value\n * @param v2\n * second (to be merged) predication value\n * @return merged value\n */\n public static Object mergePredicationValues(String key, Object v1, Object v2) {\n PredicationMerger pm = getPredicationMerger(key);\n if (pm != null) {\n return pm.merge(key, v1, v2);\n } else if (v2 != null) {\n return v2;\n } else {\n return v1;\n }\n }\n\n /**\n * Merge predications from another CA.\n *\n * @param ca\n * from which to merge\n */\n public void mergePredications(CharAssociation ca) {\n if (ca.predications != null) {\n for (Map.Entry<String, Object> e : ca.predications.entrySet()) {\n mergePredication(e.getKey(), e.getValue());\n }\n }\n }\n\n /** {@inheritDoc} */\n public Object clone() {\n try {\n CharAssociation ca = (CharAssociation) super.clone();\n if (predications != null) {\n ca.predications = new HashMap<String, Object>(predications);\n }\n return ca;\n } catch (CloneNotSupportedException e) {\n return null;\n }\n }\n\n /**\n * Register predication merger PM for KEY.\n *\n * @param key\n * for predication merger\n * @param pm\n * predication merger\n */\n public static void setPredicationMerger(String key, PredicationMerger pm) {\n if (predicationMergers == null) {\n predicationMergers = new HashMap<String, PredicationMerger>();\n }\n if (predicationMergers != null) {\n predicationMergers.put(key, pm);\n }\n }\n\n /**\n * Obtain predication merger for KEY.\n *\n * @param key\n * for predication merger\n * @return predication merger or null if none exists\n */\n public static PredicationMerger getPredicationMerger(String key) {\n if (predicationMergers != null) {\n return predicationMergers.get(key);\n } else {\n return null;\n }\n }\n\n /**\n * Replicate association to form <code>repeat</code> new associations.\n *\n * @param a\n * association to replicate\n * @param repeat\n * count\n * @return array of replicated associations\n */\n public static CharAssociation[] replicate(CharAssociation a, int repeat) {\n CharAssociation[] aa = new CharAssociation[repeat];\n for (int i = 0, n = aa.length; i < n; i++) {\n aa[i] = (CharAssociation) a.clone();\n }\n return aa;\n }\n\n /**\n * Join (merge) multiple associations into a single, potentially disjoint\n * association.\n *\n * @param aa\n * array of associations to join\n * @return (possibly disjoint) association containing joined associations\n */\n public static CharAssociation join(CharAssociation[] aa) {\n CharAssociation ca;\n // extract sorted intervals\n int[] ia = extractIntervals(aa);\n if ((ia == null) || (ia.length == 0)) {\n ca = new CharAssociation(0, 0);\n } else if (ia.length == 2) {\n int s = ia[0];\n int e = ia[1];\n ca = new CharAssociation(s, e - s);\n } else {\n ca = new CharAssociation(mergeIntervals(ia));\n }\n return mergePredicates(ca, aa);\n }\n\n private static CharAssociation mergePredicates(CharAssociation ca, CharAssociation[] aa) {\n for (CharAssociation a : aa) {\n ca.mergePredications(a);\n }\n return ca;\n }\n\n private static int getSubIntervalsStart(int[] ia) {\n int us = Integer.MAX_VALUE;\n int ue = Integer.MIN_VALUE;\n if (ia != null) {\n for (int i = 0, n = ia.length; i < n; i += 2) {\n int s = ia[i + 0];\n int e = ia[i + 1];\n if (s < us) {\n us = s;\n }\n if (e > ue) {\n ue = e;\n }\n }\n if (ue < 0) {\n ue = 0;\n }\n if (us > ue) {\n us = ue;\n }\n }\n return us;\n }\n\n private static int getSubIntervalsLength(int[] ia) {\n int us = Integer.MAX_VALUE;\n int ue = Integer.MIN_VALUE;\n if (ia != null) {\n for (int i = 0, n = ia.length; i < n; i += 2) {\n int s = ia[i + 0];\n int e = ia[i + 1];\n if (s < us) {\n us = s;\n }\n if (e > ue) {\n ue = e;\n }\n }\n if (ue < 0) {\n ue = 0;\n }\n if (us > ue) {\n us = ue;\n }\n }\n return ue - us;\n }\n\n /**\n * Extract sorted sub-intervals.\n */\n private static int[] extractIntervals(CharAssociation[] aa) {\n int ni = 0;\n for (int i = 0, n = aa.length; i < n; i++) {\n CharAssociation a = aa[i];\n if (a.isDisjoint()) {\n ni += a.getSubIntervalCount();\n } else {\n ni += 1;\n }\n }\n int[] sa = new int[ni];\n int[] ea = new int[ni];\n for (int i = 0, k = 0; i < aa.length; i++) {\n CharAssociation a = aa[i];\n if (a.isDisjoint()) {\n int[] da = a.getSubIntervals();\n for (int j = 0; j < da.length; j += 2) {\n sa[k] = da[j + 0];\n ea[k] = da[j + 1];\n k++;\n }\n } else {\n sa[k] = a.getStart();\n ea[k] = a.getEnd();\n k++;\n }\n }\n return sortIntervals(sa, ea);\n }\n\n private static final int[] SORT_INCREMENTS_16\n = {1391376, 463792, 198768, 86961, 33936, 13776, 4592, 1968, 861, 336, 112, 48, 21, 7, 3, 1};\n\n private static final int[] SORT_INCREMENTS_03\n = {7, 3, 1};\n\n /**\n * Sort sub-intervals using modified Shell Sort.\n */\n private static int[] sortIntervals(int[] sa, int[] ea) {\n assert sa != null;\n assert ea != null;\n assert sa.length == ea.length;\n int ni = sa.length;\n int[] incr = (ni < 21) ? SORT_INCREMENTS_03 : SORT_INCREMENTS_16;\n for (int k = 0; k < incr.length; k++) {\n for (int h = incr[k], i = h, n = ni, j; i < n; i++) {\n int s1 = sa[i];\n int e1 = ea[i];\n for (j = i; j >= h; j -= h) {\n int s2 = sa[j - h];\n int e2 = ea[j - h];\n if (s2 > s1) {\n sa[j] = s2;\n ea[j] = e2;\n } else if ((s2 == s1) && (e2 > e1)) {\n sa[j] = s2;\n ea[j] = e2;\n } else {\n break;\n }\n }\n sa[j] = s1;\n ea[j] = e1;\n }\n }\n int[] ia = new int[ni * 2];\n for (int i = 0; i < ni; i++) {\n ia[(i * 2) + 0] = sa[i];\n ia[(i * 2) + 1] = ea[i];\n }\n return ia;\n }\n\n /**\n * Merge overlapping and abutting sub-intervals.\n */\n private static int[] mergeIntervals(int[] ia) {\n int ni = ia.length;\n int i;\n int n;\n int nm;\n int is;\n int ie;\n // count merged sub-intervals\n for (i = 0, n = ni, nm = 0, is = ie = -1; i < n; i += 2) {\n int s = ia[i + 0];\n int e = ia[i + 1];\n if ((ie < 0) || (s > ie)) {\n is = s;\n ie = e;\n nm++;\n } else if (s >= is) {\n if (e > ie) {\n ie = e;\n }\n }\n }\n int[] mi = new int[nm * 2];\n // populate merged sub-intervals\n for (i = 0, n = ni, nm = 0, is = ie = -1; i < n; i += 2) {\n int s = ia[i + 0];\n int e = ia[i + 1];\n int k = nm * 2;\n if ((ie < 0) || (s > ie)) {\n is = s;\n ie = e;\n mi[k + 0] = is;\n mi[k + 1] = ie;\n nm++;\n } else if (s >= is) {\n if (e > ie) {\n ie = e;\n }\n mi[k - 1] = ie;\n }\n }\n return mi;\n }\n\n @Override\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append('[');\n sb.append(offset);\n sb.append(',');\n sb.append(count);\n sb.append(']');\n return sb.toString();\n }\n\n}", "public class GlyphTable {\n\n /** substitution glyph table type */\n public static final int GLYPH_TABLE_TYPE_SUBSTITUTION = 1;\n /** positioning glyph table type */\n public static final int GLYPH_TABLE_TYPE_POSITIONING = 2;\n /** justification glyph table type */\n public static final int GLYPH_TABLE_TYPE_JUSTIFICATION = 3;\n /** baseline glyph table type */\n public static final int GLYPH_TABLE_TYPE_BASELINE = 4;\n /** definition glyph table type */\n public static final int GLYPH_TABLE_TYPE_DEFINITION = 5;\n\n // (optional) glyph definition table in table types other than glyph definition table\n private GlyphTable gdef;\n\n // map from lookup specs to lists of strings, each of which identifies a lookup table (consisting of one or more subtables)\n private Map<LookupSpec, List<String>> lookups;\n\n // map from lookup identifiers to lookup tables\n private Map<String, LookupTable> lookupTables;\n\n // cache for lookups matching\n private Map<LookupSpec, Map<LookupSpec, List<LookupTable>>> matchedLookups;\n\n // if true, then prevent further subtable addition\n private boolean frozen;\n\n /**\n * Instantiate glyph table with specified lookups.\n *\n * @param gdef\n * glyph definition table that applies\n * @param lookups\n * map from lookup specs to lookup tables\n */\n public GlyphTable(GlyphTable gdef, Map<LookupSpec, List<String>> lookups) {\n if ((gdef != null) && !(gdef instanceof GlyphDefinitionTable)) {\n throw new AdvancedTypographicTableFormatException(\"bad glyph definition table\");\n } else if (lookups == null) {\n throw new AdvancedTypographicTableFormatException(\"lookups must be non-null map\");\n } else {\n this.gdef = gdef;\n this.lookups = lookups;\n this.lookupTables = new LinkedHashMap<>();\n this.matchedLookups = new HashMap<>();\n }\n }\n\n /**\n * Obtain glyph definition table.\n *\n * @return (possibly null) glyph definition table\n */\n public GlyphDefinitionTable getGlyphDefinitions() {\n return (GlyphDefinitionTable) gdef;\n }\n\n /**\n * Obtain list of all lookup specifications.\n *\n * @return (possibly empty) list of all lookup specifications\n */\n public List<LookupSpec> getLookups() {\n return matchLookupSpecs(\"*\", \"*\", \"*\");\n }\n\n /**\n * Obtain ordered list of all lookup tables, where order is by lookup identifier, which\n * lexicographic ordering follows the lookup list order.\n *\n * @return (possibly empty) ordered list of all lookup tables\n */\n public List<LookupTable> getLookupTables() {\n TreeSet<String> lids = new TreeSet<>(lookupTables.keySet());\n List<LookupTable> ltl = new ArrayList<>(lids.size());\n for (String lid : lids) {\n ltl.add(lookupTables.get(lid));\n }\n return ltl;\n }\n\n /**\n * Obtain lookup table by lookup id. This method is used by test code, and provides\n * access to embedded lookups not normally accessed by {script, language, feature} lookup spec.\n *\n * @param lid\n * lookup id\n * @return table associated with lookup id or null if none\n */\n public LookupTable getLookupTable(String lid) {\n return lookupTables.get(lid);\n }\n\n /**\n * Add a subtable.\n *\n * @param subtable\n * a (non-null) glyph subtable\n */\n protected void addSubtable(GlyphSubtable subtable) {\n // ensure table is not frozen\n if (frozen) {\n throw new IllegalStateException(\"glyph table is frozen, subtable addition prohibited\");\n }\n // set subtable's table reference to this table\n subtable.setTable(this);\n // add subtable to this table's subtable collection\n String lid = subtable.getLookupId();\n if (lookupTables.containsKey(lid)) {\n LookupTable lt = lookupTables.get(lid);\n lt.addSubtable(subtable);\n } else {\n LookupTable lt = new LookupTable(lid, subtable);\n lookupTables.put(lid, lt);\n }\n }\n\n /**\n * Freeze subtables, i.e., do not allow further subtable addition, and\n * create resulting cached state.\n */\n protected void freezeSubtables() {\n if (!frozen) {\n for (LookupTable lt : lookupTables.values()) {\n lt.freezeSubtables(lookupTables);\n }\n frozen = true;\n }\n }\n\n /**\n * Match lookup specifications according to <script,language,feature> tuple, where\n * '*' is a wildcard for a tuple component.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @return a (possibly empty) array of matching lookup specifications\n */\n public List<LookupSpec> matchLookupSpecs(String script, String language, String feature) {\n Set<LookupSpec> keys = lookups.keySet();\n List<LookupSpec> matches = new ArrayList<>();\n for (LookupSpec ls : keys) {\n if (!\"*\".equals(script)) {\n if (!ls.getScript().equals(script)) {\n continue;\n }\n }\n if (!\"*\".equals(language)) {\n if (!ls.getLanguage().equals(language)) {\n continue;\n }\n }\n if (!\"*\".equals(feature)) {\n if (!ls.getFeature().equals(feature)) {\n continue;\n }\n }\n matches.add(ls);\n }\n return matches;\n }\n\n /**\n * Match lookup specifications according to <script,language,feature> tuple, where\n * '*' is a wildcard for a tuple component.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @return a (possibly empty) map from matching lookup specifications to lists of corresponding lookup tables\n */\n public Map<LookupSpec, List<LookupTable>> matchLookups(String script, String language, String feature) {\n LookupSpec lsm = new LookupSpec(script, language, feature, true, true);\n Map<LookupSpec, List<LookupTable>> lm = matchedLookups.get(lsm);\n if (lm == null) {\n lm = new LinkedHashMap<>();\n List<LookupSpec> lsl = matchLookupSpecs(script, language, feature);\n for (LookupSpec ls : lsl) {\n lm.put(ls, findLookupTables(ls));\n }\n matchedLookups.put(lsm, lm);\n }\n if (lm.isEmpty() && !OTFScript.isDefault(script) && !OTFScript.isWildCard(script)) {\n return matchLookups(OTFScript.DEFAULT, OTFLanguage.DEFAULT, feature);\n } else {\n return lm;\n }\n }\n\n /**\n * Obtain ordered list of glyph lookup tables that match a specific lookup specification.\n *\n * @param ls\n * a (non-null) lookup specification\n * @return a (possibly empty) ordered list of lookup tables whose corresponding lookup specifications match the\n * specified lookup spec\n */\n public List<LookupTable> findLookupTables(LookupSpec ls) {\n TreeSet<LookupTable> lts = new TreeSet<>();\n List<String> ids;\n if ((ids = lookups.get(ls)) != null) {\n for (String lid : ids) {\n LookupTable lt;\n if ((lt = lookupTables.get(lid)) != null) {\n lts.add(lt);\n }\n }\n }\n return new ArrayList<>(lts);\n }\n\n /**\n * Assemble ordered array of lookup table use specifications according to the specified features and candidate\n * lookups,\n * where the order of the array is in accordance to the order of the applicable lookup list.\n *\n * @param features\n * array of feature identifiers to apply\n * @param lookups\n * a mapping from lookup specifications to lists of look tables from which to select lookup tables according to\n * the specified features\n * @return ordered array of assembled lookup table use specifications\n */\n public UseSpec[] assembleLookups(String[] features, Map<LookupSpec, List<LookupTable>> lookups) {\n TreeSet<UseSpec> uss = new TreeSet<UseSpec>();\n for (String feature : features) {\n for (Map.Entry<LookupSpec, List<LookupTable>> e : lookups.entrySet()) {\n LookupSpec ls = e.getKey();\n if (ls.getFeature().equals(feature)) {\n List<LookupTable> ltl = e.getValue();\n if (ltl != null) {\n for (LookupTable lt : ltl) {\n uss.add(new UseSpec(lt, feature));\n }\n }\n }\n }\n }\n return uss.toArray(new UseSpec[uss.size()]);\n }\n\n /**\n * Determine if table supports specific feature, i.e., supports at least one lookup.\n *\n * @param script\n * to qualify feature lookup\n * @param language\n * to qualify feature lookup\n * @param feature\n * to test\n * @return true if feature supported (has at least one lookup)\n */\n public boolean hasFeature(String script, String language, String feature) {\n UseSpec[] usa = assembleLookups(new String[]{feature}, matchLookups(script, language, feature));\n return usa.length > 0;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer(super.toString());\n sb.append(\"{\");\n sb.append(\"lookups={\");\n sb.append(lookups.toString());\n sb.append(\"},lookupTables={\");\n sb.append(lookupTables.toString());\n sb.append(\"}}\");\n return sb.toString();\n }\n\n /**\n * Obtain glyph table type from name.\n *\n * @param name\n * of table type to map to type value\n * @return glyph table type (as an integer constant)\n */\n public static int getTableTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"gsub\".equals(s)) {\n t = GLYPH_TABLE_TYPE_SUBSTITUTION;\n } else if (\"gpos\".equals(s)) {\n t = GLYPH_TABLE_TYPE_POSITIONING;\n } else if (\"jstf\".equals(s)) {\n t = GLYPH_TABLE_TYPE_JUSTIFICATION;\n } else if (\"base\".equals(s)) {\n t = GLYPH_TABLE_TYPE_BASELINE;\n } else if (\"gdef\".equals(s)) {\n t = GLYPH_TABLE_TYPE_DEFINITION;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Resolve references to lookup tables in a collection of rules sets.\n *\n * @param rsa\n * array of rule sets\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public static void resolveLookupReferences(RuleSet[] rsa, Map<String, LookupTable> lookupTables) {\n if ((rsa != null) && (lookupTables != null)) {\n for (RuleSet rs : rsa) {\n if (rs != null) {\n rs.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /**\n * A structure class encapsulating a lookup specification as a <script,language,feature> tuple.\n */\n public static class LookupSpec implements Comparable {\n\n private final String script;\n private final String language;\n private final String feature;\n\n /**\n * Instantiate lookup spec.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n */\n public LookupSpec(String script, String language, String feature) {\n this(script, language, feature, false, false);\n }\n\n /**\n * Instantiate lookup spec.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param permitEmpty\n * if true then permit empty script, language, or feature\n * @param permitWildcard\n * if true then permit wildcard script, language, or feature\n */\n LookupSpec(String script, String language, String feature, boolean permitEmpty, boolean permitWildcard) {\n if ((script == null) || (!permitEmpty && (script.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"script must be non-empty string\");\n } else if ((language == null) || (!permitEmpty && (language.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"language must be non-empty string\");\n } else if ((feature == null) || (!permitEmpty && (feature.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"feature must be non-empty string\");\n } else if (!permitWildcard && script.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"script must not be wildcard\");\n } else if (!permitWildcard && language.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"language must not be wildcard\");\n } else if (!permitWildcard && feature.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"feature must not be wildcard\");\n }\n this.script = script.trim();\n this.language = language.trim();\n this.feature = feature.trim();\n }\n\n /** @return script identifier */\n public String getScript() {\n return script;\n }\n\n /** @return language identifier */\n public String getLanguage() {\n return language;\n }\n\n /** @return feature identifier */\n public String getFeature() {\n return feature;\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n int hc = 0;\n hc = 7 * hc + (hc ^ script.hashCode());\n hc = 11 * hc + (hc ^ language.hashCode());\n hc = 17 * hc + (hc ^ feature.hashCode());\n return hc;\n }\n\n /** {@inheritDoc} */\n public boolean equals(Object o) {\n if (o instanceof LookupSpec) {\n LookupSpec l = (LookupSpec) o;\n if (!l.script.equals(script)) {\n return false;\n } else if (!l.language.equals(language)) {\n return false;\n } else {\n return l.feature.equals(feature);\n }\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int compareTo(Object o) {\n int d;\n if (o instanceof LookupSpec) {\n LookupSpec ls = (LookupSpec) o;\n if ((d = script.compareTo(ls.script)) == 0) {\n if ((d = language.compareTo(ls.language)) == 0) {\n if ((d = feature.compareTo(ls.feature)) == 0) {\n d = 0;\n }\n }\n }\n } else {\n d = -1;\n }\n return d;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer(super.toString());\n sb.append(\"{\");\n sb.append(\"<'\" + script + \"'\");\n sb.append(\",'\" + language + \"'\");\n sb.append(\",'\" + feature + \"'\");\n sb.append(\">}\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>LookupTable</code> class comprising an identifier and an ordered list\n * of glyph subtables, each of which employ the same lookup identifier.\n */\n public static class LookupTable implements Comparable {\n\n private final String id; // lookup identifier\n private final int idOrdinal; // parsed lookup identifier ordinal\n private final List<GlyphSubtable> subtables; // list of subtables\n private boolean doesSub; // performs substitutions\n private boolean doesPos; // performs positioning\n private boolean frozen; // if true, then don't permit further subtable additions\n // frozen state\n private GlyphSubtable[] subtablesArray;\n private static GlyphSubtable[] subtablesArrayEmpty = new GlyphSubtable[0];\n\n /**\n * Instantiate a LookupTable.\n *\n * @param id\n * the lookup table's identifier\n * @param subtable\n * an initial subtable (or null)\n */\n public LookupTable(String id, GlyphSubtable subtable) {\n this(id, makeSingleton(subtable));\n }\n\n /**\n * Instantiate a LookupTable.\n *\n * @param id\n * the lookup table's identifier\n * @param subtables\n * a pre-poplated list of subtables or null\n */\n public LookupTable(String id, List<GlyphSubtable> subtables) {\n this.id = id;\n this.idOrdinal = Integer.parseInt(id.substring(2));\n this.subtables = new LinkedList<GlyphSubtable>();\n if (subtables != null) {\n for (GlyphSubtable st : subtables) {\n addSubtable(st);\n }\n }\n }\n\n /** @return the subtables as an array */\n public GlyphSubtable[] getSubtables() {\n if (frozen) {\n return (subtablesArray != null) ? subtablesArray : subtablesArrayEmpty;\n } else {\n if (doesSub) {\n return subtables.toArray(new GlyphSubstitutionSubtable[subtables.size()]);\n } else if (doesPos) {\n return subtables.toArray(new GlyphPositioningSubtable[subtables.size()]);\n } else {\n return null;\n }\n }\n }\n\n /**\n * Add a subtable into this lookup table's collecion of subtables according to its\n * natural order.\n *\n * @param subtable\n * to add\n * @return true if subtable was not already present, otherwise false\n */\n public boolean addSubtable(GlyphSubtable subtable) {\n boolean added = false;\n // ensure table is not frozen\n if (frozen) {\n throw new IllegalStateException(\"glyph table is frozen, subtable addition prohibited\");\n }\n // validate subtable to ensure consistency with current subtables\n validateSubtable(subtable);\n // insert subtable into ordered list\n for (ListIterator<GlyphSubtable> lit = subtables.listIterator(0); lit.hasNext(); ) {\n GlyphSubtable st = lit.next();\n int d;\n if ((d = subtable.compareTo(st)) < 0) {\n // insert within list\n lit.set(subtable);\n lit.add(st);\n added = true;\n } else if (d == 0) {\n // duplicate entry is ignored\n added = false;\n subtable = null;\n }\n }\n // append at end of list\n if (!added && (subtable != null)) {\n subtables.add(subtable);\n added = true;\n }\n return added;\n }\n\n private void validateSubtable(GlyphSubtable subtable) {\n if (subtable == null) {\n throw new AdvancedTypographicTableFormatException(\"subtable must be non-null\");\n }\n if (subtable instanceof GlyphSubstitutionSubtable) {\n if (doesPos) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable must be positioning subtable, but is: \" + subtable);\n } else {\n doesSub = true;\n }\n }\n if (subtable instanceof GlyphPositioningSubtable) {\n if (doesSub) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable must be substitution subtable, but is: \" + subtable);\n } else {\n doesPos = true;\n }\n }\n if (subtables.size() > 0) {\n GlyphSubtable st = subtables.get(0);\n if (!st.isCompatible(subtable)) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable \" + subtable + \" is not compatible with subtable \" + st);\n }\n }\n }\n\n /**\n * Freeze subtables, i.e., do not allow further subtable addition, and\n * create resulting cached state. In addition, resolve any references to\n * lookup tables that appear in this lookup table's subtables.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void freezeSubtables(Map<String, LookupTable> lookupTables) {\n if (!frozen) {\n GlyphSubtable[] sta = getSubtables();\n resolveLookupReferences(sta, lookupTables);\n this.subtablesArray = sta;\n this.frozen = true;\n }\n }\n\n private void resolveLookupReferences(GlyphSubtable[] subtables, Map<String, LookupTable> lookupTables) {\n if (subtables != null) {\n for (GlyphSubtable st : subtables) {\n if (st != null) {\n st.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /**\n * Determine if this glyph table performs substitution.\n *\n * @return true if it performs substitution\n */\n public boolean performsSubstitution() {\n return doesSub;\n }\n\n /**\n * Perform substitution processing using this lookup table's subtables.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param sct\n * a script specific context tester (or null)\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language, String feature,\n ScriptContextTester sct) {\n if (performsSubstitution()) {\n return GlyphSubstitutionSubtable\n .substitute(gs, script, language, feature, (GlyphSubstitutionSubtable[]) subtablesArray, sct);\n } else {\n return gs;\n }\n }\n\n /**\n * Perform substitution processing on an existing glyph substitution state object using this lookup table's\n * subtables.\n *\n * @param ss\n * a glyph substitution state object\n * @param sequenceIndex\n * if non negative, then apply subtables only at specified sequence index\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSubstitutionState ss, int sequenceIndex) {\n if (performsSubstitution()) {\n return GlyphSubstitutionSubtable.substitute(ss, (GlyphSubstitutionSubtable[]) subtablesArray, sequenceIndex);\n } else {\n return ss.getInput();\n }\n }\n\n /**\n * Determine if this glyph table performs positioning.\n *\n * @return true if it performs positioning\n */\n public boolean performsPositioning() {\n return doesPos;\n }\n\n /**\n * Perform positioning processing using this lookup table's subtables.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param fontSize\n * size in device units\n * @param widths\n * array of default advancements for each glyph in font\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments,\n * in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @param sct\n * a script specific context tester (or null)\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, String feature, int fontSize,\n int[] widths, int[][] adjustments, ScriptContextTester sct) {\n return performsPositioning() && GlyphPositioningSubtable.position(gs, script, language, feature,\n fontSize, (GlyphPositioningSubtable[]) subtablesArray, widths, adjustments, sct);\n }\n\n /**\n * Perform positioning processing on an existing glyph positioning state object using this lookup table's\n * subtables.\n *\n * @param ps\n * a glyph positioning state object\n * @param sequenceIndex\n * if non negative, then apply subtables only at specified sequence index\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphPositioningState ps, int sequenceIndex) {\n return performsPositioning() &&\n GlyphPositioningSubtable.position(ps, (GlyphPositioningSubtable[]) subtablesArray, sequenceIndex);\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n return idOrdinal;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return true if identifier of the specified lookup table is the same\n * as the identifier of this lookup table\n */\n public boolean equals(Object o) {\n if (o instanceof LookupTable) {\n LookupTable lt = (LookupTable) o;\n return idOrdinal == lt.idOrdinal;\n } else {\n return false;\n }\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the result of comparing the identifier of the specified lookup table with\n * the identifier of this lookup table; lookup table identifiers take the form\n * \"lu(DIGIT)+\", with comparison based on numerical ordering of numbers expressed by\n * (DIGIT)+.\n */\n public int compareTo(Object o) {\n if (o instanceof LookupTable) {\n LookupTable lt = (LookupTable) o;\n int i = idOrdinal;\n int j = lt.idOrdinal;\n if (i < j) {\n return -1;\n } else if (i > j) {\n return 1;\n } else {\n return 0;\n }\n } else {\n return -1;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"id = \" + id);\n sb.append(\", subtables = \" + subtables);\n sb.append(\" }\");\n return sb.toString();\n }\n\n private static List<GlyphSubtable> makeSingleton(GlyphSubtable subtable) {\n if (subtable == null) {\n return null;\n } else {\n List<GlyphSubtable> stl = new ArrayList<GlyphSubtable>(1);\n stl.add(subtable);\n return stl;\n }\n }\n\n }\n\n /**\n * The <code>UseSpec</code> class comprises a lookup table reference\n * and the feature that selected the lookup table.\n */\n public static class UseSpec implements Comparable {\n\n /** lookup table to apply */\n private final LookupTable lookupTable;\n /** feature that caused selection of the lookup table */\n private final String feature;\n\n /**\n * Construct a glyph lookup table use specification.\n *\n * @param lookupTable\n * a glyph lookup table\n * @param feature\n * a feature that caused lookup table selection\n */\n public UseSpec(LookupTable lookupTable, String feature) {\n this.lookupTable = lookupTable;\n this.feature = feature;\n }\n\n /** @return the lookup table */\n public LookupTable getLookupTable() {\n return lookupTable;\n }\n\n /** @return the feature that selected this lookup table */\n public String getFeature() {\n return feature;\n }\n\n /**\n * Perform substitution processing using this use specification's lookup table.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param sct\n * a script specific context tester (or null)\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language, ScriptContextTester sct) {\n return lookupTable.substitute(gs, script, language, feature, sct);\n }\n\n /**\n * Perform positioning processing using this use specification's lookup table.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param fontSize\n * size in device units\n * @param widths\n * array of default advancements for each glyph in font\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments,\n * in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @param sct\n * a script specific context tester (or null)\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, int fontSize, int[] widths,\n int[][] adjustments, ScriptContextTester sct) {\n return lookupTable.position(gs, script, language, feature, fontSize, widths, adjustments, sct);\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n return lookupTable.hashCode();\n }\n\n /** {@inheritDoc} */\n public boolean equals(Object o) {\n if (o instanceof UseSpec) {\n UseSpec u = (UseSpec) o;\n return lookupTable.equals(u.lookupTable);\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int compareTo(Object o) {\n if (o instanceof UseSpec) {\n UseSpec u = (UseSpec) o;\n return lookupTable.compareTo(u.lookupTable);\n } else {\n return -1;\n }\n }\n\n }\n\n /**\n * The <code>RuleLookup</code> class implements a rule lookup record, comprising\n * a glyph sequence index and a lookup table index (in an applicable lookup list).\n */\n public static class RuleLookup {\n\n private final int sequenceIndex; // index into input glyph sequence\n private final int lookupIndex; // lookup list index\n private LookupTable lookup; // resolved lookup table\n\n /**\n * Instantiate a RuleLookup.\n *\n * @param sequenceIndex\n * the index into the input sequence\n * @param lookupIndex\n * the lookup table index\n */\n public RuleLookup(int sequenceIndex, int lookupIndex) {\n this.sequenceIndex = sequenceIndex;\n this.lookupIndex = lookupIndex;\n this.lookup = null;\n }\n\n /** @return the sequence index */\n public int getSequenceIndex() {\n return sequenceIndex;\n }\n\n /** @return the lookup index */\n public int getLookupIndex() {\n return lookupIndex;\n }\n\n /** @return the lookup table */\n public LookupTable getLookup() {\n return lookup;\n }\n\n /**\n * Resolve references to lookup tables.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (lookupTables != null) {\n String lid = \"lu\" + Integer.toString(lookupIndex);\n LookupTable lt = (LookupTable) lookupTables.get(lid);\n if (lt != null) {\n this.lookup = lt;\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ sequenceIndex = \" + sequenceIndex + \", lookupIndex = \" + lookupIndex + \" }\";\n }\n\n }\n\n /**\n * The <code>Rule</code> class implements an array of rule lookup records.\n */\n public abstract static class Rule {\n\n private final RuleLookup[] lookups; // rule lookups\n private final int inputSequenceLength; // input sequence length\n\n /**\n * Instantiate a Rule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * the number of glyphs in the input sequence for this rule\n */\n protected Rule(RuleLookup[] lookups, int inputSequenceLength) {\n assert lookups != null;\n this.lookups = lookups;\n this.inputSequenceLength = inputSequenceLength;\n }\n\n /** @return the lookups */\n public RuleLookup[] getLookups() {\n return lookups;\n }\n\n /** @return the input sequence length */\n public int getInputSequenceLength() {\n return inputSequenceLength;\n }\n\n /**\n * Resolve references to lookup tables, e.g., in RuleLookup, to the lookup tables themselves.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (lookups != null) {\n for (RuleLookup l : lookups) {\n if (l != null) {\n l.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ lookups = \" + Arrays.toString(lookups) + \", inputSequenceLength = \" + inputSequenceLength + \" }\";\n }\n\n }\n\n /**\n * The <code>GlyphSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph sequence.\n */\n public static class GlyphSequenceRule extends Rule {\n\n private final int[] glyphs; // glyphs\n\n /**\n * Instantiate a GlyphSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param glyphs\n * the rule's glyph sequence to match, starting with second glyph in sequence\n */\n public GlyphSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] glyphs) {\n super(lookups, inputSequenceLength);\n assert glyphs != null;\n this.glyphs = glyphs;\n }\n\n /**\n * Obtain glyphs. N.B. that this array starts with the second\n * glyph of the input sequence.\n *\n * @return the glyphs\n */\n public int[] getGlyphs() {\n return glyphs;\n }\n\n /**\n * Obtain glyphs augmented by specified first glyph entry.\n *\n * @param firstGlyph\n * to fill in first glyph entry\n * @return the glyphs augmented by first glyph\n */\n public int[] getGlyphs(int firstGlyph) {\n int[] ga = new int[glyphs.length + 1];\n ga[0] = firstGlyph;\n System.arraycopy(glyphs, 0, ga, 1, glyphs.length);\n return ga;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", glyphs = \" + Arrays.toString(glyphs));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ClassSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph class sequence.\n */\n public static class ClassSequenceRule extends Rule {\n\n private final int[] classes; // glyph classes\n\n /**\n * Instantiate a ClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param classes\n * the rule's glyph class sequence to match, starting with second glyph in sequence\n */\n public ClassSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] classes) {\n super(lookups, inputSequenceLength);\n assert classes != null;\n this.classes = classes;\n }\n\n /**\n * Obtain glyph classes. N.B. that this array starts with the class of the second\n * glyph of the input sequence.\n *\n * @return the classes\n */\n public int[] getClasses() {\n return classes;\n }\n\n /**\n * Obtain glyph classes augmented by specified first class entry.\n *\n * @param firstClass\n * to fill in first class entry\n * @return the classes augmented by first class\n */\n public int[] getClasses(int firstClass) {\n int[] ca = new int[classes.length + 1];\n ca[0] = firstClass;\n System.arraycopy(classes, 0, ca, 1, classes.length);\n return ca;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", classes = \" + Arrays.toString(classes));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>CoverageSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph coverage sequence.\n */\n public static class CoverageSequenceRule extends Rule {\n\n private final GlyphCoverageTable[] coverages; // glyph coverages\n\n /**\n * Instantiate a ClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param coverages\n * the rule's glyph coverage sequence to match, starting with first glyph in sequence\n */\n public CoverageSequenceRule(RuleLookup[] lookups, int inputSequenceLength, GlyphCoverageTable[] coverages) {\n super(lookups, inputSequenceLength);\n assert coverages != null;\n this.coverages = coverages;\n }\n\n /** @return the coverages */\n public GlyphCoverageTable[] getCoverages() {\n return coverages;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", coverages = \" + Arrays.toString(coverages));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedGlyphSequenceRule</code> class implements a subclass of <code>GlyphSequenceRule</code>\n * that supports matching on a specific glyph sequence in a specific chained contextual.\n */\n public static class ChainedGlyphSequenceRule extends GlyphSequenceRule {\n\n private final int[] backtrackGlyphs; // backtrack glyphs\n private final int[] lookaheadGlyphs; // lookahead glyphs\n\n /**\n * Instantiate a ChainedGlyphSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param glyphs\n * the rule's input glyph sequence to match, starting with second glyph in sequence\n * @param backtrackGlyphs\n * the rule's backtrack glyph sequence to match, starting with first glyph in sequence\n * @param lookaheadGlyphs\n * the rule's lookahead glyph sequence to match, starting with first glyph in sequence\n */\n public ChainedGlyphSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] glyphs, int[] backtrackGlyphs,\n int[] lookaheadGlyphs) {\n super(lookups, inputSequenceLength, glyphs);\n assert backtrackGlyphs != null;\n assert lookaheadGlyphs != null;\n this.backtrackGlyphs = backtrackGlyphs;\n this.lookaheadGlyphs = lookaheadGlyphs;\n }\n\n /** @return the backtrack glyphs */\n public int[] getBacktrackGlyphs() {\n return backtrackGlyphs;\n }\n\n /** @return the lookahead glyphs */\n public int[] getLookaheadGlyphs() {\n return lookaheadGlyphs;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", glyphs = \" + Arrays.toString(getGlyphs()));\n sb.append(\", backtrackGlyphs = \" + Arrays.toString(backtrackGlyphs));\n sb.append(\", lookaheadGlyphs = \" + Arrays.toString(lookaheadGlyphs));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedClassSequenceRule</code> class implements a subclass of <code>ClassSequenceRule</code>\n * that supports matching on a specific glyph class sequence in a specific chained contextual.\n */\n public static class ChainedClassSequenceRule extends ClassSequenceRule {\n\n private final int[] backtrackClasses; // backtrack classes\n private final int[] lookaheadClasses; // lookahead classes\n\n /**\n * Instantiate a ChainedClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param classes\n * the rule's input glyph class sequence to match, starting with second glyph in sequence\n * @param backtrackClasses\n * the rule's backtrack glyph class sequence to match, starting with first glyph in sequence\n * @param lookaheadClasses\n * the rule's lookahead glyph class sequence to match, starting with first glyph in sequence\n */\n public ChainedClassSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] classes,\n int[] backtrackClasses, int[] lookaheadClasses) {\n super(lookups, inputSequenceLength, classes);\n assert backtrackClasses != null;\n assert lookaheadClasses != null;\n this.backtrackClasses = backtrackClasses;\n this.lookaheadClasses = lookaheadClasses;\n }\n\n /** @return the backtrack classes */\n public int[] getBacktrackClasses() {\n return backtrackClasses;\n }\n\n /** @return the lookahead classes */\n public int[] getLookaheadClasses() {\n return lookaheadClasses;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", classes = \" + Arrays.toString(getClasses()));\n sb.append(\", backtrackClasses = \" + Arrays.toString(backtrackClasses));\n sb.append(\", lookaheadClasses = \" + Arrays.toString(lookaheadClasses));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedCoverageSequenceRule</code> class implements a subclass of <code>CoverageSequenceRule</code>\n * that supports matching on a specific glyph class sequence in a specific chained contextual.\n */\n public static class ChainedCoverageSequenceRule extends CoverageSequenceRule {\n\n private final GlyphCoverageTable[] backtrackCoverages; // backtrack coverages\n private final GlyphCoverageTable[] lookaheadCoverages; // lookahead coverages\n\n /**\n * Instantiate a ChainedCoverageSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param coverages\n * the rule's input glyph class sequence to match, starting with first glyph in sequence\n * @param backtrackCoverages\n * the rule's backtrack glyph class sequence to match, starting with first glyph in sequence\n * @param lookaheadCoverages\n * the rule's lookahead glyph class sequence to match, starting with first glyph in sequence\n */\n public ChainedCoverageSequenceRule(RuleLookup[] lookups, int inputSequenceLength, GlyphCoverageTable[] coverages,\n GlyphCoverageTable[] backtrackCoverages,\n GlyphCoverageTable[] lookaheadCoverages) {\n super(lookups, inputSequenceLength, coverages);\n assert backtrackCoverages != null;\n assert lookaheadCoverages != null;\n this.backtrackCoverages = backtrackCoverages;\n this.lookaheadCoverages = lookaheadCoverages;\n }\n\n /** @return the backtrack coverages */\n public GlyphCoverageTable[] getBacktrackCoverages() {\n return backtrackCoverages;\n }\n\n /** @return the lookahead coverages */\n public GlyphCoverageTable[] getLookaheadCoverages() {\n return lookaheadCoverages;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", coverages = \" + Arrays.toString(getCoverages()));\n sb.append(\", backtrackCoverages = \" + Arrays.toString(backtrackCoverages));\n sb.append(\", lookaheadCoverages = \" + Arrays.toString(lookaheadCoverages));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>RuleSet</code> class implements a collection of rules, which\n * may or may not be the same rule type.\n */\n public static class RuleSet {\n\n private final Rule[] rules; // set of rules\n\n /**\n * Instantiate a Rule Set.\n *\n * @param rules\n * the rules\n * @throws AdvancedTypographicTableFormatException\n * if rules or some element of rules is null\n */\n public RuleSet(Rule[] rules) throws AdvancedTypographicTableFormatException {\n // enforce rules array instance\n if (rules == null) {\n throw new AdvancedTypographicTableFormatException(\"rules[] is null\");\n }\n this.rules = rules;\n }\n\n /** @return the rules */\n public Rule[] getRules() {\n return rules;\n }\n\n /**\n * Resolve references to lookup tables, e.g., in RuleLookup, to the lookup tables themselves.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (rules != null) {\n for (Rule r : rules) {\n if (r != null) {\n r.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ rules = \" + Arrays.toString(rules) + \" }\";\n }\n\n }\n\n /**\n * The <code>HomogenousRuleSet</code> class implements a collection of rules, which\n * must be the same rule type (i.e., same concrete rule class) or null.\n */\n public static class HomogeneousRuleSet extends RuleSet {\n\n /**\n * Instantiate a Homogeneous Rule Set.\n *\n * @param rules\n * the rules\n * @throws AdvancedTypographicTableFormatException\n * if some rule[i] is not an instance of rule[0]\n */\n public HomogeneousRuleSet(Rule[] rules) throws AdvancedTypographicTableFormatException {\n super(rules);\n // find first non-null rule\n Rule r0 = null;\n for (int i = 1, n = rules.length; (r0 == null) && (i < n); i++) {\n if (rules[i] != null) {\n r0 = rules[i];\n }\n }\n // enforce rule instance homogeneity\n if (r0 != null) {\n Class c = r0.getClass();\n for (int i = 1, n = rules.length; i < n; i++) {\n Rule r = rules[i];\n if ((r != null) && !c.isInstance(r)) {\n throw new AdvancedTypographicTableFormatException(\"rules[\" + i + \"] is not an instance of \" + c.getName());\n }\n }\n }\n\n }\n\n }\n\n}", "public class GlyphSequence implements Cloneable {\n\n /** default character buffer capacity in case new character buffer is created */\n private static final int DEFAULT_CHARS_CAPACITY = 8;\n\n /** character buffer */\n private IntBuffer characters;\n /** glyph buffer */\n private IntBuffer glyphs;\n /** association list */\n private List associations;\n /** predications flag */\n private boolean predications;\n\n /**\n * Instantiate a glyph sequence, reusing (i.e., not copying) the referenced\n * character and glyph buffers and associations. If characters is null, then\n * an empty character buffer is created. If glyphs is null, then a glyph buffer\n * is created whose capacity is that of the character buffer. If associations is\n * null, then identity associations are created.\n *\n * @param characters\n * a (possibly null) buffer of associated (originating) characters\n * @param glyphs\n * a (possibly null) buffer of glyphs\n * @param associations\n * a (possibly null) array of glyph to character associations\n * @param predications\n * true if predications are enabled\n */\n public GlyphSequence(IntBuffer characters, IntBuffer glyphs, List associations, boolean predications) {\n if (characters == null) {\n characters = IntBuffer.allocate(DEFAULT_CHARS_CAPACITY);\n }\n if (glyphs == null) {\n glyphs = IntBuffer.allocate(characters.capacity());\n }\n if (associations == null) {\n associations = makeIdentityAssociations(characters.limit(), glyphs.limit());\n }\n this.characters = characters;\n this.glyphs = glyphs;\n this.associations = associations;\n this.predications = predications;\n }\n\n /**\n * Instantiate a glyph sequence, reusing (i.e., not copying) the referenced\n * character and glyph buffers and associations. If characters is null, then\n * an empty character buffer is created. If glyphs is null, then a glyph buffer\n * is created whose capacity is that of the character buffer. If associations is\n * null, then identity associations are created.\n *\n * @param characters\n * a (possibly null) buffer of associated (originating) characters\n * @param glyphs\n * a (possibly null) buffer of glyphs\n * @param associations\n * a (possibly null) array of glyph to character associations\n */\n public GlyphSequence(IntBuffer characters, IntBuffer glyphs, List associations) {\n this(characters, glyphs, associations, false);\n }\n\n /**\n * Instantiate a glyph sequence using an existing glyph sequence, where the new glyph sequence shares\n * the character array of the existing sequence (but not the buffer object), and creates new copies\n * of glyphs buffer and association list.\n *\n * @param gs\n * an existing glyph sequence\n */\n public GlyphSequence(GlyphSequence gs) {\n this(gs.characters.duplicate(), copyBuffer(gs.glyphs), copyAssociations(gs.associations), gs.predications);\n }\n\n /**\n * Instantiate a glyph sequence using an existing glyph sequence, where the new glyph sequence shares\n * the character array of the existing sequence (but not the buffer object), but uses the specified\n * backtrack, input, and lookahead glyph arrays to populate the glyphs, and uses the specified\n * of glyphs buffer and association list.\n * backtrack, input, and lookahead association arrays to populate the associations.\n *\n * @param gs\n * an existing glyph sequence\n * @param bga\n * backtrack glyph array\n * @param iga\n * input glyph array\n * @param lga\n * lookahead glyph array\n * @param bal\n * backtrack association list\n * @param ial\n * input association list\n * @param lal\n * lookahead association list\n */\n public GlyphSequence(GlyphSequence gs, int[] bga, int[] iga, int[] lga, CharAssociation[] bal, CharAssociation[] ial,\n CharAssociation[] lal) {\n this(gs.characters.duplicate(), concatGlyphs(bga, iga, lga), concatAssociations(bal, ial, lal), gs.predications);\n }\n\n /**\n * Obtain reference to underlying character buffer.\n *\n * @return character buffer reference\n */\n public IntBuffer getCharacters() {\n return characters;\n }\n\n /**\n * Obtain array of characters. If <code>copy</code> is true, then\n * a newly instantiated array is returned, otherwise a reference to\n * the underlying buffer's array is returned. N.B. in case a reference\n * to the undelying buffer's array is returned, the length\n * of the array is not necessarily the number of characters in array.\n * To determine the number of characters, use {@link #getCharacterCount}.\n *\n * @param copy\n * true if to return a newly instantiated array of characters\n * @return array of characters\n */\n public int[] getCharacterArray(boolean copy) {\n if (copy) {\n return toArray(characters);\n } else {\n return characters.array();\n }\n }\n\n /**\n * Obtain the number of characters in character array, where\n * each character constitutes a unicode scalar value.\n *\n * @return number of characters available in character array\n */\n public int getCharacterCount() {\n return characters.limit();\n }\n\n /**\n * Obtain glyph id at specified index.\n *\n * @param index\n * to obtain glyph\n * @return the glyph identifier of glyph at specified index\n * @throws IndexOutOfBoundsException\n * if index is less than zero\n * or exceeds last valid position\n */\n public int getGlyph(int index) throws IndexOutOfBoundsException {\n return glyphs.get(index);\n }\n\n /**\n * Set glyph id at specified index.\n *\n * @param index\n * to set glyph\n * @param gi\n * glyph index\n * @throws IndexOutOfBoundsException\n * if index is greater or equal to\n * the limit of the underlying glyph buffer\n */\n public void setGlyph(int index, int gi) throws IndexOutOfBoundsException {\n if (gi > 65535) {\n gi = 65535;\n }\n glyphs.put(index, gi);\n }\n\n /**\n * Obtain reference to underlying glyph buffer.\n *\n * @return glyph buffer reference\n */\n public IntBuffer getGlyphs() {\n return glyphs;\n }\n\n /**\n * Obtain count glyphs starting at offset. If <code>count</code> is\n * negative, then it is treated as if the number of available glyphs\n * were specified.\n *\n * @param offset\n * into glyph sequence\n * @param count\n * of glyphs to obtain starting at offset, or negative,\n * indicating all avaialble glyphs starting at offset\n * @return glyph array\n */\n public int[] getGlyphs(int offset, int count) {\n int ng = getGlyphCount();\n if (offset < 0) {\n offset = 0;\n } else if (offset > ng) {\n offset = ng;\n }\n if (count < 0) {\n count = ng - offset;\n }\n int[] ga = new int[count];\n for (int i = offset, n = offset + count, k = 0; i < n; i++) {\n if (k < ga.length) {\n ga[k++] = glyphs.get(i);\n }\n }\n return ga;\n }\n\n /**\n * Obtain array of glyphs. If <code>copy</code> is true, then\n * a newly instantiated array is returned, otherwise a reference to\n * the underlying buffer's array is returned. N.B. in case a reference\n * to the undelying buffer's array is returned, the length\n * of the array is not necessarily the number of glyphs in array.\n * To determine the number of glyphs, use {@link #getGlyphCount}.\n *\n * @param copy\n * true if to return a newly instantiated array of glyphs\n * @return array of glyphs\n */\n public int[] getGlyphArray(boolean copy) {\n if (copy) {\n return toArray(glyphs);\n } else {\n return glyphs.array();\n }\n }\n\n /**\n * Obtain the number of glyphs in glyphs array, where\n * each glyph constitutes a font specific glyph index.\n *\n * @return number of glyphs available in character array\n */\n public int getGlyphCount() {\n return glyphs.limit();\n }\n\n /**\n * Obtain association at specified index.\n *\n * @param index\n * into associations array\n * @return glyph to character associations at specified index\n * @throws IndexOutOfBoundsException\n * if index is less than zero\n * or exceeds last valid position\n */\n public CharAssociation getAssociation(int index) throws IndexOutOfBoundsException {\n return (CharAssociation) associations.get(index);\n }\n\n /**\n * Obtain reference to underlying associations list.\n *\n * @return associations list\n */\n public List getAssociations() {\n return associations;\n }\n\n /**\n * Obtain count associations starting at offset.\n *\n * @param offset\n * into glyph sequence\n * @param count\n * of associations to obtain starting at offset, or negative,\n * indicating all avaialble associations starting at offset\n * @return associations\n */\n public CharAssociation[] getAssociations(int offset, int count) {\n int ng = getGlyphCount();\n if (offset < 0) {\n offset = 0;\n } else if (offset > ng) {\n offset = ng;\n }\n if (count < 0) {\n count = ng - offset;\n }\n CharAssociation[] aa = new CharAssociation[count];\n for (int i = offset, n = offset + count, k = 0; i < n; i++) {\n if (k < aa.length) {\n aa[k++] = (CharAssociation) associations.get(i);\n }\n }\n return aa;\n }\n\n /**\n * Enable or disable predications.\n *\n * @param enable\n * true if predications are to be enabled; otherwise false to disable\n */\n public void setPredications(boolean enable) {\n this.predications = enable;\n }\n\n /**\n * Obtain predications state.\n *\n * @return true if predications are enabled\n */\n public boolean getPredications() {\n return this.predications;\n }\n\n /**\n * Set predication <KEY,VALUE> at glyph sequence OFFSET.\n *\n * @param offset\n * offset (index) into glyph sequence\n * @param key\n * predication key\n * @param value\n * predication value\n */\n public void setPredication(int offset, String key, Object value) {\n if (predications) {\n CharAssociation[] aa = getAssociations(offset, 1);\n CharAssociation ca = aa[0];\n ca.setPredication(key, value);\n }\n }\n\n /**\n * Get predication KEY at glyph sequence OFFSET.\n *\n * @param offset\n * offset (index) into glyph sequence\n * @param key\n * predication key\n * @return predication KEY at OFFSET or null if none exists\n */\n public Object getPredication(int offset, String key) {\n if (predications) {\n CharAssociation[] aa = getAssociations(offset, 1);\n CharAssociation ca = aa[0];\n return ca.getPredication(key);\n } else {\n return null;\n }\n }\n\n /**\n * Compare glyphs.\n *\n * @param gb\n * buffer containing glyph indices with which this glyph sequence's glyphs are to be compared\n * @return zero if glyphs are the same, otherwise returns 1 or -1 according to whether this glyph sequence's\n * glyphs are lexicographically greater or lesser than the glyphs in the specified string buffer\n */\n public int compareGlyphs(IntBuffer gb) {\n int ng = getGlyphCount();\n for (int i = 0, n = gb.limit(); i < n; i++) {\n if (i < ng) {\n int g1 = glyphs.get(i);\n int g2 = gb.get(i);\n if (g1 > g2) {\n return 1;\n } else if (g1 < g2) {\n return -1;\n }\n } else {\n return -1; // this gb is a proper prefix of specified gb\n }\n }\n return 0; // same lengths with no difference\n }\n\n /** {@inheritDoc} */\n public Object clone() {\n try {\n GlyphSequence gs = (GlyphSequence) super.clone();\n gs.characters = copyBuffer(characters);\n gs.glyphs = copyBuffer(glyphs);\n gs.associations = copyAssociations(associations);\n return gs;\n } catch (CloneNotSupportedException e) {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append('{');\n sb.append(\"chars = [\");\n sb.append(characters);\n sb.append(\"], glyphs = [\");\n sb.append(glyphs);\n sb.append(\"], associations = [\");\n sb.append(associations);\n sb.append(\"]\");\n sb.append('}');\n return sb.toString();\n }\n\n /**\n * Determine if two arrays of glyphs are identical.\n *\n * @param ga1\n * first glyph array\n * @param ga2\n * second glyph array\n * @return true if arrays are botth null or both non-null and have identical elements\n */\n public static boolean sameGlyphs(int[] ga1, int[] ga2) {\n if (ga1 == ga2) {\n return true;\n } else if ((ga1 == null) || (ga2 == null)) {\n return false;\n } else if (ga1.length != ga2.length) {\n return false;\n } else {\n for (int i = 0, n = ga1.length; i < n; i++) {\n if (ga1[i] != ga2[i]) {\n return false;\n }\n }\n return true;\n }\n }\n\n /**\n * Concatenante glyph arrays.\n *\n * @param bga\n * backtrack glyph array\n * @param iga\n * input glyph array\n * @param lga\n * lookahead glyph array\n * @return new integer buffer containing concatenated glyphs\n */\n public static IntBuffer concatGlyphs(int[] bga, int[] iga, int[] lga) {\n int ng = 0;\n if (bga != null) {\n ng += bga.length;\n }\n if (iga != null) {\n ng += iga.length;\n }\n if (lga != null) {\n ng += lga.length;\n }\n IntBuffer gb = IntBuffer.allocate(ng);\n if (bga != null) {\n gb.put(bga);\n }\n if (iga != null) {\n gb.put(iga);\n }\n if (lga != null) {\n gb.put(lga);\n }\n gb.flip();\n return gb;\n }\n\n /**\n * Concatenante association arrays.\n *\n * @param baa\n * backtrack association array\n * @param iaa\n * input association array\n * @param laa\n * lookahead association array\n * @return new list containing concatenated associations\n */\n public static List concatAssociations(CharAssociation[] baa, CharAssociation[] iaa, CharAssociation[] laa) {\n int na = 0;\n if (baa != null) {\n na += baa.length;\n }\n if (iaa != null) {\n na += iaa.length;\n }\n if (laa != null) {\n na += laa.length;\n }\n if (na > 0) {\n List gl = new ArrayList(na);\n if (baa != null) {\n for (int i = 0; i < baa.length; i++) {\n gl.add(baa[i]);\n }\n }\n if (iaa != null) {\n for (int i = 0; i < iaa.length; i++) {\n gl.add(iaa[i]);\n }\n }\n if (laa != null) {\n for (int i = 0; i < laa.length; i++) {\n gl.add(laa[i]);\n }\n }\n return gl;\n } else {\n return null;\n }\n }\n\n /**\n * Join (concatenate) glyph sequences.\n *\n * @param gs\n * original glyph sequence from which to reuse character array reference\n * @param sa\n * array of glyph sequences, whose glyph arrays and association lists are to be concatenated\n * @return new glyph sequence referring to character array of GS and concatenated glyphs and associations of SA\n */\n public static GlyphSequence join(GlyphSequence gs, GlyphSequence[] sa) {\n assert sa != null;\n int tg = 0;\n int ta = 0;\n for (int i = 0, n = sa.length; i < n; i++) {\n GlyphSequence s = sa[i];\n IntBuffer ga = s.getGlyphs();\n assert ga != null;\n int ng = ga.limit();\n List al = s.getAssociations();\n assert al != null;\n int na = al.size();\n assert na == ng;\n tg += ng;\n ta += na;\n }\n IntBuffer uga = IntBuffer.allocate(tg);\n ArrayList ual = new ArrayList(ta);\n for (int i = 0, n = sa.length; i < n; i++) {\n GlyphSequence s = sa[i];\n uga.put(s.getGlyphs());\n ual.addAll(s.getAssociations());\n }\n return new GlyphSequence(gs.getCharacters(), uga, ual, gs.getPredications());\n }\n\n /**\n * Reorder sequence such that [SOURCE,SOURCE+COUNT) is moved just prior to TARGET.\n *\n * @param gs\n * input sequence\n * @param source\n * index of sub-sequence to reorder\n * @param count\n * length of sub-sequence to reorder\n * @param target\n * index to which source sub-sequence is to be moved\n * @return reordered sequence (or original if no reordering performed)\n */\n public static GlyphSequence reorder(GlyphSequence gs, int source, int count, int target) {\n if (source != target) {\n int ng = gs.getGlyphCount();\n int[] ga = gs.getGlyphArray(false);\n int[] nga = new int[ng];\n CharAssociation[] aa = gs.getAssociations(0, ng);\n CharAssociation[] naa = new CharAssociation[ng];\n if (source < target) {\n int t = 0;\n for (int s = 0, e = source; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source + count, e = target; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source, e = source + count; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = target, e = ng; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n } else {\n int t = 0;\n for (int s = 0, e = target; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source, e = source + count; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = target, e = source; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source + count, e = ng; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n }\n return new GlyphSequence(gs, null, nga, null, null, naa, null);\n } else {\n return gs;\n }\n }\n\n private static int[] toArray(IntBuffer ib) {\n if (ib != null) {\n int n = ib.limit();\n int[] ia = new int[n];\n ib.get(ia, 0, n);\n return ia;\n } else {\n return new int[0];\n }\n }\n\n private static List makeIdentityAssociations(int numChars, int numGlyphs) {\n int nc = numChars;\n int ng = numGlyphs;\n List av = new ArrayList(ng);\n for (int i = 0, n = ng; i < n; i++) {\n int k = (i > nc) ? nc : i;\n av.add(new CharAssociation(i, (k == nc) ? 0 : 1));\n }\n return av;\n }\n\n private static IntBuffer copyBuffer(IntBuffer ib) {\n if (ib != null) {\n int[] ia = new int[ib.capacity()];\n int p = ib.position();\n int l = ib.limit();\n System.arraycopy(ib.array(), 0, ia, 0, ia.length);\n return IntBuffer.wrap(ia, p, l - p);\n } else {\n return null;\n }\n }\n\n private static List copyAssociations(List ca) {\n if (ca != null) {\n return new ArrayList(ca);\n } else {\n return ca;\n }\n }\n\n}", "public interface GlyphTester {\n\n /**\n * Perform a test on a glyph identifier.\n *\n * @param gi\n * glyph identififer\n * @param flags\n * that apply to lookup in scope\n * @return true if test is satisfied\n */\n boolean test(int gi, int flags);\n\n}" ]
import java.util.Map; import com.jaredrummler.fontreader.complexscripts.fonts.AdvancedTypographicTableFormatException; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphClassTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphCoverageTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphDefinitionTable; import com.jaredrummler.fontreader.complexscripts.scripts.ScriptProcessor; import com.jaredrummler.fontreader.complexscripts.util.CharAssociation; import com.jaredrummler.fontreader.truetype.GlyphTable; import com.jaredrummler.fontreader.util.GlyphSequence; import com.jaredrummler.fontreader.util.GlyphTester; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
int gi = ss.getGlyph(); int ci; if ((ci = getCoverageIndex(gi)) < 0) { return false; } else { int[] ga = getAlternatesForCoverageIndex(ci, gi); int ai = ss.getAlternatesIndex(ci); int go; if ((ai < 0) || (ai >= ga.length)) { go = gi; } else { go = ga[ai]; } if ((go < 0) || (go > 65535)) { go = 65535; } ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE); ss.consume(1); return true; } } /** * Obtain glyph alternates for coverage index. * * @param ci * coverage index * @param gi * original glyph index * @return sequence of glyphs to substitute for input glyph * @throws IllegalArgumentException * if coverage index is not valid */ public abstract int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException; static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { if (format == 1) { return new AlternateSubtableFormat1(id, sequence, flags, format, coverage, entries); } else { throw new UnsupportedOperationException(); } } } private static class AlternateSubtableFormat1 extends AlternateSubtable { private int[][] gaa; // glyph alternates array, ordered by coverage index AlternateSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { super(id, sequence, flags, format, coverage, entries); populate(entries); } /** {@inheritDoc} */ public List getEntries() { List entries = new ArrayList(gaa.length); for (int i = 0, n = gaa.length; i < n; i++) { entries.add(gaa[i]); } return entries; } /** {@inheritDoc} */ public int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException { if (gaa == null) { return null; } else if (ci >= gaa.length) { throw new IllegalArgumentException( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length); } else { return gaa[ci]; } } private void populate(List entries) { int i = 0; int n = entries.size(); int[][] gaa = new int[n][]; for (Iterator it = entries.iterator(); it.hasNext(); ) { Object o = it.next(); if (o instanceof int[]) { gaa[i++] = (int[]) o; } else { throw new AdvancedTypographicTableFormatException("illegal entries entry, must be int[]: " + o); } } assert i == n; assert this.gaa == null; this.gaa = gaa; } } private abstract static class LigatureSubtable extends GlyphSubstitutionSubtable { public LigatureSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { super(id, sequence, flags, format, coverage); } /** {@inheritDoc} */ public int getType() { return GSUB_LOOKUP_TYPE_LIGATURE; } /** {@inheritDoc} */ public boolean isCompatible(GlyphSubtable subtable) { return subtable instanceof LigatureSubtable; } /** {@inheritDoc} */ public boolean substitute(GlyphSubstitutionState ss) { int gi = ss.getGlyph(); int ci; if ((ci = getCoverageIndex(gi)) < 0) { return false; } else { LigatureSet ls = getLigatureSetForCoverageIndex(ci, gi); if (ls != null) { boolean reverse = false;
GlyphTester ignores = ss.getIgnoreDefault();
8
mpostelnicu/wicket-spring-jpa-bootstrap-boilerplate
web/src/main/java/org/sample/web/pages/HomePage.java
[ "public final class Roles {\r\n\tpublic static final String USER=\"USER\";\r\n\tpublic static final String ADMIN=\"ADMIN\";\r\n}\r", "public class IconPanel<C extends Page> extends Panel {\n\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate final BookmarkablePageLink<Void> bookmarkablePageLink;\n\tprivate final Label label;\n\tprivate Label image;\n\n\tpublic IconPanel(String id, IModel<String> labelModel, Class<C> pageClass, String iconClass) {\n\t\tsuper(id);\n\t\tbookmarkablePageLink=new BookmarkablePageLink<Void>(\"link\", pageClass);\n\t\tadd(bookmarkablePageLink);\t\t\n\t\timage=new Label(\"image\");\n\t\timage.add(AttributeModifier.append(\"class\", \"fa fa-5x \"+iconClass));\n\t\tbookmarkablePageLink.add(image);\n\t\tlabel=new Label(\"label\",labelModel);\n\t\tbookmarkablePageLink.add(label);\n\t}\n\n}", "public class ListCategoryDummyPage extends AbstractListPage<CategoryDummy> {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t@SpringBean\r\n\tprotected CategoryDummyRepository categoryDummyRepository;\r\n\t\r\n\tpublic ListCategoryDummyPage(PageParameters pageParameters) {\r\n\r\n\t\tthis.jpaRepository=categoryDummyRepository;\r\n\t\tthis.editPageClass=EditCategoryDummyPage.class;\r\n\t\tcolumns.add(new PropertyColumn<CategoryDummy,String>(new Model<String>(\"Name\"), \"name\", \"name\"));\r\n\t}\r\n\r\n\r\n}\r", "public class ListDummyPage extends AbstractListPage<Dummy> {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t@SpringBean\r\n\tprotected DummyRepository dummyRepository;\r\n\t\r\n\tpublic ListDummyPage(PageParameters pageParameters) {\r\n\r\n\t\tthis.jpaRepository=dummyRepository;\r\n\t\tthis.editPageClass=EditDummyPage.class;\r\n\t\tcolumns.add(new PropertyColumn<Dummy,String>(new Model<String>(\"Name\"), \"name\", \"name\"));\r\n\t}\r\n\r\n\r\n}\r", "public abstract class AbstractNavPage extends HeaderFooter {\n\n\tprivate static final long serialVersionUID = 1L;\n\tprotected RepeatingView listIcons;\n\n\tpublic AbstractNavPage() {\n\t\tsuper();\n\n\t\tadd(createPageTitleTag(\"nav.title\"));\n\t\tadd(createPageHeading(\"nav.title\"));\n\t\tadd(createPageMessage(\"nav.message\"));\n\n\t\tlistIcons = new RepeatingView(\"listIcons\");\n\t\tadd(listIcons);\n\t}\n\n}" ]
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.model.Model; import org.sample.web.app.security.Roles; import org.sample.web.components.IconPanel; import org.sample.web.pages.lists.ListCategoryDummyPage; import org.sample.web.pages.lists.ListDummyPage; import org.sample.web.pages.nav.AbstractNavPage;
package org.sample.web.pages; /** * @author mpostelnicu * */ @AuthorizeInstantiation({ Roles.USER }) public class HomePage extends AbstractNavPage { private static final long serialVersionUID = 1L; public HomePage() { super(); listIcons.add(new IconPanel<ListDummyPage>(listIcons.newChildId(), Model.of("Dummy"), ListDummyPage.class, "fa-book"));
listIcons.add(new IconPanel<ListCategoryDummyPage>(listIcons.newChildId(),
2
etheriau/jatetoolkit
src/main/java/uk/ac/shef/dcs/oak/jate/util/Utility.java
[ "public class JATEProperties {\r\n private static final Logger _logger = Logger.getLogger(JATEProperties.class);\r\n\r\n private final Properties _properties = new Properties();\r\n private static JATEProperties _ref = null;\r\n\r\n //public static final String NP_FILTER_PATTERN = \"[^a-zA-Z0-9\\\\-]\";\r\n //replaced by the following var:\r\n public static final String TERM_CLEAN_PATTERN = \"[^a-zA-Z0-9\\\\-]\";\r\n public static final String REGEX_QUOTES=\"[\\\"]\";\r\n \r\n\r\n public static final String NLP_PATH = \"jate.system.nlp\";\r\n public static final String TERM_MAX_WORDS = \"jate.system.term.maxwords\";\r\n public static final String TERM_IGNORE_DIGITS = \"jate.system.term.ignore_digits\";\r\n public static final String MULTITHREAD_COUNTER_NUMBERS=\"jate.system.term.frequency.counter.multithread\";\r\n public static final String CONTEXT_PERCENTAGE = \"jate.system.NCValue.percent\";\r\n //Ankit: Adding separate input parameter for ChiSquareAlgorithm\r\n public static final String TOP_FREQUENT_PERCENTAGE = \"jate.system.ChiSquare.percent\";\r\n \r\n public static final String CORPUS_PATH = \"jate.system.corpus_path\";\r\n public static final String RESULT_PATH=\"jate.system.result_path\";\r\n public static final String IGNORE_SINGLE_WORDS = \"jate.system.term.ignore_singleWords\";\r\n public static final String TERM_MIN_FREQ = \"jate.system.term.minFreq\";\r\n \r\n /*code modification RAKE : starts*/\r\n \r\n public static final String TERM_CLEAN_PATTERN_RAKE = \"[^a-zA-Z0-9\\\\-.'&_]\";\r\n \r\n /*code modification RAKE : ends*/\r\n\r\n private JATEProperties() {\r\n read();\r\n }\r\n\r\n public static JATEProperties getInstance() {\r\n if (_ref == null) {\r\n _ref = new JATEProperties();\r\n }\r\n return _ref;\r\n }\r\n\r\n private void read() {\r\n InputStream in = null;\r\n try {\r\n /*InputStream x= getClass().getResourceAsStream(\"/indexing.properties\");*/\r\n in = getClass().getResourceAsStream(\"/jate.properties\");\r\n _properties.load(in);\r\n } catch (IOException e) {\r\n _logger.error( \"Error reading properites\", e );\r\n } finally {\r\n if (in != null) try {\r\n in.close();\r\n in = null;\r\n } catch (IOException e) {\r\n _logger.error( \"Error while closing file\", e );\r\n }\r\n }\r\n }\r\n\r\n private String getProperty(String key) {\r\n return _properties.getProperty(key);\r\n }\r\n\r\n public void setProperty( String key, String value ) {\r\n _properties.setProperty( key, value );\r\n }\r\n\r\n public String getWorkPath() {\r\n return System.getProperty( \"java.io.tmpdir\" );\r\n }\r\n\r\n public String getNLPPath() {\r\n return getProperty(NLP_PATH);\r\n }\r\n\r\n public InputStream getNLPInputStream( String resource ) throws IOException {\r\n String path = getNLPPath();\r\n while ( path.endsWith( \"/\" ) || path.endsWith( \"\\\\\" ) ) {\r\n path = path.substring( 0, path.length() - 1 );\r\n }\r\n while ( resource.startsWith(\"/\") || resource.startsWith( \"\\\\\" ) ) {\r\n resource = resource.substring( 1 );\r\n }\r\n if ( path.startsWith( \"jar:\" ) ) {\r\n return getClass().getResourceAsStream( File.separator + path.substring( \"jar:\".length() ) + File.separator + resource );\r\n }\r\n return new FileInputStream( path + File.separator + resource );\r\n }\r\n\r\n public int getMaxMultipleWords() {\r\n try {\r\n return Integer.valueOf(getProperty(TERM_MAX_WORDS));\r\n } catch (NumberFormatException e) {\r\n return 5;\r\n }\r\n }\r\n\r\n public int getMultithreadCounterNumbers() {\r\n try {\r\n return Integer.valueOf(getProperty(MULTITHREAD_COUNTER_NUMBERS));\r\n } catch (NumberFormatException e) {\r\n return 5;\r\n }\r\n }\r\n\r\n public boolean isIgnoringDigits() {\r\n try {\r\n return Boolean.valueOf(getProperty(TERM_IGNORE_DIGITS));\r\n } catch (Exception e) {\r\n return true;\r\n }\r\n }\r\n \r\n //Ankit: Getter for ChiSquare top frequent percentage parameter\r\n public int getTopFrequentPercentage(){\r\n \ttry{\r\n \t\treturn Integer.valueOf(getProperty(TOP_FREQUENT_PERCENTAGE));\r\n \t} catch (Exception e){\r\n \t\treturn 10;\r\n \t}\r\n }\r\n \r\n //code modification NCValue begins\r\n \r\n public int getPercentage() {\r\n try {\r\n return Integer.valueOf(getProperty(CONTEXT_PERCENTAGE));\r\n } catch (Exception e) {\r\n return 30;\r\n }\r\n }\r\n\r\n // Only use this for testing\r\n public String getCorpusPath() {\r\n return getProperty(CORPUS_PATH);\r\n }\r\n\r\n // Only use this for testing\r\n public String getResultPath() {\r\n return getProperty(RESULT_PATH);\r\n }\r\n \r\n public boolean isIgnoringSingleWords() {\r\n try {\r\n return Boolean.valueOf(getProperty(IGNORE_SINGLE_WORDS));\r\n } catch (Exception e) {\r\n return true;\r\n }\r\n }\r\n \r\n //code modification NCValue ends\r\n \r\n //code modification chi Square begins\r\n public int getMinFreq() {\r\n try {\r\n return Integer.valueOf(getProperty(TERM_MIN_FREQ));\r\n } catch (NumberFormatException e) {\r\n return 4;\r\n }\r\n }\r\n \r\n //code modification chi Square ends\r\n \r\n\r\n}\r", "public abstract class CandidateTermExtractor {\r\n\tprotected IStopList _stoplist;\r\n\tprotected Normalizer _normaliser;\r\n\r\n\t/**\r\n\t * @param c corpus\r\n\t * @return a map containing mappings from term canonical form to its variants found in the corpus\r\n\t * @throws uk.ac.shef.dcs.oak.jate.JATEException\r\n\t */\r\n\tpublic abstract Map<String, Set<String>> extract(Corpus c) throws JATEException;\r\n\r\n\t/**\r\n\t * @param d document\r\n\t * @return a map containing mappings from term canonical form to its variants found in the document\r\n\t * @throws uk.ac.shef.dcs.oak.jate.JATEException\r\n\t */\r\n\tpublic abstract Map<String, Set<String>> extract(Document d) throws JATEException;\r\n\r\n\t/**\r\n\t * @param content a string\r\n\t * @return a map containing mappings from term canonical form to its variants found in the string\r\n\t * @throws uk.ac.shef.dcs.oak.jate.JATEException\r\n\t */\r\n\tpublic abstract Map<String, Set<String>> extract(String content) throws JATEException;\r\n\r\n /**\r\n *\r\n * @param string a string\r\n * @return true if the string contains letter; false otherwise\r\n */\r\n\tpublic static boolean containsLetter(String string) {\r\n\t\tchar[] chars = string.toCharArray();\r\n\t\tfor (char c : chars) {\r\n\t\t\tif (Character.isLetter(c)) return true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n /**\r\n *\r\n * @param string\r\n * @return true if the string contains digit; false otherwise\r\n */\r\n\tpublic static boolean containsDigit(String string) {\r\n\t\tfor (char c : string.toCharArray()) {\r\n\t\t\tif (Character.isDigit(c)) return true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n /**\r\n * Replaces [^a-zA-Z\\-] characters with \" \"(white space). Used to normalize texts and candidate terms before counting\r\n * frequencies\r\n * @param string input string to be processed\r\n * @param pattern regular expression pattern defining characters to be replaced by \" \" (white space)\r\n * @return\r\n */\r\n public static String applyCharacterReplacement(String string, String pattern) {\r\n return string.replaceAll(pattern, \" \").replaceAll(\"\\\\s+\", \" \").trim();\r\n }\r\n\r\n /**\r\n * If the input string contains \"and\", \"or\" and \",\" , it is assumed to contain multiple candidate terms, and is split.\r\n * This method is used to process extracted candidate terms. Due to imperfections of NLP tools, some times candidate\r\n * terms can be noisy and need to be further processed/normalized.\r\n *\r\n * @param string input string\r\n * @return individual strings seperated by \"and\", \"or\" and \",\"\r\n */\r\n \r\n //Code modification begins : the second and third 'if' changed to 'else if'\r\n \r\n public static String[] applySplitList(String string) {\r\n StringBuilder sb = new StringBuilder();\r\n if (string.indexOf(\" and \") != -1) {\r\n String[] parts = string.split(\"\\\\band\\\\b\");\r\n for (String s : parts) sb.append(s.trim()).append(\"|\");\r\n }\r\n else if (string.indexOf(\" or \") != -1) {\r\n String[] parts = string.split(\"\\\\bor\\\\b\");\r\n for (String s : parts) sb.append(s.trim()).append(\"|\");\r\n }\r\n else if (string.indexOf(\",\") != -1) {\r\n if (!containsDigit(string)) {\r\n String[] parts = string.split(\"\\\\,\");\r\n for (String s : parts) sb.append(s.trim()).append(\"|\");\r\n }\r\n } else {\r\n sb.append(string);\r\n }\r\n String v = sb.toString();\r\n if (v.endsWith(\"|\")) v = v.substring(0, v.lastIndexOf(\"|\"));\r\n return v.split(\"\\\\|\");\r\n }\r\n \r\n //code modification ends\r\n\r\n\r\n /**\r\n * If a string beings or ends with a stop word (e.g., \"the\"), the stop word is removed.\r\n *\r\n * This method is used to further process/normalize extracted candidate terms. Due to imperfections of NLP tools,\r\n * sometimes candidate terms can be noisy and needs further normalization.\r\n *\r\n * @param string\r\n * @param stop\r\n * @return null if the string is a stopword; otherwise the normalized string\r\n */\r\n public static String applyTrimStopwords(String string, IStopList stop, Normalizer normalizer) {\r\n //check the entire string first (e.g., \"e. g. \" and \"i. e. \" which will fail the following checks\r\n // String s = normalizer.normalize(string);\r\n \t\r\n \tif(stop.isStopWord(normalizer.normalize(string).replaceAll(\"\\\\s+\",\"\").trim()))\r\n return null;\r\n\r\n String[] e = string.split(\"\\\\s+\");\r\n if (e == null || e.length < 1) return string;\r\n\r\n int head = e.length;\r\n int end = -1;\r\n for (int i = 0; i < e.length; i++) {\r\n if (!stop.isStopWord(e[i])) {\r\n head = i;\r\n break;\r\n }\r\n }\r\n\r\n for (int i = e.length - 1; i > -1; i--) {\r\n if (!stop.isStopWord(e[i])) {\r\n end = i;\r\n break;\r\n }\r\n }\r\n\r\n if (head <= end) {\r\n String trimmed = \"\";\r\n for (int i = head; i <= end; i++) {\r\n trimmed += e[i] + \" \";\r\n }\r\n return trimmed.trim();\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * This method is used to check if candidate term is a possible noisy symbol or non-term.\r\n *\r\n * @param string\r\n * @return true if the string contains at least 2 letters or digits; false otherwise\r\n */\r\n public static boolean hasReasonableNumChars(String string) {\r\n int len = string.length();\r\n if (len < 2) return false;\r\n if (len < 5) {\r\n char[] chars = string.toCharArray();\r\n int num = 0;\r\n for (int i = 0; i < chars.length; i++) {\r\n if (Character.isLetter(chars[i]) || Character.isDigit(chars[i]))\r\n num++;\r\n if (num > 2) break;\r\n }\r\n if (num > 2) return true;\r\n return false;\r\n }\r\n return true;\r\n }\r\n}\r", "public interface IStopList {\n /**\n * @return true if the word is a stop word, false if otherwise\n */\n boolean isStopWord( String word );\n}", "public class Lemmatizer extends Normalizer {\r\n\r\n\tprivate EngLemmatiser lemmatizer;\r\n\tprivate final Map<String, Integer> tagLookUp = new HashMap<String, Integer>();\r\n\r\n\tpublic Lemmatizer() {\r\n\t\tinit();\r\n\t}\r\n\r\n\t/**\r\n\t * @param value original word\r\n\t * @param pos the part of speech of the last word\r\n\t * @return the lemma of original word\r\n\t */\r\n\tpublic String getLemma(String value, String pos) {\r\n\t\tint POS = tagLookUp.get(pos);\r\n\t\tif (POS == 0)\r\n\t\t\treturn lemmatizer.lemmatize(value);\r\n\t\telse\r\n\t\t\treturn lemmatizer.lemmatize(value, POS);\r\n\t}\r\n\r\n\t/**\r\n\t * Lemmatise a phrase or word. If a phrase, only lemmatise the most RHS word.\r\n\t * @param value\r\n\t * @return\r\n\t */\r\n\tpublic String normalize(String value) {\r\n\t\tif(value.indexOf(\" \")==-1||value.endsWith(\" s\")||value.endsWith(\"'s\")) //if string is a single word, or it is in \"XYZ's\" form where the ' char has been removed\r\n\t\t\treturn lemmatizer.lemmatize(value,1).trim();\r\n\r\n\t\tString part1 = value.substring(0,value.lastIndexOf(\" \"));\r\n\t\tString part2 = lemmatizer.lemmatize(value.substring(value.lastIndexOf(\" \")+1),1);\r\n\t\treturn part1+\" \"+part2.trim();\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Lemmatise every word in the input string\r\n\t * @param in\r\n\t * @return the lemmatised string\r\n\t */\r\n\tpublic String normalizeContent(String in){\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tStringTokenizer tokenizer = new StringTokenizer(in);\r\n\t\twhile(tokenizer.hasMoreTokens()){\r\n\t\t\tString tok=tokenizer.nextToken();\r\n\t\t\tsb.append(normalize(tok)).append(\" \");\r\n\t\t}\r\n\t\treturn sb.toString().trim();\r\n\t}\r\n\r\n\r\n\tprivate void init() {\r\n\t\t// Initializes the temporary directory if required.\r\n\t\tfinal JATEProperties instance = JATEProperties.getInstance();\r\n\t\tString path = instance.getNLPPath();\r\n\t\tif ( path.startsWith( \"jar:\" ) ) {\r\n\t\t\tString dir = instance.getWorkPath() + File.separator + \"lemmatizer\";\r\n\t\t\tpath = dir;\r\n\t\t\tFile directory = new File(dir);\r\n\t\t\tif ( !directory.exists() ) {\r\n\t\t\t\tif ( !directory.mkdirs() ) {\r\n\t\t\t\t\tthrow new UnsupportedOperationException(\"Could not initialize \" + directory);\r\n\t\t\t\t}\r\n\t\t\t\tfor ( String file : new String[]{ \"adj.exc\", \"adj.index\", \"adv.exc\", \"adv.index\", \"noun.exc\", \"stopwordexc.list\", \"umlserror.list\", \"verb.exc\", \"verb.index\" } ) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tInputStream input = null;\r\n\t\t\t\t\t\tOutputStream output = null;\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\tinput = instance.getNLPInputStream( \"lemmatizer\" + File.separator + file );\r\n\t\t\t\t\t\t\tif ( input == null ) {\r\n\t\t\t\t\t\t\t\tthrow new IOException( \"Unable to read: \" + file );\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\toutput = new FileOutputStream( dir + File.separator + file );\r\n\t\t\t\t\t\t\tbyte [] bytes = new byte[ 4096 ];\r\n\t\t\t\t\t\t\twhile ( true ) {\r\n\t\t\t\t\t\t\t\tint len = input.read( bytes );\r\n\t\t\t\t\t\t\t\tif ( len == -1 ) {\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\toutput.write( bytes, 0, len );\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} finally {\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tif ( input != null ) {\r\n\t\t\t\t\t\t\t\t\tinput.close();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} finally {\r\n\t\t\t\t\t\t\t\tif ( output != null ) {\r\n\t\t\t\t\t\t\t\t\toutput.close();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} catch ( IOException ioe ) {\r\n\t\t\t\t\t\tthrow new UnsupportedOperationException( \"Unable to copy data\", ioe );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlemmatizer = new EngLemmatiser( path, false, true );\r\n\t\ttagLookUp.put(\"NN\", 1);\r\n\t\ttagLookUp.put(\"NNS\", 1);\r\n\t\ttagLookUp.put(\"NNP\", 1);\r\n\t\ttagLookUp.put(\"NNPS\", 1);\r\n\t\ttagLookUp.put(\"VB\", 2);\r\n\t\ttagLookUp.put(\"VBG\", 2);\r\n\t\ttagLookUp.put(\"VBD\", 2);\r\n\t\ttagLookUp.put(\"VBN\", 2);\r\n\t\ttagLookUp.put(\"VBP\", 2);\r\n\t\ttagLookUp.put(\"VBZ\", 2);\r\n\t\ttagLookUp.put(\"JJ\", 3);\r\n\t\ttagLookUp.put(\"JJR\", 3);\r\n\t\ttagLookUp.put(\"JJS\", 3);\r\n\t\ttagLookUp.put(\"RB\", 4);\r\n\t\ttagLookUp.put(\"RBR\", 4);\r\n\t\ttagLookUp.put(\"RBS\", 4);\r\n\t}\r\n\r\n}\r", "public class StopList implements IStopList {\r\n\r\n\tprivate final Set<String> words = new HashSet<String>();\r\n\r\n\tprivate final boolean _caseSensitive;\r\n\r\n\t/**\r\n\t * Creates an instance of stop word list\r\n\t * @param caseSensitive whether the list should ignore cases\r\n\t * @throws IOException\r\n\t */\r\n\tpublic StopList (final boolean caseSensitive) throws IOException {\r\n\t\tsuper();\r\n\t\t_caseSensitive =caseSensitive;\r\n\t\tloadStopList( JATEProperties.getInstance().getNLPInputStream( \"stoplist.txt\" ),_caseSensitive);\r\n\t}\r\n\r\n\t/**\r\n\t * @param word\r\n\t * @return true if the word is a stop word, false if otherwise\r\n\t */\r\n\tpublic boolean isStopWord(String word){\r\n\t\tif(!_caseSensitive) return words.contains(word.toLowerCase());\r\n\t\treturn words.contains(word);\r\n\t}\r\n\r\n\tprivate void loadStopList(final InputStream stream, final boolean lowercase) throws IOException {\r\n final BufferedReader reader = new BufferedReader(new InputStreamReader( stream ));\r\n\t try {\r\n\t\t String line;\r\n\t\t while ((line = reader.readLine()) != null) {\r\n\t\t\t line = line.trim();\r\n\t\t\t if (line.equals(\"\") || line.startsWith(\"//\")) continue;\r\n\t\t\t if (lowercase) words.add(line.toLowerCase());\r\n\t\t\t else words.add(line);\r\n\t\t }\r\n\t } finally {\r\n\t\t reader.close();\r\n\t }\r\n }\r\n\r\n}\r" ]
import java.io.IOException; import java.util.HashSet; import java.util.Set; import uk.ac.shef.dcs.oak.jate.JATEProperties; import uk.ac.shef.dcs.oak.jate.core.npextractor.CandidateTermExtractor; import uk.ac.shef.dcs.oak.jate.util.control.IStopList; import uk.ac.shef.dcs.oak.jate.util.control.Lemmatizer; import uk.ac.shef.dcs.oak.jate.util.control.StopList;
package uk.ac.shef.dcs.oak.jate.util; /** Newly added. Contains the common utility functions for NCValue Algorithm and Chi Square Algorithm. * **/ public class Utility{ /** Returns the input string after lemmatization. */ public static String getLemma(String context, IStopList stoplist, Lemmatizer lemmatizer) throws IOException{ String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); return lemma; } /** Returns the input string after lemmatization. */ //Ankit: Removing this method as it is not really required. /* public static String getLemma(String context) throws IOException{ StopList stoplist = new StopList(true); Lemmatizer lemmatizer = new Lemmatizer(); String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); return lemma; } */ public static String getLemmaChiSquare(String context, StopList stoplist, Lemmatizer lemmatizer) throws IOException{ String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); //Ankit: unnecessary output information //else{ // _logger.info("null lemma" + context.trim()); //} return lemma; } /** Returns the sentence after modifying it by replacing the characters which are not in the character set [a-zA-Z0-9 -] by a space. */ public static String getModifiedSent(String sentence) { StringBuilder modified_sent = new StringBuilder(); String[] split_sent = sentence.split(" "); for(String s: split_sent){
s= CandidateTermExtractor.applyCharacterReplacement(s, JATEProperties.TERM_CLEAN_PATTERN);
0
emop/EmopAndroid
src/com/emop/client/fragment/RebateListFragment.java
[ "public class WebViewActivity extends BaseActivity {\r\n\tpublic final static int WEB_DONE = 1;\r\n\tpublic final static int WEB_MSG = 2;\r\n\tpublic final static int WEB_LOADING = 3;\r\n\tpublic final static int WEB_LOADED = 4;\t\r\n\t\r\n\tprivate ProgressBar processBar = null;\r\n\tprivate WebView web = null;\r\n\tprivate TextView titleView = null;\r\n\tprivate String curURL = \"\";\r\n \r\n\t@Override\r\n public void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.web_view);\r\n \r\n this.web = (WebView)findViewById(R.id.web);\r\n this.processBar = (ProgressBar)findViewById(R.id.progressbar_loading);\r\n \r\n web.setVerticalScrollBarEnabled(false);\r\n web.setHorizontalScrollBarEnabled(false);\r\n //web.getSettings().s\r\n web.getSettings().setJavaScriptEnabled(true);\r\n web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);\r\n web.setDownloadListener(new DownloadListener(){\r\n\t\t\t@Override\r\n\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition,\r\n\t\t\t\t\tString mimetype, long contentLength) {\r\n\t Uri uri = Uri.parse(url); \r\n\t Intent intent = new Intent(Intent.ACTION_VIEW, uri); \r\n\t startActivity(intent); \r\n\t\t\t}\r\n });\r\n \r\n CookieSyncManager.createInstance(this);\r\n \r\n //web.setWebViewClient(new TaokeWebViewClient());\r\n \r\n titleView = (TextView)findViewById(R.id.title);\r\n \r\n titleView.setLongClickable(true); \r\n titleView.setOnLongClickListener(new OnLongClickListener(){\r\n\t\t\t@Override\r\n\t\t\tpublic boolean onLongClick(View arg0) {\r\n\t\t\t\tif(curURL != null && curURL.length() > 1){\r\n\t\t Uri uri = Uri.parse(curURL); \r\n\t\t Intent intent = new Intent(Intent.ACTION_VIEW, uri); \r\n\t\t startActivity(intent); \r\n\t\t\t\t}\r\n\t\t\t\treturn false;\r\n\t\t\t}\t\t\t\r\n }); \r\n }\r\n\t\r\n protected void onResume (){\r\n \tsuper.onResume();\r\n \t\r\n \tIntent intent = this.getIntent();\r\n \tString title = intent.getStringExtra(\"title\");\r\n \tif(title != null && title.trim().length() > 0 && titleView != null){\r\n \t\ttitleView.setText(title);\r\n \t}\r\n \tif(intent.getBooleanExtra(\"taobaoLogin\", false)){\r\n \t\tweb.setWebViewClient(new TaobaoLoginWebClient(this, processBar));\r\n \t\tif(processBar != null){\r\n \t\t\tprocessBar.setVisibility(View.INVISIBLE);\r\n \t\t}\r\n \t}else {\r\n \t\tweb.setWebViewClient(new TaokeWebViewClient());\r\n \t} \t\r\n \t//Uri dataUri = intent.getData(); \r\n \tString http_url = intent.getStringExtra(\"http_url\");\r\n \tString num_iid = intent.getStringExtra(\"taoke_num_iid\");\r\n\r\n \tboolean autoMobile = autoConvertMobileLink(num_iid);\r\n \tif(!autoMobile && http_url != null && http_url.startsWith(\"http\")){\r\n \t\tLog.d(Constants.TAG_EMOP, \"loading url:\" + http_url);\r\n \t\tweb.loadUrl(http_url);\r\n \t}\r\n \t\r\n \t/**\r\n \t * 如果是淘宝商品,在客户端转换后跳转。\r\n \t */\r\n \tif(autoMobile){\r\n \t\tloadTaoboItem(num_iid, http_url);\r\n \t}\r\n }\r\n \r\n /**\r\n * 判断是否需要自动转换,移动版链接。只有冒泡自己的帐号才需要转换链接。\r\n * @param num_iid\r\n * @return\r\n */\r\n protected boolean autoConvertMobileLink(String num_iid){\r\n \tif(num_iid == null) return false;\r\n \tif(client.trackUserId != null && !client.trackUserId.equals(\"11\")){\r\n \t\treturn false;\r\n \t}\r\n \treturn true;\r\n }\r\n \r\n protected void loadTaoboItem(final String numiid, final String shortUrl){\r\n \tfinal TopAndroidClient client = TopAndroidClient.getAndroidClientByAppKey(Constants.TAOBAO_APPID);\r\n \tTopParameters param = new TopParameters();\r\n \t\r\n \tparam.setMethod(\"taobao.taobaoke.widget.items.convert\");\r\n \tparam.addFields(\"click_url\",\"num_iid\");\r\n \tparam.addParam(\"is_mobile\", \"true\");\r\n \tparam.addParam(\"num_iids\", numiid); \t\r\n\t\t\r\n \tTopApiListener listener = new TopApiListener(){\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onComplete(JSONObject json) {\r\n\t\t\t\t// TODO Auto-generated method stub\r\n\t\t\t\tString click = null;\r\n\t\t\t\t\r\n\t\t\t\ttry{\r\n\t\t\t\t\tJSONArray items = json.getJSONObject(\"taobaoke_widget_items_convert_response\").\r\n\t\t\t\t\t\tgetJSONObject(\"taobaoke_items\").getJSONArray(\"taobaoke_item\");\r\n\t\t\t\t\tJSONObject item = items.getJSONObject(0);\r\n\t\t\t\t\tclick = item.getString(\"click_url\");\r\n\t\t\t\t\tLog.i(\"emop\", \"num iid:\" + numiid + \", convert click url:\" + click);\r\n\t\t\t\t}catch(Exception e){\r\n\t\t\t\t\tLog.w(\"emop\", \"error e:\" + e.toString(), e);\r\n\t\t\t\t}finally{\r\n\t\t\t\t\tif(click != null){\r\n\t\t\t\t\t\tloadMobileUrl(click);\r\n\t\t\t\t\t}else {\t\t\t\t\t\t\r\n\t\t\t\t\t\tloadShortUrl(shortUrl);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onError(ApiError error) {\r\n\t\t\t\tLog.w(\"emop\", \"error e:\" + error.toString());\r\n\t\t\t\tloadShortUrl(shortUrl);\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onException(Exception e) {\r\n\t\t\t\tLog.w(\"emop\", \"error e:\" + e.toString(), e);\r\n\t\t\t\tloadShortUrl(shortUrl);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tprivate void loadMobileUrl(String url){\r\n\t\t\t\tweb.loadUrl(url);\r\n\t\t\t}\r\n\r\n\t\t\tprivate void loadShortUrl(String url){\r\n\t\t\t\tweb.loadUrl(url);\r\n\t\t\t}\r\n\t\t\t\r\n \t};\r\n \tclient.api(param, null, listener, true);\r\n }\r\n \r\n public void onFinish(View v){\r\n \tonBackPressed();\r\n }\r\n \r\n public void onBackPressed() {\r\n \tif(web.canGoBack()){\r\n \t\tweb.goBack();\r\n \t}else {\r\n \t\tfinish();\r\n \t}\r\n }\r\n \r\n public Handler handler = new Handler(){\r\n \t\r\n \tpublic void handleMessage(final Message msg) {\r\n \t\tString message = null;\r\n \t\tif(msg.obj != null){\r\n \t\t\tmessage = msg.obj.toString();\r\n \t\t\tif(message != null){\r\n \t\t\t\tToast.makeText(WebViewActivity.this, message, Toast.LENGTH_LONG).show();\r\n \t\t\t}\r\n \t\t}\r\n \t\tif(msg.what == WEB_DONE){\r\n \t\t\tfinish();\r\n \t\t}else if(msg.what == WEB_LOADING){\r\n \t\t\tprocessBar.setVisibility(View.VISIBLE);\r\n \t\t}else if(msg.what == WEB_LOADED){\r\n \t\t\tprocessBar.setVisibility(View.INVISIBLE);\r\n \t\t}\r\n \t}\r\n\r\n }; \r\n \r\n private class TaokeWebViewClient extends WebViewClient {\r\n \tprivate boolean inTaobao = false;\r\n\r\n @Override\r\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\r\n super.onPageStarted(view, url, favicon);\r\n Log.d(\"xx\", \"url:\" + url);\r\n curURL = url;\r\n //mSpinner.show();\r\n processBar.setVisibility(View.VISIBLE);\r\n }\r\n\r\n @Override\r\n public void onPageFinished(WebView view, String url) {\r\n super.onPageFinished(view, url);\r\n Log.d(\"xx\", \"done url:\" + url);\r\n //curURL = url;\r\n \r\n /**\r\n * 刚进入宝贝详情页时,清空回退记录。这样在点回退的时候才能退出详情页。\r\n * 不然是退回到短网址页面,会再次进入详情页。\r\n */\r\n if((!inTaobao && isProductUrl(url)) || url.endsWith(\"taobao.com/\")){\r\n \tinTaobao = true;\r\n \tweb.clearHistory();\r\n } \r\n processBar.setVisibility(View.INVISIBLE);\r\n }\r\n \r\n @Override\r\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\r\n Log.d(TAG_EMOP, \"Redirect URL: \" + url);\r\n \r\n int i = url.indexOf(\"m.taobao.com\");\r\n \tif(i > 0 && i < 15 && isAvilible(getApplicationContext(), \"com.taobao.taobao\")){\r\n \t\tIntent intent = new Intent();\t\t\t\r\n \t\t//intent.setClass(this, LoginActivity.class);\r\n \t\turl = url.replaceFirst(\"http:\", \"itaobao:\");\r\n \t\tintent.setAction(Intent.ACTION_VIEW);\r\n \t\tintent.setData(Uri.parse(url));\r\n \t//\tintent.setComponent(ComponentName.unflattenFromString(\"com.taobao.taobao/com.taobao.tao.detail.DetailActivity\"))\r\n \t\tstartActivityForResult(intent, OPEN_TAOBAO); \t\r\n \t\tfinish();\r\n \t\treturn true;\r\n \t}else {\r\n \t\treturn false;\r\n \t}\r\n }\r\n \r\n public boolean isProductUrl(String url){\r\n \tif(url.indexOf(\"s.click\") > 0 || url.indexOf(\"view_shop.htm\") > 0){\r\n \t\treturn false;\r\n \t}\r\n \tif(url.indexOf(\"tmall.com\") > 0 || url.indexOf(\"m.taobao.com\") > 0){\r\n \t\treturn true;\r\n \t}\r\n \treturn false;\r\n }\r\n }\r\n \r\n private boolean isAvilible(Context context, String packageName){ \r\n final PackageManager packageManager = context.getPackageManager();//获取packagemanager \r\n List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息 \r\n List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名 \r\n //从pinfo中将包名字逐一取出,压入pName list中 \r\n if(pinfo != null){ \r\n for(int i = 0; i < pinfo.size(); i++){ \r\n String pn = pinfo.get(i).packageName; \r\n if(pn.startsWith(packageName)){\r\n \treturn true;\r\n }\r\n //pName.add(pn); \r\n } \r\n } \r\n return false; //pName.contains(packageName);//判断pName中是否有目标程序的包名,有TRUE,没有FALSE \r\n } \r\n}\r", "public class FmeiClient {\r\n\t//public ImageCache cache = null;\r\n\t//需要长时间保存的图片,例如分类,热门。\r\n\tpublic ImageLoader appImgLoader = null;\r\n\t\r\n\t//临时图片加载,比如瀑布流图片。\r\n\tpublic ImageLoader tmpImgLoader = null;\r\n\t\r\n\tpublic String userId = null;\r\n\t//推荐应用下载的用户ID. 应用里面的链接都是包含这个用的PID\r\n\tpublic String trackUserId = null;\r\n\tpublic String trackPID = null;\r\n\t\r\n\t/**\r\n\t * 收藏夹ID.\r\n\t */\r\n\tpublic String favoriteId = null;\r\n\tpublic boolean isInited = false;\r\n\r\n\tprivate static FmeiClient ins = null;\r\n\tprivate TaodianApi api = null;\r\n\tprivate Context ctx = null;\r\n\tprivate AppConfig config = null;\r\n\t\r\n\t//private stai\r\n\t\r\n\tpublic FmeiClient(){\r\n\t\tthis.api = new TaodianApi();\r\n\t}\r\n\t\r\n\tpublic static FmeiClient getInstance(Context ctx){\r\n\t\treturn getInstance(ctx, false);\r\n\t}\r\n\t\r\n\tpublic static synchronized FmeiClient getInstance(Context ctx, boolean check_conn){\r\n\t\tif(ins == null){\r\n\t\t\tins = new FmeiClient();\r\n\t\t}\r\n\t\tif(ctx != null){\r\n\t\t\tins.ctx = ctx;\r\n\t\t\tins.api.ctx = ctx;\r\n\t\t}\r\n\t\tif(ins.appImgLoader == null && ctx != null){\r\n\t\t\tFile picDir = null;\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tpicDir = ctx.getExternalFilesDir(\"doudougou\");\r\n\t\t\t\t}catch(Throwable e){\r\n\t\t\t\t\tLog.w(TAG_EMOP, \"Error:\" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t\tif(picDir == null){\r\n\t\t\t\t\tpicDir = new File(Environment.getExternalStorageDirectory(), \"doudougou\");\r\n\t\t\t\t}\r\n\t\t\t\tLog.i(TAG_EMOP, \"App cache dir:\" + picDir.getAbsolutePath());\r\n\t\t\t\tif(!picDir.isDirectory()){\r\n\t\t\t\t\tif(!picDir.mkdirs()){\r\n\t\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(!picDir.canWrite()){\r\n\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.i(TAG_EMOP, \"The external storage is disabled.\");\t\t\t\t\r\n\t\t\t\tpicDir = ctx.getCacheDir();\t\t\t\t\r\n\t\t\t}\r\n\t\t\tLog.i(TAG_EMOP, \"App image dir:\" + picDir.getAbsolutePath());\r\n\t\t\tins.appImgLoader = new ImageLoader(ctx, picDir, \r\n\t\t\t\t\t0, 8); \r\n\t\t\tins.tmpImgLoader = ins.appImgLoader;\r\n\t\t}\r\n\t\t\r\n\t\tif(check_conn){\r\n\t\t\tins.check_networking(ctx);\r\n\t\t}\r\n\t\treturn ins;\r\n\t}\r\n\t\r\n\tpublic boolean isLogined(){\r\n\t\treturn this.userId != null && this.userId.length() > 0 && Integer.parseInt(this.userId) > 0;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 链接一下taodian API看看网络是否正常。\r\n\t * @param ctx\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult check_networking(Context ctx){\r\n\t\treturn this.api.connect(ctx);\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getTopicList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.TOPIC_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME,\r\n\t\t\t\tTopic.VIEW_ORDER\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得分类列表.\r\n\t */\r\n\tpublic Cursor getCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得热门分类列表.\r\n\t */\r\n\tpublic Cursor getHotCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.HOT_CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\t\r\n\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getItemList(ContentResolver contentResolver, Uri uri){\r\n\t\tLog.d(com.emop.client.Constants.TAG_EMOP, \"on getItemList:\" + uri.toString());\r\n\t\t\r\n\t\tCursor c = contentResolver.query(uri, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Item.SHORT_KEY, Item.PIC_URL,\r\n\t\t\t\tItem.ITEM_CONTENT_TYPE, \r\n\t\t\t\tItem.UPDATE_TIME, Item.WEIBO_ID,\r\n\t\t\t\tItem.PRICE,\r\n\t\t\t\tItem.MESSAGE,\r\n\t\t\t\tItem.RECT_RATE\r\n\t\t}, null, null, null);\r\n\t\t\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri){\r\n\t\treturn refreshDataByUri(contentResolver, uri, TaodianApi.STATUS_NORMAL);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @param async -- 是否异步返回结果。 如果为true数据在后台线程保存到数据库。网络返回后\r\n\t * @return\r\n\t */\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status){\r\n\t\treturn refreshDataByUri(contentResolver, uri, status, false);\r\n\t}\t\r\n\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status, boolean sync){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh uri:\" + uri.toString());\r\n\t\tApiResult r = null;\r\n switch (Schema.FmeiUriMatcher.match(uri)) {\r\n \tcase Schema.TYPE_CATE_ITEM_LIST:\r\n \tcase Schema.TYPE_HOT_ITEM_LIST:\r\n \tcase Schema.TYPE_TOPIC_ITEM_LIST:\r\n \t\tr = refreshTopicItemList(contentResolver, uri, sync, null);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_TOPICS:\r\n \t\tr = this.refreshTopicList(contentResolver, status, \"\");\r\n \t\tbreak;\r\n \tcase Schema.TYPE_CATES:\r\n \t\tr = this.refreshCateList(contentResolver, status);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_HOTS:\r\n \t\tr = this.refreshHotCatList(contentResolver, status);\r\n \tcase Schema.TYPE_ACT_ITEM_LIST:\r\n \t\tr = this.refreshActivityItemList(contentResolver);\r\n \tcase Schema.TYPE_MYFAV_ITEM_LIST:\r\n \t\tr = this.refreshMyFavoriteItemList(contentResolver);\r\n }\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * \r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t */\r\n\tpublic void refreshUri(ContentResolver contentResolver, Uri uri){\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver){\r\n\t\treturn refreshTopicList(contentResolver, TaodianApi.STATUS_NORMAL, \"\");\r\n\t}\r\n\t/**\r\n\t * 刷新专题列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver, int status, String noCache){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refreshList....\");\r\n\t\tApiResult r = this.api.getTopicList(10, status, noCache);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.TOPIC_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\t//contentResolver.notifyChange(Schema.TOPIC_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshCateList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh cate List....\");\r\n\t\tApiResult r = this.api.getCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshHotCatList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh hot cate List....\");\r\n\t\tApiResult r = this.api.getHotCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.HOT_CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshActList(ContentResolver contentResolver){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh act topic List....\");\r\n\t\tApiResult r = this.api.getActList(1, TaodianApi.STATUS_NORMAL);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新专题图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, int topic_id){\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/topic/\" + topic_id + \"/list\");\r\n\t\t\r\n\t\treturn this.refreshTopicItemList(contentResolver, topicList);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 刷新活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshActivityItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tint topicId = getActivityTopicId(contentResolver);\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/act/\" + topicId + \"/list\");\t\t\r\n\t\tr = this.refreshTopicItemList(contentResolver, topicList);\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新我的收藏活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshMyFavoriteItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tif(this.isLogined()){\r\n\t\t\tString fid = this.getFavoriteId();\r\n\t\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/myfav/\" + fid + \"/list\");\t\r\n\t\t\tLog.e(Constants.TAG_EMOP, \"refresh myfav item list:\" + fid);\r\n\t\t\tr = this.api.getMyFavoriteItemList(fid, this.userId);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\tJSONObject json = null;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t\t}\t\t\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\t\r\n\t\r\n\t/**\r\n\t * 链接活动页,也是一个特殊的专题活动。取到专题的ID.\r\n\t * @return\r\n\t */\r\n\tpublic int getActivityTopicId(ContentResolver contentResolver){\r\n\t\tint topicId = 0;\r\n\t\tCursor c = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\r\n\t\tif(c.getCount() == 0){\r\n\t\t\tthis.refreshActList(contentResolver);\r\n\t\t\tif(c != null)c.close();\r\n\t\t\tc = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\t\t\t\r\n\t\t}\r\n\t\tif(c.getCount() > 0){\r\n\t\t\tc.moveToFirst();\r\n\t\t\tint topic = c.getColumnIndex(BaseColumns._ID);\r\n\t\t\ttopicId = c.getInt(topic);\t\t\t\r\n\t\t}\r\n\t\tif(c != null)c.close();\r\n\t\treturn topicId;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, Uri topicList){\r\n\t\treturn refreshTopicItemList(contentResolver, topicList, false, null);\r\n\t}\r\n\tpublic ApiResult refreshTopicItemList(final ContentResolver contentResolver, final Uri topicList, boolean sync, String force){\r\n\t\tint topic_id = Integer.parseInt(topicList.getPathSegments().get(1)); // (int) ContentUris.parseId(uri);\r\n\t\tString cate = topicList.getPathSegments().get(0);\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh item list:\" + topic_id);\r\n\t\tString pageSize = topicList.getQueryParameter(\"pageSize\");\r\n\t\tString pageNo = topicList.getQueryParameter(\"pageNo\");\r\n\t\tString noCache = topicList.getQueryParameter(\"no_cache\");\r\n\t\tif(force != null && force.equals(\"y\")){\r\n\t\t\tnoCache = \"y\";\r\n\t\t}\r\n\t\t\r\n\t\tint size = 100;\r\n\t\ttry{\r\n\t\t\tsize = Integer.parseInt(pageSize);\r\n\t\t}catch(Throwable e){}\r\n\t\tfinal ApiResult r;\r\n\t\tif(cate.equals(\"act\")){\r\n\t\t\tr = this.api.getTopicItemList(topic_id, size, pageNo);\r\n\t\t}else if(cate.equals(\"shop\")){\r\n\t\t\tr = this.api.getShopItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}else {\r\n\t\t\tr = this.api.getTopicPidItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tRunnable task = new Runnable(){\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tJSONObject json = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcontentResolver.notifyChange(topicList, null);\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t};\r\n\t\t\t\r\n\t\t\tif(sync){\r\n\t\t\t\tnew Thread(task).start();\r\n\t\t\t}else {\r\n\t\t\t\ttask.run();\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过网络查询当前应用的最新版本。\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkUpgradeVersion(){\r\n\t\tApiResult r = this.api.call(\"cms_app_version_check\", null);\t\t\r\n\t\t//PackageManager packageManager = ctx.getPackageManager();\r\n\t\t//PackageInfo packInfo packageManager.getp\t\t\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key){\r\n\t\treturn addFavorite(weiboId, desc, picUrl, numId, shopId, short_url_key, \"taoke\");\r\n\t}\r\n\t\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key, String contentType){\r\n\t\tLog.d(TAG_EMOP, \"add fav, weiboId:\" + weiboId + \", numId:\" + numId + \", shopId:\" + shopId + \", picUrl:\" + picUrl);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\t\tparam.put(\"pic_url\", picUrl);\r\n\t\tparam.put(\"content_type\", contentType);\r\n\t\tparam.put(\"num_iid\", numId);\r\n\t\tparam.put(\"shop_id\", shopId);\r\n\t\tparam.put(\"short_url_key\", short_url_key);\r\n\t\t\r\n\t\tparam.put(\"item_text\", desc);\r\n\t\tr = api.call(\"tuji_topic_add_item\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult removeFavorite(String weiboId){\r\n\t\tLog.d(TAG_EMOP, \"remove fav, weiboId:\" + weiboId);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\r\n\t\tr = api.call(\"tuji_topic_remove_items\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * 加载应用配置信息,例如:sina key,什么的。\r\n\t * @return\r\n\t */\r\n\tpublic AppConfig config(){\r\n\t\tif(config == null){\r\n\t\t\tconfig = new AppConfig();\r\n\t\t\tApiResult r = api.call(\"cms_app_config_info\", null);\r\n\t\t\tif(r != null && r.isOK){\r\n\t\t\t\tconfig.json = r.getJSONObject(\"data\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn config;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 绑定外部登录用户信息,到美觅网系统。\r\n\t * @param source\r\n\t * @param userId\r\n\t * @param token\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult bindUserInfo(String source, String userId, String token){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"source\", source);\r\n\t\tparam.put(\"ref_id\", userId);\r\n\t\tparam.put(\"access_token\", token);\r\n\t\tif(this.userId != null){\r\n\t\t\tparam.put(\"user_id\", this.userId);\r\n\t\t}\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_bind_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult registerUser(Map<String, Object> param){\t\r\n\t\t/**\r\n\t\t * 有user_id是通过,第三方帐号绑定过来。已经生成了user_id.\r\n\t\t * 没有user_id是在应用里面,直接注册的。\r\n\t\t */\r\n\t\tApiResult r = null;\r\n\t\tObject user_id = param.get(\"user_id\");\r\n\t\tif(user_id != null && user_id.toString().length() > 0){\r\n\t\t\tr = api.call(\"user_update_info\", param);\r\n\t\t}else {\r\n\t\t\tr = api.call(\"user_register_new\", param);\r\n\t\t}\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult login(String email, String password){\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"email\", email);\r\n\t\tparam.put(\"password\", password);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void saveLoginUser(Activity ctx, String userId){\r\n\t\tthis.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, userId);\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void saveRefUser(Activity ctx, String source, String userId, String nick){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.putString(Constants.PREFS_SINA_UID, userId);\r\n \teditor.putString(Constants.PREFS_SINA_NICK, nick);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.putString(Constants.PREFS_TAOBAO_UID, userId);\r\n \teditor.putString(Constants.PREFS_TAOBAO_NICK, nick); \t\t\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.putString(Constants.PREFS_QQ_UID, userId);\r\n \teditor.putString(Constants.PREFS_QQ_NICK, nick); \t\t\r\n \t}\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void removeRefUser(Activity ctx, String source){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.remove(Constants.PREFS_SINA_UID);\r\n \t\teditor.remove(Constants.PREFS_SINA_NICK);\r\n \t\teditor.remove(Constants.PREFS_SINA_ACCESS_TOKEN);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_UID);\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_NICK);\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t}\r\n \teditor.commit();\r\n \tString sina = settings.getString(Constants.PREFS_SINA_UID, \"\");\r\n \tString taobao = settings.getString(Constants.PREFS_TAOBAO_UID, \"\");\r\n \tString qq = settings.getString(Constants.PREFS_QQ_UID, \"\");\r\n \t\r\n \tif((sina == null || sina.trim().length() == 0) &&\r\n \t (taobao == null || taobao.trim().length() == 0) &&\r\n \t (qq == null || qq.trim().length() == 0)\r\n \t){\r\n \t\tlogout(ctx);\r\n \t} \t\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\t\r\n\t\r\n\tpublic void logout(Activity ctx){\r\n\t\tthis.userId = null;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, \"0\");\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"logout:\" + userId);\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 我的收藏夹Id.\r\n\t * @return\r\n\t */\r\n\tpublic String getFavoriteId(){\r\n\t\tif((this.favoriteId == null || this.favoriteId.length() == 0) &&\r\n\t\t\t\tthis.isLogined()){\r\n\t\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\t\tparam.put(\"user_id\", userId);\r\n\t\t\tparam.put(\"cate\", 1);\r\n\t\t\tparam.put(\"topic_name\", \"收藏夹\");\r\n\t\t\tparam.put(\"item_head_count\", 0);\r\n\t\t\tparam.put(\"status\", TaodianApi.STATUS_NORMAL);\r\n\t\t\t\r\n\t\t\tApiResult r = api.call(\"tuji_user_topic_list\", param);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\t int count = Integer.parseInt(r.getString(\"data.item_count\").toString());\r\n\t\t\t\t if(count > 0){\r\n\t\t\t\t\t JSONObject obj = r.getJSONObject(\"data\");\r\n\t\t\t\t\t JSONArray items;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\titems = obj.getJSONArray(\"items\");\r\n\t\t\t\t\t\tthis.favoriteId = items.getJSONObject(0).getString(\"id\");\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\tLog.e(TAG_EMOP, \"Get favoriate ID error:\" + e.toString(), e);\r\n\t\t\t\t\t}\r\n\t\t\t\t }\r\n\t\t\t}\r\n\t\t\tif(this.favoriteId == null || this.favoriteId.length() == 0){\r\n\t\t\t\tr = api.call(\"tuji_create_topic\", param);\r\n\t\t\t\tif(r.isOK){\r\n\t\t\t\t\tthis.favoriteId = r.getString(\"data.topic_id\");\r\n\t\t\t\t}\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.favoriteId;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 检查用户PID是否合法。先跳过不检查。\r\n\t * @param id\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkTrackId(String id){\r\n\t\tApiResult r = new ApiResult();\r\n\t\tr.isOK = true;\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void cleanExpiredData(ContentResolver contentResolver){\r\n\t\tLog.d(Constants.TAG_EMOP, \"cleanExpiredData....\");\r\n\t\tcontentResolver.delete(Schema.TOPIC_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.ITME_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 5) + \"\"});\t\r\n\t\t\r\n\t\tcontentResolver.delete(Schema.REBATE_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.SHOP_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 更加ID加载单条内容。主要用在,应用从外部启动后。直接进入详情页面。\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult getWeiboInfo(String uuid){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uuid\", uuid);\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"cms_get_uuid_content\", param);\t\t\r\n\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult getTrackPid(){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uid\", this.trackUserId);\r\n\t\tApiResult r = api.call(\"emop_user_pid\", param);\t\t\r\n\t\tthis.trackPID = r.getString(\"data.pid\");\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult updateTrackId(){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"track_user_id\", trackUserId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_update_track_id\", param);\t\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tString tid = r.getString(\"data.track_user_id\");\r\n\t\t\tif(tid != null && tid.trim().length() > 0){\r\n\t\t\t\ttrackUserId = tid;\r\n\t\t\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\t \tSharedPreferences.Editor editor = settings.edit();\r\n\t\t \teditor.putString(Constants.PREFS_TRACK_ID, tid);\r\n\t\t \teditor.commit();\r\n\t\t\t}\r\n\t\t\tLog.d(\"xx\", \"update task as:\" + tid);\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 1. 读取sd卡\r\n\t * 2. 读取应用meta\r\n\t */\r\n\tpublic void updateLocalTrackId(){\r\n\t\tboolean writeSetting = false;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\ttrackUserId = settings.getString(Constants.PREFS_TRACK_ID, null);\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\twriteSetting = true;\r\n\t\t\ttrackUserId = readTrackIdFromSD();\r\n\t\t}\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\ttrackUserId = getMetaDataValue(\"emop_track_id\");\r\n\t\t\t//测试模式下,track id还没有替换时。默认是EMOP_USER\r\n\t\t\tif(trackUserId != null && trackUserId.equals(\"EMOP_USER\")){\r\n\t\t\t\ttrackUserId = \"11\";\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track from meta:\" + trackUserId);\r\n\t\t}\r\n\t\tif(trackUserId != null && trackUserId.trim().length() > 0){\r\n\t\t\tif(writeSetting){\r\n\t\t\t\tsaveSettings(Constants.PREFS_TRACK_ID, trackUserId);\r\n\t\t\t}\r\n\t\t\tWriteTrackIdToSD(trackUserId);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void WriteTrackIdToSD(String tid){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tOutputStream os = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"write track user pid:'\" + tid + \"' to:\" + track.getAbsolutePath());\r\n\t\t\tos = new FileOutputStream(track);\r\n\t\t\tif(os != null){\r\n\t\t\t\tos.write(tid.getBytes());\r\n\t\t\t}\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.d(TAG_EMOP, \"write error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(os != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tos.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\t\r\n\tprivate String readTrackIdFromSD(){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tBufferedReader input = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track user from:\" + track.getAbsolutePath());\r\n\t\t\tif(track.isFile()){\r\n\t\t\t\tinput = new BufferedReader(new InputStreamReader(new FileInputStream(track)));\r\n\t\t\t\tpid = input.readLine();\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read pid in sdcard:\" + pid);\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.e(TAG_EMOP, \"read pid error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(input != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn pid;\r\n\t}\r\n\t\r\n private String getMetaDataValue(String name) {\r\n Object value = null;\r\n PackageManager packageManager = ctx.getPackageManager();\r\n ApplicationInfo applicationInfo;\r\n try {\r\n applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);\r\n if (applicationInfo != null && applicationInfo.metaData != null) {\r\n value = applicationInfo.metaData.get(name);\r\n }\r\n } catch (NameNotFoundException e) {\r\n throw new RuntimeException(\r\n \"Could not read the name in the manifest file.\", e);\r\n }\r\n if (value == null) {\r\n throw new RuntimeException(\"The name '\" + name\r\n + \"' is not defined in the manifest file's meta data.\");\r\n }\r\n return value.toString();\r\n }\t\r\n\t\t\r\n\tpublic String getSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n\r\n\tpublic String saveSettings(String key, String value){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(key, value);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\t\r\n\tpublic String removeSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.remove(key);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n}\r", "public class QueryParam {\r\n\tpublic final static String PAGE_SIZE = \"pageSize\";\r\n\tpublic final static String PAGE_NO = \"pageNo\";\r\n\t\r\n\tpublic String selection;\r\n\tpublic String[] selectionArgs;\r\n\tpublic String sortOrder;\r\n\tpublic String groupBy;\r\n\tpublic String having;\r\n\tpublic QueryParam(String sel, String[] args, String order){\r\n\t\tthis.selection = sel;\r\n\t\tthis.selectionArgs = args;\r\n\t\tthis.sortOrder = order;\r\n\t}\r\n}\r", "public class Rebate {\r\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/vnd.fmei.rebates\";\r\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.fmei.rebate\";\r\n\t\r\n\tpublic static final String DB_TABLE_NAME = \"rebate\";\r\n\t\r\n\tpublic static final String LOCAL_CATE = \"local_cate\";\r\n\tpublic static final String SHORT_KEY = \"short_url_key\";\r\n\tpublic static final String NUM_IID = \"num_iid\";\r\n\tpublic static final String SHOP_ID = \"shop_id\";\r\n\tpublic static final String TITLE = \"title\";\r\n\tpublic static final String PIC_URL = \"pic_url\";\r\n\r\n\tpublic static final String PRICE = \"price\";\r\n\tpublic static final String COUPON_PRICE = \"coupon_price\";\r\n\tpublic static final String COUPON_RATE = \"coupon_rate\";\r\n\tpublic static final String COUPON_START_TIME = \"coupon_start_time\";\r\n\t\r\n\t\r\n\tpublic static final String COUPON_END_TIME = \"coupon_end_time\";\r\n\tpublic static final String ROOT_CATE = \"root_tag\";\r\n\r\n\tpublic static final String LOCAL_UPDATE_TIME = \"local_update\";\r\n\tpublic static final String WEIGHT = \"weight\";\r\n\t\r\n\tpublic static Uri update(SQLiteDatabase db, Uri uri, ContentValues values){\r\n\t\t\r\n\t\tString taskId = values.getAsString(NUM_IID);\r\n\t\t//values.remove(\"id\");\r\n\t\tList<String> seg = uri.getPathSegments(); //.get(1);\r\n\t\tvalues.put(LOCAL_UPDATE_TIME, System.currentTimeMillis());\r\n int count = db.update(DB_TABLE_NAME, values, BaseColumns._ID + \"=?\", new String[]{taskId});\r\n\t\tif(count == 0){\r\n\t\t\t//Log.d(Constants.TAG_EMOP, String.format(\"insert new item '%s:%s'\", taskId,\r\n\t\t\t//\t\tvalues.getAsString(WEIBO_ID)));\r\n\t\t\tvalues.put(BaseColumns._ID, taskId);\r\n\t\t\tdb.insert(DB_TABLE_NAME, NUM_IID, values);\r\n\t\t}else {\r\n\t\t\t//Log.d(Constants.TAG_EMOP, String.format(\"update rebate info'%s:%s'\", taskId,\r\n\t\t\t//\t\tvalues.getAsString(SHORT_KEY) + \", cate:\" + values.getAsString(ROOT_CATE)));\r\n\t\t}\t\t\r\n\t\t\r\n\t\treturn null;\t\t\t\r\n\t}\r\n\t\r\n\t\r\n\tpublic static void buildRebateListQuery(SQLiteQueryBuilder builder, \r\n\t\t\tString[] fileds, QueryParam param, Uri uri){\r\n\t\tbuilder.setTables(DB_TABLE_NAME);\t\r\n\t\tString cate = uri.getQueryParameter(\"cate\");\r\n\t\t\r\n\t\tif(cate != null){\r\n\t\t\tbuilder.appendWhere(ROOT_CATE + \"='\" + cate + \"'\");\r\n\t\t}\r\n\t\t\r\n\t\tparam.sortOrder = COUPON_START_TIME + \" \" + \"desc, local_update desc\";\r\n\t}\r\n\t\r\n\tpublic static ContentValues convertJson(JSONObject obj){\r\n\t\tContentValues v = new ContentValues();\r\n\t\ttry{\r\n\t\t\tif(obj.has(\"id\")){\r\n\t\t\t\tv.put(\"id\", obj.getInt(\"id\"));\r\n\t\t\t}\r\n\t\t\tif(obj.has(SHORT_KEY)){\r\n\t\t\t\tv.put(SHORT_KEY, obj.getString(SHORT_KEY));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(NUM_IID)){\r\n\t\t\t\tv.put(NUM_IID, obj.getString(NUM_IID));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(SHOP_ID)){\r\n\t\t\t\tv.put(SHOP_ID, obj.getString(SHOP_ID));\r\n\t\t\t}\r\n\t\r\n\t\t\tif(obj.has(TITLE)){\r\n\t\t\t\tv.put(TITLE, obj.getString(TITLE));\r\n\t\t\t}\t\r\n\t\t\t\r\n\t\t\tif(obj.has(PIC_URL)){\r\n\t\t\t\tv.put(PIC_URL, obj.getString(PIC_URL));\r\n\t\t\t}\t\r\n\r\n\t\t\tif(obj.has(PRICE)){\r\n\t\t\t\tv.put(PRICE, obj.getString(PRICE));\r\n\t\t\t}\t\t\t\r\n\t\t\t\r\n\t\t\tif(obj.has(COUPON_PRICE)){\r\n\t\t\t\tv.put(COUPON_PRICE, obj.getString(COUPON_PRICE));\r\n\t\t\t}\t\t\r\n\t\t\tif(obj.has(COUPON_RATE)){\r\n\t\t\t\tv.put(COUPON_RATE, obj.getString(COUPON_RATE));\r\n\t\t\t}\r\n\t\t\tif(obj.has(COUPON_END_TIME) && obj.getString(COUPON_END_TIME) != null){\r\n\t\t\t\tv.put(COUPON_END_TIME, obj.getString(COUPON_END_TIME));\r\n\t\t\t}\r\n\t\t\tif(obj.has(COUPON_START_TIME) && obj.getString(COUPON_START_TIME) != null){\r\n\t\t\t\tv.put(COUPON_START_TIME, obj.getString(COUPON_START_TIME));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(ROOT_CATE)){\r\n\t\t\t\tv.put(ROOT_CATE, obj.getString(ROOT_CATE));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(obj.has(LOCAL_UPDATE_TIME)){\r\n\t\t\t\tv.put(LOCAL_UPDATE_TIME, obj.getString(LOCAL_UPDATE_TIME));\r\n\t\t\t}\t\r\n\t\t\tif(obj.has(WEIGHT)){\r\n\t\t\t\tv.put(WEIGHT, obj.getString(WEIGHT));\r\n\t\t\t}\t\t\t\r\n\t\t}catch (JSONException e) {\r\n\t\t\tLog.e(Constants.TAG_EMOP, e.toString());\r\n\t\t}\r\n\t\t\r\n\t\treturn v;\t\r\n\t}\r\n\r\n}\r", "public class TimeHelper {\r\n\tpublic static DateFormat timeFormat = new SimpleDateFormat(\"HH:mm:ss\");\r\n\tpublic static DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\r\n\tpublic static DateFormat dateTimeFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\r\n\t\r\n\tpublic static String formatTime(Date time){\r\n\t\treturn timeFormat.format(time);\r\n\t}\r\n\r\n\tpublic static String formatDate(Date time){\r\n\t\treturn dateFormat.format(time);\r\n\t}\r\n\t\r\n\tpublic static String formatDateTime(Date time){\r\n\t\treturn dateTimeFormat.format(time);\r\n\t}\r\n\r\n\tpublic static Date parseDateTime(String time){\r\n\t\ttry {\r\n\t\t\treturn dateTimeFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Date parseDate(String time){\r\n\t\ttry {\r\n\t\t\treturn dateFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static Date parseTime(String time){\r\n\t\ttry {\r\n\t\t\treturn timeFormat.parse(time);\r\n\t\t} catch (ParseException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static String formatRemainHour(String end, int maxDate){\r\n\t\tDate date = parseDateTime(end);\r\n\t\tif(date != null && date.getTime() > System.currentTimeMillis()){\r\n\t\t\tlong time = date.getTime() - System.currentTimeMillis();\r\n\t\t\tlong minutes = time / 1000 / 60;\r\n\t\t\t\r\n\t\t\tlong reDay = (minutes / (60 * 24)) % maxDate;\r\n\t\t\t\r\n\t\t\tlong reHour = (minutes % (60 * 24)) / 60;\r\n\t\t\tlong reMin = minutes % 60;\r\n\t\t\treturn String.format(\"%s天%s小时%s分\", reDay, reHour, reMin);\r\n\t\t\t\r\n\t\t}\r\n\t\treturn \"0小时0分\";\r\n\t}\r\n}\r" ]
import java.util.TreeSet; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StrikethroughSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ListView; import android.widget.TextView; import com.baidu.mobstat.StatService; import com.emop.client.R; import com.emop.client.WebViewActivity; import com.emop.client.io.FmeiClient; import com.emop.client.provider.QueryParam; import com.emop.client.provider.model.Rebate; import com.emop.client.utils.TimeHelper;
convertView = getLayoutInflater(null).inflate(R.layout.rebate_list_item, null); /* convertView.setLongClickable(true); convertView.setOnLongClickListener(new OnLongClickListener(){ @Override public boolean onLongClick(View v) { View img = v.findViewById(R.id.pic_url); Log.d("image tag:", "imag tag:" + img.getTag()); // TODO Auto-generated method stub return false; } }); */ } Items tag = (Items)convertView.getTag(); if(tag == null){ tag = new Items(convertView); convertView.setTag(tag); } final RebateItem item = this.getItem(position); if(tag.title != null){ tag.title.setText(item.title); } if(tag.picUrl != null){ tag.picUrl.setTag(item.picUrl); Bitmap bm = client.tmpImgLoader.cache.get(item.picUrl, winWidth, true, false); ImageView img = (ImageView)tag.picUrl; if(bm != null){ img.setScaleType(ScaleType.CENTER_CROP); img.setImageBitmap(bm); }else { img.setScaleType(ScaleType.CENTER_INSIDE); img.setImageResource(R.drawable.loading); client.tmpImgLoader.runTask(new Runnable(){ @Override public void run() { final Bitmap newBm = client.tmpImgLoader.cache.get(item.picUrl, winWidth, true, true); if(newBm != null){ handler.post(new Runnable(){ @Override public void run() { if(isRunning){ View v = getListView().findViewWithTag(item.picUrl); if(v != null){ ImageView v2 = (ImageView)v; v2.setScaleType(ScaleType.CENTER_CROP); v2.setImageBitmap(newBm); } } } }); } } }); } } if(tag.price != null){ String price = item.price; SpannableString spanText = new SpannableString("¥" + price); spanText.setSpan(new StrikethroughSpan(), 1, 1 + price.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tag.price.setText(spanText); } if(tag.couponPrice != null){ tag.couponPrice.setText("¥" + item.couponPrice); } if(tag.couponRate != null){ tag.couponRate.setText(String.format("%1$1.1f 折", item.couponRate / 1000)); } if(tag.endTime != null){ String time = TimeHelper.formatRemainHour(item.endTime, 10); tag.endTime.setText(time); } return convertView; } /** * 加入一个商品到折扣列表。如果商品已经存在,则忽略操作。 */ public void add(RebateItem item){ if(loadedItem.add(item.numIId)){ super.add(item); } } public void clear(){ super.clear(); this.loadedItem.clear(); } } class DataLoaderCallback implements LoaderCallbacks<Cursor>{ //public Lock loading = public boolean isLoading = false; private Uri dataSource = null; private boolean isLoadMore = false; private int pageSize = 20; private int pageNo = 0; public DataLoaderCallback(Uri source, boolean isLoadMore){ this.dataSource = source; this.isLoadMore = isLoadMore; } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { Builder b = dataSource.buildUpon(); if(isLoadMore){ //加载下一页数据。 pageNo++; } b.appendQueryParameter(QueryParam.PAGE_SIZE, pageSize + ""); b.appendQueryParameter(QueryParam.PAGE_NO, pageNo + ""); return new CursorLoader(getActivity(), b.build(),
new String[] { BaseColumns._ID, Rebate.NUM_IID, Rebate.TITLE, Rebate.PIC_URL, Rebate.COUPON_PRICE,
3
treasure-lau/CSipSimple
app/src/main/java/com/csipsimple/service/SipService.java
[ "public class MediaState implements Parcelable {\n\n /**\n * Primary key for the parcelable object\n */\n public int primaryKey = -1;\n\n /**\n * Whether the microphone is currently muted\n */\n public boolean isMicrophoneMute = false;\n\n /**\n * Whether the audio routes to the speaker\n */\n public boolean isSpeakerphoneOn = false;\n /**\n * Whether the audio routes to Bluetooth SCO\n */\n public boolean isBluetoothScoOn = false;\n /**\n * Gives phone capability to mute microphone\n */\n public boolean canMicrophoneMute = true;\n /**\n * Gives phone capability to route to speaker\n */\n public boolean canSpeakerphoneOn = true;\n /**\n * Gives phone capability to route to bluetooth SCO\n */\n public boolean canBluetoothSco = false;\n\n @Override\n public boolean equals(Object o) {\n\n if (o != null && o.getClass() == MediaState.class) {\n MediaState oState = (MediaState) o;\n if (oState.isBluetoothScoOn == isBluetoothScoOn &&\n oState.isMicrophoneMute == isMicrophoneMute &&\n oState.isSpeakerphoneOn == isSpeakerphoneOn &&\n oState.canBluetoothSco == canBluetoothSco &&\n oState.canSpeakerphoneOn == canSpeakerphoneOn &&\n oState.canMicrophoneMute == canMicrophoneMute) {\n return true;\n } else {\n return false;\n }\n\n }\n return super.equals(o);\n }\n\n /**\n * Constructor for a media state object <br/>\n * It will contains default values for all flags This class as no\n * setter/getter for members flags <br/>\n * It's aim is to allow to serialize/deserialize easily the state of media\n * layer, <n>not to modify it</b>\n */\n public MediaState() {\n // Nothing to do in default constructor\n }\n\n /**\n * Construct from parcelable <br/>\n * Only used by {@link #CREATOR}\n * \n * @param in parcelable to build from\n */\n private MediaState(Parcel in) {\n primaryKey = in.readInt();\n isMicrophoneMute = (in.readInt() == 1);\n isSpeakerphoneOn = (in.readInt() == 1);\n isBluetoothScoOn = (in.readInt() == 1);\n canMicrophoneMute = (in.readInt() == 1);\n canSpeakerphoneOn = (in.readInt() == 1);\n canBluetoothSco = (in.readInt() == 1);\n }\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n public static final Creator<MediaState> CREATOR = new Creator<MediaState>() {\n public MediaState createFromParcel(Parcel in) {\n return new MediaState(in);\n }\n\n public MediaState[] newArray(int size) {\n return new MediaState[size];\n }\n };\n\n /**\n * @see Parcelable#describeContents()\n */\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(primaryKey);\n dest.writeInt(isMicrophoneMute ? 1 : 0);\n dest.writeInt(isSpeakerphoneOn ? 1 : 0);\n dest.writeInt(isBluetoothScoOn ? 1 : 0);\n dest.writeInt(canMicrophoneMute ? 1 : 0);\n dest.writeInt(canSpeakerphoneOn ? 1 : 0);\n dest.writeInt(canBluetoothSco ? 1 : 0);\n }\n}", "public class SipCallSession implements Parcelable {\n\n /**\n * Describe the control state of a call <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSIP__INV.htm#ga083ffd9c75c406c41f113479cc1ebc1c\"\n * >Pjsip documentation</a>\n */\n public static class InvState {\n /**\n * The call is in an invalid state not syncrhonized with sip stack\n */\n public static final int INVALID = -1;\n /**\n * Before INVITE is sent or received\n */\n public static final int NULL = 0;\n /**\n * After INVITE is sent\n */\n public static final int CALLING = 1;\n /**\n * After INVITE is received.\n */\n public static final int INCOMING = 2;\n /**\n * After response with To tag.\n */\n public static final int EARLY = 3;\n /**\n * After 2xx is sent/received.\n */\n public static final int CONNECTING = 4;\n /**\n * After ACK is sent/received.\n */\n public static final int CONFIRMED = 5;\n /**\n * Session is terminated.\n */\n public static final int DISCONNECTED = 6;\n\n // Should not be constructed, just an older for int values\n // Not an enum because easier to pass to Parcelable\n private InvState() {\n }\n }\n \n /**\n * Option key to flag video use for the call. <br/>\n * The value must be a boolean.\n * \n * @see Boolean\n */\n public static final String OPT_CALL_VIDEO = \"opt_call_video\";\n /**\n * Option key to add custom headers (with X- prefix). <br/>\n * The value must be a bundle with key representing header name, and value representing header value.\n * \n * @see Bundle\n */\n public static final String OPT_CALL_EXTRA_HEADERS = \"opt_call_extra_headers\";\n\n /**\n * Describe the media state of the call <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSUA__LIB__CALL.htm#ga0608027241a5462d9f2736e3a6b8e3f4\"\n * >Pjsip documentation</a>\n */\n public static class MediaState {\n /**\n * Call currently has no media\n */\n public static final int NONE = 0;\n /**\n * The media is active\n */\n public static final int ACTIVE = 1;\n /**\n * The media is currently put on hold by local endpoint\n */\n public static final int LOCAL_HOLD = 2;\n /**\n * The media is currently put on hold by remote endpoint\n */\n public static final int REMOTE_HOLD = 3;\n /**\n * The media has reported error (e.g. ICE negotiation)\n */\n public static final int ERROR = 4;\n\n // Should not be constructed, just an older for int values\n // Not an enum because easier to pass to Parcelable\n private MediaState() {\n }\n }\n\n /**\n * Status code of the sip call dialog Actually just shortcuts to SIP codes<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSIP__MSG__LINE.htm#gaf6d60351ee68ca0c87358db2e59b9376\"\n * >Pjsip documentation</a>\n */\n public static class StatusCode {\n public static final int TRYING = 100;\n public static final int RINGING = 180;\n public static final int CALL_BEING_FORWARDED = 181;\n public static final int QUEUED = 182;\n public static final int PROGRESS = 183;\n public static final int OK = 200;\n public static final int ACCEPTED = 202;\n public static final int MULTIPLE_CHOICES = 300;\n public static final int MOVED_PERMANENTLY = 301;\n public static final int MOVED_TEMPORARILY = 302;\n public static final int USE_PROXY = 305;\n public static final int ALTERNATIVE_SERVICE = 380;\n public static final int BAD_REQUEST = 400;\n public static final int UNAUTHORIZED = 401;\n public static final int PAYMENT_REQUIRED = 402;\n public static final int FORBIDDEN = 403;\n public static final int NOT_FOUND = 404;\n public static final int METHOD_NOT_ALLOWED = 405;\n public static final int NOT_ACCEPTABLE = 406;\n public static final int INTERVAL_TOO_BRIEF = 423;\n public static final int BUSY_HERE = 486;\n public static final int INTERNAL_SERVER_ERROR = 500;\n public static final int DECLINE = 603;\n /*\n * PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED = 407,\n * PJSIP_SC_REQUEST_TIMEOUT = 408, PJSIP_SC_GONE = 410,\n * PJSIP_SC_REQUEST_ENTITY_TOO_LARGE = 413,\n * PJSIP_SC_REQUEST_URI_TOO_LONG = 414, PJSIP_SC_UNSUPPORTED_MEDIA_TYPE\n * = 415, PJSIP_SC_UNSUPPORTED_URI_SCHEME = 416, PJSIP_SC_BAD_EXTENSION\n * = 420, PJSIP_SC_EXTENSION_REQUIRED = 421,\n * PJSIP_SC_SESSION_TIMER_TOO_SMALL = 422,\n * PJSIP_SC_TEMPORARILY_UNAVAILABLE = 480,\n * PJSIP_SC_CALL_TSX_DOES_NOT_EXIST = 481, PJSIP_SC_LOOP_DETECTED = 482,\n * PJSIP_SC_TOO_MANY_HOPS = 483, PJSIP_SC_ADDRESS_INCOMPLETE = 484,\n * PJSIP_AC_AMBIGUOUS = 485, PJSIP_SC_BUSY_HERE = 486,\n * PJSIP_SC_REQUEST_TERMINATED = 487, PJSIP_SC_NOT_ACCEPTABLE_HERE =\n * 488, PJSIP_SC_BAD_EVENT = 489, PJSIP_SC_REQUEST_UPDATED = 490,\n * PJSIP_SC_REQUEST_PENDING = 491, PJSIP_SC_UNDECIPHERABLE = 493,\n * PJSIP_SC_INTERNAL_SERVER_ERROR = 500, PJSIP_SC_NOT_IMPLEMENTED = 501,\n * PJSIP_SC_BAD_GATEWAY = 502, PJSIP_SC_SERVICE_UNAVAILABLE = 503,\n * PJSIP_SC_SERVER_TIMEOUT = 504, PJSIP_SC_VERSION_NOT_SUPPORTED = 505,\n * PJSIP_SC_MESSAGE_TOO_LARGE = 513, PJSIP_SC_PRECONDITION_FAILURE =\n * 580, PJSIP_SC_BUSY_EVERYWHERE = 600, PJSIP_SC_DOES_NOT_EXIST_ANYWHERE\n * = 604, PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE = 606,\n */\n }\n\n /**\n * The call signaling is not secure\n */\n public static int TRANSPORT_SECURE_NONE = 0;\n /**\n * The call signaling is secure until it arrives on server. After, nothing ensures how it goes.\n */\n public static int TRANSPORT_SECURE_TO_SERVER = 1;\n /**\n * The call signaling is supposed to be secured end to end.\n */\n public static int TRANSPORT_SECURE_FULL = 2;\n\n \n /**\n * Id of an invalid or not existant call\n */\n public static final int INVALID_CALL_ID = -1;\n\n /**\n * Primary key for the parcelable object\n */\n public int primaryKey = -1;\n /**\n * The starting time of the call\n */\n protected long callStart = 0;\n\n protected int callId = INVALID_CALL_ID;\n protected int callState = InvState.INVALID;\n protected String remoteContact;\n protected boolean isIncoming;\n protected int confPort = -1;\n protected long accId = SipProfile.INVALID_ID;\n protected int mediaStatus = MediaState.NONE;\n protected boolean mediaSecure = false;\n protected int transportSecure = 0;\n protected boolean mediaHasVideoStream = false;\n protected long connectStart = 0;\n protected int lastStatusCode = 0;\n protected String lastStatusComment = \"\";\n protected int lastReasonCode = 0;\n protected String mediaSecureInfo = \"\";\n protected boolean canRecord = false;\n protected boolean isRecording = false;\n protected boolean zrtpSASVerified = false;\n protected boolean hasZrtp = false;\n\n /**\n * Construct from parcelable <br/>\n * Only used by {@link #CREATOR}\n * \n * @param in parcelable to build from\n */\n private SipCallSession(Parcel in) {\n initFromParcel(in);\n }\n\n /**\n * Constructor for a sip call session state object <br/>\n * It will contains default values for all flags This class as no\n * setter/getter for members flags <br/>\n * It's aim is to allow to serialize/deserialize easily the state of a sip\n * call, <n>not to modify it</b>\n */\n public SipCallSession() {\n // Nothing to do in default constructor\n }\n\n /**\n * Constructor by copy\n * @param callInfo\n */\n public SipCallSession(SipCallSession callInfo) {\n Parcel p = Parcel.obtain();\n callInfo.writeToParcel(p, 0);\n p.setDataPosition(0);\n initFromParcel(p);\n p.recycle();\n }\n \n private void initFromParcel(Parcel in) {\n primaryKey = in.readInt();\n callId = in.readInt();\n callState = in.readInt();\n mediaStatus = in.readInt();\n remoteContact = in.readString();\n isIncoming = (in.readInt() == 1);\n confPort = in.readInt();\n accId = in.readInt();\n lastStatusCode = in.readInt();\n mediaSecureInfo = in.readString();\n connectStart = in.readLong();\n mediaSecure = (in.readInt() == 1);\n lastStatusComment = in.readString();\n mediaHasVideoStream = (in.readInt() == 1);\n canRecord = (in.readInt() == 1);\n isRecording = (in.readInt() == 1);\n hasZrtp = (in.readInt() == 1);\n zrtpSASVerified = (in.readInt() == 1);\n transportSecure = (in.readInt());\n lastReasonCode = in.readInt();\n }\n\n /**\n * @see Parcelable#describeContents()\n */\n @Override\n public int describeContents() {\n return 0;\n }\n\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(primaryKey);\n dest.writeInt(callId);\n dest.writeInt(callState);\n dest.writeInt(mediaStatus);\n dest.writeString(remoteContact);\n dest.writeInt(isIncoming() ? 1 : 0);\n dest.writeInt(confPort);\n dest.writeInt((int) accId);\n dest.writeInt(lastStatusCode);\n dest.writeString(mediaSecureInfo);\n dest.writeLong(connectStart);\n dest.writeInt(mediaSecure ? 1 : 0);\n dest.writeString(getLastStatusComment());\n dest.writeInt(mediaHasVideo() ? 1 : 0);\n dest.writeInt(canRecord ? 1 : 0);\n dest.writeInt(isRecording ? 1 : 0);\n dest.writeInt(hasZrtp ? 1 : 0);\n dest.writeInt(zrtpSASVerified ? 1 : 0);\n dest.writeInt(transportSecure);\n dest.writeInt(lastReasonCode);\n }\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n public static final Creator<SipCallSession> CREATOR = new Creator<SipCallSession>() {\n public SipCallSession createFromParcel(Parcel in) {\n return new SipCallSession(in);\n }\n\n public SipCallSession[] newArray(int size) {\n return new SipCallSession[size];\n }\n };\n\n\n \n\n /**\n * A sip call session is equal to another if both means the same callId\n */\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof SipCallSession)) {\n return false;\n }\n SipCallSession ci = (SipCallSession) o;\n if (ci.getCallId() == callId) {\n return true;\n }\n return false;\n }\n\n // Getters / Setters\n /**\n * Get the call id of this call info\n * \n * @return id of this call\n */\n public int getCallId() {\n return callId;\n }\n\n /**\n * Get the call state of this call info\n * \n * @return the invitation state\n * @see InvState\n */\n public int getCallState() {\n return callState;\n }\n\n public int getMediaStatus() {\n return mediaStatus;\n }\n\n /**\n * Get the remote Contact for this call info\n * \n * @return string representing the remote contact\n */\n public String getRemoteContact() {\n return remoteContact;\n }\n\n /**\n * Get the call way\n * \n * @return true if the remote party was the caller\n */\n public boolean isIncoming() {\n return isIncoming;\n }\n\n /**\n * Get the start time of the connection of the call\n * \n * @return duration in milliseconds\n * @see SystemClock#elapsedRealtime()\n */\n public long getConnectStart() {\n return connectStart;\n }\n\n /**\n * Check if the call state indicates that it is an active call in\n * progress. \n * This is equivalent to state incoming or early or calling or confirmed or connecting\n * \n * @return true if the call can be considered as in progress/active\n */\n public boolean isActive() {\n return (callState == InvState.INCOMING || callState == InvState.EARLY ||\n callState == InvState.CALLING || callState == InvState.CONFIRMED || callState == InvState.CONNECTING);\n }\n \n /**\n * Chef if the call state indicates that it's an ongoing call.\n * This is equivalent to state confirmed.\n * @return true if the call can be considered as ongoing.\n */\n public boolean isOngoing() {\n return callState == InvState.CONFIRMED;\n }\n\n /**\n * Get the sounds conference board port <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/group__PJSUA__LIB__BASE.htm#gaf5d44947e4e62dc31dfde88884534385\"\n * >Pjsip documentation</a>\n * \n * @return the conf port of the audio media of this call\n */\n public int getConfPort() {\n return confPort;\n }\n\n /**\n * Get the identifier of the account corresponding to this call <br/>\n * This identifier is the one you have in {@link SipProfile#id} <br/>\n * It may return {@link SipProfile#INVALID_ID} if no account detected for\n * this call. <i>Example, case of peer to peer call</i>\n * \n * @return The {@link SipProfile#id} of the account use for this call\n */\n public long getAccId() {\n return accId;\n }\n\n /**\n * Get the secure level of the signaling of the call.\n * \n * @return one of {@link #TRANSPORT_SECURE_NONE}, {@link #TRANSPORT_SECURE_TO_SERVER}, {@link #TRANSPORT_SECURE_FULL}\n */\n public int getTransportSecureLevel() {\n return transportSecure;\n }\n \n /**\n * Get the secure level of the media of the call\n * \n * @return true if the call has a <b>media</b> encrypted\n */\n public boolean isMediaSecure() {\n return mediaSecure;\n }\n\n /**\n * Get the information about the <b>media</b> security of this call\n * \n * @return the information about the <b>media</b> security\n */\n public String getMediaSecureInfo() {\n return mediaSecureInfo;\n }\n\n /**\n * Get the information about local held state of this call\n * \n * @return the information about local held state of media\n */\n public boolean isLocalHeld() {\n return mediaStatus == MediaState.LOCAL_HOLD;\n }\n\n /**\n * Get the information about remote held state of this call\n * \n * @return the information about remote held state of media\n */\n public boolean isRemoteHeld() {\n return (mediaStatus == MediaState.NONE && isActive() && !isBeforeConfirmed());\n }\n\n /**\n * Check if the specific call info indicates that it is a call that has not yet been confirmed by both ends.<br/>\n * In other worlds if the call is in state, calling, incoming early or connecting.\n * \n * @return true if the call can be considered not yet been confirmed\n */\n public boolean isBeforeConfirmed() {\n return (callState == InvState.CALLING || callState == InvState.INCOMING\n || callState == InvState.EARLY || callState == InvState.CONNECTING);\n }\n\n\n /**\n * Check if the specific call info indicates that it is a call that has been ended<br/>\n * In other worlds if the call is in state, disconnected, invalid or null\n * \n * @return true if the call can be considered as already ended\n */\n public boolean isAfterEnded() {\n return (callState == InvState.DISCONNECTED || callState == InvState.INVALID || callState == InvState.NULL);\n }\n\n /**\n * Get the latest status code of the sip dialog corresponding to this call\n * call\n * \n * @return the status code\n * @see StatusCode\n */\n public int getLastStatusCode() {\n return lastStatusCode;\n }\n\n /**\n * Get the last status comment of the sip dialog corresponding to this call\n * \n * @return the last status comment string from server\n */\n public String getLastStatusComment() {\n return lastStatusComment;\n }\n\n /**\n * Get the latest SIP reason code if any. \n * For now only supports 200 (if SIP reason is set to 200) or 0 in other cases (no SIP reason / sip reason set to something different).\n * \n * @return the status code\n */\n public int getLastReasonCode() {\n return lastReasonCode;\n }\n \n /**\n * Get whether the call has a video media stream connected\n * \n * @return true if the call has a video media stream\n */\n public boolean mediaHasVideo() {\n return mediaHasVideoStream;\n }\n\n /**\n * Get the current call recording status for this call.\n * \n * @return true if we are currently recording this call to a file\n */\n public boolean isRecording() {\n return isRecording;\n }\n \n /**\n * Get the capability to record the call to a file.\n * \n * @return true if it should be possible to record the call to a file\n */\n public boolean canRecord() {\n return canRecord;\n }\n\n /**\n * @return the zrtpSASVerified\n */\n public boolean isZrtpSASVerified() {\n return zrtpSASVerified;\n }\n\n /**\n * @return whether call has Zrtp encryption active\n */\n public boolean getHasZrtp() {\n return hasZrtp;\n }\n\n /**\n * Get the start time of the call.\n * @return the callStart start time of the call.\n */\n public long getCallStart() {\n return callStart;\n }\n\n}", "public final class SipManager {\n // -------\n // Static constants\n // PERMISSION\n /**\n * Permission that allows to use sip : place call, control call etc.\n */\n public static final String PERMISSION_USE_SIP = \"android.permission.USE_SIP\";\n /**\n * Permission that allows to configure sip engine : preferences, accounts.\n */\n public static final String PERMISSION_CONFIGURE_SIP = \"android.permission.CONFIGURE_SIP\";\n\n // SERVICE intents\n /**\n * Used to bind sip service to configure it.<br/>\n * This method has been deprected and should not be used anymore. <br/>\n * Use content provider approach instead\n * \n * @see SipConfigManager\n */\n public static final String INTENT_SIP_CONFIGURATION = \"com.csipsimple.service.SipConfiguration\";\n /**\n * Bind sip service to control calls.<br/>\n * If you start the service using {@link android.content.Context#startService(android.content.Intent intent)}\n * , you may want to pass {@link #EXTRA_OUTGOING_ACTIVITY} to specify you\n * are starting the service in order to make outgoing calls. You are then in\n * charge to unregister for outgoing calls when user finish with your\n * activity or when you are not anymore in calls using\n * {@link #ACTION_OUTGOING_UNREGISTER}<br/>\n * If you actually make a call or ask service to do something but wants to\n * unregister, you must defer unregister of your activity using\n * {@link #ACTION_DEFER_OUTGOING_UNREGISTER}.\n * \n * @see ISipService\n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String INTENT_SIP_SERVICE = \"com.csipsimple.service.SipService\";\n \n /**\n * Shortcut to turn on / off a sip account.\n * <p>\n * Expected Extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} as Long to choose the account to\n * activate/deactivate</li>\n * <li><i>{@link SipProfile#FIELD_ACTIVE} - optional </i> as boolean to\n * choose if should be activated or deactivated</li>\n * </ul>\n * </p>\n */\n public static final String INTENT_SIP_ACCOUNT_ACTIVATE = \"com.csipsimple.accounts.activate\";\n\n /**\n * Scheme for csip uri.\n */\n public static final String PROTOCOL_CSIP = \"csip\";\n /**\n * Scheme for sip uri.\n */\n public static final String PROTOCOL_SIP = \"sip\";\n /**\n * Scheme for sips (sip+tls) uri.\n */\n public static final String PROTOCOL_SIPS = \"sips\";\n // -------\n // ACTIONS\n /**\n * Action launched when a sip call is ongoing.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link #EXTRA_CALL_INFO} a {@link SipCallSession} containing infos of\n * the call</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_UI = \"com.csipsimple.phone.action.INCALL\";\n /**\n * Action launched when the status icon clicked.<br/>\n * Should raise the dialer.\n */\n public static final String ACTION_SIP_DIALER = \"com.csipsimple.phone.action.DIALER\";\n /**\n * Action launched when a missed call notification entry is clicked.<br/>\n * Should raise call logs list.\n */\n public static final String ACTION_SIP_CALLLOG = \"com.csipsimple.phone.action.CALLLOG\";\n /**\n * Action launched when a sip message notification entry is clicked.<br/>\n * Should raise the sip message list.\n */\n public static final String ACTION_SIP_MESSAGES = \"com.csipsimple.phone.action.MESSAGES\";\n /**\n * Action launched when user want to go in sip favorites.\n * Should raise the sip favorites view.\n */\n public static final String ACTION_SIP_FAVORITES = \"com.csipsimple.phone.action.FAVORITES\";\n /**\n * Action launched to enter fast settings.<br/>\n */\n public static final String ACTION_UI_PREFS_FAST = \"com.csipsimple.ui.action.PREFS_FAST\";\n /**\n * Action launched to enter global csipsimple settings.<br/>\n */\n public static final String ACTION_UI_PREFS_GLOBAL = \"com.csipsimple.ui.action.PREFS_GLOBAL\";\n \n // SERVICE BROADCASTS\n /**\n * Broadcastsent when a call is about to be launched.\n * <p>\n * Receiver of this ordered broadcast might rewrite and add new headers.\n * </p>\n */\n public static final String ACTION_SIP_CALL_LAUNCH = \"com.csipsimple.service.CALL_LAUNCHED\";\n /**\n * Broadcast sent when call state has changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link #EXTRA_CALL_INFO} a {@link SipCallSession} containing infos of\n * the call</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_CHANGED = \"com.csipsimple.service.CALL_CHANGED\";\n /**\n * Broadcast sent when sip account has been changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_ACCOUNT_CHANGED = \"com.csipsimple.service.ACCOUNT_CHANGED\";\n /**\n * Broadcast sent when a sip account has been deleted\n * <p>\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_ACCOUNT_DELETED = \"com.csipsimple.service.ACCOUNT_DELETED\";\n /**\n * Broadcast sent when sip account registration has changed.\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipProfile#FIELD_ID} the long id of the account</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_REGISTRATION_CHANGED = \"com.csipsimple.service.REGISTRATION_CHANGED\";\n /**\n * Broadcast sent when the state of device media has been changed.\n */\n public static final String ACTION_SIP_MEDIA_CHANGED = \"com.csipsimple.service.MEDIA_CHANGED\";\n /**\n * Broadcast sent when a ZRTP SAS\n */\n public static final String ACTION_ZRTP_SHOW_SAS = \"com.csipsimple.service.SHOW_SAS\";\n /**\n * Broadcast sent when a message has been received.<br/>\n * By message here, we mean a SIP SIMPLE message of the sip simple protocol. Understand a chat / im message.\n */\n public static final String ACTION_SIP_MESSAGE_RECEIVED = \"com.csipsimple.service.MESSAGE_RECEIVED\";\n /**\n * Broadcast sent when a conversation has been recorded.<br/>\n * This is linked to the call record feature of CSipSimple available through {@link ISipService#startRecording(int)}\n * <p>\n * Provided extras :\n * <ul>\n * <li>{@link SipManager#EXTRA_FILE_PATH} the path to the recorded file</li>\n * <li>{@link SipManager#EXTRA_CALL_INFO} the information on the call recorded</li>\n * </ul>\n * </p>\n */\n public static final String ACTION_SIP_CALL_RECORDED = \"com.csipsimple.service.CALL_RECORDED\";\n\n // REGISTERED BROADCASTS\n /**\n * Broadcast to send when the sip service can be stopped.\n */\n public static final String ACTION_SIP_CAN_BE_STOPPED = \"com.csipsimple.service.ACTION_SIP_CAN_BE_STOPPED\";\n /**\n * Broadcast to send when the sip service should be restarted.\n */\n public static final String ACTION_SIP_REQUEST_RESTART = \"com.csipsimple.service.ACTION_SIP_REQUEST_RESTART\";\n /**\n * Broadcast to send when your activity doesn't allow anymore user to make outgoing calls.<br/>\n * You have to pass registered {@link #EXTRA_OUTGOING_ACTIVITY} \n * \n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String ACTION_OUTGOING_UNREGISTER = \"com.csipsimple.service.ACTION_OUTGOING_UNREGISTER\";\n /**\n * Broadcast to send when you have launched a sip action (such as make call), but that your app will not anymore allow user to make outgoing calls actions.<br/>\n * You have to pass registered {@link #EXTRA_OUTGOING_ACTIVITY} \n * \n * @see #EXTRA_OUTGOING_ACTIVITY\n */\n public static final String ACTION_DEFER_OUTGOING_UNREGISTER = \"com.csipsimple.service.ACTION_DEFER_OUTGOING_UNREGISTER\";\n\n // PLUGINS BROADCASTS\n /**\n * Plugin action for themes.\n */\n public static final String ACTION_GET_DRAWABLES = \"com.csipsimple.themes.GET_DRAWABLES\";\n /**\n * Plugin action for call handlers.<br/>\n * You can expect {@link android.content.Intent#EXTRA_PHONE_NUMBER} as argument for the\n * number to call. <br/>\n * Your receiver must\n * {@link android.content.BroadcastReceiver#getResultExtras(boolean)} with parameter true to\n * fill response. <br/>\n * Your response contains :\n * <ul>\n * <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} with\n * {@link android.graphics.Bitmap} (mandatory) : Icon representing the call\n * handler</li>\n * <li>{@link android.content.Intent#EXTRA_TITLE} with\n * {@link String} (mandatory) : Title representing the call\n * handler</li>\n * <li>{@link android.content.Intent#EXTRA_REMOTE_INTENT_TOKEN} with\n * {@link android.app.PendingIntent} (mandatory) : The intent to fire when\n * this action is choosen</li>\n * <li>{@link android.content.Intent#EXTRA_PHONE_NUMBER} with\n * {@link String} (optional) : Phone number if the pending intent\n * launch a call intent. Empty if the pending intent launch something not\n * related to a GSM call.</li>\n * </ul>\n */\n public static final String ACTION_GET_PHONE_HANDLERS = \"com.csipsimple.phone.action.HANDLE_CALL\";\n \n /**\n * Plugin action for call management extension. <br/>\n * Any app that register this plugin and has rights to {@link #PERMISSION_USE_SIP} will appear \n * in the call cards. <br/>\n * The activity entry in manifest may have following metadata\n * <ul>\n * <li>{@link #EXTRA_SIP_CALL_MIN_STATE} minimum call state for this plugin to be active. Default {@link SipCallSession.InvState#EARLY}.</li>\n * <li>{@link #EXTRA_SIP_CALL_MAX_STATE} maximum call state for this plugin to be active. Default {@link SipCallSession.InvState#CONFIRMED}.</li>\n * <li>{@link #EXTRA_SIP_CALL_CALL_WAY} bitmask flag for selecting only one way. \n * {@link #BITMASK_IN} for incoming; \n * {@link #BITMASK_OUT} for outgoing.\n * Default ({@link #BITMASK_IN} | {@link #BITMASK_OUT}) (any way).</li>\n * </ul> \n * Receiver activity will get an extra with key {@value #EXTRA_CALL_INFO} with a {@link SipCallSession}.\n */\n public static final String ACTION_INCALL_PLUGIN = \"com.csipsimple.sipcall.action.HANDLE_CALL_PLUGIN\";\n \n public static final String EXTRA_SIP_CALL_MIN_STATE = \"com.csipsimple.sipcall.MIN_STATE\";\n public static final String EXTRA_SIP_CALL_MAX_STATE = \"com.csipsimple.sipcall.MAX_STATE\";\n public static final String EXTRA_SIP_CALL_CALL_WAY = \"com.csipsimple.sipcall.CALL_WAY\";\n \n /**\n * Bitmask to keep media/call coming from outside\n */\n public final static int BITMASK_IN = 1 << 0;\n /**\n * Bitmask to keep only media/call coming from the app\n */\n public final static int BITMASK_OUT = 1 << 1;\n /**\n * Bitmask to keep all media/call whatever incoming/outgoing\n */\n public final static int BITMASK_ALL = BITMASK_IN | BITMASK_OUT;\n \n /**\n * Plugin action for rewrite numbers. <br/> \n * You can expect {@link android.content.Intent#EXTRA_PHONE_NUMBER} as argument for the\n * number to rewrite. <br/>\n * Your receiver must\n * {@link android.content.BroadcastReceiver#getResultExtras(boolean)} with parameter true to\n * fill response. <br/>\n * Your response contains :\n * <ul>\n * <li>{@link android.content.Intent#EXTRA_PHONE_NUMBER} with\n * {@link String} (optional) : Rewritten phone number.</li>\n * </ul>\n */\n public final static String ACTION_REWRITE_NUMBER = \"com.csipsimple.phone.action.REWRITE_NUMBER\"; \n /**\n * Plugin action for audio codec.\n */\n public static final String ACTION_GET_EXTRA_CODECS = \"com.csipsimple.codecs.action.REGISTER_CODEC\";\n /**\n * Plugin action for video codec.\n */\n public static final String ACTION_GET_EXTRA_VIDEO_CODECS = \"com.csipsimple.codecs.action.REGISTER_VIDEO_CODEC\";\n /**\n * Plugin action for video.\n */\n public static final String ACTION_GET_VIDEO_PLUGIN = \"com.csipsimple.plugins.action.REGISTER_VIDEO\";\n /**\n * Meta constant name for library name.\n */\n public static final String META_LIB_NAME = \"lib_name\";\n /**\n * Meta constant name for the factory name.\n */\n public static final String META_LIB_INIT_FACTORY = \"init_factory\";\n /**\n * Meta constant name for the factory deinit name.\n */\n public static final String META_LIB_DEINIT_FACTORY = \"deinit_factory\";\n\n // Content provider\n /**\n * Authority for regular database of the application.\n */\n public static final String AUTHORITY = \"com.csipsimple.db\";\n /**\n * Base content type for csipsimple objects.\n */\n public static final String BASE_DIR_TYPE = \"vnd.android.cursor.dir/vnd.csipsimple\";\n /**\n * Base item content type for csipsimple objects.\n */\n public static final String BASE_ITEM_TYPE = \"vnd.android.cursor.item/vnd.csipsimple\";\n\n // Content Provider - call logs\n /**\n * Table name for call logs.\n */\n public static final String CALLLOGS_TABLE_NAME = \"calllogs\";\n /**\n * Content type for call logs provider.\n */\n public static final String CALLLOG_CONTENT_TYPE = BASE_DIR_TYPE + \".calllog\";\n /**\n * Item type for call logs provider.\n */\n public static final String CALLLOG_CONTENT_ITEM_TYPE = BASE_ITEM_TYPE + \".calllog\";\n /**\n * Uri for call log content provider.\n */\n public static final Uri CALLLOG_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + CALLLOGS_TABLE_NAME);\n /**\n * Base uri for a specific call log. Should be appended with id of the call log.\n */\n public static final Uri CALLLOG_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + CALLLOGS_TABLE_NAME + \"/\");\n // -- Extra fields for call logs\n /**\n * The account used for this call\n */\n public static final String CALLLOG_PROFILE_ID_FIELD = \"account_id\";\n /**\n * The final latest status code for this call.\n */\n public static final String CALLLOG_STATUS_CODE_FIELD = \"status_code\";\n /**\n * The final latest status text for this call.\n */\n public static final String CALLLOG_STATUS_TEXT_FIELD = \"status_text\";\n\n // Content Provider - filter\n /**\n * Table name for filters/rewriting rules.\n */\n public static final String FILTERS_TABLE_NAME = \"outgoing_filters\";\n /**\n * Content type for filter provider.\n */\n public static final String FILTER_CONTENT_TYPE = BASE_DIR_TYPE + \".filter\";\n /**\n * Item type for filter provider.\n */\n public static final String FILTER_CONTENT_ITEM_TYPE = BASE_ITEM_TYPE + \".filter\";\n /**\n * Uri for filters provider.\n */\n public static final Uri FILTER_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + FILTERS_TABLE_NAME);\n /**\n * Base uri for a specific filter. Should be appended with filter id.\n */\n public static final Uri FILTER_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + AUTHORITY + \"/\"\n + FILTERS_TABLE_NAME + \"/\");\n\n // EXTRAS\n /**\n * Extra key to contains infos about a sip call.<br/>\n * @see SipCallSession\n */\n public static final String EXTRA_CALL_INFO = \"call_info\";\n \n\n /**\n * Tell sip service that it's an user interface requesting for outgoing call.<br/>\n * It's an extra to add to sip service start as string representing unique key for your activity.<br/>\n * We advise to use your own component name {@link android.content.ComponentName} to avoid collisions.<br/>\n * Each activity is in charge unregistering broadcasting {@link #ACTION_OUTGOING_UNREGISTER} or {@link #ACTION_DEFER_OUTGOING_UNREGISTER}<br/>\n * \n * @see android.content.ComponentName\n */\n public static final String EXTRA_OUTGOING_ACTIVITY = \"outgoing_activity\";\n \n /**\n * Extra key to contain an string to path of a file.<br/>\n * @see String\n */\n public static final String EXTRA_FILE_PATH = \"file_path\";\n \n /**\n * Target in a sip launched call.\n * @see #ACTION_SIP_CALL_LAUNCH\n */\n public static final String EXTRA_SIP_CALL_TARGET = \"call_target\";\n /**\n * Options of a sip launched call.\n * @see #ACTION_SIP_CALL_LAUNCH\n */\n public static final String EXTRA_SIP_CALL_OPTIONS = \"call_options\";\n \n /**\n * Extra key to contain behavior of outgoing call chooser activity.<br/>\n * In case an account is specified in the outgoing call intent with {@link SipProfile#FIELD_ACC_ID}\n * and the application doesn't find this account,\n * this extra parameter allows to determine what is the fallback behavior of\n * the activity. <br/>\n * By default {@link #FALLBACK_ASK}.\n * Other options : \n */\n public static final String EXTRA_FALLBACK_BEHAVIOR = \"fallback_behavior\";\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}.\n * Prompt user with other choices without calling automatically.\n */\n public static final int FALLBACK_ASK = 0;\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}.\n * Warn user about the fact current account not valid and exit.\n * WARNING : not yet implemented, will behaves just like {@link #FALLBACK_ASK} for now\n */\n public static final int FALLBACK_PREVENT = 1;\n /**\n * Parameter for {@link #EXTRA_FALLBACK_BEHAVIOR}\n * Automatically fallback to any other available account in case requested sip profile is not there.\n */\n public static final int FALLBACK_AUTO_CALL_OTHER = 2;\n \n // Constants\n /**\n * Constant for success return\n */\n public static final int SUCCESS = 0;\n /**\n * Constant for network errors return\n */\n public static final int ERROR_CURRENT_NETWORK = 10;\n\n /**\n * Possible presence status.\n */\n public enum PresenceStatus {\n /**\n * Unknown status\n */\n UNKNOWN,\n /**\n * Online status\n */\n ONLINE,\n /**\n * Offline status\n */\n OFFLINE,\n /**\n * Busy status\n */\n BUSY,\n /**\n * Away status\n */\n AWAY,\n }\n\n /**\n * Current api version number.<br/>\n * Major version x 1000 + minor version. <br/>\n * Major version are backward compatible.\n */\n public static final int CURRENT_API = 2005;\n\n /**\n * Ensure capability of the remote sip service to reply our requests <br/>\n * \n * @param service the bound service to check\n * @return true if we can safely use the API\n */\n public static boolean isApiCompatible(ISipService service) {\n if (service != null) {\n try {\n int version = service.getVersion();\n return (Math.floor(version / 1000) == Math.floor(CURRENT_API % 1000));\n } catch (RemoteException e) {\n // We consider this is a bad api version that does not have\n // versionning at all\n return false;\n }\n }\n\n return false;\n }\n}", "public enum PresenceStatus {\n /**\n * Unknown status\n */\n UNKNOWN,\n /**\n * Online status\n */\n ONLINE,\n /**\n * Offline status\n */\n OFFLINE,\n /**\n * Busy status\n */\n BUSY,\n /**\n * Away status\n */\n AWAY,\n}", "public class SipMessage {\n\n /**\n * Primary key id.\n * \n * @see Long\n */\n public static final String FIELD_ID = \"id\";\n /**\n * From / sender.\n * \n * @see String\n */\n public static final String FIELD_FROM = \"sender\";\n /**\n * To / receiver.\n * \n * @see String\n */\n public static final String FIELD_TO = \"receiver\";\n /**\n * Contact of the sip message.\n */\n public static final String FIELD_CONTACT = \"contact\";\n /**\n * Body / content of the sip message.\n * \n * @see String\n */\n public static final String FIELD_BODY = \"body\";\n /**\n * Mime type of the sip message.\n * \n * @see String\n */\n public static final String FIELD_MIME_TYPE = \"mime_type\";\n /**\n * Way type of the message.\n * \n * @see Integer\n * @see #MESSAGE_TYPE_INBOX\n * @see #MESSAGE_TYPE_FAILED\n * @see #MESSAGE_TYPE_QUEUED\n * @see #MESSAGE_TYPE_SENT\n */\n public static final String FIELD_TYPE = \"type\";\n /**\n * Reception date of the message.\n * \n * @see Long\n */\n public static final String FIELD_DATE = \"date\";\n /**\n * Latest pager status.\n * \n * @see Integer\n */\n public static final String FIELD_STATUS = \"status\";\n /**\n * Read status of the message.\n * \n * @see Boolean\n */\n public static final String FIELD_READ = \"read\";\n /**\n * Non canonical sip from\n * \n * @see String\n */\n public static final String FIELD_FROM_FULL = \"full_sender\";\n\n /**\n * Message received type.\n */\n public static final int MESSAGE_TYPE_INBOX = 1;\n /**\n * Message sent type.\n */\n public static final int MESSAGE_TYPE_SENT = 2;\n /**\n * Failed outgoing message.\n */\n public static final int MESSAGE_TYPE_FAILED = 5;\n /**\n * Message to send later.\n */\n public static final int MESSAGE_TYPE_QUEUED = 6;\n\n // Content Provider - account\n /**\n * Table for sip message.\n */\n public static final String MESSAGES_TABLE_NAME = \"messages\";\n /**\n * Content type for sip message.\n */\n public static final String MESSAGE_CONTENT_TYPE = SipManager.BASE_DIR_TYPE + \".message\";\n /**\n * Item type for a sip message.\n */\n public static final String MESSAGE_CONTENT_ITEM_TYPE = SipManager.BASE_ITEM_TYPE + \".message\";\n /**\n * Uri for content provider of sip message\n */\n public static final Uri MESSAGE_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + MESSAGES_TABLE_NAME);\n /**\n * Base uri for sip message content provider.<br/>\n * To append with {@link #FIELD_ID}\n * \n * @see ContentUris#appendId(Uri.Builder, long)\n */\n public static final Uri MESSAGE_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + MESSAGES_TABLE_NAME + \"/\");\n /**\n * Table for threads. <br/>\n * It's an alias.\n */\n public static final String THREAD_ALIAS = \"thread\";\n /**\n * Uri for content provider of threads view.\n */\n public static final Uri THREAD_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + THREAD_ALIAS);\n /**\n * Base uri for thread views.\n */\n public static final Uri THREAD_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + THREAD_ALIAS + \"/\");\n\n /**\n * Status unknown for a message.\n */\n public static final int STATUS_NONE = -1;\n /**\n * Constant to represent self as sender or receiver of the message.\n */\n public static final String SELF = \"SELF\";\n\n private String from;\n private String fullFrom;\n private String to;\n private String contact;\n private String body;\n private String mimeType;\n private long date;\n private int type;\n private int status = STATUS_NONE;\n private boolean read = false;\n\n /**\n * Construct from raw datas.\n * \n * @param aForm {@link #FIELD_FROM}\n * @param aTo {@link #FIELD_TO}\n * @param aContact {@link #FIELD_CONTACT}\n * @param aBody {@link #FIELD_BODY}\n * @param aMimeType {@link #FIELD_MIME_TYPE}\n * @param aDate {@link #FIELD_DATE}\n * @param aType {@link #FIELD_TYPE}\n * @param aFullFrom {@link #FIELD_FROM_FULL}\n */\n public SipMessage(String aForm, String aTo, String aContact, String aBody, String aMimeType,\n long aDate, int aType, String aFullFrom) {\n from = aForm;\n to = aTo;\n contact = aContact;\n body = aBody;\n mimeType = aMimeType;\n date = aDate;\n type = aType;\n fullFrom = aFullFrom;\n }\n\n /**\n * Construct a sip message wrapper from a cursor retrieved with a\n * {@link ContentProvider} query on {@link #MESSAGES_TABLE_NAME}.\n * \n * @param c the cursor to unpack\n */\n public SipMessage(Cursor c) {\n ContentValues args = new ContentValues();\n DatabaseUtils.cursorRowToContentValues(c, args);\n createFromContentValue(args);\n }\n\n /**\n * Pack the object content value to store\n * \n * @return The content value representing the message\n */\n public ContentValues getContentValues() {\n ContentValues cv = new ContentValues();\n cv.put(FIELD_FROM, from);\n cv.put(FIELD_TO, to);\n cv.put(FIELD_CONTACT, contact);\n cv.put(FIELD_BODY, body);\n cv.put(FIELD_MIME_TYPE, mimeType);\n cv.put(FIELD_TYPE, type);\n cv.put(FIELD_DATE, date);\n cv.put(FIELD_STATUS, status);\n cv.put(FIELD_READ, read);\n cv.put(FIELD_FROM_FULL, fullFrom);\n return cv;\n }\n \n public final void createFromContentValue(ContentValues args) {\n Integer tmp_i;\n String tmp_s;\n Long tmp_l;\n Boolean tmp_b;\n \n tmp_s = args.getAsString(FIELD_FROM);\n if(tmp_s != null) {\n from = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_TO);\n if(tmp_s != null) {\n to = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_CONTACT);\n if(tmp_s != null) {\n contact = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_BODY);\n if(tmp_s != null) {\n body = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_MIME_TYPE);\n if(tmp_s != null) {\n mimeType = tmp_s;\n }\n tmp_l = args.getAsLong(FIELD_DATE);\n if(tmp_l != null) {\n date = tmp_l;\n }\n tmp_i = args.getAsInteger(FIELD_TYPE);\n if(tmp_i != null) {\n type = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_STATUS);\n if(tmp_i != null) {\n status = tmp_i;\n }\n tmp_b = args.getAsBoolean(FIELD_READ);\n if(tmp_b != null) {\n read = tmp_b;\n }\n\n tmp_s = args.getAsString(FIELD_FROM_FULL);\n if(tmp_s != null) {\n fullFrom = tmp_s;\n }\n }\n\n /**\n * Get the from of the message.\n * \n * @return the From of the sip message\n */\n public String getFrom() {\n return from;\n }\n\n /**\n * Get the body of the message.\n * \n * @return the Body of the message\n */\n public String getBody() {\n return body;\n }\n\n /**\n * Get to of the message.\n * \n * @return the To of the sip message\n */\n public String getTo() {\n return to;\n }\n\n /**\n * Set the message as read or unread.\n * \n * @param b true when read.\n */\n public void setRead(boolean b) {\n read = b;\n\n }\n\n /**\n * Get the display name of remote party.\n * \n * @return The remote display name\n */\n public String getDisplayName() {\n return SipUri.getDisplayedSimpleContact(fullFrom);\n }\n \n /**\n * Get the number of the remote party.\n * \n * @return The remote party number\n */\n public String getRemoteNumber() {\n if (SipMessage.SELF.equalsIgnoreCase(from)) {\n return to;\n }else {\n return from;\n }\n }\n \n /**\n * Get the content of the body without error tag\n * @return The body of the sip message\n */\n public String getBodyContent() {\n int splitIndex = body.indexOf(\" // \");\n if(splitIndex != -1) {\n return body.substring(0, splitIndex);\n }\n return body;\n }\n /**\n * Get optional error of the sip message\n * \n * @return The error string repr if any, null otherwise.\n */\n public String getErrorContent() {\n if (status == SipMessage.STATUS_NONE\n || status == SipCallSession.StatusCode.OK\n || status == SipCallSession.StatusCode.ACCEPTED) {\n return null;\n }\n \n int splitIndex = body.indexOf(\" // \");\n if(splitIndex != -1) {\n return body.substring(splitIndex + 4, body.length());\n }\n return null;\n }\n \n /**\n * Get the way of the message is send by the user of the application\n * \n * @return true if message is sent by the user of the application\n */\n public boolean isOutgoing() {\n if (SipMessage.SELF.equalsIgnoreCase(from)) {\n return true;\n }else {\n return false;\n }\n }\n \n /**\n * Get the send/receive date of the message.\n * @return the date of the send of the message for outgoing, of receive for incoming.\n */\n public long getDate() {\n return date;\n }\n \n /**\n * Get the complete remote contact from which the message comes.<br/>\n * This includes display name.\n * \n * @return the sip uri of remote contact as announced when sending this message.\n */\n public String getFullFrom() {\n return fullFrom;\n }\n\n /**\n * Get the type of the message.\n * \n * @return Message type\n * @see #MESSAGE_TYPE_FAILED\n * @see #MESSAGE_TYPE_INBOX\n * @see #MESSAGE_TYPE_QUEUED\n * @see #MESSAGE_TYPE_SENT\n */\n public int getType() {\n return type;\n }\n\n /**\n * Get the mime type of the message.\n * \n * @return the message mime type sent by remote party.\n */\n public String getMimeType() {\n return mimeType;\n }\n}", "public class SipProfile implements Parcelable {\n private static final String THIS_FILE = \"SipProfile\";\n\n // Constants\n /**\n * Constant for an invalid account id.\n */\n public final static long INVALID_ID = -1;\n\n // Transport choices\n /**\n * Automatically choose transport.<br/>\n * By default it uses UDP, if packet is higher than UDP limit it will switch\n * to TCP.<br/>\n * Take care with that , because not all sip servers support udp/tcp\n * correclty.\n */\n public final static int TRANSPORT_AUTO = 0;\n /**\n * Force UDP transport.\n */\n public final static int TRANSPORT_UDP = 1;\n /**\n * Force TCP transport.\n */\n public final static int TRANSPORT_TCP = 2;\n /**\n * Force TLS transport.\n */\n public final static int TRANSPORT_TLS = 3;\n\n // Stack choices\n /**\n * Use pjsip as backend.<br/>\n * For now it's the only one supported\n */\n public static final int PJSIP_STACK = 0;\n /**\n * @deprecated Use google google android 2.3 backend.<br/>\n * This is not supported for now.\n */\n public static final int GOOGLE_STACK = 1;\n\n // Password type choices\n /**\n * Plain password mode.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see #datatype\n */\n public static final int CRED_DATA_PLAIN_PASSWD = 0;\n /**\n * Digest mode.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see #datatype\n */\n public static final int CRED_DATA_DIGEST = 1;\n /**\n * @deprecated This mode is not supported by csipsimple for now.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * @see #datatype\n */\n public static final int CRED_CRED_DATA_EXT_AKA = 2;\n\n // Scheme credentials choices\n /**\n * Digest scheme for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see #scheme\n */\n public static final String CRED_SCHEME_DIGEST = \"Digest\";\n /**\n * PGP scheme for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see #scheme\n */\n public static final String CRED_SCHEME_PGP = \"PGP\";\n\n /**\n * Separator for proxy field once stored in database.<br/>\n * It's the pipe char.\n * \n * @see #FIELD_PROXY\n */\n public static final String PROXIES_SEPARATOR = \"|\";\n\n // Content Provider - account\n /**\n * Table name of content provider for accounts storage\n */\n public final static String ACCOUNTS_TABLE_NAME = \"accounts\";\n /**\n * Content type for account / sip profile\n */\n public final static String ACCOUNT_CONTENT_TYPE = SipManager.BASE_DIR_TYPE + \".account\";\n /**\n * Item type for account / sip profile\n */\n public final static String ACCOUNT_CONTENT_ITEM_TYPE = SipManager.BASE_ITEM_TYPE + \".account\";\n /**\n * Uri of accounts / sip profiles\n */\n public final static Uri ACCOUNT_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_TABLE_NAME);\n /**\n * Base uri for the account / sip profile. <br/>\n * To append with {@link #FIELD_ID}\n * \n * @see ContentUris#appendId(Uri.Builder, long)\n */\n public final static Uri ACCOUNT_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_TABLE_NAME + \"/\");\n\n // Content Provider - account status\n /**\n * Virutal table name for sip profile adding/registration table.<br/>\n * An application should use it in read only mode.\n */\n public final static String ACCOUNTS_STATUS_TABLE_NAME = \"accounts_status\";\n /**\n * Content type for sip profile adding/registration state\n */\n public final static String ACCOUNT_STATUS_CONTENT_TYPE = SipManager.BASE_DIR_TYPE\n + \".account_status\";\n /**\n * Content type for sip profile adding/registration state item\n */\n public final static String ACCOUNT_STATUS_CONTENT_ITEM_TYPE = SipManager.BASE_ITEM_TYPE\n + \".account_status\";\n /**\n * Uri for the sip profile adding/registration state.\n */\n public final static Uri ACCOUNT_STATUS_URI = Uri.parse(ContentResolver.SCHEME_CONTENT + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_STATUS_TABLE_NAME);\n /**\n * Base uri for the sip profile adding/registration state. <br/>\n * To append with {@link #FIELD_ID}\n * \n * @see ContentUris#appendId(Uri.Builder, long)\n */\n public final static Uri ACCOUNT_STATUS_ID_URI_BASE = Uri.parse(ContentResolver.SCHEME_CONTENT\n + \"://\"\n + SipManager.AUTHORITY + \"/\" + ACCOUNTS_STATUS_TABLE_NAME + \"/\");\n\n // Fields for table accounts\n /**\n * Primary key identifier of the account in the database.\n * \n * @see Long\n */\n public static final String FIELD_ID = \"id\";\n /**\n * Activation state of the account.<br/>\n * If false this account will be ignored by the sip stack.\n * \n * @see Boolean\n */\n public static final String FIELD_ACTIVE = \"active\";\n /**\n * The wizard associated to this account.<br/>\n * Used for icon and edit layout view.\n * \n * @see String\n */\n public static final String FIELD_WIZARD = \"wizard\";\n /**\n * The display name of the account. <br/>\n * This is used in the application interface to show the label representing\n * the account.\n * \n * @see String\n */\n public static final String FIELD_DISPLAY_NAME = \"display_name\";\n /**\n * The priority of the account.<br/>\n * This is used in the interface when presenting list of accounts.<br/>\n * This can also be used to choose the default account. <br/>\n * Higher means highest priority.\n * \n * @see Integer\n */\n public static final String FIELD_PRIORITY = \"priority\";\n /**\n * The full SIP URL for the account. <br/>\n * The value can take name address or URL format, and will look something\n * like \"sip:account@serviceprovider\".<br/>\n * This field is mandatory.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ab290b04e8150ed9627335a67e6127b7c\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_ACC_ID = \"acc_id\";\n \n /**\n * Data useful for the wizard internal use.\n * The format here is specific to the wizard and no assumption is made.\n * Could be simplestring, json, base64 encoded stuff etc.\n * \n * @see String\n */\n public static final String FIELD_WIZARD_DATA = \"wizard_data\";\n \n /**\n * This is the URL to be put in the request URI for the registration, and\n * will look something like \"sip:serviceprovider\".<br/>\n * This field should be specified if registration is desired. If the value\n * is empty, no account registration will be performed.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a08473de6401e966d23f34d3a9a05bdd0\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_REG_URI = \"reg_uri\";\n /**\n * Subscribe to message waiting indication events (RFC 3842).<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a0158ae24d72872a31a0b33c33450a7ab\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_MWI_ENABLED = \"mwi_enabled\";\n /**\n * If this flag is set, the presence information of this account will be\n * PUBLISH-ed to the server where the account belongs.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a0d4128f44963deffda4ea9c15183a787\"\n * >Pjsip documentation</a>\n * 1 for true, 0 for false\n * \n * @see Integer\n */\n public static final String FIELD_PUBLISH_ENABLED = \"publish_enabled\";\n /**\n * Optional interval for registration, in seconds. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a2c097b9ae855783bfbb00056055dd96c\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_TIMEOUT = \"reg_timeout\";\n /**\n * Specify the number of seconds to refresh the client registration before\n * the registration expires.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a52a35fdf8c17263b2a27d2b17111c040\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_DELAY_BEFORE_REFRESH = \"reg_dbr\";\n /**\n * Set the interval for periodic keep-alive transmission for this account. <br/>\n * If this value is zero, keep-alive will be disabled for this account.<br/>\n * The keep-alive transmission will be sent to the registrar's address,\n * after successful registration.<br/>\n * Note that in csipsimple this value is not applied anymore in flavor to\n * {@link SipConfigManager#KEEP_ALIVE_INTERVAL_MOBILE} and\n * {@link SipConfigManager#KEEP_ALIVE_INTERVAL_WIFI} <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a98722b6464d16b5a76aec81f2d2a0694\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_KA_INTERVAL = \"ka_interval\";\n /**\n * Optional PIDF tuple ID for outgoing PUBLISH and NOTIFY. <br/>\n * If this value is not specified, a random string will be used. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#aa603989566022840b4671f0171b6cba1\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_PIDF_TUPLE_ID = \"pidf_tuple_id\";\n /**\n * Optional URI to be put as Contact for this account.<br/>\n * It is recommended that this field is left empty, so that the value will\n * be calculated automatically based on the transport address.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a5dfdfba40038e33af95819fbe2b896f9\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_FORCE_CONTACT = \"force_contact\";\n\n /**\n * This option is used to update the transport address and the Contact\n * header of REGISTER request.<br/>\n * When this option is enabled, the library will keep track of the public IP\n * address from the response of REGISTER request. <br/>\n * Once it detects that the address has changed, it will unregister current\n * Contact, update the Contact with transport address learned from Via\n * header, and register a new Contact to the registrar.<br/>\n * This will also update the public name of UDP transport if STUN is\n * configured.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a22961bb72ea75f7ca7008464f081ca06\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_CONTACT_REWRITE = \"allow_contact_rewrite\";\n /**\n * Specify how Contact update will be done with the registration, if\n * allow_contact_rewrite is enabled.<br/>\n * <ul>\n * <li>If set to 1, the Contact update will be done by sending\n * unregistration to the currently registered Contact, while simultaneously\n * sending new registration (with different Call-ID) for the updated\n * Contact.</li>\n * <li>If set to 2, the Contact update will be done in a single, current\n * registration session, by removing the current binding (by setting its\n * Contact's expires parameter to zero) and adding a new Contact binding,\n * all done in a single request.</li>\n * </ul>\n * Value 1 is the legacy behavior.<br/>\n * Value 2 is the default behavior.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a73b69a3a8d225147ce386e310e588285\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_CONTACT_REWRITE_METHOD = \"contact_rewrite_method\";\n\n /**\n * Additional parameters that will be appended in the Contact header for\n * this account.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#abef88254f9ef2a490503df6d3b297e54\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_CONTACT_PARAMS = \"contact_params\";\n /**\n * Additional URI parameters that will be appended in the Contact URI for\n * this account.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#aced70341308928ae951525093bf47562\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_CONTACT_URI_PARAMS = \"contact_uri_params\";\n /**\n * Transport to use for this account.<br/>\n * \n * @see #TRANSPORT_AUTO\n * @see #TRANSPORT_UDP\n * @see #TRANSPORT_TCP\n * @see #TRANSPORT_TLS\n */\n public static final String FIELD_TRANSPORT = \"transport\";\n /**\n * Default scheme to automatically add for this account when calling without uri scheme.<br/>\n * \n * This is free field but should be one of :\n * sip, sips, tel\n * If invalid (or empty) will automatically fallback to sip\n */\n public static final String FIELD_DEFAULT_URI_SCHEME = \"default_uri_scheme\";\n /**\n * Way the application should use SRTP. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a34b00edb1851924a99efd8fedab917ba\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_USE_SRTP = \"use_srtp\";\n /**\n * Way the application should use SRTP. <br/>\n * -1 means use default global value of {@link SipConfigManager#USE_ZRTP} <br/>\n * 0 means disabled for this account <br/>\n * 1 means enabled for this account\n * \n * @see Integer\n */\n public static final String FIELD_USE_ZRTP = \"use_zrtp\";\n\n /**\n * Optional URI of the proxies to be visited for all outgoing requests that\n * are using this account (REGISTER, INVITE, etc).<br/>\n * If multiple separate it by {@link #PROXIES_SEPARATOR}. <br/>\n * Warning, for now api doesn't allow multiple credentials so if you have\n * one credential per proxy may not work.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a93ad0699020c17ddad5eb98dea69f699\"\n * >Pjsip documentation</a>\n * \n * @see String\n * @see #PROXIES_SEPARATOR\n */\n public static final String FIELD_PROXY = \"proxy\";\n /**\n * Specify how the registration uses the outbound and account proxy\n * settings. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ad932bbb3c2c256f801c775319e645717\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_REG_USE_PROXY = \"reg_use_proxy\";\n\n // For now, assume unique credential\n /**\n * Realm to filter on for credentials.<br/>\n * Put star \"*\" char if you want it to match all requests.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a96eee6bdc2b0e7e3b7eea9b4e1c15674\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_REALM = \"realm\";\n /**\n * Scheme (e.g. \"digest\").<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ae31c9ec1c99fb1ffa20be5954ee995a7\"\n * >Pjsip documentation</a>\n * \n * @see String\n * @see #CRED_SCHEME_DIGEST\n * @see #CRED_SCHEME_PGP\n */\n public static final String FIELD_SCHEME = \"scheme\";\n /**\n * Credential username.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a3e1f72a171886985c6dfcd57d4bc4f17\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_USERNAME = \"username\";\n /**\n * Type of the data for credentials.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#a8b1e563c814bdf8012f0bdf966d0ad9d\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n * @see #CRED_DATA_PLAIN_PASSWD\n * @see #CRED_DATA_DIGEST\n * @see #CRED_CRED_DATA_EXT_AKA\n */\n public static final String FIELD_DATATYPE = \"datatype\";\n /**\n * The data, which can be a plaintext password or a hashed digest.<br/>\n * This is available on in read only for third party application for obvious\n * security reason.<br/>\n * If you update the content provider without passing this parameter it will\n * not override it. <br/>\n * If in a third party app you want to store the password to allow user to\n * see it, you have to manage this by your own. <br/>\n * However, it's highly recommanded to not store it by your own, and keep it\n * stored only in csipsimple.<br/>\n * It available for write/overwrite. <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsip__cred__info.htm#ab3947a7800c51d28a1b25f4fdaea78bd\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_DATA = \"data\";\n \n /**\n * If this flag is set, the authentication client framework will send an empty Authorization header in each initial request. Default is no.\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/docs/latest/pjsip/docs/html/structpjsip__auth__clt__pref.htm#ac3487e53d8d6b3ea392315b08e2aac4a\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_AUTH_INITIAL_AUTH = \"initial_auth\";\n \n /**\n * If this flag is set, the authentication client framework will send an empty Authorization header in each initial request. Default is no.\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/docs/latest/pjsip/docs/html/structpjsip__auth__clt__pref.htm#ac3487e53d8d6b3ea392315b08e2aac4a\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_AUTH_ALGO = \"auth_algo\";\n\n // Android stuff\n /**\n * The backend sip stack to use for this account.<br/>\n * For now only pjsip backend is supported.\n * \n * @see Integer\n * @see #PJSIP_STACK\n * @see #GOOGLE_STACK\n */\n public static final String FIELD_SIP_STACK = \"sip_stack\";\n /**\n * Sip contact to call if user want to consult his voice mail.<br/>\n * \n * @see String\n */\n public static final String FIELD_VOICE_MAIL_NBR = \"vm_nbr\";\n /**\n * Associated contact group for buddy list of this account.<br/>\n * Users of this group will be considered as part of the buddy list of this\n * account and will automatically try to subscribe presence if activated.<br/>\n * Warning : not implemented for now.\n * \n * @see String\n */\n public static final String FIELD_ANDROID_GROUP = \"android_group\";\n\n // Sip outbound\n /**\n * Control the use of SIP outbound feature. <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a306e4641988606f1ef0993e398ff98e7\"\n * >Pjsip documentation</a>\n * \n * @see Integer\n */\n public static final String FIELD_USE_RFC5626 = \"use_rfc5626\";\n /**\n * Specify SIP outbound (RFC 5626) instance ID to be used by this\n * application.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#ae025bf4538d1f9f9506b45015a46a8f6\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_RFC5626_INSTANCE_ID = \"rfc5626_instance_id\";\n /**\n * Specify SIP outbound (RFC 5626) registration ID.<br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm#a71376e1f32e35401fc6c2c3bcb2087d8\"\n * >Pjsip documentation</a>\n * \n * @see String\n */\n public static final String FIELD_RFC5626_REG_ID = \"rfc5626_reg_id\";\n\n // Video config\n /**\n * Auto show video of the remote party.<br/>\n * TODO : complete when pjsip-2.x stable documentation out\n */\n public static final String FIELD_VID_IN_AUTO_SHOW = \"vid_in_auto_show\";\n /**\n * Auto transmit video of our party.<br/>\n * TODO : complete when pjsip-2.x stable documentation out\n */\n public static final String FIELD_VID_OUT_AUTO_TRANSMIT = \"vid_out_auto_transmit\";\n\n // RTP config\n /**\n * Begin RTP port for the media of this account.<br/>\n * By default it will use {@link SipConfigManager#RTP_PORT}\n * \n * @see Integer\n */\n public static final String FIELD_RTP_PORT = \"rtp_port\";\n /**\n * Public address to announce in SDP as self media address.<br/>\n * Only use if you have static and known public ip on your device regarding\n * the sip server. <br/>\n * May be helpful in VPN configurations.\n */\n public static final String FIELD_RTP_PUBLIC_ADDR = \"rtp_public_addr\";\n /**\n * Address to bound from client to enforce on interface to be used. <br/>\n * By default the application bind all addresses. (0.0.0.0).<br/>\n * This is only useful if you want to avoid one interface to be bound, but\n * is useless to get audio path correctly working use\n * {@link #FIELD_RTP_PUBLIC_ADDR}\n */\n public static final String FIELD_RTP_BOUND_ADDR = \"rtp_bound_addr\";\n /**\n * Should the QoS be enabled on this account.<br/>\n * By default it will use {@link SipConfigManager#ENABLE_QOS}.<br/>\n * Default value is -1 to use global setting. 0 means disabled, 1 means\n * enabled.<br/>\n * \n * @see Integer\n * @see SipConfigManager#ENABLE_QOS\n */\n public static final String FIELD_RTP_ENABLE_QOS = \"rtp_enable_qos\";\n /**\n * The value of DSCP.<br/>\n * \n * @see Integer\n * @see SipConfigManager#DSCP_VAL\n */\n public static final String FIELD_RTP_QOS_DSCP = \"rtp_qos_dscp\";\n\n /**\n * Should the application try to clean registration of all sip clients if no\n * registration found.<br/>\n * This is useful if the sip server manage limited serveral concurrent\n * registrations.<br/>\n * Since in this case the registrations may leak in case of failing\n * unregisters, this option will unregister all contacts previously\n * registred.\n * \n * @see Boolean\n */\n public static final String FIELD_TRY_CLEAN_REGISTERS = \"try_clean_reg\";\n \n \n /**\n * This option is used to overwrite the \"sent-by\" field of the Via header\n * for outgoing messages with the same interface address as the one in\n * the REGISTER request, as long as the request uses the same transport\n * instance as the previous REGISTER request. <br/>\n *\n * Default: false <br/>\n * <a target=\"_blank\" href=\n * \"http://www.pjsip.org/pjsip/docs/html/structpjsua__acc__config.htm\"\n * >Pjsip documentation</a>\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_VIA_REWRITE = \"allow_via_rewrite\";\n\n /**\n * This option controls whether the IP address in SDP should be replaced\n * with the IP address found in Via header of the REGISTER response, ONLY\n * when STUN and ICE are not used. If the value is FALSE (the original\n * behavior), then the local IP address will be used. If TRUE, and when\n * STUN and ICE are disabled, then the IP address found in registration\n * response will be used.\n *\n * Default:no\n * \n * @see Boolean\n */\n public static final String FIELD_ALLOW_SDP_NAT_REWRITE = \"allow_sdp_nat_rewrite\";\n \n /**\n * Control the use of STUN for the SIP signaling.\n */\n public static final String FIELD_SIP_STUN_USE = \"sip_stun_use\";\n \n /**\n * Control the use of STUN for the transports.\n */\n public static final String FIELD_MEDIA_STUN_USE = \"media_stun_use\";\n \n /**\n * Control the use of ICE in the account. \n * By default, the settings in the pjsua_media_config will be used. \n */\n public static final String FIELD_ICE_CFG_USE = \"ice_cfg_use\";\n\n /**\n * Enable ICE. \n */\n public static final String FIELD_ICE_CFG_ENABLE = \"ice_cfg_enable\";\n \n /**\n * Control the use of TURN in the account. \n * By default, the settings in the pjsua_media_config will be used. \n */\n public static final String FIELD_TURN_CFG_USE = \"turn_cfg_use\";\n \n /**\n * Enable TURN.\n */\n public static final String FIELD_TURN_CFG_ENABLE = \"turn_cfg_enable\";\n \n /**\n * TURN server.\n */\n public static final String FIELD_TURN_CFG_SERVER = \"turn_cfg_server\";\n \n /**\n * TURN username.\n */\n public static final String FIELD_TURN_CFG_USER = \"turn_cfg_user\";\n \n /**\n * TURN password.\n */\n public static final String FIELD_TURN_CFG_PASSWORD = \"turn_cfg_pwd\";\n \n /**\n * Should media use ipv6?\n */\n public static final String FIELD_IPV6_MEDIA_USE = \"ipv6_media_use\";\n \n /**\n * Simple project to use if you want to list accounts with basic infos on it\n * only.\n * \n * @see #FIELD_ACC_ID\n * @see #FIELD_ACTIVE\n * @see #FIELD_WIZARD\n * @see #FIELD_DISPLAY_NAME\n * @see #FIELD_WIZARD\n * @see #FIELD_PRIORITY\n * @see #FIELD_REG_URI\n */\n public static final String[] LISTABLE_PROJECTION = new String[] {\n SipProfile.FIELD_ID,\n SipProfile.FIELD_ACC_ID,\n SipProfile.FIELD_ACTIVE,\n SipProfile.FIELD_DISPLAY_NAME,\n SipProfile.FIELD_WIZARD,\n SipProfile.FIELD_PRIORITY,\n SipProfile.FIELD_REG_URI\n };\n\n // Properties\n /**\n * Primary key for serialization of the object.\n */\n public int primaryKey = -1;\n /**\n * @see #FIELD_ID\n */\n public long id = INVALID_ID;\n /**\n * @see #FIELD_DISPLAY_NAME\n */\n public String display_name = \"\";\n /**\n * @see #FIELD_WIZARD\n */\n public String wizard = \"EXPERT\";\n /**\n * @see #FIELD_TRANSPORT\n */\n public Integer transport = 0;\n /**\n * @see #FIELD_DEFAULT_URI_SCHEME\n */\n public String default_uri_scheme = \"sip\";\n /**\n * @see #FIELD_ACTIVE\n */\n public boolean active = true;\n /**\n * @see #FIELD_PRIORITY\n */\n public int priority = 100;\n /**\n * @see #FIELD_ACC_ID\n */\n public String acc_id = null;\n\n /**\n * @see #FIELD_REG_URI\n */\n public String reg_uri = null;\n /**\n * @see #FIELD_PUBLISH_ENABLED\n */\n public int publish_enabled = 0;\n /**\n * @see #FIELD_REG_TIMEOUT\n */\n public int reg_timeout = 900;\n /**\n * @see #FIELD_KA_INTERVAL\n */\n public int ka_interval = 0;\n /**\n * @see #FIELD_PIDF_TUPLE_ID\n */\n public String pidf_tuple_id = null;\n /**\n * @see #FIELD_FORCE_CONTACT\n */\n public String force_contact = null;\n /**\n * @see #FIELD_ALLOW_CONTACT_REWRITE\n */\n public boolean allow_contact_rewrite = true;\n /**\n * @see #FIELD_CONTACT_REWRITE_METHOD\n */\n public int contact_rewrite_method = 2;\n /**\n * @see #FIELD_ALLOW_VIA_REWRITE\n */\n public boolean allow_via_rewrite = false;\n /**\n * @see #FIELD_ALLOW_SDP_NAT_REWRITE\n */\n public boolean allow_sdp_nat_rewrite = false;\n /**\n * Exploded array of proxies\n * \n * @see #FIELD_PROXY\n */\n public String[] proxies = null;\n /**\n * @see #FIELD_REALM\n */\n public String realm = null;\n /**\n * @see #FIELD_USERNAME\n */\n public String username = null;\n /**\n * @see #FIELD_SCHEME\n */\n public String scheme = null;\n /**\n * @see #FIELD_DATATYPE\n */\n public int datatype = 0;\n /**\n * @see #FIELD_DATA\n */\n public String data = null;\n /**\n * @see #FIELD_AUTH_INITIAL_AUTH\n */\n public boolean initial_auth = false;\n /**\n * @see #FIELD_AUTH_ALGO\n */\n public String auth_algo = \"\"; \n /**\n * @see #FIELD_USE_SRTP\n */\n public int use_srtp = -1;\n /**\n * @see #FIELD_USE_ZRTP\n */\n public int use_zrtp = -1;\n /**\n * @see #FIELD_REG_USE_PROXY\n */\n public int reg_use_proxy = 3;\n /**\n * @see #FIELD_SIP_STACK\n */\n public int sip_stack = PJSIP_STACK;\n /**\n * @see #FIELD_VOICE_MAIL_NBR\n */\n public String vm_nbr = null;\n /**\n * @see #FIELD_REG_DELAY_BEFORE_REFRESH\n */\n public int reg_delay_before_refresh = -1;\n /**\n * @see #FIELD_TRY_CLEAN_REGISTERS\n */\n public int try_clean_registers = 1;\n /**\n * Chache holder icon for the account wizard representation.<br/>\n * This will not not be filled by default. You have to get it from wizard\n * infos.\n */\n public Bitmap icon = null;\n /**\n * @see #FIELD_USE_RFC5626\n */\n public boolean use_rfc5626 = true;\n /**\n * @see #FIELD_RFC5626_INSTANCE_ID\n */\n public String rfc5626_instance_id = \"\";\n /**\n * @see #FIELD_RFC5626_REG_ID\n */\n public String rfc5626_reg_id = \"\";\n /**\n * @see #FIELD_VID_IN_AUTO_SHOW\n */\n public int vid_in_auto_show = -1;\n /**\n * @see #FIELD_VID_OUT_AUTO_TRANSMIT\n */\n public int vid_out_auto_transmit = -1;\n /**\n * @see #FIELD_RTP_PORT\n */\n public int rtp_port = -1;\n /**\n * @see #FIELD_RTP_PUBLIC_ADDR\n */\n public String rtp_public_addr = \"\";\n /**\n * @see #FIELD_RTP_BOUND_ADDR\n */\n public String rtp_bound_addr = \"\";\n /**\n * @see #FIELD_RTP_ENABLE_QOS\n */\n public int rtp_enable_qos = -1;\n /**\n * @see #FIELD_RTP_QOS_DSCP\n */\n public int rtp_qos_dscp = -1;\n /**\n * @see #FIELD_ANDROID_GROUP\n */\n public String android_group = \"\";\n /**\n * @see #FIELD_MWI_ENABLED\n */\n public boolean mwi_enabled = true;\n /**\n * @see #FIELD_SIP_STUN_USE\n */\n public int sip_stun_use = -1;\n /**\n * @see #FIELD_MEDIA_STUN_USE\n */\n public int media_stun_use = -1;\n /**\n * @see #FIELD_ICE_CFG_USE\n */\n public int ice_cfg_use = -1;\n /**\n * @see #FIELD_ICE_CFG_ENABLE\n */\n public int ice_cfg_enable = 0;\n /**\n * @see #FIELD_TURN_CFG_USE\n */\n public int turn_cfg_use = -1;\n /**\n * @see #FIELD_TURN_CFG_ENABLE\n */\n public int turn_cfg_enable = 0;\n /**\n * @see #FIELD_TURN_CFG_SERVER\n */\n public String turn_cfg_server = \"\";\n /**\n * @see #FIELD_TURN_CFG_USER\n */\n public String turn_cfg_user = \"\";\n /**\n * @see #FIELD_TURN_CFG_PASSWORD\n */\n public String turn_cfg_password = \"\";\n /**\n * @see #FIELD_IPV6_MEDIA_USE\n */\n public int ipv6_media_use = 0;\n /**\n * @see #FIELD_WIZARD_DATA\n */\n public String wizard_data = \"\";\n \n public SipProfile() {\n display_name = \"\";\n wizard = \"EXPERT\";\n active = true;\n }\n\n /**\n * Construct a sip profile wrapper from a cursor retrieved with a\n * {@link ContentProvider} query on {@link #ACCOUNTS_TABLE_NAME}.\n * \n * @param c the cursor to unpack\n */\n public SipProfile(Cursor c) {\n super();\n createFromDb(c);\n }\n\n /**\n * Construct from parcelable <br/>\n * Only used by {@link #CREATOR}\n * \n * @param in parcelable to build from\n */\n private SipProfile(Parcel in) {\n primaryKey = in.readInt();\n id = in.readInt();\n display_name = in.readString();\n wizard = in.readString();\n transport = in.readInt();\n active = (in.readInt() != 0) ? true : false;\n priority = in.readInt();\n acc_id = getReadParcelableString(in.readString());\n reg_uri = getReadParcelableString(in.readString());\n publish_enabled = in.readInt();\n reg_timeout = in.readInt();\n ka_interval = in.readInt();\n pidf_tuple_id = getReadParcelableString(in.readString());\n force_contact = getReadParcelableString(in.readString());\n proxies = TextUtils.split(getReadParcelableString(in.readString()),\n Pattern.quote(PROXIES_SEPARATOR));\n realm = getReadParcelableString(in.readString());\n username = getReadParcelableString(in.readString());\n datatype = in.readInt();\n data = getReadParcelableString(in.readString());\n use_srtp = in.readInt();\n allow_contact_rewrite = (in.readInt() != 0);\n contact_rewrite_method = in.readInt();\n sip_stack = in.readInt();\n reg_use_proxy = in.readInt();\n use_zrtp = in.readInt();\n vm_nbr = getReadParcelableString(in.readString());\n reg_delay_before_refresh = in.readInt();\n icon = (Bitmap) in.readParcelable(Bitmap.class.getClassLoader());\n try_clean_registers = in.readInt();\n use_rfc5626 = (in.readInt() != 0);\n rfc5626_instance_id = getReadParcelableString(in.readString());\n rfc5626_reg_id = getReadParcelableString(in.readString());\n vid_in_auto_show = in.readInt();\n vid_out_auto_transmit = in.readInt();\n rtp_port = in.readInt();\n rtp_public_addr = getReadParcelableString(in.readString());\n rtp_bound_addr = getReadParcelableString(in.readString());\n rtp_enable_qos = in.readInt();\n rtp_qos_dscp = in.readInt();\n android_group = getReadParcelableString(in.readString());\n mwi_enabled = (in.readInt() != 0);\n allow_via_rewrite = (in.readInt() != 0);\n sip_stun_use = in.readInt();\n media_stun_use = in.readInt();\n ice_cfg_use = in.readInt();\n ice_cfg_enable = in.readInt();\n turn_cfg_use = in.readInt();\n turn_cfg_enable = in.readInt();\n turn_cfg_server = getReadParcelableString(in.readString());\n turn_cfg_user = getReadParcelableString(in.readString());\n turn_cfg_password = getReadParcelableString(in.readString());\n ipv6_media_use = in.readInt();\n initial_auth = (in.readInt() != 0);\n auth_algo = getReadParcelableString(in.readString());\n wizard_data = getReadParcelableString(in.readString());\n default_uri_scheme = getReadParcelableString(in.readString());\n allow_sdp_nat_rewrite = (in.readInt() != 0);\n }\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n public static final Creator<SipProfile> CREATOR = new Creator<SipProfile>() {\n public SipProfile createFromParcel(Parcel in) {\n return new SipProfile(in);\n }\n\n public SipProfile[] newArray(int size) {\n return new SipProfile[size];\n }\n };\n\n /**\n * @see Parcelable#describeContents()\n */\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(primaryKey);\n dest.writeInt((int) id);\n dest.writeString(display_name);\n dest.writeString(wizard);\n dest.writeInt(transport);\n dest.writeInt(active ? 1 : 0);\n dest.writeInt(priority);\n dest.writeString(getWriteParcelableString(acc_id));\n dest.writeString(getWriteParcelableString(reg_uri));\n dest.writeInt(publish_enabled);\n dest.writeInt(reg_timeout);\n dest.writeInt(ka_interval);\n dest.writeString(getWriteParcelableString(pidf_tuple_id));\n dest.writeString(getWriteParcelableString(force_contact));\n if (proxies != null) {\n dest.writeString(getWriteParcelableString(TextUtils.join(PROXIES_SEPARATOR, proxies)));\n } else {\n dest.writeString(\"\");\n }\n dest.writeString(getWriteParcelableString(realm));\n dest.writeString(getWriteParcelableString(username));\n dest.writeInt(datatype);\n dest.writeString(getWriteParcelableString(data));\n dest.writeInt(use_srtp);\n dest.writeInt(allow_contact_rewrite ? 1 : 0);\n dest.writeInt(contact_rewrite_method);\n dest.writeInt(sip_stack);\n dest.writeInt(reg_use_proxy);\n dest.writeInt(use_zrtp);\n dest.writeString(getWriteParcelableString(vm_nbr));\n dest.writeInt(reg_delay_before_refresh);\n dest.writeParcelable((Parcelable) icon, flags);\n dest.writeInt(try_clean_registers);\n dest.writeInt(use_rfc5626 ? 1 : 0);\n dest.writeString(getWriteParcelableString(rfc5626_instance_id));\n dest.writeString(getWriteParcelableString(rfc5626_reg_id));\n dest.writeInt(vid_in_auto_show);\n dest.writeInt(vid_out_auto_transmit);\n dest.writeInt(rtp_port);\n dest.writeString(getWriteParcelableString(rtp_public_addr));\n dest.writeString(getWriteParcelableString(rtp_bound_addr));\n dest.writeInt(rtp_enable_qos);\n dest.writeInt(rtp_qos_dscp);\n dest.writeString(getWriteParcelableString(android_group));\n dest.writeInt(mwi_enabled ? 1 : 0);\n dest.writeInt(allow_via_rewrite ? 1 : 0);\n dest.writeInt(sip_stun_use);\n dest.writeInt(media_stun_use);\n dest.writeInt(ice_cfg_use);\n dest.writeInt(ice_cfg_enable);\n dest.writeInt(turn_cfg_use);\n dest.writeInt(turn_cfg_enable);\n dest.writeString(getWriteParcelableString(turn_cfg_server));\n dest.writeString(getWriteParcelableString(turn_cfg_user));\n dest.writeString(getWriteParcelableString(turn_cfg_password));\n dest.writeInt(ipv6_media_use);\n dest.writeInt(initial_auth ? 1 : 0);\n dest.writeString(getWriteParcelableString(auth_algo));\n dest.writeString(getWriteParcelableString(wizard_data));\n dest.writeString(getWriteParcelableString(default_uri_scheme));\n dest.writeInt(allow_sdp_nat_rewrite ? 1 : 0);\n }\n\n // Yes yes that's not clean but well as for now not problem with that.\n // and we send null.\n private String getWriteParcelableString(String str) {\n return (str == null) ? \"null\" : str;\n }\n\n private String getReadParcelableString(String str) {\n return str.equalsIgnoreCase(\"null\") ? null : str;\n }\n\n /**\n * Create account wrapper with cursor datas.\n * \n * @param c cursor on the database\n */\n private final void createFromDb(Cursor c) {\n ContentValues args = new ContentValues();\n DatabaseUtils.cursorRowToContentValues(c, args);\n createFromContentValue(args);\n }\n\n /**\n * Create account wrapper with content values pairs.\n * \n * @param args the content value to unpack.\n */\n private final void createFromContentValue(ContentValues args) {\n Integer tmp_i;\n String tmp_s;\n \n // Application specific settings\n tmp_i = args.getAsInteger(FIELD_ID);\n if (tmp_i != null) {\n id = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DISPLAY_NAME);\n if (tmp_s != null) {\n display_name = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_WIZARD);\n if (tmp_s != null) {\n wizard = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_TRANSPORT);\n if (tmp_i != null) {\n transport = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DEFAULT_URI_SCHEME);\n if (tmp_s != null) {\n default_uri_scheme = tmp_s;\n }\n\n tmp_i = args.getAsInteger(FIELD_ACTIVE);\n if (tmp_i != null) {\n active = (tmp_i != 0);\n } else {\n active = true;\n }\n tmp_s = args.getAsString(FIELD_ANDROID_GROUP);\n if (tmp_s != null) {\n android_group = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_WIZARD_DATA);\n if (tmp_s != null) {\n wizard_data = tmp_s;\n }\n\n // General account settings\n tmp_i = args.getAsInteger(FIELD_PRIORITY);\n if (tmp_i != null) {\n priority = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_ACC_ID);\n if (tmp_s != null) {\n acc_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_REG_URI);\n if (tmp_s != null) {\n reg_uri = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_PUBLISH_ENABLED);\n if (tmp_i != null) {\n publish_enabled = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_REG_TIMEOUT);\n if (tmp_i != null && tmp_i >= 0) {\n reg_timeout = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_REG_DELAY_BEFORE_REFRESH);\n if (tmp_i != null && tmp_i >= 0) {\n reg_delay_before_refresh = tmp_i;\n }\n\n tmp_i = args.getAsInteger(FIELD_KA_INTERVAL);\n if (tmp_i != null && tmp_i >= 0) {\n ka_interval = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_PIDF_TUPLE_ID);\n if (tmp_s != null) {\n pidf_tuple_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_FORCE_CONTACT);\n if (tmp_s != null) {\n force_contact = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_CONTACT_REWRITE);\n if (tmp_i != null) {\n allow_contact_rewrite = (tmp_i == 1);\n }\n tmp_i = args.getAsInteger(FIELD_CONTACT_REWRITE_METHOD);\n if (tmp_i != null) {\n contact_rewrite_method = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_VIA_REWRITE);\n if (tmp_i != null) {\n allow_via_rewrite = (tmp_i == 1);\n }\n tmp_i = args.getAsInteger(FIELD_ALLOW_SDP_NAT_REWRITE);\n if (tmp_i != null) {\n allow_sdp_nat_rewrite = (tmp_i == 1);\n }\n\n tmp_i = args.getAsInteger(FIELD_USE_SRTP);\n if (tmp_i != null && tmp_i >= 0) {\n use_srtp = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_USE_ZRTP);\n if (tmp_i != null && tmp_i >= 0) {\n use_zrtp = tmp_i;\n }\n\n // Proxy\n tmp_s = args.getAsString(FIELD_PROXY);\n if (tmp_s != null) {\n proxies = TextUtils.split(tmp_s, Pattern.quote(PROXIES_SEPARATOR));\n }\n tmp_i = args.getAsInteger(FIELD_REG_USE_PROXY);\n if (tmp_i != null && tmp_i >= 0) {\n reg_use_proxy = tmp_i;\n }\n\n // Auth\n tmp_s = args.getAsString(FIELD_REALM);\n if (tmp_s != null) {\n realm = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_SCHEME);\n if (tmp_s != null) {\n scheme = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_USERNAME);\n if (tmp_s != null) {\n username = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_DATATYPE);\n if (tmp_i != null) {\n datatype = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_DATA);\n if (tmp_s != null) {\n data = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_AUTH_INITIAL_AUTH);\n if (tmp_i != null) {\n initial_auth = (tmp_i == 1);\n }\n tmp_s = args.getAsString(FIELD_AUTH_ALGO);\n if (tmp_s != null) {\n auth_algo = tmp_s;\n }\n \n\n tmp_i = args.getAsInteger(FIELD_SIP_STACK);\n if (tmp_i != null && tmp_i >= 0) {\n sip_stack = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_MWI_ENABLED);\n if(tmp_i != null && tmp_i >= 0) {\n mwi_enabled = (tmp_i == 1);\n }\n tmp_s = args.getAsString(FIELD_VOICE_MAIL_NBR);\n if (tmp_s != null) {\n vm_nbr = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_TRY_CLEAN_REGISTERS);\n if (tmp_i != null && tmp_i >= 0) {\n try_clean_registers = tmp_i;\n }\n\n // RFC 5626\n tmp_i = args.getAsInteger(FIELD_USE_RFC5626);\n if (tmp_i != null && tmp_i >= 0) {\n use_rfc5626 = (tmp_i != 0);\n }\n tmp_s = args.getAsString(FIELD_RFC5626_INSTANCE_ID);\n if (tmp_s != null) {\n rfc5626_instance_id = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_RFC5626_REG_ID);\n if (tmp_s != null) {\n rfc5626_reg_id = tmp_s;\n }\n\n // Video\n tmp_i = args.getAsInteger(FIELD_VID_IN_AUTO_SHOW);\n if (tmp_i != null && tmp_i >= 0) {\n vid_in_auto_show = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_VID_OUT_AUTO_TRANSMIT);\n if (tmp_i != null && tmp_i >= 0) {\n vid_out_auto_transmit = tmp_i;\n }\n\n // RTP cfg\n tmp_i = args.getAsInteger(FIELD_RTP_PORT);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_port = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_RTP_PUBLIC_ADDR);\n if (tmp_s != null) {\n rtp_public_addr = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_RTP_BOUND_ADDR);\n if (tmp_s != null) {\n rtp_bound_addr = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_RTP_ENABLE_QOS);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_enable_qos = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_RTP_QOS_DSCP);\n if (tmp_i != null && tmp_i >= 0) {\n rtp_qos_dscp = tmp_i;\n }\n \n\n tmp_i = args.getAsInteger(FIELD_SIP_STUN_USE);\n if (tmp_i != null && tmp_i >= 0) {\n sip_stun_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_MEDIA_STUN_USE);\n if (tmp_i != null && tmp_i >= 0) {\n media_stun_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ICE_CFG_USE);\n if (tmp_i != null && tmp_i >= 0) {\n ice_cfg_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_ICE_CFG_ENABLE);\n if (tmp_i != null && tmp_i >= 0) {\n ice_cfg_enable = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_TURN_CFG_USE);\n if (tmp_i != null && tmp_i >= 0) {\n turn_cfg_use = tmp_i;\n }\n tmp_i = args.getAsInteger(FIELD_TURN_CFG_ENABLE);\n if (tmp_i != null && tmp_i >= 0) {\n turn_cfg_enable = tmp_i;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_SERVER);\n if (tmp_s != null) {\n turn_cfg_server = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_USER);\n if (tmp_s != null) {\n turn_cfg_user = tmp_s;\n }\n tmp_s = args.getAsString(FIELD_TURN_CFG_PASSWORD);\n if (tmp_s != null) {\n turn_cfg_password = tmp_s;\n }\n tmp_i = args.getAsInteger(FIELD_IPV6_MEDIA_USE);\n if (tmp_i != null && tmp_i >= 0) {\n ipv6_media_use = tmp_i;\n }\n }\n\n /**\n * Transform pjsua_acc_config into ContentValues that can be insert into\n * database. <br/>\n * Take care that if your SipProfile is incomplete this content value may\n * also be uncomplete and lead to override unwanted values of the existing\n * database. <br/>\n * So if updating, take care on what you actually want to update instead of\n * using this utility method.\n * \n * @return Complete content values from the current wrapper around sip\n * profile.\n */\n public ContentValues getDbContentValues() {\n ContentValues args = new ContentValues();\n\n if (id != INVALID_ID) {\n args.put(FIELD_ID, id);\n }\n // TODO : ensure of non nullity of some params\n\n args.put(FIELD_ACTIVE, active ? 1 : 0);\n args.put(FIELD_WIZARD, wizard);\n args.put(FIELD_DISPLAY_NAME, display_name);\n args.put(FIELD_TRANSPORT, transport);\n args.put(FIELD_DEFAULT_URI_SCHEME, default_uri_scheme);\n args.put(FIELD_WIZARD_DATA, wizard_data);\n\n args.put(FIELD_PRIORITY, priority);\n args.put(FIELD_ACC_ID, acc_id);\n args.put(FIELD_REG_URI, reg_uri);\n\n args.put(FIELD_PUBLISH_ENABLED, publish_enabled);\n args.put(FIELD_REG_TIMEOUT, reg_timeout);\n args.put(FIELD_KA_INTERVAL, ka_interval);\n args.put(FIELD_PIDF_TUPLE_ID, pidf_tuple_id);\n args.put(FIELD_FORCE_CONTACT, force_contact);\n args.put(FIELD_ALLOW_CONTACT_REWRITE, allow_contact_rewrite ? 1 : 0);\n args.put(FIELD_ALLOW_VIA_REWRITE, allow_via_rewrite ? 1 : 0);\n args.put(FIELD_ALLOW_SDP_NAT_REWRITE, allow_sdp_nat_rewrite ? 1 : 0);\n args.put(FIELD_CONTACT_REWRITE_METHOD, contact_rewrite_method);\n args.put(FIELD_USE_SRTP, use_srtp);\n args.put(FIELD_USE_ZRTP, use_zrtp);\n\n // CONTACT_PARAM and CONTACT_PARAM_URI not yet in JNI\n\n if (proxies != null) {\n args.put(FIELD_PROXY, TextUtils.join(PROXIES_SEPARATOR, proxies));\n } else {\n args.put(FIELD_PROXY, \"\");\n }\n args.put(FIELD_REG_USE_PROXY, reg_use_proxy);\n\n // Assume we have an unique credential\n args.put(FIELD_REALM, realm);\n args.put(FIELD_SCHEME, scheme);\n args.put(FIELD_USERNAME, username);\n args.put(FIELD_DATATYPE, datatype);\n if (!TextUtils.isEmpty(data)) {\n args.put(FIELD_DATA, data);\n }\n args.put(FIELD_AUTH_INITIAL_AUTH, initial_auth ? 1 : 0);\n if(!TextUtils.isEmpty(auth_algo)) {\n args.put(FIELD_AUTH_ALGO, auth_algo);\n }\n\n args.put(FIELD_SIP_STACK, sip_stack);\n args.put(FIELD_MWI_ENABLED, mwi_enabled);\n args.put(FIELD_VOICE_MAIL_NBR, vm_nbr);\n args.put(FIELD_REG_DELAY_BEFORE_REFRESH, reg_delay_before_refresh);\n args.put(FIELD_TRY_CLEAN_REGISTERS, try_clean_registers);\n \n \n args.put(FIELD_RTP_BOUND_ADDR, rtp_bound_addr);\n args.put(FIELD_RTP_ENABLE_QOS, rtp_enable_qos);\n args.put(FIELD_RTP_PORT, rtp_port);\n args.put(FIELD_RTP_PUBLIC_ADDR, rtp_public_addr);\n args.put(FIELD_RTP_QOS_DSCP, rtp_qos_dscp);\n \n args.put(FIELD_VID_IN_AUTO_SHOW, vid_in_auto_show);\n args.put(FIELD_VID_OUT_AUTO_TRANSMIT, vid_out_auto_transmit);\n \n args.put(FIELD_RFC5626_INSTANCE_ID, rfc5626_instance_id);\n args.put(FIELD_RFC5626_REG_ID, rfc5626_reg_id);\n args.put(FIELD_USE_RFC5626, use_rfc5626 ? 1 : 0);\n\n args.put(FIELD_ANDROID_GROUP, android_group);\n \n args.put(FIELD_SIP_STUN_USE, sip_stun_use);\n args.put(FIELD_MEDIA_STUN_USE, media_stun_use);\n args.put(FIELD_ICE_CFG_USE, ice_cfg_use);\n args.put(FIELD_ICE_CFG_ENABLE, ice_cfg_enable);\n args.put(FIELD_TURN_CFG_USE, turn_cfg_use);\n args.put(FIELD_TURN_CFG_ENABLE, turn_cfg_enable);\n args.put(FIELD_TURN_CFG_SERVER, turn_cfg_server);\n args.put(FIELD_TURN_CFG_USER, turn_cfg_user);\n args.put(FIELD_TURN_CFG_PASSWORD, turn_cfg_password);\n \n args.put(FIELD_IPV6_MEDIA_USE, ipv6_media_use);\n \n return args;\n }\n\n /**\n * Get the default domain for this account\n * \n * @return the default domain for this account\n */\n public String getDefaultDomain() {\n ParsedSipContactInfos parsedAoR = SipUri.parseSipContact(acc_id);\n ParsedSipUriInfos parsedInfo = null;\n if(TextUtils.isEmpty(parsedAoR.domain)) {\n // Try to fallback\n if (!TextUtils.isEmpty(reg_uri)) {\n parsedInfo = SipUri.parseSipUri(reg_uri);\n } else if (proxies != null && proxies.length > 0) {\n parsedInfo = SipUri.parseSipUri(proxies[0]);\n }\n }else {\n parsedInfo = parsedAoR.getServerSipUri();\n }\n\n if (parsedInfo == null) {\n return null;\n }\n\n if (parsedInfo.domain != null) {\n String dom = parsedInfo.domain;\n if (parsedInfo.port != 5060) {\n dom += \":\" + Integer.toString(parsedInfo.port);\n }\n return dom;\n } else {\n Log.d(THIS_FILE, \"Domain not found for this account\");\n }\n return null;\n }\n\n // Android API\n\n /**\n * Gets the flag of 'Auto Registration'\n * \n * @return true if auto register this account\n */\n public boolean getAutoRegistration() {\n return true;\n }\n\n /**\n * Gets the display name of the user.\n * \n * @return the caller id for this account\n */\n public String getDisplayName() {\n if (acc_id != null) {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.displayName != null) {\n return parsed.displayName;\n }\n }\n return \"\";\n }\n\n /**\n * Gets the password.\n * \n * @return the password of the sip profile Using this from an external\n * application will always be empty\n */\n public String getPassword() {\n return data;\n }\n\n /**\n * Gets the (user-defined) name of the profile.\n * \n * @return the display name for this profile\n */\n public String getProfileName() {\n return display_name;\n }\n\n /**\n * Gets the network address of the server outbound proxy.\n * \n * @return the first proxy server if any else empty string\n */\n public String getProxyAddress() {\n if (proxies != null && proxies.length > 0) {\n return proxies[0];\n }\n return \"\";\n }\n\n /**\n * Gets the SIP domain when acc_id is username@domain.\n * \n * @return the sip domain for this account\n */\n public String getSipDomain() {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.domain != null) {\n return parsed.domain;\n }\n return \"\";\n }\n\n /**\n * Gets the SIP URI string of this profile.\n */\n public String getUriString() {\n return acc_id;\n }\n\n /**\n * Gets the username when acc_id is username@domain. WARNING : this is\n * different from username of SipProfile which is the authentication name\n * cause of pjsip naming\n * \n * @return the username of the account sip id. <br/>\n * Example if acc_id is \"Display Name\" <sip:[email protected]>, it\n * will return user.\n */\n public String getSipUserName() {\n ParsedSipContactInfos parsed = SipUri.parseSipContact(acc_id);\n if (parsed.userName != null) {\n return parsed.userName;\n }\n return \"\";\n }\n \n public ParsedSipContactInfos formatCalleeNumber(String fuzzyNumber) {\n ParsedSipContactInfos finalCallee = SipUri.parseSipContact(fuzzyNumber);\n\n if (TextUtils.isEmpty(finalCallee.domain)) {\n String defaultDomain = getDefaultDomain();\n if(TextUtils.isEmpty(defaultDomain)) {\n finalCallee.domain = finalCallee.userName;\n finalCallee.userName = null;\n }else {\n finalCallee.domain = defaultDomain;\n }\n }\n if (TextUtils.isEmpty(finalCallee.scheme)) {\n if (!TextUtils.isEmpty(default_uri_scheme)) {\n finalCallee.scheme = default_uri_scheme;\n } else {\n finalCallee.scheme = SipManager.PROTOCOL_SIP;\n }\n }\n return finalCallee;\n }\n\n // Helpers static factory\n /**\n * Helper method to retrieve a SipProfile object from its account database\n * id.<br/>\n * You have to specify the projection you want to use for to retrieve infos.<br/>\n * As consequence the wrapper SipProfile object you'll get may be\n * incomplete. So take care if you try to reinject it by updating to not\n * override existing values of the database that you don't get here.\n * \n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param accountId The sip profile {@link #FIELD_ID} you want to retrieve.\n * @param projection The list of fields you want to retrieve. Must be in FIELD_* of this class.<br/>\n * Reducing your requested fields to minimum will improve speed of the request.\n * @return A wrapper SipProfile object on the request you done. If not found an invalid account with an {@link #id} equals to {@link #INVALID_ID}\n */\n public static SipProfile getProfileFromDbId(Context ctxt, long accountId, String[] projection) {\n SipProfile account = new SipProfile();\n if (accountId != INVALID_ID) {\n Cursor c = ctxt.getContentResolver().query(\n ContentUris.withAppendedId(ACCOUNT_ID_URI_BASE, accountId),\n projection, null, null, null);\n\n if (c != null) {\n try {\n if (c.getCount() > 0) {\n c.moveToFirst();\n account = new SipProfile(c);\n }\n } catch (Exception e) {\n Log.e(THIS_FILE, \"Something went wrong while retrieving the account\", e);\n } finally {\n c.close();\n }\n }\n }\n return account;\n }\n\n /**\n * Get the list of sip profiles available.\n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param onlyActive Pass it to true if you are only interested in active accounts.\n * @return The list of SipProfiles containings only fields of {@link #LISTABLE_PROJECTION} filled.\n * @see #LISTABLE_PROJECTION\n */\n public static ArrayList<SipProfile> getAllProfiles(Context ctxt, boolean onlyActive) {\n return getAllProfiles(ctxt, onlyActive, LISTABLE_PROJECTION);\n }\n \n /**\n * Get the list of sip profiles available.\n * @param ctxt Your application context. Mainly useful to get the content provider for the request.\n * @param onlyActive Pass it to true if you are only interested in active accounts.\n * @param projection The projection to use for cursor\n * @return The list of SipProfiles\n */\n public static ArrayList<SipProfile> getAllProfiles(Context ctxt, boolean onlyActive, String[] projection) {\n ArrayList<SipProfile> result = new ArrayList<SipProfile>();\n\n String selection = null;\n String[] selectionArgs = null;\n if (onlyActive) {\n selection = SipProfile.FIELD_ACTIVE + \"=?\";\n selectionArgs = new String[] {\n \"1\"\n };\n }\n Cursor c = ctxt.getContentResolver().query(ACCOUNT_URI, projection, selection, selectionArgs, null);\n\n if (c != null) {\n try {\n if (c.moveToFirst()) {\n do {\n result.add(new SipProfile(c));\n } while (c.moveToNext());\n }\n } catch (Exception e) {\n Log.e(THIS_FILE, \"Error on looping over sip profiles\", e);\n } finally {\n c.close();\n }\n }\n\n return result;\n }\n}", "public class SipProfileState implements Parcelable, Serializable{\n\n /**\n * Primary key for serialization of the object.\n */\n\tprivate static final long serialVersionUID = -3630993161572726153L;\n\tpublic int primaryKey = -1;\n\tprivate int databaseId;\n\tprivate int pjsuaId;\n\tprivate String wizard;\n\tprivate boolean active;\n\tprivate int statusCode;\n\tprivate String statusText;\n\tprivate int addedStatus;\n\tprivate int expires;\n\tprivate String displayName;\n\tprivate int priority;\n\tprivate String regUri = \"\";\n\n\t/**\n\t * Account id.<br/>\n\t * Identifier of the SIP account associated. It's the identifier of the account for the API.\n\t * \n\t * @see SipProfile#FIELD_ID\n\t * @see Integer\n\t */\n\tpublic final static String ACCOUNT_ID = \"account_id\";\n\t/**\n\t * Identifier for underlying sip stack. <br/>\n\t * This is an internal identifier you normally don't need to use when using the api from an external application.\n\t * \n\t * @see Integer\n\t */\n\tpublic final static String PJSUA_ID = \"pjsua_id\";\n\t/**\n\t * Wizard key. <br/>\n\t * Wizard identifier associated to the account. This is a shortcut to not have to query {@link SipProfile} database\n\t * \n\t * @see String\n\t */\n\tpublic final static String WIZARD = \"wizard\";\n\t/**\n\t * Activation state.<br/>\n\t * Active state of the account. This is a shortcut to not have to query {@link SipProfile} database\n\t * \n\t * @see Boolean\n\t */\n\tpublic final static String ACTIVE = \"active\";\n\t/**\n\t * Status code of the latest registration.<br/>\n\t * SIP code of latest registration.\n\t * \n\t * @see Integer\n\t */\n\tpublic final static String STATUS_CODE = \"status_code\";\n\t/**\n\t * Status comment of latest registration.<br/>\n\t * Sip comment of latest registration.\n\t * \n\t * @see String\n\t */\n\tpublic final static String STATUS_TEXT = \"status_text\";\n\t/**\n\t * Status of sip stack adding of the account.<br/>\n\t * When the application adds the account to the stack it may fails if the sip profile is invalid.\n\t * \n\t * @see Integer\n\t */\n\tpublic final static String ADDED_STATUS = \"added_status\";\n\t/**\n\t * Latest know expires time. <br/>\n\t * Expires value of latest registration. It's actually usefull to detect that it was unregister testing 0 value. \n\t * Else it's not necessarily relevant information.\n\t * \n\t * @see Integer\n\t */\n\tpublic final static String EXPIRES = \"expires\";\n\t/**\n\t * Display name of the account.<br.>\n\t * This is a shortcut to not have to query {@link SipProfile} database\n\t */\n\tpublic final static String DISPLAY_NAME = \"display_name\";\n\t/**\n * Priority of the account.<br.>\n * This is a shortcut to not have to query {@link SipProfile} database\n */\n\tpublic final static String PRIORITY = \"priority\";\n\t/**\n * Registration uri of the account.<br.>\n * This is a shortcut to not have to query {@link SipProfile} database\n */\n\tpublic final static String REG_URI = \"reg_uri\";\n\t\n\n\tpublic static final String [] FULL_PROJECTION = new String[] {\n\t\tACCOUNT_ID, PJSUA_ID, WIZARD, ACTIVE, STATUS_CODE, STATUS_TEXT, EXPIRES, DISPLAY_NAME, PRIORITY, REG_URI\n\t};\n\t\n\t\n\tpublic SipProfileState(Parcel in) {\n\t\treadFromParcel(in);\n\t}\n\t\n\t/**\n * Should not be used for external use of the API.\n\t * Default constructor.\n\t */\n\tpublic SipProfileState() {\n\t\t//Set default values\n\t\taddedStatus = -1;\n\t\tpjsuaId = -1;\n\t\tstatusCode = -1;\n\t\tstatusText = \"\";\n\t\texpires = 0;\n\t}\n\t/**\n * Should not be used for external use of the API.\n\t * Constructor on the top of a sip account.\n\t * \n\t * @param account The sip profile to associate this wrapper info to.\n\t */\n\tpublic SipProfileState(SipProfile account) {\n\t\tthis();\n\t\t\n\t\tdatabaseId = (int) account.id;\n\t\twizard = account.wizard;\n\t\tactive = account.active;\n\t\tdisplayName = account.display_name;\n\t\tpriority = account.priority;\n\t\tregUri = account.reg_uri;\n\t\t\n\t}\n\n /**\n * Construct a sip state wrapper from a cursor retrieved with a\n * {@link ContentProvider} query on {@link SipProfile#ACCOUNT_STATUS_URI}.\n * \n * @param c the cursor to unpack\n */\n\tpublic SipProfileState(Cursor c) {\n\t\tsuper();\n\t\tcreateFromDb(c);\n\t}\n\n /**\n * @see Parcelable#describeContents()\n */\n\t@Override\n\tpublic int describeContents() {\n\t\treturn 0;\n\t}\n\t\n\n\tprivate final void readFromParcel(Parcel in) {\n\t\tprimaryKey = in.readInt();\n\t\tdatabaseId = in.readInt();\n\t\tpjsuaId = in.readInt();\n\t\twizard = in.readString();\n\t\tactive = (in.readInt() == 1);\n\t\tstatusCode = in.readInt();\n\t\tstatusText = in.readString();\n\t\taddedStatus = in.readInt();\n\t\texpires = in.readInt();\n\t\tdisplayName = in.readString();\n\t\tpriority = in.readInt();\n\t\tregUri = in.readString();\n\t}\n\n /**\n * @see Parcelable#writeToParcel(Parcel, int)\n */\n\t@Override\n\tpublic void writeToParcel(Parcel out, int arg1) {\n\t\tout.writeInt(primaryKey);\n\t\tout.writeInt(databaseId);\n\t\tout.writeInt(pjsuaId);\n\t\tout.writeString(wizard);\n\t\tout.writeInt( (active?1:0) );\n\t\tout.writeInt(statusCode);\n\t\tout.writeString(statusText);\n\t\tout.writeInt(addedStatus);\n\t\tout.writeInt(expires);\n\t\tout.writeString(displayName);\n\t\tout.writeInt(priority);\n\t\tout.writeString(regUri);\n\t}\n\t\n\n /**\n * Parcelable creator. So that it can be passed as an argument of the aidl\n * interface\n */\n\tpublic static final Creator<SipProfileState> CREATOR = new Creator<SipProfileState>() {\n\t\tpublic SipProfileState createFromParcel(Parcel in) {\n\t\t\treturn new SipProfileState(in);\n\t\t}\n\n\t\tpublic SipProfileState[] newArray(int size) {\n\t\t\treturn new SipProfileState[size];\n\t\t}\n\t};\n\t\n\t\n\n\t/** \n\t * Fill account state object from cursor.\n\t * @param c cursor on the database queried from {@link SipProfile#ACCOUNT_STATUS_URI}\n\t */\n\tpublic final void createFromDb(Cursor c) {\n\t\tContentValues args = new ContentValues();\n\t\tDatabaseUtils.cursorRowToContentValues(c, args);\n\t\tcreateFromContentValue(args);\n\t}\n\n /** \n * Fill account state object from content values.\n * @param args content values to wrap.\n */\n\tpublic final void createFromContentValue(ContentValues args) {\n\t\tInteger tmp_i;\n\t\tString tmp_s;\n\t\tBoolean tmp_b;\n\t\t\n\t\ttmp_i = args.getAsInteger(ACCOUNT_ID);\n\t\tif(tmp_i != null) {\n\t\t\tdatabaseId = tmp_i;\n\t\t}\n\t\ttmp_i = args.getAsInteger(PJSUA_ID);\n\t\tif(tmp_i != null) {\n\t\t\tpjsuaId = tmp_i;\n\t\t}\n\t\ttmp_s = args.getAsString(WIZARD);\n\t\tif(tmp_s != null) {\n\t\t\twizard = tmp_s;\n\t\t}\n\t\ttmp_b = args.getAsBoolean(ACTIVE);\n\t\tif(tmp_b != null) {\n\t\t\tactive = tmp_b;\n\t\t}\n\t\ttmp_i = args.getAsInteger(STATUS_CODE);\n\t\tif(tmp_i != null) {\n\t\t\tstatusCode = tmp_i;\n\t\t}\n\t\ttmp_s = args.getAsString(STATUS_TEXT);\n\t\tif(tmp_s != null) {\n\t\t\tstatusText = tmp_s;\n\t\t}\n\t\ttmp_i = args.getAsInteger(ADDED_STATUS);\n\t\tif(tmp_i != null) {\n\t\t\taddedStatus = tmp_i;\n\t\t}\n\t\ttmp_i = args.getAsInteger(EXPIRES);\n\t\tif(tmp_i != null) {\n\t\t\texpires = tmp_i;\n\t\t}\n\t\ttmp_s = args.getAsString(DISPLAY_NAME);\n\t\tif(tmp_s != null) {\n\t\t\tdisplayName = tmp_s;\n\t\t}\n\t\ttmp_s = args.getAsString(REG_URI);\n\t\tif(tmp_s != null) {\n\t\t\tregUri = tmp_s;\n\t\t}\n\t\ttmp_i = args.getAsInteger(PRIORITY);\n\t\tif(tmp_i != null) {\n\t\t\tpriority = tmp_i;\n\t\t}\n\t\t\n\t}\n\n /**\n * Should not be used for external use of the API.\n * Produce content value from the wrapper.\n * \n * @return Complete content values from the current wrapper around sip\n * profile state.\n */\n\tpublic ContentValues getAsContentValue() {\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(ACCOUNT_ID, databaseId);\n\t\tcv.put(ACTIVE, active);\n\t\tcv.put(ADDED_STATUS, addedStatus);\n\t\tcv.put(DISPLAY_NAME, displayName);\n\t\tcv.put(EXPIRES, expires);\n\t\tcv.put(PJSUA_ID, pjsuaId);\n\t\tcv.put(PRIORITY, priority);\n\t\tcv.put(REG_URI, regUri);\n\t\tcv.put(STATUS_CODE, statusCode);\n\t\tcv.put(STATUS_TEXT, statusText);\n\t\tcv.put(WIZARD, wizard);\n\t\treturn cv;\n\t}\n\n\t/**\n\t * @param databaseId the databaseId to set\n\t */\n\tpublic void setDatabaseId(int databaseId) {\n\t\tthis.databaseId = databaseId;\n\t}\n\n\t/**\n * Get the identifier identifier of the account that this state is linked to.\n\t * @return the accountId identifier of the account : {@link #ACCOUNT_ID}\n\t */\n\tpublic int getAccountId() {\n\t\treturn databaseId;\n\t}\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param pjsuaId the pjsuaId to set\n\t */\n\tpublic void setPjsuaId(int pjsuaId) {\n\t\tthis.pjsuaId = pjsuaId;\n\t}\n\n\t/**\n\t * Should not be used for external use of the API.\n\t * @return the pjsuaId {@link #PJSUA_ID}\n\t */\n\tpublic int getPjsuaId() {\n\t\treturn pjsuaId;\n\t}\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param wizard the wizard to set\n\t */\n\tpublic void setWizard(String wizard) {\n\t\tthis.wizard = wizard;\n\t}\n\n\t/**\n\t * @return the wizard {@link #WIZARD}\n\t */\n\tpublic String getWizard() {\n\t\treturn wizard;\n\t}\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param active the active to set\n\t */\n\tpublic void setActive(boolean active) {\n\t\tthis.active = active;\n\t}\n\n\t/**\n\t * @return the active {@link #ACTIVE}\n\t */\n\tpublic boolean isActive() {\n\t\treturn active;\n\t}\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param statusCode the statusCode to set\n\t */\n\tpublic void setStatusCode(int statusCode) {\n\t\tthis.statusCode = statusCode;\n\t}\n\n\t/**\n\t * @return the statusCode {@link #STATUS_TEXT}\n\t */\n\tpublic int getStatusCode() {\n\t\treturn statusCode;\n\t}\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param statusText the statusText to set\n\t */\n\tpublic void setStatusText(String statusText) {\n\t\tthis.statusText = statusText;\n\t}\n\n\t/**\n\t * @return the statusText {@link #STATUS_TEXT}\n\t */\n\tpublic String getStatusText() {\n\t\treturn statusText;\n\t}\n\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param addedStatus the addedStatus to set\n\t */\n\tpublic void setAddedStatus(int addedStatus) {\n\t\tthis.addedStatus = addedStatus;\n\t}\n\n\n\t/**\n\t * @return the addedStatus {@link #ADDED_STATUS}\n\t */\n\tpublic int getAddedStatus() {\n\t\treturn addedStatus;\n\t}\n\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param expires the expires to set\n\t */\n\tpublic void setExpires(int expires) {\n\t\tthis.expires = expires;\n\t}\n\n\n\t/**\n\t * @return the expires {@link #EXPIRES}\n\t */\n\tpublic int getExpires() {\n\t\treturn expires;\n\t}\n \n /**\n * @return the display name {@link #DISPLAY_NAME}\n */\n\tpublic CharSequence getDisplayName() {\n\t\treturn displayName;\n\t}\n\n\t/**\n\t * @return the priority {@link #PRIORITY}\n\t */\n\tpublic int getPriority() {\n\t\treturn priority;\n\t}\n\t/**\n * Should not be used for external use of the API.\n\t * @param priority\n\t */\n\tpublic void setPriority(int priority) {\n\t\tthis.priority = priority;\n\t}\n\t\n\n\t/**\n * Should not be used for external use of the API.\n\t * @param regUri the regUri to set\n\t */\n\tpublic void setRegUri(String regUri) {\n\t\tthis.regUri = regUri;\n\t}\n\n\n\t/**\n\t * @return the regUri {@link #REG_URI}\n\t */\n\tpublic String getRegUri() {\n\t\treturn regUri;\n\t}\n\n\t/**\n\t * Is the account added to sip stack yet?\n\t * @return true if the account has been added to sip stack and has a sip stack id.\n\t */\n\tpublic boolean isAddedToStack() {\n\t\treturn pjsuaId != -1;\n\t}\n\t\n\t/**\n\t * Is the account valid for sip calls?\n\t * @return true if it should be possible to make a call using the associated account.\n\t */\n\tpublic boolean isValidForCall() {\n\t\tif(active) {\n\t\t\tif(TextUtils.isEmpty(getRegUri())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn (isAddedToStack() && getStatusCode() == SipCallSession.StatusCode.OK && getExpires() > 0);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Compare accounts profile states.\n\t * @return a comparator instance to compare profile states by priorities.\n\t */\n\tpublic final static Comparator<SipProfileState> getComparator(){\n\t\treturn ACC_INFO_COMPARATOR;\n\t}\n\n\n\tprivate static final Comparator<SipProfileState> ACC_INFO_COMPARATOR = new Comparator<SipProfileState>() {\n\t\t@Override\n\t\tpublic int compare(SipProfileState infos1,SipProfileState infos2) {\n\t\t\tif (infos1 != null && infos2 != null) {\n\t\t\t\t\n\t\t\t\tint c1 = infos1.getPriority();\n\t\t\t\tint c2 = infos2.getPriority();\n\t\t\t\t\n\t\t\t\tif (c1 > c2) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tif (c1 < c2) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\t};\n}", "public class UAStateReceiver extends Callback {\n private final static String THIS_FILE = \"SIP UA Receiver\";\n private final static String ACTION_PHONE_STATE_CHANGED = \"android.intent.action.PHONE_STATE\";\n\n private SipNotifications notificationManager;\n private PjSipService pjService;\n // private ComponentName remoteControlResponder;\n\n // Time in ms during which we should not relaunch call activity again\n final static long LAUNCH_TRIGGER_DELAY = 2000;\n private long lastLaunchCallHandler = 0;\n\n private int eventLockCount = 0;\n private boolean mIntegrateWithCallLogs;\n private boolean mPlayWaittone;\n private int mPreferedHeadsetAction;\n private boolean mAutoRecordCalls;\n private int mMicroSource;\n\n private void lockCpu() {\n if (eventLock != null) {\n Log.d(THIS_FILE, \"< LOCK CPU\");\n eventLock.acquire();\n eventLockCount++;\n }\n }\n\n private void unlockCpu() {\n if (eventLock != null && eventLock.isHeld()) {\n eventLock.release();\n eventLockCount--;\n Log.d(THIS_FILE, \"> UNLOCK CPU \" + eventLockCount);\n }\n }\n\n /*\n * private class IncomingCallInfos { public SipCallSession callInfo; public\n * Integer accId; }\n */\n @Override\n public void on_incoming_call(final int accId, final int callId, SWIGTYPE_p_pjsip_rx_data rdata) {\n lockCpu();\n\n // Check if we have not already an ongoing call\n boolean hasOngoingSipCall = false;\n if (pjService != null && pjService.service != null) {\n SipCallSessionImpl[] calls = getCalls();\n if (calls != null) {\n for (SipCallSessionImpl existingCall : calls) {\n if (!existingCall.isAfterEnded() && existingCall.getCallId() != callId) {\n if (!pjService.service.supportMultipleCalls) {\n Log.e(THIS_FILE,\n \"Settings to not support two call at the same time !!!\");\n // If there is an ongoing call and we do not support\n // multiple calls\n // Send busy here\n pjsua.call_hangup(callId, StatusCode.BUSY_HERE, null, null);\n unlockCpu();\n return;\n } else {\n hasOngoingSipCall = true;\n }\n }\n }\n }\n }\n\n try {\n SipCallSessionImpl callInfo = updateCallInfoFromStack(callId, null);\n Log.d(THIS_FILE, \"Incoming call << for account \" + accId);\n\n // Extra check if set reference counted is false ???\n if (!ongoingCallLock.isHeld()) {\n ongoingCallLock.acquire();\n }\n\n final String remContact = callInfo.getRemoteContact();\n callInfo.setIncoming(true);\n notificationManager.showNotificationForCall(callInfo);\n\n // Auto answer feature\n SipProfile acc = pjService.getAccountForPjsipId(accId);\n Bundle extraHdr = new Bundle();\n fillRDataHeader(\"Call-Info\", rdata, extraHdr);\n final int shouldAutoAnswer = pjService.service.shouldAutoAnswer(remContact, acc,\n extraHdr);\n Log.d(THIS_FILE, \"Should I anto answer ? \" + shouldAutoAnswer);\n if (shouldAutoAnswer >= 200) {\n // Automatically answer incoming calls with 200 or higher final\n // code\n pjService.callAnswer(callId, shouldAutoAnswer);\n } else {\n // Ring and inform remote about ringing with 180/RINGING\n pjService.callAnswer(callId, 180);\n\n if (pjService.mediaManager != null) {\n if (pjService.service.getGSMCallState() == TelephonyManager.CALL_STATE_IDLE\n && !hasOngoingSipCall) {\n pjService.mediaManager.startRing(remContact);\n } else {\n pjService.mediaManager.playInCallTone(MediaManager.TONE_CALL_WAITING);\n }\n }\n broadCastAndroidCallState(\"RINGING\", remContact);\n }\n if (shouldAutoAnswer < 300) {\n // Or by api\n launchCallHandler(callInfo);\n Log.d(THIS_FILE, \"Incoming call >>\");\n }\n } catch (SameThreadException e) {\n // That's fine we are in a pjsip thread\n } finally {\n unlockCpu();\n }\n\n }\n\n @Override\n public void on_call_state(final int callId, pjsip_event e) {\n pjsua.css_on_call_state(callId, e);\n lockCpu();\n\n Log.d(THIS_FILE, \"Call state <<\");\n try {\n // Get current infos now on same thread cause fix has been done on\n // pj\n final SipCallSession callInfo = updateCallInfoFromStack(callId, e);\n int callState = callInfo.getCallState();\n\n // If disconnected immediate stop required stuffs\n if (callState == SipCallSession.InvState.DISCONNECTED) {\n if (pjService.mediaManager != null) {\n if(getRingingCall() == null) {\n pjService.mediaManager.stopRingAndUnfocus();\n pjService.mediaManager.resetSettings();\n }\n }\n if (ongoingCallLock != null && ongoingCallLock.isHeld()) {\n ongoingCallLock.release();\n }\n // Call is now ended\n pjService.stopDialtoneGenerator(callId);\n pjService.stopRecording(callId);\n pjService.stopPlaying(callId);\n pjService.stopWaittoneGenerator(callId);\n } else {\n if (ongoingCallLock != null && !ongoingCallLock.isHeld()) {\n ongoingCallLock.acquire();\n }\n }\n\n msgHandler.sendMessage(msgHandler.obtainMessage(ON_CALL_STATE, callInfo));\n Log.d(THIS_FILE, \"Call state >>\");\n } catch (SameThreadException ex) {\n // We don't care about that we are at least in a pjsua thread\n } finally {\n // Unlock CPU anyway\n unlockCpu();\n }\n\n }\n\n @Override\n public void on_call_tsx_state(int call_id, org.pjsip.pjsua.SWIGTYPE_p_pjsip_transaction tsx, pjsip_event e) {\n lockCpu();\n\n Log.d(THIS_FILE, \"Call TSX state <<\");\n try {\n updateCallInfoFromStack(call_id, e);\n Log.d(THIS_FILE, \"Call TSX state >>\");\n } catch (SameThreadException ex) {\n // We don't care about that we are at least in a pjsua thread\n } finally {\n // Unlock CPU anyway\n unlockCpu();\n }\n }\n\n @Override\n public void on_buddy_state(int buddyId) {\n lockCpu();\n\n pjsua_buddy_info binfo = new pjsua_buddy_info();\n pjsua.buddy_get_info(buddyId, binfo);\n\n Log.d(THIS_FILE, \"On buddy \" + buddyId + \" state \" + binfo.getMonitor_pres() + \" state \"\n + PjSipService.pjStrToString(binfo.getStatus_text()));\n PresenceStatus presStatus = PresenceStatus.UNKNOWN;\n // First get info from basic status\n String presStatusTxt = PjSipService.pjStrToString(binfo.getStatus_text());\n boolean isDefaultTxt = presStatusTxt.equalsIgnoreCase(\"Online\")\n || presStatusTxt.equalsIgnoreCase(\"Offline\");\n switch (binfo.getStatus()) {\n case PJSUA_BUDDY_STATUS_ONLINE:\n presStatus = PresenceStatus.ONLINE;\n break;\n case PJSUA_BUDDY_STATUS_OFFLINE:\n presStatus = PresenceStatus.OFFLINE;\n break;\n case PJSUA_BUDDY_STATUS_UNKNOWN:\n default:\n presStatus = PresenceStatus.UNKNOWN;\n break;\n }\n // Now get infos from RPID\n switch (binfo.getRpid().getActivity()) {\n case PJRPID_ACTIVITY_AWAY:\n presStatus = PresenceStatus.AWAY;\n if (isDefaultTxt) {\n presStatusTxt = \"\";\n }\n break;\n case PJRPID_ACTIVITY_BUSY:\n presStatus = PresenceStatus.BUSY;\n if (isDefaultTxt) {\n presStatusTxt = \"\";\n }\n break;\n default:\n break;\n }\n\n// pjService.service.presenceMgr.changeBuddyState(PjSipService.pjStrToString(binfo.getUri()),\n// binfo.getMonitor_pres(), presStatus, presStatusTxt);\n unlockCpu();\n }\n\n @Override\n public void on_pager(int callId, pj_str_t from, pj_str_t to, pj_str_t contact,\n pj_str_t mime_type, pj_str_t body) {\n lockCpu();\n\n long date = System.currentTimeMillis();\n String fromStr = PjSipService.pjStrToString(from);\n String canonicFromStr = SipUri.getCanonicalSipContact(fromStr);\n String contactStr = PjSipService.pjStrToString(contact);\n String toStr = PjSipService.pjStrToString(to);\n String bodyStr = PjSipService.pjStrToString(body);\n String mimeStr = PjSipService.pjStrToString(mime_type);\n\n // Sanitize from sip uri\n int slashIndex = fromStr.indexOf(\"/\");\n if (slashIndex != -1){\n fromStr = fromStr.substring(0, slashIndex);\n }\n \n SipMessage msg = new SipMessage(canonicFromStr, toStr, contactStr, bodyStr, mimeStr,\n date, SipMessage.MESSAGE_TYPE_INBOX, fromStr);\n\n // Insert the message to the DB\n ContentResolver cr = pjService.service.getContentResolver();\n cr.insert(SipMessage.MESSAGE_URI, msg.getContentValues());\n\n // Broadcast the message\n Intent intent = new Intent(SipManager.ACTION_SIP_MESSAGE_RECEIVED);\n // TODO : could be parcelable !\n intent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());\n intent.putExtra(SipMessage.FIELD_BODY, msg.getBody());\n pjService.service.sendBroadcast(intent, SipManager.PERMISSION_USE_SIP);\n\n // Notify android os of the new message\n notificationManager.showNotificationForMessage(msg);\n unlockCpu();\n }\n\n @Override\n public void on_pager_status(int callId, pj_str_t to, pj_str_t body, pjsip_status_code status,\n pj_str_t reason) {\n lockCpu();\n // TODO : treat error / acknowledge of messages\n int messageType = (status.equals(pjsip_status_code.PJSIP_SC_OK)\n || status.equals(pjsip_status_code.PJSIP_SC_ACCEPTED)) ? SipMessage.MESSAGE_TYPE_SENT\n : SipMessage.MESSAGE_TYPE_FAILED;\n String toStr = SipUri.getCanonicalSipContact(PjSipService.pjStrToString(to));\n String reasonStr = PjSipService.pjStrToString(reason);\n String bodyStr = PjSipService.pjStrToString(body);\n int statusInt = status.swigValue();\n Log.d(THIS_FILE, \"SipMessage in on pager status \" + status.toString() + \" / \" + reasonStr);\n\n // Update the db\n ContentResolver cr = pjService.service.getContentResolver();\n ContentValues args = new ContentValues();\n args.put(SipMessage.FIELD_TYPE, messageType);\n args.put(SipMessage.FIELD_STATUS, statusInt);\n if (statusInt != StatusCode.OK\n && statusInt != StatusCode.ACCEPTED) {\n args.put(SipMessage.FIELD_BODY, bodyStr + \" // \" + reasonStr);\n }\n cr.update(SipMessage.MESSAGE_URI, args,\n SipMessage.FIELD_TO + \"=? AND \" +\n SipMessage.FIELD_BODY + \"=? AND \" +\n SipMessage.FIELD_TYPE + \"=\" + SipMessage.MESSAGE_TYPE_QUEUED,\n new String[] {\n toStr, bodyStr\n });\n\n // Broadcast the information\n Intent intent = new Intent(SipManager.ACTION_SIP_MESSAGE_RECEIVED);\n intent.putExtra(SipMessage.FIELD_FROM, toStr);\n pjService.service.sendBroadcast(intent, SipManager.PERMISSION_USE_SIP);\n unlockCpu();\n }\n\n @Override\n public void on_reg_state(final int accountId) {\n lockCpu();\n pjService.service.getExecutor().execute(new SipRunnable() {\n @Override\n public void doRun() throws SameThreadException {\n // Update java infos\n pjService.updateProfileStateFromService(accountId);\n }\n });\n unlockCpu();\n }\n\n @Override\n public void on_call_media_state(final int callId) {\n pjsua.css_on_call_media_state(callId);\n\n lockCpu();\n if (pjService.mediaManager != null) {\n // Do not unfocus here since we are probably in call.\n // Unfocus will be done anyway on call disconnect\n pjService.mediaManager.stopRing();\n }\n\n try {\n final SipCallSession callInfo = updateCallInfoFromStack(callId, null);\n\n /*\n * Connect ports appropriately when media status is ACTIVE or REMOTE\n * HOLD, otherwise we should NOT connect the ports.\n */\n boolean connectToOtherCalls = false;\n int callConfSlot = callInfo.getConfPort();\n int mediaStatus = callInfo.getMediaStatus();\n if (mediaStatus == SipCallSession.MediaState.ACTIVE ||\n mediaStatus == SipCallSession.MediaState.REMOTE_HOLD) {\n \n connectToOtherCalls = true;\n pjsua.conf_connect(callConfSlot, 0);\n pjsua.conf_connect(0, callConfSlot);\n\n // Adjust software volume\n if (pjService.mediaManager != null) {\n pjService.mediaManager.setSoftwareVolume();\n }\n\n // Auto record\n if (mAutoRecordCalls && pjService.canRecord(callId)\n && !pjService.isRecording(callId)) {\n pjService\n .startRecording(callId, SipManager.BITMASK_IN | SipManager.BITMASK_OUT);\n }\n }\n \n\n // Connects/disconnnect to other active calls (for conferencing).\n boolean hasOtherCall = false;\n synchronized (callsList) {\n if (callsList != null) {\n for (int i = 0; i < callsList.size(); i++) {\n SipCallSessionImpl otherCallInfo = getCallInfo(i);\n if (otherCallInfo != null && otherCallInfo != callInfo) {\n int otherMediaStatus = otherCallInfo.getMediaStatus();\n if(otherCallInfo.isActive() && otherMediaStatus != SipCallSession.MediaState.NONE) {\n hasOtherCall = true;\n boolean connect = connectToOtherCalls && (otherMediaStatus == SipCallSession.MediaState.ACTIVE ||\n otherMediaStatus == SipCallSession.MediaState.REMOTE_HOLD);\n int otherCallConfSlot = otherCallInfo.getConfPort();\n if(connect) {\n pjsua.conf_connect(callConfSlot, otherCallConfSlot);\n pjsua.conf_connect(otherCallConfSlot, callConfSlot);\n }else {\n pjsua.conf_disconnect(callConfSlot, otherCallConfSlot);\n pjsua.conf_disconnect(otherCallConfSlot, callConfSlot);\n }\n }\n }\n }\n }\n }\n\n // Play wait tone\n if(mPlayWaittone) {\n if(mediaStatus == SipCallSession.MediaState.REMOTE_HOLD && !hasOtherCall) {\n pjService.startWaittoneGenerator(callId);\n }else {\n pjService.stopWaittoneGenerator(callId);\n }\n }\n\n msgHandler.sendMessage(msgHandler.obtainMessage(ON_MEDIA_STATE, callInfo));\n } catch (SameThreadException e) {\n // Nothing to do we are in a pj thread here\n }\n\n unlockCpu();\n }\n\n @Override\n public void on_mwi_info(int acc_id, pj_str_t mime_type, pj_str_t body) {\n lockCpu();\n // Treat incoming voice mail notification.\n\n String msg = PjSipService.pjStrToString(body);\n // Log.d(THIS_FILE, \"We have a message :: \" + acc_id + \" | \" +\n // mime_type.getPtr() + \" | \" + body.getPtr());\n\n boolean hasMessage = false;\n boolean hasSomeNumberOfMessage = false;\n int numberOfMessages = 0;\n // String accountNbr = \"\";\n\n String lines[] = msg.split(\"\\\\r?\\\\n\");\n // Decapsulate the application/simple-message-summary\n // TODO : should we check mime-type?\n // rfc3842\n Pattern messWaitingPattern = Pattern.compile(\".*Messages-Waiting[ \\t]?:[ \\t]?(yes|no).*\",\n Pattern.CASE_INSENSITIVE);\n // Pattern messAccountPattern =\n // Pattern.compile(\".*Message-Account[ \\t]?:[ \\t]?(.*)\",\n // Pattern.CASE_INSENSITIVE);\n Pattern messVoiceNbrPattern = Pattern.compile(\n \".*Voice-Message[ \\t]?:[ \\t]?([0-9]*)/[0-9]*.*\", Pattern.CASE_INSENSITIVE);\n Pattern messFaxNbrPattern = Pattern.compile(\n \".*Fax-Message[ \\t]?:[ \\t]?([0-9]*)/[0-9]*.*\", Pattern.CASE_INSENSITIVE);\n\n for (String line : lines) {\n Matcher m;\n m = messWaitingPattern.matcher(line);\n if (m.matches()) {\n Log.w(THIS_FILE, \"Matches : \" + m.group(1));\n if (\"yes\".equalsIgnoreCase(m.group(1))) {\n Log.d(THIS_FILE, \"Hey there is messages !!! \");\n hasMessage = true;\n\n }\n continue;\n }\n /*\n * m = messAccountPattern.matcher(line); if(m.matches()) {\n * accountNbr = m.group(1); Log.d(THIS_FILE, \"VM acc : \" +\n * accountNbr); continue; }\n */\n m = messVoiceNbrPattern.matcher(line);\n if (m.matches()) {\n try {\n numberOfMessages = Integer.parseInt(m.group(1));\n hasSomeNumberOfMessage = true;\n } catch (NumberFormatException e) {\n Log.w(THIS_FILE, \"Not well formated number \" + m.group(1));\n }\n Log.d(THIS_FILE, \"Nbr : \" + numberOfMessages);\n continue;\n }\n if(messFaxNbrPattern.matcher(line).matches()) {\n hasSomeNumberOfMessage = true;\n }\n }\n\n if (hasMessage && (numberOfMessages > 0 || !hasSomeNumberOfMessage)) {\n SipProfile acc = pjService.getAccountForPjsipId(acc_id);\n if (acc != null) {\n Log.d(THIS_FILE, acc_id + \" -> Has found account \" + acc.getDefaultDomain() + \" \"\n + acc.id + \" >> \" + acc.getProfileName());\n }\n Log.d(THIS_FILE, \"We can show the voice messages notification\");\n notificationManager.showNotificationForVoiceMail(acc, numberOfMessages);\n }\n unlockCpu();\n }\n\n /* (non-Javadoc)\n * @see org.pjsip.pjsua.Callback#on_call_transfer_status(int, int, org.pjsip.pjsua.pj_str_t, int, org.pjsip.pjsua.SWIGTYPE_p_int)\n */\n @Override\n public void on_call_transfer_status(int callId, int st_code, pj_str_t st_text, int final_,\n SWIGTYPE_p_int p_cont) {\n lockCpu();\n if((st_code / 100) == 2) {\n pjsua.call_hangup(callId, 0, null, null);\n }\n unlockCpu();\n }\n \n \n // public String sasString = \"\";\n // public boolean zrtpOn = false;\n\n public int on_validate_audio_clock_rate(int clockRate) {\n if (pjService != null) {\n return pjService.validateAudioClockRate(clockRate);\n }\n return -1;\n }\n\n @Override\n public void on_setup_audio(int beforeInit) {\n if (pjService != null) {\n pjService.setAudioInCall(beforeInit);\n }\n }\n\n @Override\n public void on_teardown_audio() {\n if (pjService != null) {\n pjService.unsetAudioInCall();\n }\n }\n\n @Override\n public pjsip_redirect_op on_call_redirected(int call_id, pj_str_t target) {\n Log.w(THIS_FILE, \"Ask for redirection, not yet implemented, for now allow all \"\n + PjSipService.pjStrToString(target));\n return pjsip_redirect_op.PJSIP_REDIRECT_ACCEPT;\n }\n\n @Override\n public void on_nat_detect(pj_stun_nat_detect_result res) {\n Log.d(THIS_FILE, \"NAT TYPE DETECTED !!!\" + res.getNat_type_name());\n if (pjService != null) {\n pjService.setDetectedNatType(res.getNat_type_name(), res.getStatus());\n }\n }\n\n @Override\n public int on_set_micro_source() {\n return mMicroSource;\n }\n\n @Override\n public int timer_schedule(int entry, int entryId, int time) {\n return TimerWrapper.schedule(entry, entryId, time);\n }\n\n @Override\n public int timer_cancel(int entry, int entryId) {\n return TimerWrapper.cancel(entry, entryId);\n }\n\n /**\n * Map callId to known {@link SipCallSession}. This is cache of known\n * session maintained by the UA state receiver. The UA state receiver is in\n * charge to maintain calls list integrity for {@link PjSipService}. All\n * information it gets comes from the stack. Except recording status that\n * comes from service.\n */\n private SparseArray<SipCallSessionImpl> callsList = new SparseArray<SipCallSessionImpl>();\n\n /**\n * Update the call information from pjsip stack by calling pjsip primitives.\n * \n * @param callId The id to the call to update\n * @param e the pjsip_even that raised the update request\n * @return The built sip call session. It's also stored in cache.\n * @throws SameThreadException if we are calling that from outside the pjsip\n * thread. It's a virtual exception to make sure not called from\n * bad place.\n */\n private SipCallSessionImpl updateCallInfoFromStack(Integer callId, pjsip_event e)\n throws SameThreadException {\n SipCallSessionImpl callInfo;\n Log.d(THIS_FILE, \"Updating call infos from the stack\");\n synchronized (callsList) {\n callInfo = callsList.get(callId);\n if (callInfo == null) {\n callInfo = new SipCallSessionImpl();\n callInfo.setCallId(callId);\n }\n }\n // We update session infos. callInfo is both in/out and will be updated\n PjSipCalls.updateSessionFromPj(callInfo, e, pjService.service);\n // We update from our current recording state\n callInfo.setIsRecording(pjService.isRecording(callId));\n callInfo.setCanRecord(pjService.canRecord(callId));\n synchronized (callsList) {\n // Re-add to list mainly for case newly added session\n callsList.put(callId, callInfo);\n }\n return callInfo;\n }\n\n /**\n * Get call info for a given call id.\n * \n * @param callId the id of the call we want infos for\n * @return the call session infos.\n */\n public SipCallSessionImpl getCallInfo(Integer callId) {\n SipCallSessionImpl callInfo;\n synchronized (callsList) {\n callInfo = callsList.get(callId, null);\n }\n return callInfo;\n }\n\n /**\n * Get list of calls session available.\n * \n * @return List of calls.\n */\n public SipCallSessionImpl[] getCalls() {\n if (callsList != null) {\n List<SipCallSessionImpl> calls = new ArrayList<SipCallSessionImpl>();\n\n synchronized (callsList) {\n for (int i = 0; i < callsList.size(); i++) {\n SipCallSessionImpl callInfo = getCallInfo(i);\n if (callInfo != null) {\n calls.add(callInfo);\n }\n }\n }\n return calls.toArray(new SipCallSessionImpl[calls.size()]);\n }\n return new SipCallSessionImpl[0];\n }\n\n private WorkerHandler msgHandler;\n private HandlerThread handlerThread;\n private WakeLock ongoingCallLock;\n private WakeLock eventLock;\n\n // private static final int ON_INCOMING_CALL = 1;\n private static final int ON_CALL_STATE = 2;\n private static final int ON_MEDIA_STATE = 3;\n\n // private static final int ON_REGISTRATION_STATE = 4;\n // private static final int ON_PAGER = 5;\n\n private static class WorkerHandler extends Handler {\n WeakReference<UAStateReceiver> sr;\n\n public WorkerHandler(Looper looper, UAStateReceiver stateReceiver) {\n super(looper);\n Log.d(THIS_FILE, \"Create async worker !!!\");\n sr = new WeakReference<UAStateReceiver>(stateReceiver);\n }\n\n public void handleMessage(Message msg) {\n UAStateReceiver stateReceiver = sr.get();\n if (stateReceiver == null) {\n return;\n }\n stateReceiver.lockCpu();\n switch (msg.what) {\n case ON_CALL_STATE: {\n SipCallSessionImpl callInfo = (SipCallSessionImpl) msg.obj;\n final int callState = callInfo.getCallState();\n\n switch (callState) {\n case SipCallSession.InvState.INCOMING:\n case SipCallSession.InvState.CALLING:\n stateReceiver.notificationManager.showNotificationForCall(callInfo);\n stateReceiver.launchCallHandler(callInfo);\n stateReceiver.broadCastAndroidCallState(\"RINGING\",\n callInfo.getRemoteContact());\n break;\n case SipCallSession.InvState.EARLY:\n case SipCallSession.InvState.CONNECTING:\n case SipCallSession.InvState.CONFIRMED:\n // As per issue #857 we should re-ensure\n // notification + callHandler at each state\n // cause we can miss some states due to the fact\n // treatment of call state is threaded\n // Anyway if we miss the call early + confirmed we\n // do not need to show the UI.\n stateReceiver.notificationManager.showNotificationForCall(callInfo);\n stateReceiver.launchCallHandler(callInfo);\n stateReceiver.broadCastAndroidCallState(\"OFFHOOK\",\n callInfo.getRemoteContact());\n\n if (stateReceiver.pjService.mediaManager != null) {\n if (callState == SipCallSession.InvState.CONFIRMED) {\n // Don't unfocus here\n stateReceiver.pjService.mediaManager.stopRing();\n }\n }\n // Auto send pending dtmf\n if (callState == SipCallSession.InvState.CONFIRMED) {\n stateReceiver.sendPendingDtmf(callInfo.getCallId());\n }\n // If state is confirmed and not already intialized\n if (callState == SipCallSession.InvState.CONFIRMED\n && callInfo.getCallStart() == 0) {\n callInfo.setCallStart(System.currentTimeMillis());\n }\n break;\n case SipCallSession.InvState.DISCONNECTED:\n if (stateReceiver.pjService.mediaManager != null && stateReceiver.getRingingCall() == null) {\n stateReceiver.pjService.mediaManager.stopRing();\n }\n\n stateReceiver.broadCastAndroidCallState(\"IDLE\",\n callInfo.getRemoteContact());\n\n // If no remaining calls, cancel the notification\n if (stateReceiver.getActiveCallInProgress() == null) {\n stateReceiver.notificationManager.cancelCalls();\n // We should now ask parent to stop if needed\n if (stateReceiver.pjService != null\n && stateReceiver.pjService.service != null) {\n stateReceiver.pjService.service\n .treatDeferUnregistersForOutgoing();\n }\n }\n\n // CallLog\n ContentValues cv = CallLogHelper.logValuesForCall(\n stateReceiver.pjService.service, callInfo,\n callInfo.getCallStart());\n\n // Fill our own database\n stateReceiver.pjService.service.getContentResolver().insert(\n SipManager.CALLLOG_URI, cv);\n Integer isNew = cv.getAsInteger(Calls.NEW);\n if (isNew != null && isNew == 1) {\n stateReceiver.notificationManager.showNotificationForMissedCall(cv);\n }\n\n // If the call goes out in error...\n if (callInfo.getLastStatusCode() != 200 && callInfo.getLastReasonCode() != 200) {\n // We notify the user with toaster\n stateReceiver.pjService.service.notifyUserOfMessage(callInfo\n .getLastStatusCode()\n + \" / \"\n + callInfo.getLastStatusComment());\n }\n\n // If needed fill native database\n if (stateReceiver.mIntegrateWithCallLogs) {\n // Don't add with new flag\n cv.put(Calls.NEW, false);\n // Remove csipsimple custom entries\n cv.remove(SipManager.CALLLOG_PROFILE_ID_FIELD);\n cv.remove(SipManager.CALLLOG_STATUS_CODE_FIELD);\n cv.remove(SipManager.CALLLOG_STATUS_TEXT_FIELD);\n\n // Reformat number for callogs\n ParsedSipContactInfos callerInfos = SipUri.parseSipContact(cv\n .getAsString(Calls.NUMBER));\n if (callerInfos != null) {\n String phoneNumber = SipUri.getPhoneNumber(callerInfos);\n\n // Only log numbers that can be called by\n // GSM too.\n // TODO : if android 2.3 add sip uri also\n if (!TextUtils.isEmpty(phoneNumber)) {\n cv.put(Calls.NUMBER, phoneNumber);\n // For log in call logs => don't add as\n // new calls... we manage it ourselves.\n cv.put(Calls.NEW, false);\n ContentValues extraCv = new ContentValues();\n\n if (callInfo.getAccId() != SipProfile.INVALID_ID) {\n SipProfile acc = stateReceiver.pjService.service\n .getAccount(callInfo.getAccId());\n if (acc != null && acc.display_name != null) {\n extraCv.put(CallLogHelper.EXTRA_SIP_PROVIDER,\n acc.display_name);\n }\n }\n CallLogHelper.addCallLog(stateReceiver.pjService.service,\n cv, extraCv);\n }\n }\n }\n callInfo.applyDisconnect();\n break;\n default:\n break;\n }\n stateReceiver.onBroadcastCallState(callInfo);\n break;\n }\n case ON_MEDIA_STATE: {\n SipCallSession mediaCallInfo = (SipCallSession) msg.obj;\n SipCallSessionImpl callInfo = stateReceiver.callsList.get(mediaCallInfo\n .getCallId());\n callInfo.setMediaStatus(mediaCallInfo.getMediaStatus());\n stateReceiver.callsList.put(mediaCallInfo.getCallId(), callInfo);\n stateReceiver.onBroadcastCallState(callInfo);\n break;\n }\n }\n stateReceiver.unlockCpu();\n }\n };\n\n // -------\n // Public configuration for receiver\n // -------\n\n public void initService(PjSipService srv) {\n pjService = srv;\n notificationManager = pjService.service.notificationManager;\n\n if (handlerThread == null) {\n handlerThread = new HandlerThread(\"UAStateAsyncWorker\");\n handlerThread.start();\n }\n if (msgHandler == null) {\n msgHandler = new WorkerHandler(handlerThread.getLooper(), this);\n }\n\n if (eventLock == null) {\n PowerManager pman = (PowerManager) pjService.service\n .getSystemService(Context.POWER_SERVICE);\n eventLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,\n \"com.csipsimple.inEventLock\");\n eventLock.setReferenceCounted(true);\n\n }\n if (ongoingCallLock == null) {\n PowerManager pman = (PowerManager) pjService.service\n .getSystemService(Context.POWER_SERVICE);\n ongoingCallLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,\n \"com.csipsimple.ongoingCallLock\");\n ongoingCallLock.setReferenceCounted(false);\n }\n }\n\n public void stopService() {\n\n Threading.stopHandlerThread(handlerThread, true);\n handlerThread = null;\n msgHandler = null;\n\n // Ensure lock is released since this lock is a ref counted one.\n if (eventLock != null) {\n while (eventLock.isHeld()) {\n eventLock.release();\n }\n }\n if (ongoingCallLock != null) {\n if (ongoingCallLock.isHeld()) {\n ongoingCallLock.release();\n }\n }\n }\n\n public void reconfigure(Context ctxt) {\n mIntegrateWithCallLogs = SipConfigManager.getPreferenceBooleanValue(ctxt,\n SipConfigManager.INTEGRATE_WITH_CALLLOGS);\n mPreferedHeadsetAction = SipConfigManager.getPreferenceIntegerValue(ctxt,\n SipConfigManager.HEADSET_ACTION, SipConfigManager.HEADSET_ACTION_CLEAR_CALL);\n mAutoRecordCalls = SipConfigManager.getPreferenceBooleanValue(ctxt,\n SipConfigManager.AUTO_RECORD_CALLS);\n mMicroSource = SipConfigManager.getPreferenceIntegerValue(ctxt,\n SipConfigManager.MICRO_SOURCE);\n mPlayWaittone = SipConfigManager.getPreferenceBooleanValue(ctxt, \n SipConfigManager.PLAY_WAITTONE_ON_HOLD, false);\n }\n\n // --------\n // Private methods\n // --------\n\n /**\n * Broadcast csipsimple intent about the fact we are currently have a sip\n * call state change.<br/>\n * This may be used by third party applications that wants to track\n * csipsimple call state\n * \n * @param callInfo the new call state infos\n */\n private void onBroadcastCallState(final SipCallSession callInfo) {\n SipCallSession publicCallInfo = new SipCallSession(callInfo);\n Intent callStateChangedIntent = new Intent(SipManager.ACTION_SIP_CALL_CHANGED);\n callStateChangedIntent.putExtra(SipManager.EXTRA_CALL_INFO, publicCallInfo);\n pjService.service.sendBroadcast(callStateChangedIntent, SipManager.PERMISSION_USE_SIP);\n\n }\n\n /**\n * Broadcast to android system that we currently have a phone call. This may\n * be managed by other sip apps that want to keep track of incoming calls\n * for example.\n * \n * @param state The state of the call\n * @param number The corresponding remote number\n */\n private void broadCastAndroidCallState(String state, String number) {\n // Android normalized event\n if(!Compatibility.isCompatible(19)) {\n // Not allowed to do that from kitkat\n Intent intent = new Intent(ACTION_PHONE_STATE_CHANGED);\n intent.putExtra(TelephonyManager.EXTRA_STATE, state);\n if (number != null) {\n intent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, number);\n }\n intent.putExtra(pjService.service.getString(R.string.app_name), true);\n pjService.service.sendBroadcast(intent, android.Manifest.permission.READ_PHONE_STATE);\n }\n }\n\n /**\n * Start the call activity for a given Sip Call Session. <br/>\n * The call activity should take care to get any ongoing calls when started\n * so the currentCallInfo2 parameter is indication only. <br/>\n * This method ensure that the start of the activity is not fired too much\n * in short delay and may just ignore requests if last time someone ask for\n * a launch is too recent\n * \n * @param currentCallInfo2 the call info that raise this request to open the\n * call handler activity\n */\n private synchronized void launchCallHandler(SipCallSession currentCallInfo2) {\n long currentElapsedTime = SystemClock.elapsedRealtime();\n // Synchronized ensure we do not get this launched several time\n // We also ensure that a minimum delay has been consumed so that we do\n // not fire this too much times\n // Specially for EARLY - CONNECTING states\n if (lastLaunchCallHandler + LAUNCH_TRIGGER_DELAY < currentElapsedTime) {\n Context ctxt = pjService.service;\n\n // Launch activity to choose what to do with this call\n Intent callHandlerIntent = SipService.buildCallUiIntent(ctxt, currentCallInfo2);\n\n Log.d(THIS_FILE, \"Anounce call activity\");\n ctxt.startActivity(callHandlerIntent);\n lastLaunchCallHandler = currentElapsedTime;\n } else {\n Log.d(THIS_FILE, \"Ignore extra launch handler\");\n }\n }\n\n /**\n * Check if any of call infos indicate there is an active call in progress.\n * \n * @see SipCallSession#isActive()\n */\n public SipCallSession getActiveCallInProgress() {\n // Go through the whole list of calls and find the first active state.\n synchronized (callsList) {\n for (int i = 0; i < callsList.size(); i++) {\n SipCallSession callInfo = getCallInfo(i);\n if (callInfo != null && callInfo.isActive()) {\n return callInfo;\n }\n }\n }\n return null;\n }\n\n /**\n * Check if any of call infos indicate there is an active call in progress.\n * \n * @see SipCallSession#isActive()\n */\n public SipCallSession getActiveCallOngoing() {\n // Go through the whole list of calls and find the first active state.\n synchronized (callsList) {\n for (int i = 0; i < callsList.size(); i++) {\n SipCallSession callInfo = getCallInfo(i);\n if (callInfo != null && callInfo.isActive() && callInfo.isOngoing()) {\n return callInfo;\n }\n }\n }\n return null;\n }\n \n public SipCallSession getRingingCall() {\n // Go through the whole list of calls and find the first ringing state.\n synchronized (callsList) {\n for (int i = 0; i < callsList.size(); i++) {\n SipCallSession callInfo = getCallInfo(i);\n if (callInfo != null && callInfo.isActive() && callInfo.isBeforeConfirmed() && callInfo.isIncoming()) {\n return callInfo;\n }\n }\n }\n return null;\n \n }\n\n /**\n * Broadcast the Headset button press event internally if there is any call\n * in progress. TODO : register and unregister only while in call\n */\n public boolean handleHeadsetButton() {\n final SipCallSession callInfo = getActiveCallInProgress();\n if (callInfo != null) {\n // Headset button has been pressed by user. If there is an\n // incoming call ringing the button will be used to answer the\n // call. If there is an ongoing call in progress the button will\n // be used to hangup the call or mute the microphone.\n int state = callInfo.getCallState();\n if (callInfo.isIncoming() &&\n (state == SipCallSession.InvState.INCOMING ||\n state == SipCallSession.InvState.EARLY)) {\n if (pjService != null && pjService.service != null) {\n pjService.service.getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n\n pjService.callAnswer(callInfo.getCallId(),\n pjsip_status_code.PJSIP_SC_OK.swigValue());\n }\n });\n }\n return true;\n } else if (state == SipCallSession.InvState.INCOMING ||\n state == SipCallSession.InvState.EARLY ||\n state == SipCallSession.InvState.CALLING ||\n state == SipCallSession.InvState.CONFIRMED ||\n state == SipCallSession.InvState.CONNECTING) {\n //\n // In the Android phone app using the media button during\n // a call mutes the microphone instead of terminating the call.\n // We check here if this should be the behavior here or if\n // the call should be cleared.\n //\n if (pjService != null && pjService.service != null) {\n pjService.service.getExecutor().execute(new SipRunnable() {\n\n @Override\n protected void doRun() throws SameThreadException {\n if (mPreferedHeadsetAction == SipConfigManager.HEADSET_ACTION_CLEAR_CALL) {\n pjService.callHangup(callInfo.getCallId(), 0);\n } else if (mPreferedHeadsetAction == SipConfigManager.HEADSET_ACTION_HOLD) {\n pjService.callHold(callInfo.getCallId());\n } else if (mPreferedHeadsetAction == SipConfigManager.HEADSET_ACTION_MUTE) {\n pjService.mediaManager.toggleMute();\n }\n }\n });\n }\n return true;\n }\n }\n return false;\n }\n\n /**\n * Update status of call recording info in call session info\n * \n * @param callId The call id to modify\n * @param canRecord if we can now record the call\n * @param isRecording if we are currently recording the call\n */\n public void updateRecordingStatus(int callId, boolean canRecord, boolean isRecording) {\n SipCallSessionImpl callInfo = getCallInfo(callId);\n callInfo.setCanRecord(canRecord);\n callInfo.setIsRecording(isRecording);\n synchronized (callsList) {\n // Re-add it just to be sure\n callsList.put(callId, callInfo);\n }\n onBroadcastCallState(callInfo);\n }\n\n private void sendPendingDtmf(final int callId) {\n pjService.service.getExecutor().execute(new SipRunnable() {\n @Override\n protected void doRun() throws SameThreadException {\n pjService.sendPendingDtmf(callId);\n }\n });\n }\n\n private void fillRDataHeader(String hdrName, SWIGTYPE_p_pjsip_rx_data rdata, Bundle out)\n throws SameThreadException {\n String valueHdr = PjSipService.pjStrToString(pjsua.get_rx_data_header(\n pjsua.pj_str_copy(hdrName), rdata));\n if (!TextUtils.isEmpty(valueHdr)) {\n out.putString(hdrName, valueHdr);\n }\n }\n\n public void updateCallMediaState(int callId) throws SameThreadException {\n SipCallSession callInfo = updateCallInfoFromStack(callId, null);\n msgHandler.sendMessage(msgHandler.obtainMessage(ON_MEDIA_STATE, callInfo));\n }\n}", "@SuppressWarnings(\"deprecation\")\npublic final class Compatibility {\n\n private Compatibility() {\n }\n\n private static final String THIS_FILE = \"Compat\";\n\n public static int getApiLevel() {\n return Build.VERSION.SDK_INT;\n }\n\n public static boolean isCompatible(int apiLevel) {\n return Build.VERSION.SDK_INT >= apiLevel;\n }\n\n /**\n * Get the stream id for in call track. Can differ on some devices. Current\n * device for which it's different :\n * \n * @return\n */\n public static int getInCallStream(boolean requestBluetooth) {\n /* Archos 5IT */\n if (Build.BRAND.equalsIgnoreCase(\"archos\")\n && Build.DEVICE.equalsIgnoreCase(\"g7a\")) {\n // Since archos has no voice call capabilities, voice call stream is\n // not implemented\n // So we have to choose the good stream tag, which is by default\n // falled back to music\n return AudioManager.STREAM_MUSIC;\n }\n if (requestBluetooth) {\n return 6; /* STREAM_BLUETOOTH_SCO -- Thx @Stefan for the contrib */\n }\n\n // return AudioManager.STREAM_MUSIC;\n return AudioManager.STREAM_VOICE_CALL;\n }\n\n public static boolean shouldUseRoutingApi() {\n Log.d(THIS_FILE, \"Current device \" + Build.BRAND + \" - \"\n + Build.DEVICE);\n\n // HTC evo 4G\n if (Build.PRODUCT.equalsIgnoreCase(\"htc_supersonic\")) {\n return true;\n }\n\n // ZTE joe\n if (Build.DEVICE.equalsIgnoreCase(\"joe\")) {\n return true;\n }\n\n // Samsung GT-S5830\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-S\")) {\n return true;\n }\n\n if (!isCompatible(4)) {\n // If android 1.5, force routing api use\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean shouldUseModeApi() {\n\n // ZTE blade et joe\n if (Build.DEVICE.equalsIgnoreCase(\"blade\")\n || Build.DEVICE.equalsIgnoreCase(\"joe\")) {\n return true;\n }\n // Samsung GT-S5360 GT-S5830 GT-S6102 ... probably all..\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-\") ||\n Build.PRODUCT.toUpperCase().startsWith(\"GT-\") ||\n Build.DEVICE.toUpperCase().startsWith(\"YP-\")) {\n return true;\n }\n\n // HTC evo 4G\n if (Build.PRODUCT.equalsIgnoreCase(\"htc_supersonic\")) {\n return true;\n }\n // LG P500, Optimus V\n if (Build.DEVICE.toLowerCase().startsWith(\"thunder\")) {\n return true;\n }\n // LG-E720(b)\n if (Build.MODEL.toUpperCase().startsWith(\"LG-E720\")\n && !Compatibility.isCompatible(9)) {\n return true;\n }\n // LG-G2\n if (Build.DEVICE.toLowerCase().startsWith(\"g2\")\n && Build.BRAND.toLowerCase().startsWith(\"lge\")) {\n return true;\n }\n // LG-LS840\n if (Build.DEVICE.toLowerCase().startsWith(\"cayman\")) {\n return true;\n }\n\n // Huawei\n if (Build.DEVICE.equalsIgnoreCase(\"U8150\") ||\n Build.DEVICE.equalsIgnoreCase(\"U8110\") ||\n Build.DEVICE.equalsIgnoreCase(\"U8120\") ||\n Build.DEVICE.equalsIgnoreCase(\"U8100\") ||\n Build.DEVICE.toUpperCase().startsWith(\"U8836\") ||\n Build.PRODUCT.equalsIgnoreCase(\"U8655\") ||\n Build.DEVICE.toUpperCase().startsWith(\"HWU9700\")) {\n return true;\n }\n\n // Moto defy mini\n if (Build.MODEL.equalsIgnoreCase(\"XT320\")) {\n return true;\n }\n\n // Alcatel\n if (Build.DEVICE.toUpperCase().startsWith(\"ONE_TOUCH_993D\")) {\n return true;\n }\n\n // N4\n if (Build.DEVICE.toUpperCase().startsWith(\"MAKO\")) {\n return true;\n }\n\n return false;\n }\n\n public static String guessInCallMode() {\n // New api for 2.3.3 is not available on galaxy S II :(\n if (!isCompatible(11) && Build.DEVICE.toUpperCase().startsWith(\"GT-I9100\")) {\n return Integer.toString(AudioManager.MODE_NORMAL);\n }\n\n if (Build.BRAND.equalsIgnoreCase(\"sdg\") || isCompatible(10)) {\n // Note that in APIs this is only available from level 11.\n return \"3\";\n }\n if (Build.DEVICE.equalsIgnoreCase(\"blade\")) {\n return Integer.toString(AudioManager.MODE_IN_CALL);\n }\n\n if (!isCompatible(5)) {\n return Integer.toString(AudioManager.MODE_IN_CALL);\n }\n\n return Integer.toString(AudioManager.MODE_NORMAL);\n }\n\n public static String getDefaultMicroSource() {\n // Except for galaxy S II :(\n if (!isCompatible(11) && Build.DEVICE.toUpperCase().startsWith(\"GT-I9100\")) {\n return Integer.toString(AudioSource.MIC);\n }\n\n if (isCompatible(10)) {\n // Note that in APIs this is only available from level 11.\n // VOICE_COMMUNICATION\n return Integer.toString(0x7);\n }\n /*\n * Too risky in terms of regressions else if (isCompatible(4)) { //\n * VOICE_CALL return 0x4; }\n */\n /*\n * if(android.os.Build.MODEL.equalsIgnoreCase(\"X10i\")) { // VOICE_CALL\n * return Integer.toString(0x4); }\n */\n /*\n * Not relevant anymore, atrix I tested sounds fine with that\n * if(android.os.Build.DEVICE.equalsIgnoreCase(\"olympus\")) { //Motorola\n * atrix bug // CAMCORDER return Integer.toString(0x5); }\n */\n\n return Integer.toString(AudioSource.DEFAULT);\n }\n\n public static String getDefaultFrequency() {\n if (Build.DEVICE.equalsIgnoreCase(\"olympus\")) {\n // Atrix bug\n return \"32000\";\n }\n if (Build.DEVICE.toUpperCase().equals(\"GT-P1010\")) {\n // Galaxy tab see issue 932\n return \"32000\";\n }\n\n return isCompatible(4) ? \"16000\" : \"8000\";\n }\n\n public static String getCpuAbi() {\n if (isCompatible(4)) {\n Field field;\n try {\n field = Build.class.getField(\"CPU_ABI\");\n return field.get(null).toString();\n } catch (Exception e) {\n Log.w(THIS_FILE, \"Announce to be android 1.6 but no CPU ABI field\", e);\n }\n\n }\n return \"armeabi\";\n }\n\n public final static int getNumCores() {\n // Private Class to display only CPU devices in the directory listing\n class CpuFilter implements FileFilter {\n @Override\n public boolean accept(File pathname) {\n // Check if filename is \"cpu\", followed by a single digit number\n if (Pattern.matches(\"cpu[0-9]\", pathname.getName())) {\n return true;\n }\n return false;\n }\n }\n try {\n // Get directory containing CPU info\n File dir = new File(\"/sys/devices/system/cpu/\");\n // Filter to only list the devices we care about\n File[] files = dir.listFiles(new CpuFilter());\n // Return the number of cores (virtual CPU devices)\n return files.length;\n } catch (Exception e) {\n return Runtime.getRuntime().availableProcessors();\n }\n }\n\n private static boolean needPspWorkaround() {\n // New api for 2.3 does not work on Incredible S\n if (Build.DEVICE.equalsIgnoreCase(\"vivo\")) {\n return true;\n }\n\n // New API for android 2.3 should be able to manage this but do only for\n // honeycomb cause seems not correctly supported by all yet\n if (isCompatible(11)) {\n return false;\n }\n\n // All htc except....\n if (Build.PRODUCT.toLowerCase().startsWith(\"htc\")\n || Build.BRAND.toLowerCase().startsWith(\"htc\")\n || Build.PRODUCT.toLowerCase().equalsIgnoreCase(\"inc\") /*\n * For\n * Incredible\n */\n || Build.DEVICE.equalsIgnoreCase(\"passion\") /* N1 */) {\n if (Build.DEVICE.equalsIgnoreCase(\"hero\") /* HTC HERO */\n || Build.DEVICE.equalsIgnoreCase(\"magic\") /*\n * Magic\n * Aka\n * Dev\n * G2\n */\n || Build.DEVICE.equalsIgnoreCase(\"tatoo\") /* Tatoo */\n || Build.DEVICE.equalsIgnoreCase(\"dream\") /*\n * Dream\n * Aka\n * Dev\n * G1\n */\n || Build.DEVICE.equalsIgnoreCase(\"legend\") /* Legend */\n\n ) {\n return false;\n }\n\n // Older than 2.3 has no chance to have the new full perf wifi mode\n // working since does not exists\n if (!isCompatible(9)) {\n return true;\n } else {\n // N1 is fine with that\n if (Build.DEVICE.equalsIgnoreCase(\"passion\")) {\n return false;\n }\n return true;\n }\n\n }\n // Dell streak\n if (Build.BRAND.toLowerCase().startsWith(\"dell\") &&\n Build.DEVICE.equalsIgnoreCase(\"streak\")) {\n return true;\n }\n // Motorola milestone 1 and 2 & motorola droid & defy not under 2.3\n if ((Build.DEVICE.toLowerCase().contains(\"milestone2\") ||\n Build.BOARD.toLowerCase().contains(\"sholes\") ||\n Build.PRODUCT.toLowerCase().contains(\"sholes\") ||\n Build.DEVICE.equalsIgnoreCase(\"olympus\") ||\n Build.DEVICE.toLowerCase().contains(\"umts_jordan\")) && !isCompatible(9)) {\n return true;\n }\n // Moto defy mini\n if (Build.MODEL.equalsIgnoreCase(\"XT320\")) {\n return true;\n }\n\n // Alcatel ONE touch\n if (Build.DEVICE.startsWith(\"one_touch_990\")) {\n return true;\n }\n\n return false;\n }\n\n private static boolean needToneWorkaround() {\n if (Build.PRODUCT.toLowerCase().startsWith(\"gt-i5800\") ||\n Build.PRODUCT.toLowerCase().startsWith(\"gt-i5801\") ||\n Build.PRODUCT.toLowerCase().startsWith(\"gt-i9003\")) {\n return true;\n }\n return false;\n }\n\n private static boolean needSGSWorkaround() {\n if (isCompatible(9)) {\n return false;\n }\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-I9000\") ||\n Build.DEVICE.toUpperCase().startsWith(\"GT-P1000\")) {\n return true;\n }\n return false;\n }\n\n private static boolean needWebRTCImplementation() {\n if (Build.DEVICE.toLowerCase().contains(\"droid2\")) {\n return true;\n }\n if (Build.MODEL.toLowerCase().contains(\"droid bionic\")) {\n return true;\n }\n if (Build.DEVICE.toLowerCase().contains(\"sunfire\")) {\n return true;\n }\n // Huawei Y300\n if (Build.DEVICE.equalsIgnoreCase(\"U8833\")) {\n return true;\n }\n return false;\n }\n\n public static boolean shouldSetupAudioBeforeInit() {\n // Setup for GT / GS samsung devices.\n if (Build.DEVICE.toLowerCase().startsWith(\"gt-\")\n || Build.PRODUCT.toLowerCase().startsWith(\"gt-\")) {\n return true;\n }\n return false;\n }\n\n private static boolean shouldFocusAudio() {\n /* HTC One X */\n if (Build.DEVICE.toLowerCase().startsWith(\"endeavoru\") ||\n Build.DEVICE.toLowerCase().startsWith(\"evita\")) {\n return false;\n }\n\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-P7510\") && isCompatible(15)) {\n return false;\n }\n return true;\n }\n\n private static int getDefaultAudioImplementation() {\n // Acer A510\n if (Build.DEVICE.toLowerCase().startsWith(\"picasso\")) {\n return SipConfigManager.AUDIO_IMPLEMENTATION_JAVA;\n }\n if (Compatibility.isCompatible(11)) {\n return SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES;\n }\n if (Build.DEVICE.equalsIgnoreCase(\"ST25i\") && Compatibility.isCompatible(10)) {\n return SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES;\n }\n if (Build.DEVICE.equalsIgnoreCase(\"u8510\") && Compatibility.isCompatible(10)) {\n return SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES;\n }\n if (Build.DEVICE.toLowerCase().startsWith(\"rk31sdk\")) {\n return SipConfigManager.AUDIO_IMPLEMENTATION_JAVA;\n }\n return SipConfigManager.AUDIO_IMPLEMENTATION_JAVA;\n }\n\n private static void resetCodecsSettings(PreferencesWrapper preferencesWrapper) {\n boolean supportFloating = false;\n boolean isHeavyCpu = false;\n String abi = getCpuAbi();\n if (!TextUtils.isEmpty(abi)) {\n if (abi.equalsIgnoreCase(\"mips\") || abi.equalsIgnoreCase(\"x86\")) {\n supportFloating = true;\n }\n if (abi.equalsIgnoreCase(\"armeabi-v7a\") || abi.equalsIgnoreCase(\"x86\")) {\n isHeavyCpu = true;\n }\n }\n\n // For Narrowband\n preferencesWrapper.setCodecPriority(\"PCMU/8000/1\", SipConfigManager.CODEC_NB, \"60\");\n preferencesWrapper.setCodecPriority(\"PCMA/8000/1\", SipConfigManager.CODEC_NB, \"50\");\n preferencesWrapper.setCodecPriority(\"speex/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"speex/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"speex/32000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"GSM/8000/1\", SipConfigManager.CODEC_NB, \"230\");\n preferencesWrapper.setCodecPriority(\"G722/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G729/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"iLBC/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/8000/1\", SipConfigManager.CODEC_NB, \"239\");\n preferencesWrapper.setCodecPriority(\"SILK/12000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/24000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"CODEC2/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G7221/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G7221/32000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"ISAC/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"ISAC/32000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"AMR/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"AMR-WB/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/24000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/48000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-16/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-24/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-32/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-40/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n preferencesWrapper.setCodecPriority(\"mpeg4-generic/48000/1\", SipConfigManager.CODEC_NB, \"0\");\n\n // For Wideband\n preferencesWrapper.setCodecPriority(\"PCMU/8000/1\", SipConfigManager.CODEC_WB, \"60\");\n preferencesWrapper.setCodecPriority(\"PCMA/8000/1\", SipConfigManager.CODEC_WB, \"50\");\n preferencesWrapper.setCodecPriority(\"speex/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"speex/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"speex/32000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"GSM/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G722/16000/1\", SipConfigManager.CODEC_WB,\n supportFloating ? \"235\" : \"0\");\n preferencesWrapper.setCodecPriority(\"G729/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"iLBC/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/12000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"SILK/16000/1\", SipConfigManager.CODEC_WB,\n isHeavyCpu ? \"0\" : \"220\");\n preferencesWrapper.setCodecPriority(\"SILK/24000/1\", SipConfigManager.CODEC_WB,\n isHeavyCpu ? \"220\" : \"0\");\n preferencesWrapper.setCodecPriority(\"CODEC2/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G7221/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G7221/32000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"ISAC/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"ISAC/32000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"AMR/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"AMR-WB/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/24000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"opus/48000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-16/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-24/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-32/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"G726-40/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n preferencesWrapper.setCodecPriority(\"mpeg4-generic/48000/1\", SipConfigManager.CODEC_WB, \"0\");\n\n // Bands repartition\n preferencesWrapper.setPreferenceStringValue(\"band_for_wifi\", SipConfigManager.CODEC_WB);\n preferencesWrapper.setPreferenceStringValue(\"band_for_other\", SipConfigManager.CODEC_WB);\n preferencesWrapper.setPreferenceStringValue(\"band_for_3g\", SipConfigManager.CODEC_NB);\n preferencesWrapper.setPreferenceStringValue(\"band_for_gprs\", SipConfigManager.CODEC_NB);\n preferencesWrapper.setPreferenceStringValue(\"band_for_edge\", SipConfigManager.CODEC_NB);\n\n }\n\n public static void setFirstRunParameters(PreferencesWrapper preferencesWrapper) {\n preferencesWrapper.startEditing();\n resetCodecsSettings(preferencesWrapper);\n\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.SND_MEDIA_QUALITY, getCpuAbi()\n .equalsIgnoreCase(\"armeabi-v7a\") ? \"4\" : \"3\");\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.SND_AUTO_CLOSE_TIME,\n isCompatible(4) ? \"1\" : \"5\");\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.SND_CLOCK_RATE,\n getDefaultFrequency());\n // HTC PSP mode hack\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.MEDIA_THREAD_COUNT,\n getNumCores() > 1 ? \"2\" : \"1\");\n\n // Proximity sensor inverted\n if (Build.PRODUCT.equalsIgnoreCase(\"SPH-M900\") /* Sgs moment */) {\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.INVERT_PROXIMITY_SENSOR,\n true);\n }\n\n // Tablet settings\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.PREVENT_SCREEN_ROTATION,\n !Compatibility.isTabletScreen(preferencesWrapper.getContext()));\n\n // Galaxy S default settings\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-I9000\") && !isCompatible(9)) {\n preferencesWrapper.setPreferenceFloatValue(SipConfigManager.SND_MIC_LEVEL, (float) 0.4);\n preferencesWrapper.setPreferenceFloatValue(SipConfigManager.SND_SPEAKER_LEVEL,\n (float) 0.2);\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SOFT_VOLUME, true);\n }\n // HTC evo 4G\n if (Build.PRODUCT.equalsIgnoreCase(\"htc_supersonic\") && !isCompatible(9)) {\n preferencesWrapper.setPreferenceFloatValue(SipConfigManager.SND_MIC_LEVEL, (float) 0.5);\n preferencesWrapper.setPreferenceFloatValue(SipConfigManager.SND_SPEAKER_LEVEL,\n (float) 1.5);\n\n }\n\n // Api to use for routing\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.USE_ROUTING_API,\n shouldUseRoutingApi());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.SET_AUDIO_GENERATE_TONE,\n needToneWorkaround());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SGS_CALL_HACK,\n needSGSWorkaround());\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.SIP_AUDIO_MODE,\n guessInCallMode());\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.MICRO_SOURCE,\n getDefaultMicroSource());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK,\n needWebRTCImplementation());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO,\n shouldFocusAudio());\n\n boolean usePriviledged = shouldUsePriviledgedIntegration(preferencesWrapper.getContext());\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_TEL_PRIVILEGED,\n usePriviledged);\n if (usePriviledged) {\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_DIALER,\n !usePriviledged);\n }\n\n if (Build.PRODUCT.startsWith(\"GoGear_Connect\")) {\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_CALLLOGS,\n false);\n }\n\n preferencesWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n preferencesWrapper.setPreferenceBooleanValue(SipConfigManager.SETUP_AUDIO_BEFORE_INIT,\n shouldSetupAudioBeforeInit());\n\n preferencesWrapper.endEditing();\n }\n\n public static boolean useFlipAnimation() {\n if (Build.BRAND.equalsIgnoreCase(\"archos\")\n && Build.DEVICE.equalsIgnoreCase(\"g7a\")) {\n return false;\n }\n return true;\n }\n\n /**\n * Check if we can make gsm calls from within the application It will check\n * setting and capability of the device\n * \n * @param context\n * @return\n */\n public static boolean canMakeGSMCall(Context context) {\n int integType = SipConfigManager.getPreferenceIntegerValue(context,\n SipConfigManager.GSM_INTEGRATION_TYPE, SipConfigManager.GENERIC_TYPE_PREVENT);\n if (integType == SipConfigManager.GENERIC_TYPE_AUTO) {\n return PhoneCapabilityTester.isPhone(context);\n }\n if (integType == SipConfigManager.GENERIC_TYPE_PREVENT) {\n return false;\n }\n return true;\n }\n\n public static Intent getContactPhoneIntent() {\n Intent intent = new Intent(Intent.ACTION_PICK);\n /*\n * intent.setAction(Intent.ACTION_GET_CONTENT);\n * intent.setType(Contacts.Phones.CONTENT_ITEM_TYPE);\n */\n if (isCompatible(5)) {\n // Don't use constant to allow backward compat simply\n intent.setData(Uri.parse(\"content://com.android.contacts/contacts\"));\n } else {\n // Fallback for android 4\n intent.setData(Contacts.People.CONTENT_URI);\n }\n\n return intent;\n\n }\n\n private static boolean shouldUsePriviledgedIntegration(Context ctxt) {\n return !PhoneCapabilityTester.isPhone(ctxt);\n }\n\n public static void updateVersion(PreferencesWrapper prefWrapper, int lastSeenVersion,\n int runningVersion) {\n\n prefWrapper.startEditing();\n if (lastSeenVersion < 14) {\n\n // Galaxy S default settings\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-I9000\") && !isCompatible(9)) {\n prefWrapper.setPreferenceFloatValue(SipConfigManager.SND_MIC_LEVEL, (float) 0.4);\n prefWrapper\n .setPreferenceFloatValue(SipConfigManager.SND_SPEAKER_LEVEL, (float) 0.2);\n }\n\n if (TextUtils.isEmpty(prefWrapper\n .getPreferenceStringValue(SipConfigManager.STUN_SERVER))) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.STUN_SERVER,\n \"stun.counterpath.com\");\n }\n }\n if (lastSeenVersion < 15) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.ENABLE_STUN, false);\n }\n // Now we use svn revisions\n if (lastSeenVersion < 369) {\n // Galaxy S default settings\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-I9000\") && !isCompatible(9)) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SOFT_VOLUME, true);\n }\n\n }\n\n if (lastSeenVersion < 385) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_ROUTING_API,\n shouldUseRoutingApi());\n prefWrapper\n .setPreferenceBooleanValue(SipConfigManager.USE_MODE_API, shouldUseModeApi());\n prefWrapper\n .setPreferenceStringValue(SipConfigManager.SIP_AUDIO_MODE, guessInCallMode());\n }\n if (lastSeenVersion < 575) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.SET_AUDIO_GENERATE_TONE,\n needToneWorkaround());\n\n if (lastSeenVersion > 0) {\n prefWrapper.setPreferenceBooleanValue(PreferencesWrapper.HAS_ALREADY_SETUP_SERVICE,\n true);\n }\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.ENABLE_QOS, false);\n // HTC evo 4G\n if (Build.PRODUCT.equalsIgnoreCase(\"htc_supersonic\")) {\n prefWrapper.setPreferenceFloatValue(SipConfigManager.SND_MIC_LEVEL, (float) 0.5);\n prefWrapper\n .setPreferenceFloatValue(SipConfigManager.SND_SPEAKER_LEVEL, (float) 1.5);\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_ROUTING_API, true);\n }\n\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n // Proximity sensor inverted\n if (Build.PRODUCT.equalsIgnoreCase(\"SPH-M900\") /*\n * Sgs\n * moment\n */) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.INVERT_PROXIMITY_SENSOR,\n true);\n }\n }\n if (lastSeenVersion < 591) {\n resetCodecsSettings(prefWrapper);\n }\n if (lastSeenVersion < 596) {\n prefWrapper\n .setPreferenceBooleanValue(SipConfigManager.USE_MODE_API, shouldUseModeApi());\n }\n if (lastSeenVersion < 613) {\n resetCodecsSettings(prefWrapper);\n }\n if (lastSeenVersion < 704) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SGS_CALL_HACK,\n needSGSWorkaround());\n }\n if (lastSeenVersion < 794) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.MICRO_SOURCE,\n getDefaultMicroSource());\n prefWrapper.setPreferenceStringValue(SipConfigManager.SND_CLOCK_RATE,\n getDefaultFrequency());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n }\n if (lastSeenVersion < 814) {\n // Now default is to get a random port for local binding of tcp, tls\n // and udp\n prefWrapper.setPreferenceStringValue(SipConfigManager.TCP_TRANSPORT_PORT, \"0\");\n prefWrapper.setPreferenceStringValue(SipConfigManager.UDP_TRANSPORT_PORT, \"0\");\n prefWrapper.setPreferenceStringValue(SipConfigManager.TLS_TRANSPORT_PORT, \"0\");\n }\n\n if (lastSeenVersion < 882) {\n prefWrapper.setCodecPriority(\"G7221/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n prefWrapper.setCodecPriority(\"G7221/32000/1\", SipConfigManager.CODEC_WB, \"0\");\n }\n if (lastSeenVersion < 906) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.PREVENT_SCREEN_ROTATION,\n !Compatibility.isTabletScreen(prefWrapper.getContext()));\n }\n if (lastSeenVersion < 911 && Build.DEVICE.toUpperCase().startsWith(\"GT-I9100\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.MICRO_SOURCE,\n getDefaultMicroSource());\n prefWrapper\n .setPreferenceStringValue(SipConfigManager.SIP_AUDIO_MODE, guessInCallMode());\n\n }\n if (lastSeenVersion < 915) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n }\n if (lastSeenVersion < 939) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO, true);\n }\n if (lastSeenVersion < 955 && Build.DEVICE.toLowerCase().contains(\"droid2\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK, true);\n }\n if (lastSeenVersion < 997) {\n // New webrtc echo mode\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.ECHO_CANCELLATION, true);\n prefWrapper.setPreferenceStringValue(SipConfigManager.ECHO_MODE, \"3\"); /* WEBRTC */\n\n // By default, disable new codecs\n prefWrapper.setCodecPriority(\"ISAC/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n prefWrapper.setCodecPriority(\"ISAC/32000/1\", SipConfigManager.CODEC_WB, \"0\");\n prefWrapper.setCodecPriority(\"ISAC/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n prefWrapper.setCodecPriority(\"ISAC/32000/1\", SipConfigManager.CODEC_NB, \"0\");\n prefWrapper.setCodecPriority(\"AMR/8000/1\", SipConfigManager.CODEC_WB, \"0\");\n prefWrapper.setCodecPriority(\"AMR/8000/1\", SipConfigManager.CODEC_NB, \"0\");\n\n // Fix typo in previous versions\n prefWrapper.setCodecPriority(\"G7221/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n prefWrapper.setCodecPriority(\"G7221/32000/1\", SipConfigManager.CODEC_NB, \"0\");\n\n }\n if (lastSeenVersion < 1006) {\n // Add U8100 to list of device that require mode api\n if (Build.DEVICE.equalsIgnoreCase(\"U8100\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if (lastSeenVersion < 1033 && Build.PRODUCT.toLowerCase().startsWith(\"thunder\")) {\n prefWrapper\n .setPreferenceBooleanValue(SipConfigManager.USE_MODE_API, shouldUseModeApi());\n }\n if (lastSeenVersion < 1076 && Build.DEVICE.toUpperCase().equals(\"GT-P1010\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.SND_CLOCK_RATE,\n getDefaultFrequency());\n }\n if (lastSeenVersion < 1109) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.TIMER_MIN_SE, \"90\");\n prefWrapper.setPreferenceStringValue(SipConfigManager.TIMER_SESS_EXPIRES, \"1800\");\n resetCodecsSettings(prefWrapper);\n }\n if (lastSeenVersion < 1581 && needWebRTCImplementation()) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK,\n needWebRTCImplementation());\n }\n if (lastSeenVersion < 1634) {\n if (Build.PRODUCT.toLowerCase().startsWith(\"gt-i9003\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.SET_AUDIO_GENERATE_TONE,\n needToneWorkaround());\n }\n }\n if (lastSeenVersion < 1653 && !PhoneCapabilityTester.isPhone(prefWrapper.getContext())) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_TEL_PRIVILEGED, true);\n }\n if (lastSeenVersion < 1688) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.THREAD_COUNT, \"0\");\n }\n if (lastSeenVersion < 1729) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n // Audio routing/mode api\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-S\")\n || Build.PRODUCT.equalsIgnoreCase(\"U8655\")\n || Build.DEVICE.equalsIgnoreCase(\"joe\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_ROUTING_API,\n shouldUseRoutingApi());\n }\n }\n if (lastSeenVersion < 1752) {\n boolean usePriv = shouldUsePriviledgedIntegration(prefWrapper.getContext());\n if (usePriv) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_TEL_PRIVILEGED,\n usePriv);\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_DIALER,\n !usePriv);\n }\n }\n if (lastSeenVersion < 1777 && Build.DEVICE.startsWith(\"one_touch_990\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n }\n\n if (lastSeenVersion < 1798 && Build.DEVICE.toLowerCase().startsWith(\"picasso\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n }\n if (lastSeenVersion < 1834 && !shouldFocusAudio()) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO,\n shouldFocusAudio());\n }\n if (lastSeenVersion < 1931 && Build.DEVICE.equalsIgnoreCase(\"ST25i\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n }\n if (lastSeenVersion < 1943) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.SETUP_AUDIO_BEFORE_INIT,\n shouldSetupAudioBeforeInit());\n if (Build.DEVICE.toUpperCase().startsWith(\"GT-\") ||\n Build.PRODUCT.toUpperCase().startsWith(\"GT-\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if (lastSeenVersion < 2010) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.DTMF_PRESS_TONE_MODE,\n Integer.toString(SipConfigManager.GENERIC_TYPE_PREVENT));\n }\n if (lastSeenVersion < 2030) {\n if ((Build.MODEL.toUpperCase().startsWith(\"LG-E720\")\n && !Compatibility.isCompatible(9))\n || Build.MODEL.equalsIgnoreCase(\"XT320\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if (lastSeenVersion < 2052) {\n if (Build.DEVICE.equalsIgnoreCase(\"u8510\") && Compatibility.isCompatible(10)) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n }\n }\n if (lastSeenVersion < 2069) {\n if (Build.DEVICE.toUpperCase().startsWith(\"ONE_TOUCH_993D\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if (lastSeenVersion < 2081) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.DISABLE_RPORT, false);\n }\n if (lastSeenVersion < 2105 && Build.DEVICE.toLowerCase().startsWith(\"cayman\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n if (lastSeenVersion < 2111) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.MEDIA_THREAD_COUNT, \"2\");\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.HAS_IO_QUEUE, true);\n }\n if (lastSeenVersion < 2147) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.DSCP_RTP_VAL, \"48\");\n }\n\n if (lastSeenVersion < 2172 && Build.DEVICE.toUpperCase().startsWith(\"MAKO\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n\n if (lastSeenVersion < 2175) {\n // By default, disable new codecs\n prefWrapper.setCodecPriority(\"AMR-WB/16000/1\", SipConfigManager.CODEC_WB, \"0\");\n prefWrapper.setCodecPriority(\"AMR-WB/16000/1\", SipConfigManager.CODEC_NB, \"0\");\n }\n if (lastSeenVersion < 2195) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.MEDIA_THREAD_COUNT,\n getNumCores() > 1 ? \"2\" : \"1\");\n }\n if (lastSeenVersion < 2202 && Build.DEVICE.equalsIgnoreCase(\"U8833\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK,\n needWebRTCImplementation());\n }\n if (lastSeenVersion < 2254 && Build.MODEL.equalsIgnoreCase(\"XT320\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n }\n if (lastSeenVersion < 2297) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.UNLOCKER_TYPE, Integer.toString(SipConfigManager.GENERIC_TYPE_AUTO));\n }\n if (lastSeenVersion < 2302) {\n if (Build.DEVICE.toUpperCase().startsWith(\"U8836\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if(lastSeenVersion < 2348) {\n if (Build.DEVICE.toLowerCase().startsWith(\"g2\")\n && Build.BRAND.toLowerCase().startsWith(\"lge\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if(lastSeenVersion < 2418) {\n if (Build.DEVICE.toUpperCase().startsWith(\"HWU9700\")) {\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API,\n shouldUseModeApi());\n }\n }\n if(lastSeenVersion < 2442) {\n if (Build.DEVICE.toLowerCase().startsWith(\"rk31sdk\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.AUDIO_IMPLEMENTATION,\n Integer.toString(getDefaultAudioImplementation()));\n }\n }\n\n if (lastSeenVersion < 2457) {\n String method = prefWrapper.getPreferenceStringValue(SipConfigManager.TLS_METHOD);\n if (method.equals(\"1\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.TLS_METHOD, \"31\");\n } else if (method.equals(\"2\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.TLS_METHOD, \"20\");\n } else if (method.equals(\"3\")) {\n prefWrapper.setPreferenceStringValue(SipConfigManager.TLS_METHOD, \"30\");\n }\n }\n\n prefWrapper.endEditing();\n }\n\n public static void updateApiVersion(PreferencesWrapper prefWrapper, int lastSeenVersion,\n int runningVersion) {\n prefWrapper.startEditing();\n // Always do for downgrade cases\n // if(isCompatible(9)) {\n // Reset media settings since now interface is clean and works (should\n // work...)\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_ROUTING_API,\n shouldUseRoutingApi());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_MODE_API, shouldUseModeApi());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.SET_AUDIO_GENERATE_TONE,\n needToneWorkaround());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SGS_CALL_HACK,\n needSGSWorkaround());\n prefWrapper.setPreferenceStringValue(SipConfigManager.SIP_AUDIO_MODE, guessInCallMode());\n prefWrapper\n .setPreferenceStringValue(SipConfigManager.MICRO_SOURCE, getDefaultMicroSource());\n if (isCompatible(9)) {\n prefWrapper.setPreferenceFloatValue(SipConfigManager.SND_MIC_LEVEL, (float) 1.0);\n prefWrapper.setPreferenceFloatValue(SipConfigManager.SND_SPEAKER_LEVEL, (float) 1.0);\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.USE_SOFT_VOLUME, false);\n }\n\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL,\n needPspWorkaround());\n prefWrapper.setPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO, shouldFocusAudio());\n\n // }\n\n prefWrapper.endEditing();\n }\n\n public static boolean isTabletScreen(Context ctxt) {\n boolean isTablet = false;\n if (!isCompatible(4)) {\n return false;\n }\n Configuration cfg = ctxt.getResources().getConfiguration();\n int screenLayoutVal = 0;\n try {\n Field f = Configuration.class.getDeclaredField(\"screenLayout\");\n screenLayoutVal = (Integer) f.get(cfg);\n } catch (Exception e) {\n return false;\n }\n int screenLayout = (screenLayoutVal & 0xF);\n // 0xF = SCREENLAYOUT_SIZE_MASK but avoid 1.5 incompat doing that\n if (screenLayout == 0x3 || screenLayout == 0x4) {\n // 0x3 = SCREENLAYOUT_SIZE_LARGE but avoid 1.5 incompat doing that\n // 0x4 = SCREENLAYOUT_SIZE_XLARGE but avoid 1.5 incompat doing that\n isTablet = true;\n }\n\n return isTablet;\n }\n\n public static int getHomeMenuId() {\n return 0x0102002c;\n // return android.R.id.home;\n }\n\n public static boolean isInstalledOnSdCard(Context context) {\n // check for API level 8 and higher\n if (Compatibility.isCompatible(8)) {\n PackageManager pm = context.getPackageManager();\n try {\n PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);\n ApplicationInfo ai = pi.applicationInfo;\n return (ai.flags & 0x00040000 /*\n * ApplicationInfo.\n * FLAG_EXTERNAL_STORAGE\n */) == 0x00040000 /*\n * ApplicationInfo.\n * FLAG_EXTERNAL_STORAGE\n */;\n } catch (NameNotFoundException e) {\n // ignore\n }\n }\n\n // check for API level 7 - check files dir\n try {\n String filesDir = context.getFilesDir().getAbsolutePath();\n if (filesDir.startsWith(\"/data/\")) {\n return false;\n } else if (filesDir.contains(Environment.getExternalStorageDirectory().getPath())) {\n return true;\n }\n } catch (Throwable e) {\n // ignore\n }\n\n return false;\n }\n\n /**\n * Get the current wifi sleep policy\n * @param ctntResolver android content resolver\n * @return the current wifi sleep policy\n */\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n public static int getWifiSleepPolicy(ContentResolver ctntResolver) {\n if(Compatibility.isCompatible(Build.VERSION_CODES.JELLY_BEAN_MR1)) {\n return Settings.Global.getInt(ctntResolver, Settings.Global.WIFI_SLEEP_POLICY, Settings.Global.WIFI_SLEEP_POLICY_DEFAULT);\n }else {\n return Settings.System.getInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);\n }\n }\n\n /**\n * @return default wifi sleep policy\n */\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n public static int getWifiSleepPolicyDefault() {\n if(Compatibility.isCompatible(Build.VERSION_CODES.JELLY_BEAN_MR1)) {\n return Settings.Global.WIFI_SLEEP_POLICY_DEFAULT;\n }else {\n return Settings.System.WIFI_SLEEP_POLICY_DEFAULT;\n }\n }\n\n /**\n * @return wifi policy to never sleep\n */\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n public static int getWifiSleepPolicyNever() {\n if(Compatibility.isCompatible(Build.VERSION_CODES.JELLY_BEAN_MR1)) {\n return Settings.Global.WIFI_SLEEP_POLICY_NEVER;\n }else {\n return Settings.System.WIFI_SLEEP_POLICY_NEVER;\n }\n }\n \n /**\n * Set wifi policy to a value\n * @param ctntResolver context content resolver\n * @param policy the policy to set\n */\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n public static void setWifiSleepPolicy(ContentResolver ctntResolver, int policy) {\n if(!Compatibility.isCompatible(Build.VERSION_CODES.JELLY_BEAN_MR1)) {\n Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, policy);\n }else {\n // We are not granted permission to change that in api 17+\n //Settings.Global.putInt(ctntResolver, Settings.Global.WIFI_SLEEP_POLICY, policy);\n }\n }\n\n /**\n * Wrapper to set alarm at exact time\n * @see AlarmManager#setExact(int, long, PendingIntent)\n */\n @TargetApi(Build.VERSION_CODES.KITKAT)\n public static void setExactAlarm(AlarmManager alarmManager, int alarmType, long firstTime,\n PendingIntent pendingIntent) {\n if(isCompatible(Build.VERSION_CODES.KITKAT)) {\n alarmManager.setExact(alarmType, firstTime, pendingIntent);\n }else {\n alarmManager.set(alarmType, firstTime, pendingIntent);\n }\n }\n}" ]
import android.app.Activity; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Parcelable; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.RemoteException; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.view.SurfaceView; import android.widget.Toast; import com.csipsimple.R; import com.csipsimple.api.ISipConfiguration; import com.csipsimple.api.ISipService; import com.csipsimple.api.MediaState; import com.csipsimple.api.SipCallSession; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.api.SipManager.PresenceStatus; import com.csipsimple.api.SipMessage; import com.csipsimple.api.SipProfile; import com.csipsimple.api.SipProfileState; import com.csipsimple.api.SipUri; import com.csipsimple.db.DBProvider; import com.csipsimple.models.Filter; import com.csipsimple.pjsip.PjSipCalls; import com.csipsimple.pjsip.PjSipService; import com.csipsimple.pjsip.UAStateReceiver; import com.csipsimple.service.receiver.DynamicReceiver4; import com.csipsimple.service.receiver.DynamicReceiver5; import com.csipsimple.ui.incall.InCallMediaControl; import com.csipsimple.utils.Compatibility; import com.csipsimple.utils.CustomDistribution; import com.csipsimple.utils.ExtraPlugins; import com.csipsimple.utils.ExtraPlugins.DynActivityPlugin; import com.csipsimple.utils.Log; import com.csipsimple.utils.PreferencesProviderWrapper; import com.csipsimple.utils.PreferencesWrapper; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.regex.Matcher; import java.util.regex.Pattern;
public void confAdjustRxLevel(float speakVolume) throws SameThreadException { if(pjService != null) { pjService.confAdjustRxLevel(0, speakVolume); } } /** * Add a buddy to list * @param buddyUri the sip uri of the buddy to add */ public int addBuddy(String buddyUri) throws SameThreadException { int retVal = -1; if(pjService != null) { Log.d(THIS_FILE, "Trying to add buddy " + buddyUri); retVal = pjService.addBuddy(buddyUri); } return retVal; } /** * Remove a buddy from buddies * @param buddyUri the sip uri of the buddy to remove */ public void removeBuddy(String buddyUri) throws SameThreadException { if(pjService != null) { pjService.removeBuddy(buddyUri); } } private boolean holdResources = false; /** * Ask to take the control of the wifi and the partial wake lock if * configured */ private synchronized void acquireResources() { if(holdResources) { return; } // Add a wake lock for CPU if necessary if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_PARTIAL_WAKE_LOCK)) { PowerManager pman = (PowerManager) getSystemService(Context.POWER_SERVICE); if (wakeLock == null) { wakeLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.SipService"); wakeLock.setReferenceCounted(false); } // Extra check if set reference counted is false ??? if (!wakeLock.isHeld()) { wakeLock.acquire(); } } // Add a lock for WIFI if necessary WifiManager wman = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiLock == null) { int mode = WifiManager.WIFI_MODE_FULL; if(Compatibility.isCompatible(9) && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI_PERFS)) { mode = 0x3; // WIFI_MODE_FULL_HIGH_PERF } wifiLock = wman.createWifiLock(mode, "com.csipsimple.SipService"); wifiLock.setReferenceCounted(false); } if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI) && !wifiLock.isHeld()) { WifiInfo winfo = wman.getConnectionInfo(); if (winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); // We assume that if obtaining ip addr, we are almost connected // so can keep wifi lock if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if (!wifiLock.isHeld()) { wifiLock.acquire(); } } } } holdResources = true; } private synchronized void releaseResources() { if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } if (wifiLock != null && wifiLock.isHeld()) { wifiLock.release(); } holdResources = false; } private static final int TOAST_MESSAGE = 0; private Handler serviceHandler = new ServiceHandler(this); private static class ServiceHandler extends Handler { WeakReference<SipService> s; public ServiceHandler(SipService sipService) { s = new WeakReference<SipService>(sipService); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); SipService sipService = s.get(); if(sipService == null) { return; } if (msg.what == TOAST_MESSAGE) { if (msg.arg1 != 0) { Toast.makeText(sipService, msg.arg1, Toast.LENGTH_LONG).show(); } else { Toast.makeText(sipService, (String) msg.obj, Toast.LENGTH_LONG).show(); } } } };
public UAStateReceiver getUAStateReceiver() {
7