answer
stringlengths 17
10.2M
|
|---|
package com.cronutils;
import java.time.ZonedDateTime;
import org.junit.Test;
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import static org.junit.Assert.assertEquals;
public class Issue228Test {
/**
* This is the UNIX cron definition with a single modification to match both Day Of Week and Day Of Month
*/
private CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
.withMinutes().and()
.withHours().and()
.withDayOfMonth().and()
.withMonth().and()
.withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).and()
.enforceStrictRanges()
.matchDayOfWeekAndDayOfMonth() // the regular UNIX cron definition permits matching either DoW or DoM
.instance();
@Test
public void testFirstMondayOfTheMonthNextExecution() {
CronParser parser = new CronParser(cronDefinition);
// This is 9am on a day between the 1st and 7th which is a Monday (in this case it should be Oct 2
Cron myCron = parser.parse("0 9 1-7 * 1");
ZonedDateTime time = ZonedDateTime.parse("2017-09-29T14:46:01.166-07:00");
ZonedDateTime next = ExecutionTime.forCron(myCron).nextExecution(time).isPresent()?ExecutionTime.forCron(myCron).nextExecution(time).get():null;
assertEquals(ZonedDateTime.parse("2017-10-02T09:00-07:00"), next);
}
@Test
public void testEveryWeekdayFirstWeekOfMonthNextExecution() {
CronParser parser = new CronParser(cronDefinition);
// This is 9am on Mon-Fri day between the 1st and 7th (in this case it should be Oct 2)
Cron myCron = parser.parse("0 9 1-7 * 1-5");
ZonedDateTime time = ZonedDateTime.parse("2017-09-29T14:46:01.166-07:00");
ZonedDateTime next = ExecutionTime.forCron(myCron).nextExecution(time).isPresent()?ExecutionTime.forCron(myCron).nextExecution(time).get():null;
assertEquals(ZonedDateTime.parse("2017-10-02T09:00-07:00"), next);
}
@Test
public void testEveryWeekendFirstWeekOfMonthNextExecution() {
CronParser parser = new CronParser(cronDefinition);
// This is 9am on Sat and Sun day between the 1st and 7th (in this case it should be Oct 1)
Cron myCron = parser.parse("0 9 1-7 * 6-7");
ZonedDateTime time = ZonedDateTime.parse("2017-09-29T14:46:01.166-07:00");
ZonedDateTime next = ExecutionTime.forCron(myCron).nextExecution(time).isPresent()?ExecutionTime.forCron(myCron).nextExecution(time).get():null;
assertEquals(ZonedDateTime.parse("2017-10-01T09:00-07:00"), next);
}
@Test
public void testEveryWeekdaySecondWeekOfMonthNextExecution() {
CronParser parser = new CronParser(cronDefinition);
// This is 9am on Mon-Fri day between the 8th and 14th (in this case it should be Oct 9 Mon)
Cron myCron = parser.parse("0 9 8-14 * 1-5");
ZonedDateTime time = ZonedDateTime.parse("2017-09-29T14:46:01.166-07:00");
ZonedDateTime next = ExecutionTime.forCron(myCron).nextExecution(time).isPresent()?ExecutionTime.forCron(myCron).nextExecution(time).get():null;
assertEquals(ZonedDateTime.parse("2017-10-09T09:00-07:00"), next);
}
@Test
public void testEveryWeekendForthWeekOfMonthNextExecution() {
CronParser parser = new CronParser(cronDefinition);
// This is 9am on Sat and Sun day between the 22nd and 28th (in this case it should be Oct 22)
Cron myCron = parser.parse("0 9 22-28 * 6-7");
ZonedDateTime time = ZonedDateTime.parse("2017-09-29T14:46:01.166-07:00");
ZonedDateTime next = ExecutionTime.forCron(myCron).nextExecution(time).isPresent()?ExecutionTime.forCron(myCron).nextExecution(time).get():null;
assertEquals(ZonedDateTime.parse("2017-10-22T09:00-07:00"), next);
}
}
|
package guitests;
import org.junit.Test;
import ui.UI;
import ui.issuepanel.IssuePanel;
import util.PlatformEx;
import util.events.UILogicRefreshEvent;
import util.events.UpdateDummyRepoEvent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ModelUpdateUITest extends UITest {
private final int EVENT_DELAY = 1000;
@Test
@SuppressWarnings("unchecked")
public void addIssueTest() throws InterruptedException, ExecutionException {
resetRepo();
sleep(EVENT_DELAY);
addIssue();
sleep(EVENT_DELAY);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void addMultipleIssuesTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
addIssue();
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(13, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void countIssuesTest() throws InterruptedException, ExecutionException {
addIssue();
resetRepo();
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(10, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void deleteIssueTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
deleteIssue(1);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void deleteMultipleIssuesTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
addIssue();
deleteIssue(1);
deleteIssue(2);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
@Test
public void otherTriggersTest() throws InterruptedException, ExecutionException {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_LABEL, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_MILESTONE, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_USER, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_LABEL, "dummy/dummy", "Label 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_MILESTONE, "dummy/dummy", "Milestone 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_USER, "dummy/dummy", "User 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.UPDATE_ISSUE, "dummy/dummy", 1, null, "Issue 11"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.UPDATE_MILESTONE, "dummy/dummy", 1, null, "Milestone 11"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void resetRepo() {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.RESET_REPO, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void addIssue() {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_ISSUE, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void deleteIssue(int itemId) {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_ISSUE, "dummy/dummy", itemId));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
}
|
package guitests;
import org.junit.Test;
import ui.UI;
import ui.issuepanel.IssuePanel;
import util.PlatformEx;
import util.events.UILogicRefreshEvent;
import util.events.UpdateDummyRepoEvent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ModelUpdateUITest extends UITest {
private final int EVENT_DELAY = 1000;
@Test
@SuppressWarnings("unchecked")
public void addIssueTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
sleep(4 * EVENT_DELAY);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void addMultipleIssuesTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
addIssue();
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(13, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void countIssuesTest() throws InterruptedException, ExecutionException {
addIssue();
resetRepo();
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(10, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void deleteIssueTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
deleteIssue(1);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
@Test
@SuppressWarnings("unchecked")
public void deleteMultipleIssuesTest() throws InterruptedException, ExecutionException {
resetRepo();
addIssue();
addIssue();
addIssue();
deleteIssue(1);
deleteIssue(2);
FutureTask countIssues = new FutureTask(((IssuePanel) find("#dummy/dummy_col0"))::getIssueCount);
PlatformEx.runAndWait(countIssues);
assertEquals(11, countIssues.get());
}
// TODO no way to check correctness of these events as of yet as they are not reflected on the UI
@Test
public void otherTriggersTest() throws InterruptedException, ExecutionException {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_LABEL, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_MILESTONE, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_USER, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_LABEL, "dummy/dummy", "Label 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_MILESTONE, "dummy/dummy", "Milestone 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_USER, "dummy/dummy", "User 1"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.UPDATE_ISSUE, "dummy/dummy", 1, null, "Issue 11"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.UPDATE_MILESTONE, "dummy/dummy", 1, null, "Milestone 11"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void resetRepo() {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.RESET_REPO, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void addIssue() {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.NEW_ISSUE, "dummy/dummy"));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
public void deleteIssue(int itemId) {
UI.events.triggerEvent(new UpdateDummyRepoEvent(UpdateDummyRepoEvent.UpdateType.DELETE_ISSUE, "dummy/dummy", itemId));
UI.events.triggerEvent(new UILogicRefreshEvent());
sleep(EVENT_DELAY);
}
}
|
package intellij.mark;
import com.intellij.ide.DataManager;
import com.intellij.ide.CopyProvider;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.testFramework.LightIdeaTestCase;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public abstract class MarkTestCase extends LightIdeaTestCase {
private EditorFactory editorFactory;
private List<Editor> openEditors;
private Editor currentEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
editorFactory = EditorFactory.getInstance();
openEditors = new ArrayList<Editor>();
}
@Override
protected void tearDown() throws Exception {
for (Editor editor : openEditors) {
editorFactory.releaseEditor(editor);
}
}
protected Editor createEditorWithText(String text) {
Document document = getDocument(createFile("test.txt", text));
Editor editor = editorFactory.createEditor(document);
openEditors.add(editor);
return editor;
}
protected void invokeActionInEditor(Editor editor, String actionName) {
this.currentEditor = editor;
ActionManager actionManager = ActionManager.getInstance();
AnAction editorAction = actionManager.getAction(actionName);
Application application = ApplicationManager.getApplication();
DataContext dataContext = DataManager.getInstance().getDataContext();
editorAction.actionPerformed(new AnActionEvent(
null,
dataContext,
"",
editorAction.getTemplatePresentation(),
ActionManager.getInstance(),
0
)
);
}
@Override
public Object getData(String s) {
if ("editor".equals(s)) {
return currentEditor;
}
return super.getData(s);
}
protected MarkManager getMarkManager() {
Application application = ApplicationManager.getApplication();
return application.getComponent(MarkManager.class);
}
protected String contentsOfClipboard() {
Transferable contents = CopyPasteManager.getInstance().getContents();
String copiedData = null;
try {
copiedData = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return copiedData;
}
protected void assumeClipboardIs(String data) {
CopyPasteManager.getInstance().setContents(new StringSelection(data));
}
}
|
package io.vertx.ext.jdbc;
import io.vertx.core.VertxOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.metrics.MetricsOptions;
import io.vertx.ext.sql.SQLClient;
import io.vertx.test.core.VertxTestBase;
import io.vertx.test.fakemetrics.FakeMetricsFactory;
import io.vertx.test.fakemetrics.FakePoolMetrics;
import org.h2.tools.Server;
import org.junit.After;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class PoolTest extends VertxTestBase {
Server server;
SQLClient client;
@Override
public void setUp() throws Exception {
server = Server.createTcpServer("-tcp").start();
super.setUp();
}
@Override
protected VertxOptions getOptions() {
MetricsOptions options = new MetricsOptions().setEnabled(true);
options.setFactory(new FakeMetricsFactory());
return new VertxOptions().setMetricsOptions(options);
}
@Test(timeout = 30000)
public void testUseAvailableResources() {
int poolSize = 3;
waitFor(poolSize + 1);
JsonObject config = new JsonObject()
.put("url", "jdbc:h2:mem:test_mem")
.put("driver_class", "org.h2.Driver")
.put("initial_pool_size", poolSize)
.put("max_pool_size", poolSize);
client = JDBCClient.createShared(vertx, config);
vertx.setPeriodic(10, timerId -> {
FakePoolMetrics metrics = getMetrics();
if (metrics != null && poolSize == metrics.numberOfRunningTasks()) {
vertx.cancelTimer(timerId);
complete();
}
});
client.query("CREATE ALIAS SLEEP FOR \"io.vertx.ext.jdbc.PoolTest.sleep\";", onSuccess(def -> {
for (int i = 0; i < poolSize; i++) {
client.query("SELECT SLEEP(500)", onSuccess(rs -> complete()));
}
}));
await();
}
@SuppressWarnings("unused")
public static int sleep(int howLong) {
try {
Thread.sleep(howLong);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
}
return howLong;
}
@After
public void after() throws Exception {
if (client != null) {
CountDownLatch latch = new CountDownLatch(1);
client.close(ar -> latch.countDown());
awaitLatch(latch);
}
super.after();
if (server != null) {
server.stop();
}
}
private FakePoolMetrics getMetrics() {
return (FakePoolMetrics) FakePoolMetrics.getPoolMetrics().get(JDBCClient.DEFAULT_DS_NAME);
}
}
|
package j2html.tags;
import org.junit.Test;
import static j2html.TagCreator.*;
import static org.junit.Assert.assertEquals;
public class TagCreatorTest {
@Test
public void testAllTags() throws Exception {
//Special Tags
assertEquals(tag("tagname").render(), "<tagname></tagname>");
assertEquals(emptyTag("tagname").render(), "<tagname>");
assertEquals(text("text").render(), "text");
assertEquals(text("<script> and \"</script>\"").render(), "<script> and "</script>"");
assertEquals(unsafeHtml("<script>").render(), "<script>");
assertEquals(styleWithInlineFile_min("/test.css").render(), "<style>body{background:#daa520;margin-bottom:10px;margin-left:10px;margin-right:10px;margin-top:10px}</style>");
assertEquals(scriptWithInlineFile_min("/test.js").render(), "<script>(function(){console.log(15)})();</script>");
assertEquals(fileAsString("/test.html").render(), "<body>\r\n"+" Any content\r\n"+"</body>\r\n");
assertEquals(fileAsEscapedString("/test.html").render(), "<body>\r\n"+" Any content\r\n"+"</body>\r\n");
assertEquals(fileAsString("/test.java").render(), "public class AnyContent{}\r\n");
//EmptyTags
assertEquals(document().render(), "<!DOCTYPE html>");
assertEquals(area().render(), "<area>");
assertEquals(base().render(), "<base>");
assertEquals(br().render(), "<br>");
assertEquals(col().render(), "<col>");
assertEquals(embed().render(), "<embed>");
assertEquals(hr().render(), "<hr>");
assertEquals(img().render(), "<img>");
assertEquals(input().render(), "<input>");
assertEquals(keygen().render(), "<keygen>");
assertEquals(link().render(), "<link>");
assertEquals(meta().render(), "<meta>");
assertEquals(param().render(), "<param>");
assertEquals(source().render(), "<source>");
assertEquals(track().render(), "<track>");
assertEquals(wbr().render(), "<wbr>");
//ContainerTags
assertEquals(a().render(), "<a></a>");
assertEquals(a("Text").render(), "<a>Text</a>");
assertEquals(abbr().render(), "<abbr></abbr>");
assertEquals(address().render(), "<address></address>");
assertEquals(article().render(), "<article></article>");
assertEquals(aside().render(), "<aside></aside>");
assertEquals(audio().render(), "<audio></audio>");
assertEquals(b().render(), "<b></b>");
assertEquals(b("Text").render(), "<b>Text</b>");
assertEquals(bdi().render(), "<bdi></bdi>");
assertEquals(bdi("Text").render(), "<bdi>Text</bdi>");
assertEquals(bdo().render(), "<bdo></bdo>");
assertEquals(bdo("Text").render(), "<bdo>Text</bdo>");
assertEquals(blockquote().render(), "<blockquote></blockquote>");
assertEquals(blockquote("Text").render(), "<blockquote>Text</blockquote>");
assertEquals(body().render(), "<body></body>");
assertEquals(button().render(), "<button></button>");
assertEquals(button("Text").render(), "<button>Text</button>");
assertEquals(canvas().render(), "<canvas></canvas>");
assertEquals(caption().render(), "<caption></caption>");
assertEquals(caption("Text").render(), "<caption>Text</caption>");
assertEquals(cite().render(), "<cite></cite>");
assertEquals(cite("Text").render(), "<cite>Text</cite>");
assertEquals(code().render(), "<code></code>");
assertEquals(colgroup().render(), "<colgroup></colgroup>");
assertEquals(datalist().render(), "<datalist></datalist>");
assertEquals(dd().render(), "<dd></dd>");
assertEquals(dd("Text").render(), "<dd>Text</dd>");
assertEquals(del().render(), "<del></del>");
assertEquals(del("Text").render(), "<del>Text</del>");
assertEquals(details().render(), "<details></details>");
assertEquals(dfn().render(), "<dfn></dfn>");
assertEquals(dfn("Text").render(), "<dfn>Text</dfn>");
assertEquals(dialog().render(), "<dialog></dialog>");
assertEquals(dialog("Text").render(), "<dialog>Text</dialog>");
assertEquals(div().render(), "<div></div>");
assertEquals(dl().render(), "<dl></dl>");
assertEquals(dt().render(), "<dt></dt>");
assertEquals(dt("Text").render(), "<dt>Text</dt>");
assertEquals(em().render(), "<em></em>");
assertEquals(em("Text").render(), "<em>Text</em>");
assertEquals(fieldset().render(), "<fieldset></fieldset>");
assertEquals(figcaption().render(), "<figcaption></figcaption>");
assertEquals(figcaption("Text").render(), "<figcaption>Text</figcaption>");
assertEquals(figure().render(), "<figure></figure>");
assertEquals(footer().render(), "<footer></footer>");
assertEquals(form().render(), "<form></form>");
assertEquals(h1().render(), "<h1></h1>");
assertEquals(h1("Text").render(), "<h1>Text</h1>");
assertEquals(h2().render(), "<h2></h2>");
assertEquals(h2("Text").render(), "<h2>Text</h2>");
assertEquals(h3().render(), "<h3></h3>");
assertEquals(h3("Text").render(), "<h3>Text</h3>");
assertEquals(h4().render(), "<h4></h4>");
assertEquals(h4("Text").render(), "<h4>Text</h4>");
assertEquals(h5().render(), "<h5></h5>");
assertEquals(h5("Text").render(), "<h5>Text</h5>");
assertEquals(h6().render(), "<h6></h6>");
assertEquals(h6("Text").render(), "<h6>Text</h6>");
assertEquals(head().render(), "<head></head>");
assertEquals(header().render(), "<header></header>");
assertEquals(html().render(), "<html></html>");
assertEquals(i().render(), "<i></i>");
assertEquals(i("Text").render(), "<i>Text</i>");
assertEquals(iframe().render(), "<iframe></iframe>");
assertEquals(ins().render(), "<ins></ins>");
assertEquals(ins("Text").render(), "<ins>Text</ins>");
assertEquals(kbd().render(), "<kbd></kbd>");
assertEquals(label().render(), "<label></label>");
assertEquals(label("Text").render(), "<label>Text</label>");
assertEquals(legend().render(), "<legend></legend>");
assertEquals(legend("Text").render(), "<legend>Text</legend>");
assertEquals(li().render(), "<li></li>");
assertEquals(li("Text").render(), "<li>Text</li>");
assertEquals(main().render(), "<main></main>");
assertEquals(map().render(), "<map></map>");
assertEquals(mark().render(), "<mark></mark>");
assertEquals(menu().render(), "<menu></menu>");
assertEquals(menuitem().render(), "<menuitem></menuitem>");
assertEquals(meter().render(), "<meter></meter>");
assertEquals(nav().render(), "<nav></nav>");
assertEquals(noscript().render(), "<noscript></noscript>");
assertEquals(object().render(), "<object></object>");
assertEquals(ol().render(), "<ol></ol>");
assertEquals(optgroup().render(), "<optgroup></optgroup>");
assertEquals(option().render(), "<option></option>");
assertEquals(option("Text").render(), "<option>Text</option>");
assertEquals(output().render(), "<output></output>");
assertEquals(p().render(), "<p></p>");
assertEquals(p("Text").render(), "<p>Text</p>");
assertEquals(pre().render(), "<pre></pre>");
assertEquals(progress().render(), "<progress></progress>");
assertEquals(q().render(), "<q></q>");
assertEquals(q("Text").render(), "<q>Text</q>");
assertEquals(rp().render(), "<rp></rp>");
assertEquals(rt().render(), "<rt></rt>");
assertEquals(ruby().render(), "<ruby></ruby>");
assertEquals(s().render(), "<s></s>");
assertEquals(samp().render(), "<samp></samp>");
assertEquals(script().render(), "<script></script>");
assertEquals(section().render(), "<section></section>");
assertEquals(select().render(), "<select></select>");
assertEquals(small().render(), "<small></small>");
assertEquals(small("Text").render(), "<small>Text</small>");
assertEquals(span().render(), "<span></span>");
assertEquals(span("Text").render(), "<span>Text</span>");
assertEquals(strong().render(), "<strong></strong>");
assertEquals(strong("Text").render(), "<strong>Text</strong>");
assertEquals(style().render(), "<style></style>");
assertEquals(sub().render(), "<sub></sub>");
assertEquals(sub("Text").render(), "<sub>Text</sub>");
assertEquals(summary().render(), "<summary></summary>");
assertEquals(summary("Text").render(), "<summary>Text</summary>");
assertEquals(sup().render(), "<sup></sup>");
assertEquals(sup("Text").render(), "<sup>Text</sup>");
assertEquals(table().render(), "<table></table>");
assertEquals(tbody().render(), "<tbody></tbody>");
assertEquals(td().render(), "<td></td>");
assertEquals(td("Text").render(), "<td>Text</td>");
assertEquals(textarea().render(), "<textarea></textarea>");
assertEquals(tfoot().render(), "<tfoot></tfoot>");
assertEquals(th().render(), "<th></th>");
assertEquals(th("Text").render(), "<th>Text</th>");
assertEquals(thead().render(), "<thead></thead>");
assertEquals(time().render(), "<time></time>");
assertEquals(title().render(), "<title></title>");
assertEquals(tr().render(), "<tr></tr>");
assertEquals(u().render(), "<u></u>");
assertEquals(u("Text").render(), "<u>Text</u>");
assertEquals(ul().render(), "<ul></ul>");
assertEquals(var().render(), "<var></var>");
assertEquals(video().render(), "<video></video>");
}
}
|
package javaslang;
import static javaslang.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.assertThat;
import javaslang.Requirements.UnsatisfiedRequirementException;
import org.junit.Test;
public class RequirementsTest {
@Test
public void shouldNotInstantiable() {
assertThat(Requirements.class).isNotInstantiable();
}
// -- require(condition, message)
@Test
public void shouldThrowOnRequireWithMessageWhenConditionIsFalse() {
assertThat(() -> Requirements.require(false, "false")).isThrowing(UnsatisfiedRequirementException.class,
"false");
}
@Test
public void shouldPassOnRequireWithMessageWhenConditionIsTrue() {
Requirements.require(true, "");
}
// -- require(condition, () -> message)
@Test
public void shouldThrowOnRequireWithMessageSupplierWhenConditionIsFalse() {
assertThat(() -> Requirements.require(false, () -> "false")).isThrowing(UnsatisfiedRequirementException.class,
"false");
}
@Test
public void shouldPassOnRequireWithMessageSupplierWhenConditionIsTrue() {
Requirements.require(true, () -> "");
}
// -- requireNonNull(obj)
@Test
public void shouldRequireNonNullOnNonNull() {
final Object o = new Object();
assertThat(Requirements.requireNonNull(o) == o).isTrue();
}
@Test
public void shouldRequireNonNullOnNull() {
// TODO: jdk needs full qualified name javaslang.Assertions.assertThat() to compile, eclipse not
javaslang.Assertions.assertThat(() -> Requirements.requireNonNull(null)).isThrowing(
UnsatisfiedRequirementException.class, "Object is null");
}
// -- requireNonNull(obj, message)
@Test
public void shouldRequireNonNullOnNonNullWithMessage() {
final Object o = new Object();
assertThat(Requirements.requireNonNull(o, "") == o).isTrue();
}
@Test
public void shouldRequireNonNullOnNulWithMessage() {
// TODO: jdk needs full qualified name javaslang.Assertions.assertThat() to compile, eclipse not
javaslang.Assertions.assertThat(() -> Requirements.requireNonNull(null, "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
// -- requireNonNull(obj, () -> message)
@Test
public void shouldRequireNonNullOnNonNullWithMessageSupplier() {
final Object o = new Object();
assertThat(Requirements.requireNonNull(o, () -> "") == o).isTrue();
}
@Test
public void shouldRequireNonNullOnNulWithMessageSupplier() {
// TODO: jdk needs full qualified name javaslang.Assertions.assertThat() to compile, eclipse not
javaslang.Assertions.assertThat(() -> Requirements.requireNonNull(null, () -> "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
// -- requireNotNullOrEmpty(array)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWhenNull() {
final Object[] array = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(array)).isThrowing(UnsatisfiedRequirementException.class,
"Object is null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWhenEmpty() {
final Object[] array = {};
assertThat(() -> Requirements.requireNotNullOrEmpty(array)).isThrowing(UnsatisfiedRequirementException.class,
"Array is empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForArrayWhenNotNullOrEmpty() {
final Object[] array = { null };
assertThat(Requirements.requireNotNullOrEmpty(array) == array).isTrue();
}
// -- requireNotNullOrEmpty(array, message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWithMessageWhenNull() {
final Object[] array = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(array, "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWithMessageWhenEmpty() {
final Object[] array = {};
assertThat(() -> Requirements.requireNotNullOrEmpty(array, "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForArrayWithMessageWhenNotNullOrEmpty() {
final Object[] array = { null };
assertThat(Requirements.requireNotNullOrEmpty(array, "") == array).isTrue();
}
// -- requireNotNullOrEmpty(array, () -> message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWithMessageSupplierWhenNull() {
final Object[] array = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(array, () -> "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForArrayWithMessageSupplierWhenEmpty() {
final Object[] array = {};
assertThat(() -> Requirements.requireNotNullOrEmpty(array, () -> "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForArrayWithMessageSupplierWhenNotNullOrEmpty() {
final Object[] array = { null };
assertThat(Requirements.requireNotNullOrEmpty(array, () -> "") == array).isTrue();
}
// -- requireNotNullOrEmpty(charSequence)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence)).isThrowing(
UnsatisfiedRequirementException.class, "Object is null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence)).isThrowing(
UnsatisfiedRequirementException.class, "CharSequence is empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForCharSequenceWhenNotNullOrEmpty() {
final CharSequence charSequence = " ";
assertThat(Requirements.requireNotNullOrEmpty(charSequence) == charSequence).isTrue();
}
// -- requireNotNullOrEmpty(array, message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWithMessageWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence, "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWithMessageWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence, "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForCharSequenceWithMessageWhenNotNullOrEmpty() {
final CharSequence charSequence = " ";
assertThat(Requirements.requireNotNullOrEmpty(charSequence, "") == charSequence).isTrue();
}
// -- requireNotNullOrEmpty(charSequence, () -> message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWithMessageSupplierWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence, () -> "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyForCharSequenceWithMessageSupplierWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmpty(charSequence, () -> "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyForCharSequenceWithMessageSupplierWhenNotNullOrEmpty() {
final CharSequence charSequence = " ";
assertThat(Requirements.requireNotNullOrEmpty(charSequence, () -> "") == charSequence).isTrue();
}
// -- requireNotNullOrEmptyTrimmed(charSequence)
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence)).isThrowing(
UnsatisfiedRequirementException.class, "Object is null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence)).isThrowing(
UnsatisfiedRequirementException.class, "CharSequence is empty");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWhenWhitespaceTrimmed() {
final CharSequence charSequence = " ";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence)).isThrowing(
UnsatisfiedRequirementException.class, "CharSequence is empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyTrimmedForCharSequenceWhenNotNullOrEmptyTrimmed() {
final CharSequence charSequence = ".";
assertThat(Requirements.requireNotNullOrEmptyTrimmed(charSequence) == charSequence).isTrue();
}
// -- requireNotNullOrEmptyTrimmed(array, message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageWhenWhitespaceTrimmed() {
final CharSequence charSequence = " ";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageWhenNotNullOrEmptyTrimmed() {
final CharSequence charSequence = ".";
assertThat(Requirements.requireNotNullOrEmptyTrimmed(charSequence, "") == charSequence).isTrue();
}
// -- requireNotNullOrEmptyTrimmed(charSequence, () -> message)
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageSupplierWhenNull() {
final CharSequence charSequence = null;
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, () -> "null")).isThrowing(
UnsatisfiedRequirementException.class, "null");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageSupplierWhenEmpty() {
final CharSequence charSequence = "";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, () -> "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldThrowOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageSupplierWhenWhitespaceTrimmed() {
final CharSequence charSequence = " ";
assertThat(() -> Requirements.requireNotNullOrEmptyTrimmed(charSequence, () -> "empty")).isThrowing(
UnsatisfiedRequirementException.class, "empty");
}
@Test
public void shouldPassOnRequireNotNullOrEmptyTrimmedForCharSequenceWithMessageSupplierWhenNotNullOrEmptyTrimmed() {
final CharSequence charSequence = ".";
assertThat(Requirements.requireNotNullOrEmptyTrimmed(charSequence, () -> "") == charSequence).isTrue();
}
}
|
package objektwerks;
import java.util.*;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
enum Level {
high,
medium,
low;
int toInt() {
return switch(this) {
case high -> 1;
case medium -> 2;
case low -> 3;
};
}
}
class CollectionTest {
@Test void enumTest() {
var high = Level.high;
assert(high.toString().equals("high"));
assert(Level.valueOf("high") == high);
assert(Level.values().length == 3);
for (Level level : Level.values()) {
assert(!level.name().isEmpty());
}
assert(Level.high.toInt() == 1);
assert(Level.medium.toInt() == 2);
assert(Level.low.toInt() == 3);
}
@Test void enumSetTest() {
var enumSet = EnumSet.of(Level.high, Level.medium, Level.low);
assert(enumSet.size() == 3);
assert(enumSet.contains(Level.high));
assert(enumSet.contains(Level.medium));
assert(enumSet.contains(Level.low));
}
@Test void enumMapTest() {
var enumMap = new EnumMap<Level, Integer>(Level.class);
enumMap.put(Level.high, 1);
enumMap.put(Level.medium, 2);
enumMap.put(Level.low, 3);
assert(enumMap.size() == 3);
assert(enumMap.get(Level.high) == 1);
assert(enumMap.get(Level.medium) == 2);
assert(enumMap.get(Level.low) == 3);
}
public int add(Integer... zeroOrMoreIntegers) {
return Stream
.of(zeroOrMoreIntegers)
.reduce(Integer::sum)
.orElse(-1);
}
@Test void varargsTest() {
assert(add(1, 2, 3) == 6);
}
@Test void arrayTest() {
int[] xs = {1, 2, 3};
assert(xs.length == 3);
int[] ys = new int[3];
ys[0] = 1;
ys[1] = 2;
ys[2] = 3;
assert(ys.length == 3);
assert(xs != ys); // reference equality
assert(Arrays.equals(xs, ys)); // structural equality
}
@Test void arrayListTest() {
int[] xs = {1, 2, 3};
ArrayList<Integer> ys = new ArrayList<>();
for (int x : xs) {
ys.add(x);
}
assert(ys.size() == 3);
}
@Test void immutableListTest() {
var immutableList = List.of(1, 2, 3);
assert(immutableList.size() == 3);
assert(immutableList.get(0) == 1);
}
@Test void mutableListTest() {
var mutableList = new ArrayList<Integer>();
mutableList.add(1);
mutableList.add(2);
mutableList.add(3);
assert(mutableList.add(4));
assert(mutableList.remove(3) == 4);
}
@Test void setTest() {
var set = Set.of(1, 2, 3);
assert(set.size() == 3);
assert(set.contains(1));
assert(set.contains(2));
assert(set.contains(3));
}
@Test void sortedSetTest() {
var set = new TreeSet<Integer>();
set.add(3);
set.add(2);
set.add(1);
assert(set.size() == 3);
assert(set.first() == 1);
assert(set.last() == 3);
}
@Test void mapTest() {
var map = Map.of(1, 1, 2, 2, 3, 3);
assert(map.size() == 3 );
assert(map.get(1) == 1);
assert(map.get(2) == 2);
assert(map.get(3) == 3);
}
@Test void sortedMapTest() {
var map = new TreeMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
assert(map.size() == 3);
assert(map.firstKey() == 1);
assert(map.lastKey() == 3);
}
}
|
package org.apache.maven;
import junit.framework.TestCase;
public class TestMaths extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testSum() {
assertEquals(Maths.sum(2, 3),5);
}
}
|
package org.takes.http;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.jcabi.http.request.JdkRequest;
import com.jcabi.http.response.RestResponse;
import com.jcabi.matchers.RegexMatchers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.rq.RqSocket;
import org.takes.rq.RqWithHeaders;
import org.takes.rs.RsEmpty;
import org.takes.tk.TkText;
/**
* Test case for {@link BkBasic}.
*
* @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com)
* @version $Id$
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
* @todo #306:30min At the moment we don't support HTTP
* persistent connections. Would be great to implement
* this feature. BkBasic.accept should handle more
* than one HTTP request in one connection.
* @since 0.15.2
*/
@SuppressWarnings({
"PMD.ExcessiveImports",
"PMD.DoNotUseThreads",
"PMD.TooManyMethods"}
)
public final class BkBasicTest {
/**
* Carriage return constant.
*/
private static final String CRLF = "\r\n";
/**
* POST header constant.
*/
private static final String POST = "POST / HTTP/1.1";
/**
* Host header constant.
*/
private static final String HOST = "Host:localhost";
/**
* BkBasic can handle socket data.
*
* @throws IOException If some problem inside
*/
@Test
public void handlesSocket() throws IOException {
final Socket socket = createMockSocket();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
Mockito.when(socket.getOutputStream()).thenReturn(baos);
new BkBasic(new TkText("Hello world!")).accept(socket);
MatcherAssert.assertThat(
baos.toString(),
Matchers.containsString("Hello world")
);
}
/**
* BkBasic can return HTTP status 404 when accessing invalid URL.
*
* @throws IOException if any I/O error occurs.
*/
@Test
public void returnsProperResponseCodeOnInvalidUrl() throws IOException {
new FtRemote(
new TkFork(
new FkRegex("/path/a", new TkText("a")),
new FkRegex("/path/b", new TkText("b"))
)
).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
new JdkRequest(String.format("%s/path/c", home))
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_NOT_FOUND);
}
}
);
}
/**
* BkBasic produces headers with addresses without slashes.
*
* @throws IOException If some problem inside
*/
@Test
public void addressesInHeadersAddedWithoutSlashes() throws IOException {
final Socket socket = BkBasicTest.createMockSocket();
final AtomicReference<Request> ref = new AtomicReference<Request>();
new BkBasic(
new Take() {
@Override
public Response act(final Request req) {
ref.set(req);
return new RsEmpty();
}
}
).accept(socket);
final Request request = ref.get();
MatcherAssert.assertThat(
request,
Matchers.is(
Matchers.notNullValue()
)
);
MatcherAssert.assertThat(
request,
Matchers.is(
Matchers.instanceOf(
RqWithHeaders.class
)
)
);
final Collection<String> head = Lists.newArrayList(request.head());
MatcherAssert.assertThat(head, Matchers.not(Matchers.<String>empty()));
final Collection<String> found = Collections2.filter(
head,
new Predicate<String>() {
@Override
public boolean apply(final String header) {
return header.contains("X-Takes")
&& header.contains("Address");
}
}
);
for (final String header : found) {
MatcherAssert.assertThat(
header,
Matchers.not(
Matchers.containsString("/")
)
);
}
MatcherAssert.assertThat(
new RqSocket(request).getLocalAddress(),
Matchers.notNullValue()
);
MatcherAssert.assertThat(
new RqSocket(request).getRemoteAddress(),
Matchers.notNullValue()
);
}
/**
* BkBasic can handle two requests in one connection.
*
* @throws Exception If some problem inside
*/
@Ignore
@Test
public void handlesTwoRequestInOneConnection() throws Exception {
final String text = "Hello Twice!";
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final ServerSocket server = new ServerSocket(0);
try {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText(text)).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
final Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
);
try {
socket.getOutputStream().write(
Joiner.on(BkBasicTest.CRLF).join(
BkBasicTest.POST,
BkBasicTest.HOST,
"Content-Length: 11",
"",
"Hello First",
BkBasicTest.POST,
BkBasicTest.HOST,
"Content-Length: 12",
"",
"Hello Second"
).getBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
} finally {
socket.close();
}
} finally {
server.close();
}
MatcherAssert.assertThat(
output.toString(),
RegexMatchers.containsPattern(text + ".*?" + text)
);
}
/**
* BkBasic can return HTTP status 411 when a persistent connection request
* has no Content-Length.
*
* @throws Exception If some problem inside
*/
@Ignore
@Test
public void returnsProperResponseCodeOnNoContentLength() throws Exception {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final ServerSocket server = new ServerSocket(0);
try {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText("411 Test")).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
final Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
);
try {
socket.getOutputStream().write(
Joiner.on(BkBasicTest.CRLF).join(
BkBasicTest.POST,
BkBasicTest.HOST,
"",
"Hello World!"
).getBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
} finally {
socket.close();
}
} finally {
server.close();
}
MatcherAssert.assertThat(
output.toString(),
Matchers.containsString("HTTP/1.1 411 Length Required")
);
}
/**
* BkBasic can accept no content-length on closed connection.
*
* @throws Exception If some problem inside
*/
@Ignore
@Test
public void acceptsNoContentLengthOnClosedConnection() throws Exception {
final String text = "Close Test";
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final ServerSocket server = new ServerSocket(0);
try {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText(text)).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
final Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
);
try {
socket.getOutputStream().write(
Joiner.on(BkBasicTest.CRLF).join(
BkBasicTest.POST,
BkBasicTest.HOST,
"Connection: Close",
"",
"Hello World!"
).getBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
} finally {
socket.close();
}
} finally {
server.close();
}
MatcherAssert.assertThat(
output.toString(),
Matchers.containsString(text)
);
}
/**
* Creates Socket mock for reuse.
*
* @return Prepared Socket mock
* @throws IOException If some problem inside
*/
private static Socket createMockSocket() throws IOException {
final Socket socket = Mockito.mock(Socket.class);
Mockito.when(socket.getInputStream()).thenReturn(
new ByteArrayInputStream(
Joiner.on(BkBasicTest.CRLF).join(
"GET / HTTP/1.1",
"Host:localhost",
"Content-Length: 2",
"",
"hi"
).getBytes()
)
);
Mockito.when(socket.getLocalAddress()).thenReturn(
InetAddress.getLocalHost()
);
Mockito.when(socket.getLocalPort()).thenReturn(0);
Mockito.when(socket.getInetAddress()).thenReturn(
InetAddress.getLocalHost()
);
Mockito.when(socket.getPort()).thenReturn(0);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
Mockito.when(socket.getOutputStream()).thenReturn(baos);
return socket;
}
}
|
package uk.ac.ebi.subs.api;
import uk.ac.ebi.subs.data.client.Study;
import uk.ac.ebi.subs.data.component.*;
import uk.ac.ebi.subs.data.status.ProcessingStatusEnum;
import uk.ac.ebi.subs.data.status.SubmissionStatusEnum;
import uk.ac.ebi.subs.repository.model.ProcessingStatus;
import uk.ac.ebi.subs.repository.model.Sample;
import uk.ac.ebi.subs.repository.model.Submission;
import uk.ac.ebi.subs.repository.model.SubmissionStatus;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Helpers {
public static Submission generateSubmission() {
Submission s = new Submission();
s.setSubmitter(generateTestSubmitter());
return s;
}
private static Submitter generateTestSubmitter() {
Submitter u = new Submitter();
u.setEmail("test@test.org");
return u;
}
public static List<Sample> generateTestSamples() {
return generateTestSamples(2);
}
public static List<uk.ac.ebi.subs.data.client.Sample> generateTestClientSamples(int numberOfSamplesRequired) {
List<uk.ac.ebi.subs.data.client.Sample> samples = new ArrayList<>(numberOfSamplesRequired);
for (int i = 1; i <= numberOfSamplesRequired; i++) {
uk.ac.ebi.subs.data.client.Sample s = new uk.ac.ebi.subs.data.client.Sample();
samples.add(s);
s.setAlias("D" + i);
s.setTitle("NA12878_D" + i);
s.setDescription("Material derived from cell line NA12878");
s.setTaxon("Homo sapiens");
s.setTaxonId(9606L);
s.setReleaseDate(LocalDate.of(2017, Month.JANUARY, 1));
Attribute cellLineType = attribute("Cell line type", "EBV-LCL cell line");
Term ebvLclCellLine = new Term();
ebvLclCellLine.setUrl("http://purl.obolibrary.org/obo/BTO_0003335");
cellLineType.getTerms().add(ebvLclCellLine);
s.getAttributes().add(cellLineType);
}
return samples;
}
public static List<uk.ac.ebi.subs.data.client.Study> generateTestClientStudies(int numberOfStudiesRequired) {
List<uk.ac.ebi.subs.data.client.Study> studies= new ArrayList<>(numberOfStudiesRequired);
for (int i = 1; i <= numberOfStudiesRequired; i++) {
uk.ac.ebi.subs.data.client.Study s = new uk.ac.ebi.subs.data.client.Study();
studies.add(s);
Attribute studyType = new Attribute();
studyType.setName("study_type");
studyType.setValue("Whole Genome Sequencing");
s.setAlias("Study" + i);
s.setTitle("My Sequencing Study " + i);
s.setDescription("We sequenced some humans to discover variants linked with a disease");
s.setStudyType(StudyDataType.Sequencing);
Attribute studyAbstract = new Attribute();
studyAbstract.setName("study_abstract");
studyAbstract.setValue(s.getDescription());
s.getAttributes().add(studyType);
s.getAttributes().add(studyAbstract);
LocalDate releaseDate = LocalDate.parse("2020-12-25");
s.setReleaseDate(releaseDate);
}
return studies;
}
private static Attribute attribute(String name, String value){
Attribute attribute = new Attribute();
attribute.setName(name);
attribute.setValue(value);
return attribute;
}
public static List<uk.ac.ebi.subs.data.client.Assay> generateTestClientAssays(int numberOfAssaysRequired) {
List<uk.ac.ebi.subs.data.client.Assay> assays = new ArrayList<>(numberOfAssaysRequired);
Study study = generateTestClientStudies(1).get(0);
StudyRef studyRef = new StudyRef();
studyRef.setAlias(study.getAlias());
studyRef.setTeam(TEAM_NAME);
List<uk.ac.ebi.subs.data.client.Sample> samples = generateTestClientSamples(numberOfAssaysRequired);
for (int i = 1; i <= numberOfAssaysRequired; i++) {
uk.ac.ebi.subs.data.client.Assay a = new uk.ac.ebi.subs.data.client.Assay();
assays.add(a);
a.setAlias("A" + i);
a.setTitle("Assay " + i);
a.setDescription("Human sequencing experiment");
a.setStudyRef(studyRef);
SampleRef sampleRef = new SampleRef();
sampleRef.setAlias(samples.get(i-1).getAlias());
sampleRef.setTeam(TEAM_NAME);
SampleUse sampleUse = new SampleUse();
sampleUse.setSampleRef( sampleRef);
a.getSampleUses().add(sampleUse);
a.getAttributes().add(attribute("library_strategy","WGS"));
a.getAttributes().add(attribute("library_source","GENOMIC"));
a.getAttributes().add(attribute("library_selection","RANDOM"));
a.getAttributes().add(attribute("library_layout","SINGLE"));
a.getAttributes().add(attribute("platform_type","ILLUMINA"));
a.getAttributes().add(attribute("instrument_model","Illumina HiSeq 2000"));
}
return assays;
}
public static List<uk.ac.ebi.subs.data.client.AssayData> generateTestClientAssayData(int numberOfAssaysRequired) {
List<uk.ac.ebi.subs.data.client.AssayData> assayData = new ArrayList<>(numberOfAssaysRequired);
List<uk.ac.ebi.subs.data.client.Assay> assays = generateTestClientAssays(numberOfAssaysRequired);
for (int i = 1; i <= numberOfAssaysRequired; i++) {
uk.ac.ebi.subs.data.client.AssayData ad = new uk.ac.ebi.subs.data.client.AssayData();
assayData.add(ad);
ad.setAlias("AD" + i);
ad.setTitle("AssayData" + i);
ad.setDescription("Human sequencing experiment run");
AssayRef assayRef = new AssayRef();
assayRef.setAlias(assays.get(i-1).getAlias());
assayRef.setTeam(TEAM_NAME);
ad.setAssayRef(assayRef);
File file = new File();
file.setName("sequencingData.cram");
file.setType("CRAM");
file.setChecksum("4bb1c4561d99d88c8b38a40d694267dc");
ad.getFiles().add(file);
}
return assayData;
}
public static List<Sample> generateTestSamples(int numberOfSamplesRequired) {
List<Sample> samples = new ArrayList<>(numberOfSamplesRequired);
for (int i = 1; i <= numberOfSamplesRequired; i++) {
Sample s = new Sample();
samples.add(s);
s.setId(createId());
s.setTeam(generateTestTeam());
s.setAlias("D" + i);
s.setTitle("Donor " + i);
s.setDescription("Human sample donor");
s.setTaxon("Homo sapiens");
s.setTaxonId(9606L);
s.setProcessingStatus(new ProcessingStatus(ProcessingStatusEnum.Draft));
}
return samples;
}
public static Team generateTestTeam() {
Team d = new Team();
d.setName(TEAM_NAME);
return d;
}
public final static String TEAM_NAME = "self.usi-user";
public static Submission generateTestSubmission() {
Submission sub = new Submission();
Team d = new Team();
sub.setId(createId());
sub.setTeam(generateTestTeam());
sub.setSubmissionStatus(new SubmissionStatus(SubmissionStatusEnum.Draft));
return sub;
}
private static String createId() {
return UUID.randomUUID().toString();
}
}
|
package tests.jfmi.repo;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import jfmi.repo.SQLiteRepository;
/** Implements unit tests for the jfmi.repo.SQLiteRepository class.
*/
public class SQLiteRepositoryTest {
@Test
public void testInstance()
{
System.out.println("testInstance()");
assertTrue(SQLiteRepository.instance() == SQLiteRepository.instance());
}
@Test
public void testSetRepoPath_NonNullParams()
{
System.out.println("testSetRepoPath_NonNullParams()");
final String path = "testpath/repo.db";
SQLiteRepository.instance().setRepoPath(path);
String actual = SQLiteRepository.instance().getRepoPath();
assertEquals(path, actual);
}
@Test
public void testSetRepoPath_NullParams()
{
System.out.println("testSetRepoPath_NullParams()");
final String expected = "";
SQLiteRepository.instance().setRepoPath(null);
String actual = SQLiteRepository.instance().getRepoPath();
assertEquals(expected, actual);
}
}
|
package com.makeagame.magerevenge;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.makeagame.core.component.Position;
import com.makeagame.core.model.Model;
import com.makeagame.core.resource.ResourceManager;
import com.makeagame.tools.State;
public class GameModel implements Model {
public final static String SCREEN_MAIN = "main";
public final static String SCREEN_BATTLE = "battle";
public final static String SCREEN_MENU = "levelmenu";
String screen; // "main", "battle", "levelmenu"
boolean isStoreOpen;
int currentTime;
boolean start;
Random rand = new Random();
ArrayList<Role> roles;
State moneyGetState;
State skillCDState;
long moneyGetTime = 300;
long skillCDTime = 3000;
Player[] player; // You & computer(before change to online mode)
int moneyGet = 5;
// int maxCastleLevel = 3;
public GameModel() {
roles = new ArrayList<Role>();
player = new Player[] { new Player(0), new Player(1) };
roles.add(new Role(ResourceManager.get().read(MakeAGame.CASTLE + "L"), 0));
roles.add(new Role(ResourceManager.get().read(MakeAGame.CASTLE + "R"), 1));
startLevel(1, 1);
moneyGetState = new State(new long[][] { { State.BLOCK, moneyGetTime }, { State.ALLOW, State.BLOCK } });
skillCDState = new State(new long[][] { { State.BLOCK, skillCDTime }, { State.ALLOW, State.BLOCK } });
}
private void startLevel(int level, int difficulty) {
screen = "battle";
resumeGame();
// TODO
}
private void pause() {
start = false;
// TODO
}
private void resumeGame() {
start = true;
// TODO
}
private void gameOver() {
start = false;
// TODO
}
@Override
public void process(int command, JSONObject params) throws JSONException {
State.setNowTime(System.currentTimeMillis());
if (start) {
switch (command)
{
case Sign.MAIN_NewGame:
startLevel(params.getInt("level"), params.getInt("difficulty"));
break;
case Sign.MAIN_EnterLevelMenu:
// TODO
break;
case Sign.MAIN_StartMenu:
// TODO
break;
case Sign.BATTLE_SendSoldier:
String soldierType = params.getString("soldierType");
int soldierId = 0;
if (soldierType.equals(MakeAGame.ROLE_1)) {
soldierId = 1;
} else if (soldierType.equals(MakeAGame.ROLE_2)) {
soldierId = 2;
} else if (soldierType.equals(MakeAGame.ROLE_3)) {
soldierId = 3;
} else if (soldierType.equals(MakeAGame.ROLE_4)) {
soldierId = 4;
}
player[params.getInt("player")].click(soldierId);
break;
case Sign.BATTLE_UsePower:
if (skillCDState.enter(1)) {
// TODO power
powerApplyTime = State.global_current;
skillCDState.enter(0);
}
break;
case Sign.BATTLE_Upgrade:
player[params.getInt("player")].click(0);
break;
case Sign.BATTLE_UseItem:
// TODO
break;
case Sign.BATTLE_Pause:
if (params.getBoolean("toggle")) {
pause();
} else {
resumeGame();
}
break;
case Sign.BATTLE_Surrender:
gameOver();
break;
case Sign.STORE_OpenStore:
// TODO
break;
case Sign.STORE_Checkout:
// TODO
break;
case Sign.STORE_Deal:
// TODO
break;
case Sign.DEBUG_AddMoney:
player[0].totalMoney += params.getInt("amonut");
break;
case Sign.DEBUG_ResetColddown:
// TODO
break;
case Sign.DEBUG_PrintData:
System.out.println(hold());
break;
default:
// Engine.logE("get unknow command " + command);
}
// earn money
if (moneyGetState.enter(1)) {
player[0].totalMoney += moneyGet * player[0].castleLevel;
player[1].totalMoney += moneyGet * player[1].castleLevel;
moneyGetState.enter(0);
}
player[1].ai();
// run role
for (ListIterator<Role> it = roles.listIterator(); it.hasNext();) {
Role r = it.next();
if (r.state.currentStat() != Role.STATE_DEATH) {
r.run();
} else {
it.remove();
}
}
}
}
long powerApplyTime;
@Override
public String hold() {
Hold hold = new Hold();
hold.screen = screen;
if (screen.equals(SCREEN_BATTLE)) {
hold.money = player[0].totalMoney;
hold.resource = new int[] { 0, 0, 0 };
hold.sendcard = new Hold.SendCard[player[0].sendCards.length];
for (int i = 0; i < player[0].sendCards.length; i++) {
hold.sendcard[i] = player[0].sendCards[i].hold();
}
hold.soldier = new ArrayList<Hold.Unit>();
hold.castle = new Hold.Unit[2];
for (Role r : roles) {
if (!r.m.id.equals(MakeAGame.CASTLE)) {
hold.soldier.add(r.hold());
} else {
int id = r.m.group;
hold.castle[id] = r.hold();
}
}
hold.powerApplyTime = powerApplyTime;
hold.powerCD = (float) skillCDState.elapsed() / (float) skillCDTime;
}
hold.isStoreOpen = false;
hold.currentTime = State.global_current;
return new Gson().toJson(hold);
}
@Override
public String info() {
return "main model";
}
class Player {
int group;
int totalMoney;
int castleLevel;
SendCard[] sendCards;
public Player(int group) {
this.group = group;
totalMoney = 0;
castleLevel = 1;
if (group == 0) {
sendCards = new SendCard[] {
new SendCard(MakeAGame.CASTLE, 150, 1000),
new SendCard(MakeAGame.ROLE_1, 100, 3000),
new SendCard(MakeAGame.ROLE_2, 250, 6000),
new SendCard(MakeAGame.ROLE_3, 300, 12000),
new SendCard(MakeAGame.ROLE_4),
};
} else {
sendCards = new SendCard[] {
new SendCard(MakeAGame.CASTLE, 200, 1000),
new SendCard(MakeAGame.ROLE_1, 130, 3500),
new SendCard(MakeAGame.ROLE_2),
new SendCard(MakeAGame.ROLE_3),
new SendCard(MakeAGame.ROLE_4),
};
}
}
public void ai() {
// TODO
for (SendCard card : sendCards) {
if (card.canClick(this)) {
card.send(this);
}
}
// create enemy
// if (enemyCreateState.enter(1)) {
// roles.add(new Role(ResourceManager.get().read(MakeAGame.ROLE_1), 1));
// enemyCreateState.enter(0);
}
public void click(int id) {
sendCards[id].send(this);
}
}
class SendCard {
long cdTime;
State state;
boolean locked;
int costMoney;
int[] costResource;
String type;
int strongLevel;
public SendCard(String type) {
this.type = type;
this.locked = true;
}
public SendCard(String type, int costMoney, long cdTime) {
this.type = type;
this.costMoney = costMoney;
this.cdTime = cdTime;
state = new State(new long[][] { { State.BLOCK, cdTime }, { State.ALLOW, State.BLOCK } });
costResource = new int[] { 0, 0, 0 };
locked = false;
strongLevel = 1;
}
public Hold.SendCard hold() {
Hold.SendCard h = new Hold.SendCard();
h.type = type;
h.locked = locked;
if (!locked) {
h.costMoney = costMoney;
h.costResource = costResource;
h.sendCD = (float) state.elapsed() / (float) cdTime;
h.strongLevel = strongLevel;
}
return h;
}
public boolean canClick(Player player) {
if (locked) {
return false;
}
if (player.totalMoney < costMoney) {
return false;
}
return true;
}
public void send(Player player) {
if (canClick(player)) {
if (state.enter(1)) {
player.totalMoney -= costMoney;
if (type.equals(MakeAGame.CASTLE)) {
costMoney *= 2;
player.castleLevel++;
} else {
roles.add(new Role(ResourceManager.get().read(type), player.group));
}
state.enter(0);
}
}
}
}
class Role {
// 1 Moving, 2 Preparing, 3 Attacking, 4 Backing, 5 Death
public final static int STATE_MOVING = 0;
public final static int STATE_PERPARING = 1;
public final static int STATE_ATTACKING = 2;
public final static int STATE_BACKING = 3;
public final static int STATE_DEATH = 4;
State state;
Role meet;
Attribute m;
long lastAttackTime;
long backingTime = 50;
ArrayList<Hold.Hurt> hurtRecord;
public Role(String gson, int group) {
m = init(gson);
m.group = group;
m.x = group == 0 ? 110 : 848;
m.y = 340 + (20 - rand.nextInt(40));
m.maxHp = m.hp;
m.baseAtkTime = m.atkTime;
m.level = 1;
hurtRecord = new ArrayList<Hold.Hurt>();
state = new State(new long[][] {
{ State.ALLOW, State.ALLOW, State.BLOCK, State.ALLOW, State.ALLOW },
{ State.ALLOW, State.BLOCK, m.atkTime, State.ALLOW, State.ALLOW },
{ State.ALLOW, State.ALLOW, State.BLOCK, State.ALLOW, State.ALLOW },
{ backingTime, backingTime, State.BLOCK, State.BLOCK, State.ALLOW },
{ State.BLOCK, State.BLOCK, State.BLOCK, State.BLOCK, State.BLOCK } });
}
public class Attribute {
public String id;
int group; // 0 mine, 1 others
int hp;
int maxHp;
int atk;
int x;
int y;
float sX;
int money;
int beAtk;
long atkTime;
long baseAtkTime;
int range;
int level;
}
public Attribute init(String gson) {
// Engine.logI("init with gson " + gson);
Attribute model = new Gson().fromJson(gson, Attribute.class);
return model;
}
public long getAtkTime(boolean atked) {
m.atkTime = (long) (m.baseAtkTime * (atked ? 1.4f : 0.6f));
return m.atkTime;
}
public void run() {
// stop while meet other groups role
meet = null;
for (Role r : roles) {
if (m.group == 0 && r.m.group == 1 && m.x + m.range >= r.m.x
|| (m.group == 1 && r.m.group == 0 && m.x - m.range <= r.m.x)) {
meet = r;
// System.out.println(m.id + " meet to " + meet.m.id);
}
}
if (meet == null) {
state.enter(Role.STATE_MOVING);
} else {
state.enter(Role.STATE_PERPARING);
}
if (m.atk > 0) {
if (state.enter(Role.STATE_ATTACKING)) {
// System.out.println(m.id + " attack to " + meet.m.id);
meet.m.hp -= m.atk;
if (!meet.m.id.equals("castle")) {
meet.m.beAtk = m.atk;
}
meet.hurtRecord.add(new Hold.Hurt(State.global_current, m.atk));
meet.state.enter(Role.STATE_BACKING);
state.setTableValue(getAtkTime(true), 1, 2);
meet.state.setTableValue(meet.getAtkTime(false), 1, 2);
}
}
// die
if (m.hp <= 0) {
if (state.enter(Role.STATE_DEATH)) {
player[m.group == 0 ? 1 : 0].totalMoney += m.money;
if (m.id.equals("castle")) {
gameOver();
}
}
}
// System.out.println(m.id + " state is " + state.currentStat());
switch (state.currentStat()) {
case Role.STATE_MOVING:
m.x += (m.group == 0 ? 1 : -1) * m.sX;
break;
case Role.STATE_PERPARING:
break;
case Role.STATE_ATTACKING:
break;
case Role.STATE_BACKING:
m.x += (m.group == 0 ? -1 : 1) * m.beAtk * 0.5f;
break;
case Role.STATE_DEATH:
break;
}
}
public Hold.Unit hold() {
Hold.Unit h = new Hold.Unit();
h.group = m.group;
h.hpp = (float) m.hp / (float) m.maxHp;
h.hurtRecord = new ArrayList<Hold.Hurt>();
// is not a good function
for (int i = 0; i < hurtRecord.size(); i++) {
if (hurtRecord.get(i).time > State.global_current - 10000) {
h.hurtRecord.add(hurtRecord.get(i));
}
}
h.lastAttackTime = state.elapsed(STATE_ATTACKING);
h.lastBackingTime = state.elapsed(STATE_BACKING);
h.lastDeathTime = state.elapsed(STATE_DEATH);
h.lastPreparingTime = state.elapsed(STATE_PERPARING);
h.lastWalkTime = state.elapsed(STATE_MOVING);
h.pos = new Position<Integer>(m.x, m.y);
h.stateRecord = state.currentStat();
h.strongLevel = m.level;
h.type = m.id;
return h;
}
}
}
|
package com.mygdx.game.stages;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.mygdx.game.managers.GameStateManager;
public class MainMenuStage extends Stage {
private Skin skin;
public MainMenuStage(final GameStateManager gsm) {
skin = new Skin(Gdx.files.internal("MainMenuSkin.json"));
Table table = new Table();
final TextButton button = new TextButton("New Game", skin, "default");
final TextButton exitButton = new TextButton("Quit Game", skin, "default");
button.setSize(200f, 50f);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
gsm.setState(GameStateManager.State.PLAY);
}
});
exitButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.setWidth(this.getWidth());
table.align(Align.center|Align.top);
table.setPosition(0, Gdx.graphics.getHeight());
table.padTop(30);
table.add(button).padBottom(30f);
table.row();
table.add(exitButton);
this.addActor(table);
}
@Override
public void draw() {
SpriteBatch batch = new SpriteBatch();
Sprite sprite = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")));
sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.begin();
sprite.draw(batch);
batch.end();
super.draw();
}
}
|
package hudson.cli;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.TopLevelItem;
import hudson.Extension;
import org.kohsuke.args4j.Argument;
import java.io.Serializable;
/**
* Copies a job from CLI.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class CopyJobCommand extends CLICommand implements Serializable {
@Override
public String getShortDescription() {
return "Copies a job";
}
@Argument(metaVar="SRC",usage="Name of the job to copy")
public String src;
@Argument(metaVar="DST",usage="Name of the new job to be created.",index=1)
public String dst;
protected int run() throws Exception {
Hudson h = Hudson.getInstance();
TopLevelItem s = h.getItem(src);
if (s==null) {
stderr.println("No such job '"+src+"' perhaps you meant "+ AbstractProject.findNearest(src)+"?");
return -1;
}
if (h.getItem(dst)!=null) {
stderr.println("Job '"+dst+"' already exists");
return -1;
}
h.copy(s,dst);
return 0;
}
}
|
package uk.co.alynn.games.suchrobot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class NodeSet implements Iterable<PathNode> {
private static final class RoutingKey {
public final String sourceNode;
public final String destNode;
public RoutingKey(String src, String dst) {
sourceNode = src;
destNode = dst;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof RoutingKey))
return false;
RoutingKey o = (RoutingKey)obj;
return o.sourceNode.equals(sourceNode) && o.destNode.equals(destNode);
}
@Override
public int hashCode() {
return (903*sourceNode.hashCode()) + destNode.hashCode();
}
}
private List<PathNode> nodes = new ArrayList<PathNode>();
private Map<String, List<PathNode>> directConnections = new HashMap<String, List<PathNode>>();
private Map<RoutingKey, PathNode> nextHops = null;
public NodeSet() {
}
public void addNode(String type, String name, Rational x, Rational y) {
PathNode newNode = new PathNode(name, x, y);
nodes.add(newNode);
directConnections.put(name, new ArrayList<PathNode>());
}
public void addConnection(String from, String to) {
directConnections.get(from).add(lookup(to));
directConnections.get(to).add(lookup(from));
}
public void compile() {
System.err.println("computing routing tables");
nextHops = new HashMap<RoutingKey, PathNode>();
for (PathNode node : this) {
System.err.println("- " + node);
runDijkstra(node);
}
}
private void runDijkstra(PathNode node) {
// Not Dijkstra's algorithm!
for (PathNode targetNode : this) {
RoutingKey key = new RoutingKey(node.name, targetNode.name);
nextHops.put(key, targetNode);
}
}
public PathNode lookup(String name) {
for (PathNode node : this) {
if (node.name.equals(name))
return node;
}
throw new RuntimeException("Missing path node " + name);
}
public Iterable<PathNode> connectionsFrom(PathNode node) {
return directConnections.get(node.name);
}
public PathNode nextNodeFor(PathNode from, PathNode to) {
RoutingKey key = new RoutingKey(from.name, to.name);
return nextHops.get(key);
}
@Override
public Iterator<PathNode> iterator() {
return nodes.iterator();
}
}
|
package wge3.game.entity.creatures;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.MathUtils;
import static com.badlogic.gdx.math.MathUtils.PI;
import static com.badlogic.gdx.math.MathUtils.PI2;
import static com.badlogic.gdx.math.MathUtils.radiansToDegrees;
import static com.badlogic.gdx.math.MathUtils.random;
import static com.badlogic.gdx.utils.TimeUtils.millis;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static wge3.game.engine.constants.Direction.*;
import wge3.game.engine.constants.Statistic;
import wge3.game.engine.constants.Team;
import static wge3.game.engine.gamestates.PlayState.mStream;
import wge3.game.engine.gui.Drawable;
import static wge3.game.engine.utilities.Math.floatPosToTilePos;
import static wge3.game.engine.utilities.Math.getDiff;
import wge3.game.engine.utilities.StatIndicator;
import wge3.game.engine.utilities.Statistics;
import static wge3.game.engine.utilities.pathfinding.PathFinder.findPath;
import wge3.game.entity.Area;
import wge3.game.entity.Tile;
import wge3.game.entity.creatures.utilities.Inventory;
import wge3.game.entity.tilelayers.grounds.OneWayFloor;
import wge3.game.entity.tilelayers.mapobjects.Item;
import wge3.game.entity.tilelayers.mapobjects.Teleport;
public abstract class Creature implements Drawable {
protected Area area;
protected Statistics statistics;
protected float x;
protected float y;
protected int previousTileX;
protected int previousTileY;
protected Circle bounds;
protected Team team;
protected int size;
protected int defaultSpeed;
protected int currentSpeed;
protected float walkToRunMultiplier;
protected float direction;
protected float turningSpeed;
protected int sight;
protected float FOV;
protected String name;
protected StatIndicator HP;
protected StatIndicator energy;
protected int strength;
protected int defense;
protected int unarmedAttackSize; // radius
// Regen rates: the amount of milliseconds between regenerating 1 unit.
protected int HPRegenRate;
protected int energyRegenRate;
protected int energyConsumptionRate;
protected long lastHPRegen;
protected long lastEnergyRegen;
protected long lastEnergyConsumption;
protected boolean isRunning;
protected boolean isInvisible;
protected boolean picksUpItems;
protected boolean canSeeEverything;
protected boolean isGhost;
protected boolean isFlying;
protected Inventory inventory;
protected Item selectedItem;
protected Texture texture;
protected Sprite sprite;
protected boolean goingForward;
protected boolean goingBackward;
protected boolean turningLeft;
protected boolean turningRight;
public Creature() {
texture = new Texture(Gdx.files.internal("graphics/graphics.png"));
size = Tile.size / 3;
defaultSpeed = 75;
currentSpeed = defaultSpeed;
walkToRunMultiplier = 1.35f;
direction = random() * PI2;
turningSpeed = 3.5f;
sight = 12;
FOV = PI;
unarmedAttackSize = Tile.size/2;
HP = new StatIndicator();
energy = new StatIndicator(100);
HPRegenRate = 1000;
lastHPRegen = millis();
lastEnergyRegen = millis();
lastEnergyConsumption = millis();
energyRegenRate = 500;
energyConsumptionRate = 80;
canSeeEverything = false;
isGhost = false;
bounds = new Circle(new Vector2(), size);
inventory = new Inventory(this);
selectedItem = null;
goingForward = false;
goingBackward = false;
turningLeft = false;
turningRight = false;
isRunning = false;
isInvisible = false;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
updateSpritePosition();
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
updateSpritePosition();
}
public void setPosition(float x, float y) {
this.x = x;
this.y = y;
updateSpritePosition();
}
public void setPosition(int x, int y) {
this.x = x * Tile.size + Tile.size/2;
this.y = y * Tile.size + Tile.size/2;
updateSpritePosition();
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public int getDefaultSpeed() {
return defaultSpeed;
}
public void setDefaultSpeed(int defaultSpeed) {
this.defaultSpeed = defaultSpeed;
}
public void setCurrentSpeed(int speed) {
this.currentSpeed = speed;
}
public float getDirection() {
return direction;
}
public float getTurningSpeed() {
return turningSpeed;
}
public void setTurningSpeed(float turningSpeed) {
this.turningSpeed = turningSpeed;
}
public int getMaxHP() {
return HP.getMaximum();
}
public void setMaxHP(int newMaxHP) {
HP.setMaximum(newMaxHP);
}
public int getEnergy() {
return energy.getCurrent();
}
public int getMaxEnergy() {
return energy.getMaximum();
}
public int getHP() {
return HP.getCurrent();
}
public void setHP(int newHP) {
HP.setCurrent(newHP);
}
public int getSize() {
return size;
}
public int getCurrentSpeed() {
return currentSpeed;
}
public Inventory getInventory() {
return inventory;
}
@Override
public void draw(Batch batch) {
sprite.draw(batch);
}
public void turnLeft(float delta) {
direction += turningSpeed * delta;
if (direction >= PI2) direction -= PI2;
updateSpriteRotation();
}
public void turnRight(float delta) {
direction -= turningSpeed * delta;
if (direction < 0) direction += PI2;
updateSpriteRotation();
}
public void move(float dx, float dy) {
// Apply movement modifiers:
if (!this.isGhost) {
float movementModifier = area.getTileAt(getX(), getY()).getMovementModifier();
dx *= movementModifier;
dy *= movementModifier;
}
if (isRunning()) {
long currentTime = millis();
boolean consumeOrTakeDamage = currentTime - lastEnergyConsumption > energyConsumptionRate;
if (canRun()) {
dx *= walkToRunMultiplier;
dy *= walkToRunMultiplier;
if (consumeOrTakeDamage) {
consumeEnergy();
lastEnergyConsumption = currentTime;
}
} else {
dx *= walkToRunMultiplier * HP.getFraction();
dy *= walkToRunMultiplier * HP.getFraction();
if (consumeOrTakeDamage) {
this.dealDamage(1);
lastEnergyConsumption = currentTime;
}
}
}
// Calculate actual movement:
float destX = getX() + dx;
float destY = getY() + dy;
if (canMoveTo(destX, destY)) {
setX(destX);
setY(destY);
} else if (canMoveTo(getX(), destY)) {
setY(destY);
} else if (canMoveTo(destX, getY())) {
setX(destX);
}
// These should be optimized to be checked less than FPS times per second:
if (hasMovedToANewTile()) {
if (getTile().hasTeleport() && !getPreviousTile().hasTeleport()) {
Teleport tele = (Teleport) getTile().getObject();
tele.teleport(this);
}
previousTileX = getTileX();
previousTileY = getTileY();
if (picksUpItems()) pickUpItems();
}
}
public boolean hasMovedToANewTile() {
return getTileX() != previousTileX
|| getTileY() != previousTileY;
}
public void pickUpItems() {
Tile currentTile = getTile();
if (currentTile.hasItem()) {
inventory.addItem((Item) currentTile.getObject());
currentTile.removeObject();
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.ITEMSPICKEDUP, 1);
}
}
}
public boolean canMoveTo(float x, float y) {
if (!area.hasLocation(x, y)) {
return false;
}
if (this.isGhost()) {
return true;
}
Tile destination = area.getTileAt(x, y);
if (this.isFlying()) {
return destination.isPassable() || !destination.isIndoors();
}
if (destination.isOneWay()) {
OneWayFloor oneWayTile = (OneWayFloor) destination.getGround();
if (oneWayTile.getDirection() == LEFT && x - getX() > 0) {
return false;
}
if (oneWayTile.getDirection() == RIGHT && x - getX() < 0) {
return false;
}
if (oneWayTile.getDirection() == UP && y - getY() < 0) {
return false;
}
if (oneWayTile.getDirection() == DOWN && y - getY() > 0) {
return false;
}
}
if (!this.isOnPassableObject() && !this.getTile().isIndoors()) {
return true;
}
return (destination.isPassable());
}
public boolean canMoveTo(Tile dest) {
return findPath(this.getTile(), dest) != null;
}
public void useItem() {
if (this.isInvisible()) {
if (!selectedItem.isPotion()) {
this.setInvisibility(false);
}
}
if (selectedItem == null) attackUnarmed();
else {
selectedItem.use(this);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.ITEMSUSED, 1);
}
}
}
public void changeItem() {
setSelectedItem(inventory.getNextItem());
}
public void setSelectedItem(Item selectedItem) {
this.selectedItem = selectedItem;
}
public Item getSelectedItem() {
return selectedItem;
}
public int getSight() {
return sight;
}
public float getFOV() {
return FOV;
}
public boolean canSeeEverything() {
return canSeeEverything;
}
public void toggleCanSeeEverything() {
canSeeEverything = canSeeEverything == false;
}
public boolean isGhost() {
return isGhost;
}
public void toggleGhostMode() {
isGhost = isGhost == false;
if (isGhost()) mStream.addMessage("Ghost Mode On");
else mStream.addMessage("Ghost Mode Off");
}
public boolean isInCenterOfATile() {
float x = (getX() % Tile.size) / Tile.size;
float y = (getY() % Tile.size) / Tile.size;
return (x >= 0.25f && x <= 0.75f) && (y >= 0.25f && y <= 0.75f);
}
public void dealDamage(int amount) {
int decreaseAmount = max(amount - defense, 1);
HP.decrease(decreaseAmount);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.DAMAGETAKEN, decreaseAmount);
}
}
public boolean isDead() {
return HP.isEmpty();
}
public void regenerate(long currentTime) {
if (currentTime - lastHPRegen > HPRegenRate) {
regenerateHP();
lastHPRegen = currentTime;
}
if (!isRunning && currentTime - lastEnergyRegen > energyRegenRate) {
regenerateEnergy();
lastEnergyRegen = currentTime;
}
}
public void regenerateEnergy() {
energy.increase();
}
public void regenerateHP() {
HP.increase();
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.HEALTHREGAINED, 1);
}
}
public void updateSpritePosition() {
sprite.setPosition(getX() - Tile.size/2, getY() - Tile.size/2);
}
public void updateSpriteRotation() {
sprite.setRotation(direction * radiansToDegrees);
}
public void attackUnarmed() {
float destX = getX() + MathUtils.cos(direction) * Tile.size;
float destY = getY() + MathUtils.sin(direction) * Tile.size;
Circle dest = new Circle(destX, destY, getUnarmedAttackSize());
for (Creature creature : area.getCreatures()) {
if (dest.contains(creature.getX(), creature.getY())) {
if (creature.getTeam() != this.getTeam()) {
creature.dealDamage(this.strength);
}
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.DAMAGEDEALT, strength);
}
}
}
area.getTileAt(destX, destY).dealDamage(this.strength);
}
public boolean isPlayer() {
return this.getClass() == Player.class;
}
public void doMovement(float delta) {
if (goingForward) {
goingForward = false;
float dx = MathUtils.cos(direction) * currentSpeed * delta;
float dy = MathUtils.sin(direction) * currentSpeed * delta;
move(dx, dy);
} else if (goingBackward) {
goingBackward = false;
float dx = -(MathUtils.cos(direction) * currentSpeed/1.5f * delta);
float dy = -(MathUtils.sin(direction) * currentSpeed/1.5f * delta);
move(dx, dy);
}
if (turningLeft) {
turningLeft = false;
turnLeft(delta);
} else if (turningRight) {
turningRight = false;
turnRight(delta);
}
}
public void goForward() {
goingForward = true;
}
public void goBackward() {
goingBackward = true;
}
public void turnLeft() {
turningLeft = true;
}
public void turnRight() {
turningRight = true;
}
public boolean canBeSeenBy(Creature creature) {
return getTile().canBeSeenBy(creature) && !this.isInvisible();
}
public void setLighting(Color color) {
sprite.setColor(color);
}
public Tile getTile() {
return area.getTileAt(getX(), getY());
}
public Tile getPreviousTile() {
return area.getTileAt(previousTileX, previousTileY);
}
public Team getTeam() {
return team;
}
public List<Tile> getPossibleMovementDestinations() {
List<Tile> tiles = new LinkedList<Tile>();
for (Tile tile : area.getTiles()) {
if (tile.canBeSeenBy(this) && tile.isAnOKMoveDestinationFor(this)) tiles.add(tile);
}
return tiles;
}
public Tile getNewMovementDestination() {
// Returns a random tile from all the tiles that are
// ok move destinations and can be seen by creature.
List<Tile> tiles = getPossibleMovementDestinations();
return tiles.get(random(tiles.size() - 1));
}
public String getName() {
return name;
}
public int getUnarmedAttackSize() {
return unarmedAttackSize;
}
public boolean isEnemyOf(Creature other) {
return this.getTeam() != other.getTeam();
}
public boolean picksUpItems() {
return picksUpItems;
}
//SORT THIS, make comparator
public List<Creature> getEnemiesWithinFOV() {
List<Creature> enemiesWithinFOV = new LinkedList<Creature>();
for (Creature creature : getArea().getCreatures()) {
if (creature.isEnemyOf(this) && creature.canBeSeenBy(this)) {
enemiesWithinFOV.add(creature);
}
}
return enemiesWithinFOV;
}
public List<Creature> getFriendliesWithinFOV() {
List<Creature> friendlies = new ArrayList<Creature>();
for (Creature creature : getArea().getCreatures()) {
if (!creature.isEnemyOf(this) && creature.canBeSeenBy(this)) {
friendlies.add(creature);
}
}
return friendlies;
}
public void addHP(int amount) {
HP.increase(amount);
if (this.isPlayer()) {
statistics.addStatToPlayer(this, Statistic.HEALTHREGAINED, amount);
}
}
public void addEnergy(int amount) {
energy.increase(amount);
}
public float getDistanceTo(float x, float y) {
float dx = x - this.x;
float dy = y - this.y;
return (float) Math.sqrt(dx*dx + dy*dy);
}
public float getDistanceInTilesTo(float x, float y) {
return getDistanceTo(x, y) / Tile.size;
}
public float getDistanceTo(Creature other) {
return getDistanceTo(other.getX(), other.getY());
}
public float getDistanceTo(Tile tile) {
// Returns distance to middle point of tile
return getDistanceInTilesTo(tile.getMiddleX(), tile.getMiddleY());
}
public void startRunning() {
isRunning = true;
}
public void stopRunning() {
isRunning = false;
}
public boolean isRunning() {
return isRunning;
}
public void consumeEnergy() {
energy.decrease();
}
public boolean canRun() {
return !energy.isEmpty();
}
public int getTileX() {
return floatPosToTilePos(x);
}
public int getTileY() {
return floatPosToTilePos(y);
}
public void setTeam(Team team) {
this.team = team;
}
public boolean isInSameTileAs(Creature other) {
return this.getTileX() == other.getTileX()
&& this.getTileY() == other.getTileY();
}
public void setInvisibility(boolean truth) {
if (truth) sprite.setAlpha(0.3f);
else sprite.setAlpha(1);
isInvisible = truth;
}
public boolean isInvisible() {
return isInvisible;
}
public void removeItem(Item item) {
inventory.removeItem(item);
}
public boolean isFacing(Creature target) {
return abs(getDiff(this.getDirection(), target.direction)) < PI/48;
}
public boolean isFlying() {
return isFlying;
}
public void setFlying(boolean truth) {
isFlying = truth;
}
public void setSprite(int x, int y) {
sprite = new Sprite(texture, x*Tile.size, y*Tile.size, Tile.size, Tile.size);
updateSpriteRotation();
}
public float getHPAsFraction() {
return HP.getFraction();
}
public float getEnergyAsFraction() {
return energy.getFraction();
}
public void setStatistics(Statistics statistics) {
this.statistics = statistics;
}
public Statistics getStatistics() {
return statistics;
}
public int getDefence() {
return this.defense;
}
public boolean isOnPassableObject() {
return (this.getTile().isPassable());
}
public Circle getBounds() {
return bounds;
}
}
|
package br.usp.ime.ep2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.preference.PreferenceManager;
import android.util.Log;
import br.usp.ime.ep2.Constants.Collision;
import br.usp.ime.ep2.Constants.Colors;
import br.usp.ime.ep2.Constants.Config;
import br.usp.ime.ep2.Constants.Hit;
import br.usp.ime.ep2.Constants.Lives;
import br.usp.ime.ep2.Constants.Scales;
import br.usp.ime.ep2.Constants.Score;
import br.usp.ime.ep2.Constants.ScoreMultiplier;
import br.usp.ime.ep2.effects.Explosion;
import br.usp.ime.ep2.forms.Ball;
import br.usp.ime.ep2.forms.Brick;
import br.usp.ime.ep2.forms.Brick.Type;
import br.usp.ime.ep2.forms.MobileBrick;
import br.usp.ime.ep2.forms.Paddle;
public class Game {
private static final String TAG = Game.class.getSimpleName();
private static final int SCREEN_INITIAL_X = 0;
private static final int SCREEN_INITIAL_Y = 0;
private Paddle mPaddle;
private Ball mBall;
private Brick[][] mBricks;
private SoundPool mSoundPool;
private HashMap<String, Integer> mSoundIds;
private Context mContext;
private List<Explosion> mExplosions;
private List<MobileBrick> mMobileBricks;
// Game preferences
protected static int sLifeCount;
protected static int sHitScore;
protected static int sScoreMultiplier;
protected static float sBallSpeed;
protected static boolean sInvincibility;
public static float sScreenHigherY;
public static float sScreenLowerY;
public static float sScreenHigherX;
public static float sScreenLowerX;
public Game(Context context) {
mContext = context;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
sLifeCount = sharedPrefs.getInt("lives", 7777);
sHitScore = sharedPrefs.getInt("hit_score", 7777);
sScoreMultiplier = sharedPrefs.getInt("max_multiplier", 0);
sBallSpeed = sharedPrefs.getFloat("ball_speed", 0);
sInvincibility = sharedPrefs.getBoolean("invincibility", true);
// Load sound pool, audio shouldn't change between levels
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundIds = new HashMap<String, Integer>(4);
mSoundIds.put("lost_life", mSoundPool.load(mContext, R.raw.lost_life, 1));
mSoundIds.put("wall_hit", mSoundPool.load(mContext, R.raw.wall_hit, 1));
mSoundIds.put("paddle_hit", mSoundPool.load(mContext, R.raw.paddle_hit, 1));
mSoundIds.put("brick_hit", mSoundPool.load(mContext, R.raw.brick_hit, 1));
mSoundIds.put("explosive_brick", mSoundPool.load(mContext, R.raw.explosive_brick, 1));
// Create level elements
resetElements();
}
public void resetElements() {
mExplosions = new ArrayList<Explosion>();
mMobileBricks = new ArrayList<MobileBrick>();
/* We don't have the screen measures on the first call of this function,
* so set to a sane default. */
sScreenHigherX = 1.0f;
sScreenLowerX = -1.0f;
sScreenHigherY = 1.0f;
sScreenLowerY = -1.0f;
// Initialize game state
State.setGameOver(false);
State.setLives(Lives.RESTART_LEVEL);
State.setScore(Score.RESTART_LEVEL);
State.setScoreMultiplier(ScoreMultiplier.RESTART_LEVEL);
// Initialize graphics
mPaddle = new Paddle(Colors.WHITE, Config.PADDLE_INITIAL_POS_Y, Scales.PADDLE);
Log.d(TAG, "Created paddle:" +
" BottomY: " + mPaddle.getBottomY() +
" TopY: " + mPaddle.getTopY() +
" LeftX: " + mPaddle.getLeftX() +
" RightX: " + mPaddle.getRightX()
);
mBall = new Ball(Colors.WHITE, Config.BALL_INITIAL_POS_X, Config.BALL_INITIAL_POS_Y,
Scales.BALL, sBallSpeed);
Log.d(TAG, "Created ball:" +
" BottomY: " + mBall.getBottomY() +
" TopY: " + mBall.getTopY() +
" LeftX: " + mBall.getLeftX() +
" RightX: " + mBall.getRightX()
);
/* The first brick should be put on the corner of the screen, but if we put too close
* to screen the brick matrix doesn't stay on center. The constant compensates this.*/
float initialX = -Config.SCREEN_RATIO + Config.SPACE_BETWEEN_BRICKS;
createLevel(Config.NUMBER_OF_LINES_OF_BRICKS, Config.NUMBER_OF_COLUMNS_OF_BRICKS,
initialX, Config.BRICKS_INITIAL_POS_Y);
mExplosions = new ArrayList<Explosion>();
}
private void createLevel (int blocksX, int blocksY, float initialX, float initialY) {
mBricks = new Brick[blocksX][blocksY];
// The initial position of the brick should be the one passed from the call of this function
float newPosX = initialX;
float newPosY = initialY;
for (int i = 0; i < blocksX; i++) {
float sign = 1;
for (int j = 0; j < blocksY; j++) {
sign *= -1; //consecutive bricks start moving to different directions
// Create special bricks (explosive and hard types) on a random probability
double prob = Math.random();
if (prob <= (Brick.MOBILE_BRICK_PROBABILITY + Brick.EXPLOSIVE_BRICK_PROBABILITY + Brick.GRAY_BRICK_PROBABILITY)) {
if (prob <= Brick.MOBILE_BRICK_PROBABILITY) {
MobileBrick mBrick = new MobileBrick(Colors.GREEN, newPosX, newPosY, Scales.BRICK, Type.MOBILE, 3);
mBrick.setXVelocity(sign * mBrick.getWidth()/30);
mBrick.setGlobalBrickMatrixIndex(i, j);
mBricks[i][j] = mBrick;
mMobileBricks.add(mBrick);
} else if ((prob-Brick.MOBILE_BRICK_PROBABILITY) <= Brick.EXPLOSIVE_BRICK_PROBABILITY) {
mBricks[i][j] = new Brick(Colors.RED, newPosX, newPosY, Scales.BRICK, Type.EXPLOSIVE);
} else {
mBricks[i][j] = new Brick(Colors.GRAY, newPosX, newPosY, Scales.BRICK, Type.HARD);
}
} else {
mBricks[i][j] = new Brick(Colors.WHITE, newPosX, newPosY, Scales.BRICK, Type.NORMAL);
}
// The position of the next brick on the same line should be on the right side of the last brick
newPosX += mBricks[i][j].getSizeX() + Config.SPACE_BETWEEN_BRICKS;
}
// Finished filling a line of bricks, resetting to initial X position so we can do the same on the next line
newPosX = initialX;
// Same as the X position, put the next line of bricks on bottom of the last one
newPosY += mBricks[i][0].getSizeY() + Config.SPACE_BETWEEN_BRICKS;
}
}
public void drawElements(GL10 gl) {
// Draw ball and paddle elements on surface
mPaddle.draw(gl);
mBall.draw(gl);
// Need to draw each block on surface
for (int i=0; i<mBricks.length; i++) {
for (int j=0; j<mBricks[i].length; j++) {
// Checking if the brick is not destroyed
if (mBricks[i][j] != null) {
mBricks[i][j].draw(gl);
}
}
}
// Initialize explosives
for (int i = 0; i < mExplosions.size(); i++) {
mExplosions.get(i).draw(gl);
}
}
private void updateBrickExplosion() {
for (int i = 0; i < mExplosions.size(); i++) {
Explosion explosion = mExplosions.get(i);
if (explosion.isAlive()) {
explosion.update2();
}
}
}
public void updatePaddlePosX(float x) {
/* We need to update Paddle position from touch, but we can't access touch updates
* directly from TouchSurfaceView, so create a wrapper and call it a day. */
mPaddle.setPosX(x);
}
private float calcReflectedAngle(float x2, float x1) {
return Constants.ANGLE_OF_REFLECTION_BOUND * (x2 - x1)/(mPaddle.getWidth()/2);
}
public void updateState(float deltaTime) {
/* If the game is over, stop updating state (so we don't have unwanted
* events after the game is over) and freeze the last frame so user can see
* what happened. */
if(!State.getGameOver()) {
/* The frame rate can be variable, so instead of using a fixed ball speed we
* actually compensate the ball speed: if the FPS is less than 60FPS, we
* increase the speed of the ball. */
mBall.setBallSpeed(deltaTime);
float reflectedAngle = 0.0f, angleOfBallSlope = 0.0f;
Collision collisionType = detectCollision();
switch (collisionType) {
case WALL_RIGHT_LEFT_SIDE:
/* Wall hit collision is almost the same, but the equation is different so we
* need to differentiate here */
Log.d(TAG, "Right/Left side collision detected");
Log.d(TAG, "previous slope: " + mBall.getSlope());
mSoundPool.play(mSoundIds.get("wall_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.RIGHT_LEFT);
Log.d(TAG, "next slope: " + mBall.getSlope());
break;
case WALL_TOP_BOTTOM_SIDE:
Log.d(TAG, "Top/Bottom side collision detected");
Log.d(TAG, "previous slope: " + mBall.getSlope());
mSoundPool.play(mSoundIds.get("wall_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
Log.d(TAG, "next slope: " + mBall.getSlope());
break;
case BRICK_BALL:
// When the user hits a brick, increase the score and multiplier and play the sound effect
State.setScore(Score.BRICK_HIT);
Log.i(TAG, "Score multiplier: " + State.getScoreMultiplier() + " Score: " + State.getScore());
State.setScoreMultiplier(ScoreMultiplier.BRICK_HIT); // Update multiplier for the next brick hit
mSoundPool.play(mSoundIds.get("brick_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
break;
case EX_BRICK_BALL:
// Explosive brick has a different sound effect and score, but the rest is the same
State.setScore(Score.EX_BRICK_HIT);
Log.i(TAG, "Score multiplier: " + State.getScoreMultiplier() + " Score: " + State.getScore());
State.setScoreMultiplier(ScoreMultiplier.BRICK_HIT);
mSoundPool.play(mSoundIds.get("explosive_brick"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
break;
case PADDLE_BALL:
Log.d(TAG, "collided into the top left part of the paddle");
Log.d(TAG, "paddlePosX: " + mPaddle.getPosX());
State.setScoreMultiplier(ScoreMultiplier.PADDLE_HIT);
mSoundPool.play(mSoundIds.get("paddle_hit"), 100, 100, 1, 0, 1.0f);
if (mPaddle.getPosX() >= mBall.getPosX()) { //the ball hit the paddle in the right half-part.
reflectedAngle = calcReflectedAngle(mBall.getPosX(), mPaddle.getPosX());
angleOfBallSlope = (Constants.RIGHT_ANGLE - reflectedAngle);
} else { //the ball hit the paddle in the left half-part.
reflectedAngle = calcReflectedAngle(mPaddle.getPosX(), mBall.getPosX());
/* Besides being the complement, the angle of the slope is the negative complement,
* since the ball is going to the left. */
angleOfBallSlope = -1 * (Constants.RIGHT_ANGLE - reflectedAngle);
}
mBall.turnByAngle(angleOfBallSlope);
break;
case LIFE_LOST:
State.setLives(Lives.LOST_LIFE);
mSoundPool.play(mSoundIds.get("lost_life"), 100, 100, 1, 0, 1.0f);
// If the user still has lives left, create a new ball and reset score multiplier
if (!State.getGameOver()) {
mBall = new Ball(Colors.WHITE, Config.BALL_INITIAL_POS_X, Config.BALL_INITIAL_POS_Y,
Scales.BALL, sBallSpeed);
State.setScoreMultiplier(ScoreMultiplier.LOST_LIFE);
}
break;
case NOT_AVAILABLE:
// Nothing to do here
break;
default:
Log.e(TAG, "Invalid collision");
break;
}
updateBrickExplosion();
moveMobileBricks();
mBall.move();
}
}
private void moveMobileBricks() {
for (int a = 0; a < mMobileBricks.size(); a++) {
Log.d(TAG, "going to call move, brick: ["+mMobileBricks.get(a).getIndexI()+"]["+mMobileBricks.get(a).getIndexJ()+"]");
mMobileBricks.get(a).move();
}
}
private void explosiveBrick(int i, int j) {
// Deleting surrounding bricks
for (int a=Math.max(i-1, 0); a< Math.min(i+2, mBricks.length); a++) {
for (int b=Math.max(j-1, 0); b<Math.min(j+2, mBricks[i].length); b++) {
if (mBricks[a][b] != null) {
if (mBricks[a][b].getLives() == 0) {
mBricks[a][b] = null; // Deleting brick
State.setScore(Score.BRICK_HIT); // And add brick to score
}
else {
decrementBrickLife(a, b);
}
}
}
}
}
private void decrementBrickLife(int i, int j) {
mBricks[i][j].decrementLives();
if (mBricks[i][j].getType() == Type.HARD) {
mBricks[i][j].setColor(Colors.WHITE);
}
}
private void detectCollisionOfMobileBricks() {
for (int a = 0; a < mMobileBricks.size(); a++) {
boolean collided = false;
MobileBrick mBrick = mMobileBricks.get(a);
int i = mBrick.getIndexI();
int j = mBrick.getIndexJ();
for (int x = 0; x < Config.NUMBER_OF_COLUMNS_OF_BRICKS; x++) {
if (x != j) {
Brick brick = mBricks[i][x];
if ((brick != null) && (mBrick.detectCollisionWithBrick(brick))) {
Log.d(TAG, "going to call invert, brick: ["+i+"]["+j+"]");
mBrick.invertDirection();
collided = true;
break;
}
}
}
if (!collided && mBrick.detectCollisionWithWall()) {
mBrick.invertDirection();
}
}
}
private Collision detectCollision() {
detectCollisionOfMobileBricks();
// Detecting collision between ball and wall
if ((mBall.getRightX() >= sScreenHigherX) //collided in the right wall
|| (mBall.getLeftX() <= sScreenLowerX)) //collided in the left wall
{
return Collision.WALL_RIGHT_LEFT_SIDE;
} else if ((mBall.getTopY() >= sScreenHigherY) //collided in the top wall
|| (mBall.getBottomY() <= sScreenLowerY) //collided in the bottom wall...
&& sInvincibility) //and invincibility is on
{
return Collision.WALL_TOP_BOTTOM_SIDE;
} else if (mBall.getBottomY() <= sScreenLowerY //if invincibility is off and the ball
&& !sInvincibility) //collided with bottom wall, user loses a life
{
return Collision.LIFE_LOST;
}
//detecting collision between the ball and the paddle
if (mBall.getTopY() >= mPaddle.getBottomY() && mBall.getBottomY() <= mPaddle.getTopY() &&
mBall.getRightX() >= mPaddle.getLeftX() && mBall.getLeftX() <= mPaddle.getRightX())
{
return Collision.PADDLE_BALL;
}
// If the game is finished, there should be no bricks left
boolean gameFinish = true;
for (int i=0; i<mBricks.length; i++) {
for (int j=0; j<mBricks[i].length; j++) {
// Check if the brick is not destroyed yet
if(mBricks[i][j] != null) {
// If there are still bricks, the game is not over yet
gameFinish = false;
// Detecting collision between the ball and the bricks
if (mBall.getTopY() >= mBricks[i][j].getBottomY()
&& mBall.getBottomY() <= mBricks[i][j].getTopY()
&& mBall.getRightX() >= mBricks[i][j].getLeftX()
&& mBall.getLeftX() <= mBricks[i][j].getRightX()
)
{
Log.d(TAG, "Detected collision between ball and brick[" + i + "][" + j + "]");
/* Since the update happens so fast (on each draw frame) we can update the brick
* state on the next frame. */
if (mBricks[i][j].getLives() == 0) {
if (mBricks[i][j].getType() == Type.EXPLOSIVE) {
Log.d(TAG, "inserted explosion");
mExplosions.add(new Explosion
(Brick.GRAY_EXPLOSION_SIZE, mBricks[i][j].getPosX(), mBricks[i][j].getPosY()));
// Explosive brick is a special type of collision, treat this case
explosiveBrick(i, j);
return Collision.EX_BRICK_BALL;
} else if (mBricks[i][j].getType() == Type.MOBILE){
deleteMobileBrick(i, j);
}
mBricks[i][j] = null; // Deleting brick
} else {
decrementBrickLife(i, j);
}
return Collision.BRICK_BALL;
}
}
}
}
// If there is no more blocks, the game is over
State.setGameOver(gameFinish);
return Collision.NOT_AVAILABLE;
}
public void deleteMobileBrick(int i, int j) {
for (int a = 0; a < mMobileBricks.size(); a++) {
if (mMobileBricks.get(a).equal(i, j)) {
mMobileBricks.remove(a);
return;
}
}
}
public void updateScreenMeasures(float screenWidth, float screenHeight) {
/* Calculate the new screen measure. This is important since we need to delimit a wall
* to the ball. */
sScreenLowerX = SCREEN_INITIAL_X - screenWidth/2;
sScreenHigherX = SCREEN_INITIAL_X + screenWidth/2;
sScreenLowerY = SCREEN_INITIAL_Y - screenHeight/2;
sScreenHigherY = SCREEN_INITIAL_Y + screenHeight/2;
Log.i(TAG, "screenWidth: " + screenWidth + ", screenHeight: " + screenHeight);
Log.i(TAG, "Screen limits =>" + " -X: " + sScreenLowerX + " +X: " + sScreenHigherX +
" -Y: " + sScreenLowerY + " +Y: " + sScreenHigherY
);
}
/**
* Represents the game state, like the actual game score and multiplier, number of lives and
* if the game is over or not.
*
* This class should be static since we need to access these informations outside the game object,
* like on UI activity.
*/
public static class State {
private static long sScore;
private static int sScoreMultiplier;
private static int sLives;
private static boolean sGameOver;
public static void setScore (Score event) {
switch(event) {
case BRICK_HIT:
sScore += Game.sHitScore * getScoreMultiplier();
break;
case RESTART_LEVEL:
sScore = 0;
break;
case EX_BRICK_HIT:
sScore += Game.sHitScore * 2 * getScoreMultiplier();
break;
}
}
public static void setScoreMultiplier(ScoreMultiplier event) {
switch(event) {
case RESTART_LEVEL:
case LOST_LIFE:
sScoreMultiplier = 1;
break;
case BRICK_HIT:
if (sScoreMultiplier < Game.sScoreMultiplier) {
sScoreMultiplier *= 2;
}
break;
case PADDLE_HIT:
if (sScoreMultiplier > 1) {
sScoreMultiplier /= 2;
}
break;
}
}
public static void setLives(Lives event) {
switch(event) {
case RESTART_LEVEL:
sGameOver = false;
sLives = Game.sLifeCount;
break;
case LOST_LIFE:
if (sLives > 0) {
sLives
} else {
sGameOver = true;
}
break;
}
}
public static void setGameOver(boolean gameIsOver) {
sGameOver = gameIsOver;
}
public static boolean getGameOver() {
return sGameOver;
}
public static long getScore() {
return sScore;
}
public static int getScoreMultiplier() {
return sScoreMultiplier;
}
public static int getLifes() {
return sLives;
}
}
}
|
package br.usp.ime.ep2;
import javax.microedition.khronos.opengles.GL10;
import br.usp.ime.ep2.Constants.Colors;
import br.usp.ime.ep2.forms.Ball;
import br.usp.ime.ep2.forms.Brick;
import br.usp.ime.ep2.forms.Paddle;
import android.util.Log;
public class Game {
private static final String TAG = Game.class.getSimpleName();
private static final int MS_PER_SECONDS = 1000 /* milliseconds */;
private static final int NANOS_PER_SECONDS = 1000 /* nanoseconds */ * MS_PER_SECONDS;
private static final double MS_PER_FRAME = (1.0/60.0) * MS_PER_SECONDS; // 60 FPS
private static final int WALL_RIGHT_LEFT_SIDE = 1;
private static final int WALL_TOP_BOTTOM_SIDE = 2;
private static final int SCREEN_INITIAL_X = 0;
private static final int SCREEN_INITIAL_Y = 0;
private float SCREEN_HIGHER_Y;
private float SCREEN_LOWER_Y;
private float SCREEN_HIGHER_X;
private float SCREEN_LOWER_X;
private long mPrevCurrentBeginFrameTime;
private int mFramesWithoutBallMov;
private Paddle mPaddle;
private Ball mBall;
private Brick[][] mBlocks;
public Game() {
SCREEN_HIGHER_Y = 1.0f;
SCREEN_LOWER_Y = -1.0f;
SCREEN_HIGHER_X = 1.0f;
SCREEN_LOWER_X = -1.0f;
resetElements();
}
public void resetElements() {
mPrevCurrentBeginFrameTime = 0;
mPaddle = new Paddle(Colors.RAINBOW, 0.0f, -0.7f, 0.1f);
mBall = new Ball(Colors.RAINBOW, 0.0f, 0.0f, -0.05f, -0.05f, 0.1f, 1, 0.01f);
createLevel(Colors.RAINBOW, 8, 12, -0.55f, 0.7f, 0.1f, 0.04f);
mFramesWithoutBallMov = mBall.getSpeed();
}
private void createLevel (float[] colors,int blocksX, int blocksY, float initialX, float initialY,
float spaceX, float spaceY)
{
mBlocks = new Brick[blocksX][blocksY];
float newPosX = initialX;
float newPosY = initialY;
for (int i=0; i<mBlocks.length; i++) {
for (int j=0; j<mBlocks[i].length; j++) {
mBlocks[i][j] = new Brick(colors, newPosX, newPosY, 0.1f);
newPosX += spaceX;
}
newPosX = initialX;
newPosY -= spaceY;
}
}
public void drawElements(GL10 gl) {
mPaddle.draw(gl);
mBall.draw(gl);
// Need to draw each block on surface
for (int i=0; i<mBlocks.length; i++) {
for (int j=0; j<mBlocks[i].length; j++) {
mBlocks[i][j].draw(gl);
}
}
}
public void updatePaddleXPosition(float x) {
mPaddle.setXPosition(x);
}
//Update next frame state
public void updateState() {
if (mPrevCurrentBeginFrameTime == 0) {
mPrevCurrentBeginFrameTime = System.nanoTime();
}
long currentTime = System.nanoTime();
double elapsedFrameTime = (currentTime - mPrevCurrentBeginFrameTime)/NANOS_PER_SECONDS;
if (elapsedFrameTime < MS_PER_FRAME) { //it doesn't reach next frame yet
Log.v(TAG, "Frame rendering faster than " + MS_PER_FRAME + ", skipping this frame");
return;
}
//Now it's time to update next frame.
int collisionType = detectColision();
//I'm considering the ball is being updated in a different rate compared to the frame update rate.
if (mFramesWithoutBallMov == 0) {
switch (collisionType) {
case WALL_RIGHT_LEFT_SIDE:
mBall.turnToPerpendicularDirection(true);
break;
case WALL_TOP_BOTTOM_SIDE:
mBall.turnToPerpendicularDirection(false);
break;
}
//Log.i(TAG, "time to move the ball");
mBall.move();
mFramesWithoutBallMov = mBall.getSpeed();
}
mFramesWithoutBallMov
mPrevCurrentBeginFrameTime = currentTime;
}
private int detectColision() {
float ballPosX = mBall.getPosX();
float ballPosY = mBall.getPosY();
//detecting collision between ball and wall
if ((ballPosX > SCREEN_HIGHER_X) //collided in the right side
|| (ballPosX < SCREEN_LOWER_X)) { //collided in the left side
return WALL_RIGHT_LEFT_SIDE;
} else if ((ballPosY > SCREEN_HIGHER_Y) //collided in the top part
|| (ballPosY < SCREEN_LOWER_Y)) { //collided in the bottom part
return WALL_TOP_BOTTOM_SIDE;
}
//detecting collision between the ball and the paddle
float paddleTopY = mPaddle.getPosY() + Paddle.VERTICES[3];
float paddleLeftX = mPaddle.getPosX() + Paddle.VERTICES[0];
float paddleRightX = mPaddle.getPosX() + Paddle.VERTICES[4];
float ballBottomY = ballPosY + Ball.VERTICES[1];
float ballLeftX = ballPosX + Ball.VERTICES[0];
float ballRightX = ballPosX + Ball.VERTICES[4];
// if ((ballBottomY <= paddleTopY)
// && (ballRightX))
return -1;
}
public void updateScreenMeasures(float screenWidth, float screenHeight) {
Log.i(TAG, "screenWidth: "+screenWidth+", screenHeight: "+screenHeight);
SCREEN_LOWER_X = SCREEN_INITIAL_X - screenWidth/2;
SCREEN_HIGHER_X = SCREEN_INITIAL_X + screenWidth/2;
SCREEN_LOWER_Y = SCREEN_INITIAL_Y - screenHeight/2;
SCREEN_HIGHER_Y = SCREEN_INITIAL_Y + screenHeight/2;
}
}
|
package net.dlogic.kryonet.common.entity;
import java.util.ArrayList;
import java.util.List;
public class Room {
private int id;
private String name;
private List<User> userList;
public Room() {
userList = new ArrayList<User>();
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public boolean addUser(User user) {
return userList.add(user);
}
public boolean removeUser(User user) {
return userList.remove(user);
}
public boolean containsUser(User user) {
return userList.contains(user);
}
}
|
package net.java.otr4j.crypto;
import java.math.BigInteger;
public interface CryptoConstants {
public static String MODULUS_TEXT = "00FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF";
public static BigInteger MODULUS = new BigInteger(MODULUS_TEXT, 16);
public static BigInteger BIGINTEGER_TWO = BigInteger.valueOf(2);
public static BigInteger MODULUS_MINUS_TWO = MODULUS.subtract(BIGINTEGER_TWO);
public static String GENERATOR_TEXT = "2";
public static BigInteger GENERATOR = new BigInteger(GENERATOR_TEXT, 10);
public static final int AES_KEY_BYTE_LENGTH = 16;
public static final int SHA256_HMAC_KEY_BYTE_LENGTH = 32;
public static final int DH_PRIVATE_KEY_MINIMUM_BIT_LENGTH = 320;
public static byte[] ZERO_CTR = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static byte[] DSA_PUB_TYPE = new byte[] { 0x00, 0x00 };
public static byte SSID_START = (byte) 0x00;
public static byte C_START = (byte) 0x01;
public static byte M1_START = (byte) 0x02;
public static byte M2_START = (byte) 0x03;
public static byte M1p_START = (byte) 0x04;
public static byte M2p_START = (byte) 0x05;
public static int SSID_LENGTH = 8;
}
|
package org.anddev.andengine.entity.text;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.entity.HorizontalAlign;
import org.anddev.andengine.entity.primitives.RectangularShape;
import org.anddev.andengine.opengl.GLHelper;
import org.anddev.andengine.opengl.buffer.BaseBuffer;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.buffer.TextTextureBuffer;
import org.anddev.andengine.opengl.vertex.TextVertexBuffer;
import org.anddev.andengine.util.StringUtils;
/**
* @author Nicolas Gramlich
* @since 10:54:59 - 03.04.2010
*/
public class Text extends RectangularShape {
// Constants
// Fields
protected final int mVertexCount;
private final TextTextureBuffer mTextTextureBuffer;
private final String mText;
private final String[] mLines;
private final int[] mWidths;
private final Font mFont;
private final int mMaximumLineWidth;
protected final int mCharacterCount;
// Constructors
public Text(final float pX, final float pY, final Font pFont, final String pText) {
this(pX, pY, pFont, pText, HorizontalAlign.LEFT);
}
public Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign) {
super(pX, pY, 0, 0, new TextVertexBuffer(pText, pHorizontalAlign, GL11.GL_STATIC_DRAW));
this.mCharacterCount = pText.length() - StringUtils.countOccurences(pText, "\n");
this.mVertexCount = TextVertexBuffer.VERTICES_PER_CHARACTER * this.mCharacterCount;
this.mTextTextureBuffer = new TextTextureBuffer(2 * this.mVertexCount * BaseBuffer.BYTES_PER_FLOAT, GL11.GL_STATIC_DRAW);
BufferObjectManager.loadBufferObject(this.mTextTextureBuffer); // TODO Unload irgendwann oder so...
this.mFont = pFont;
this.mText = pText;
/* Init Metrics. */
{
this.mLines = this.mText.split("\n");
final String[] lines = this.mLines;
final int lineCount = lines.length;
this.mWidths = new int[lineCount];
final int[] widths = this.mWidths;
int maximumLineWidth = 0;
for (int i = lineCount - 1; i >= 0; i
widths[i] = pFont.getStringWidth(lines[i]);
maximumLineWidth = Math.max(maximumLineWidth, widths[i]);
}
this.mMaximumLineWidth = maximumLineWidth;
super.mWidth = this.mMaximumLineWidth;
super.mBaseWidth = super.mWidth;
super.mHeight = lineCount * this.mFont.getLineHeight() + (lineCount - 1) * this.mFont.getLineGap();
super.mBaseHeight = super.mHeight;
}
this.mTextTextureBuffer.update(this.mFont, this.mLines);
this.updateVertexBuffer();
}
// Getter & Setter
public int getCharacterCount() {
return this.mCharacterCount;
}
@Override
public TextVertexBuffer getVertexBuffer() {
return (TextVertexBuffer)super.getVertexBuffer();
}
// Methods for/from SuperClass/Interfaces
@Override
protected void onInitDraw(final GL10 pGL) {
super.onInitDraw(pGL);
GLHelper.enableTextures(pGL);
GLHelper.enableTexCoordArray(pGL);
}
@Override
protected void drawVertices(final GL10 pGL) {
pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertexCount);
}
@Override
protected void onUpdateVertexBuffer() {
final Font font = this.mFont;
if(font != null) {
this.getVertexBuffer().update(this.mFont, this.mMaximumLineWidth, this.mWidths, this.mLines);
}
}
@Override
protected void onPostTransformations(final GL10 pGL) {
super.onPostTransformations(pGL);
this.applyTexture(pGL);
}
// Methods
private void applyTexture(final GL10 pGL) {
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
final GL11 gl11 = (GL11)pGL;
this.mTextTextureBuffer.selectOnHardware(gl11);
GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID());
GLHelper.texCoordZeroPointer(gl11);
} else {
GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID());
GLHelper.texCoordPointer(pGL, this.mTextTextureBuffer.getFloatBuffer());
}
}
// Inner and Anonymous Classes
}
|
package com.jme3.scene;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.material.Material;
import com.jme3.math.Matrix4f;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.util.IntMap.Entry;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BatchNode holds geometrie that are batched version of all geometries that are in its sub scenegraph.
* There is one geometry per different material in the sub tree.
* this geometries are directly attached to the node in the scene graph.
* usage is like any other node except you have to call the {@link #batch()} method once all geoms have been attached to the sub scene graph and theire material set
* (see todo more automagic for further enhancements)
* all the geometry that have been batched are set to {@link CullHint#Always} to not render them.
* the sub geometries can be transformed as usual their transforms are used to update the mesh of the geometryBatch.
* sub geoms can be removed but it may be slower than the normal spatial removing
* Sub geoms can be added after the batch() method has been called but won't be batched and will be rendered as normal geometries.
* To integrate them in the batch you have to call the batch() method again on the batchNode.
*
* TODO normal or tangents or both looks a bit weird
* TODO more automagic (batch when needed in the updateLigicalState)
* @author Nehon
*/
public class BatchNode extends Node implements Savable {
private static final Logger logger = Logger.getLogger(BatchNode.class.getName());
/**
* the map of geometry holding the batched meshes
*/
protected Map<Material, Batch> batches = new HashMap<Material, Batch>();
/**
* used to store transformed vectors before proceeding to a bulk put into the FloatBuffer
*/
private float[] tmpFloat;
private float[] tmpFloatN;
private float[] tmpFloatT;
/**
* Construct a batchNode
*/
public BatchNode() {
super();
}
public BatchNode(String name) {
super(name);
}
@Override
public void updateGeometricState() {
if ((refreshFlags & RF_LIGHTLIST) != 0) {
updateWorldLightList();
}
if ((refreshFlags & RF_TRANSFORM) != 0) {
// combine with parent transforms- same for all spatial
// subclasses.
updateWorldTransforms();
}
if (!children.isEmpty()) {
// the important part- make sure child geometric state is refreshed
// first before updating own world bound. This saves
// a round-trip later on.
// NOTE 9/19/09
// Although it does save a round trip,
for (Spatial child : children.getArray()) {
child.updateGeometricState();
}
for (Batch batch : batches.values()) {
if (batch.needMeshUpdate) {
batch.geometry.getMesh().updateBound();
batch.geometry.updateWorldBound();
batch.needMeshUpdate = false;
}
}
}
if ((refreshFlags & RF_BOUND) != 0) {
updateWorldBound();
}
assert refreshFlags == 0;
}
protected Transform getTransforms(Geometry geom) {
return geom.getWorldTransform();
}
protected void updateSubBatch(Geometry bg) {
Batch batch = batches.get(bg.getMaterial());
if (batch != null) {
Mesh mesh = batch.geometry.getMesh();
VertexBuffer pvb = mesh.getBuffer(VertexBuffer.Type.Position);
FloatBuffer posBuf = (FloatBuffer) pvb.getData();
VertexBuffer nvb = mesh.getBuffer(VertexBuffer.Type.Normal);
FloatBuffer normBuf = (FloatBuffer) nvb.getData();
if (mesh.getBuffer(VertexBuffer.Type.Tangent) != null) {
VertexBuffer tvb = mesh.getBuffer(VertexBuffer.Type.Tangent);
FloatBuffer tanBuf = (FloatBuffer) tvb.getData();
doTransformsTangents(posBuf, normBuf, tanBuf, bg.startIndex, bg.startIndex + bg.getVertexCount(), bg.cachedOffsetMat);
tvb.updateData(tanBuf);
} else {
doTransforms(posBuf, normBuf, bg.startIndex, bg.startIndex + bg.getVertexCount(), bg.cachedOffsetMat);
}
pvb.updateData(posBuf);
nvb.updateData(normBuf);
batch.needMeshUpdate = true;
}
}
/**
* Batch this batchNode
* every geometry of the sub scene graph of this node will be batched into a single mesh that will be rendered in one call
*/
public void batch() {
doBatch();
//we set the batch geometries to ignore transforms to avoid transforms of parent nodes to be applied twice
for (Batch batch : batches.values()) {
batch.geometry.setIgnoreTransform(true);
}
}
protected void doBatch() {
///List<Geometry> tmpList = new ArrayList<Geometry>();
Map<Material, List<Geometry>> matMap = new HashMap<Material, List<Geometry>>();
gatherGeomerties(matMap, this);
batches.clear();
int nbGeoms = 0;
for (Material material : matMap.keySet()) {
Mesh m = new Mesh();
List<Geometry> list = matMap.get(material);
nbGeoms += list.size();
mergeGeometries(m, list);
m.setDynamic();
Batch batch = new Batch();
batch.geometry = new Geometry(name + "-batch" + batches.size());
batch.geometry.setMaterial(material);
this.attachChild(batch.geometry);
batch.geometry.setMesh(m);
batch.geometry.getMesh().updateCounts();
batch.geometry.getMesh().updateBound();
batches.put(material, batch);
}
logger.log(Level.INFO, "Batched {0} geometries in {1} batches.", new Object[]{nbGeoms, batches.size()});
}
private void gatherGeomerties(Map<Material, List<Geometry>> map, Spatial n) {
if (n.getClass() == Geometry.class) {
if (!isBatch(n) && n.getBatchHint() != BatchHint.Never) {
Geometry g = (Geometry) n;
if (g.getMaterial() == null) {
throw new IllegalStateException("No material is set for Geometry: " + g.getName() + " please set a material before batching");
}
List<Geometry> list = map.get(g.getMaterial());
if (list == null) {
list = new ArrayList<Geometry>();
map.put(g.getMaterial(), list);
}
list.add(g);
}
} else if (n instanceof Node) {
for (Spatial child : ((Node) n).getChildren()) {
if (child instanceof BatchNode) {
continue;
}
gatherGeomerties(map, child);
}
}
}
private boolean isBatch(Spatial s) {
for (Batch batch : batches.values()) {
if (batch.geometry == s) {
return true;
}
}
return false;
}
/**
* Sets the material to the all the batches of this BatchNode
* use setMaterial(Material material,int batchIndex) to set a material to a specific batch
*
* @param material the material to use for this geometry
*/
@Override
public void setMaterial(Material material) {
// for (Batch batch : batches.values()) {
// batch.geometry.setMaterial(material);
throw new UnsupportedOperationException("Unsupported for now, please set the material on the geoms before batching");
}
/**
* Returns the material that is used for the first batch of this BatchNode
*
* use getMaterial(Material material,int batchIndex) to get a material from a specific batch
*
* @return the material that is used for the first batch of this BatchNode
*
* @see #setMaterial(com.jme3.material.Material)
*/
public Material getMaterial() {
if (!batches.isEmpty()) {
Batch b = batches.get(batches.keySet().iterator().next());
return b.geometry.getMaterial();
}
return null;//material;
}
// /**
// * Sets the material to the a specific batch of this BatchNode
// *
// *
// * @param material the material to use for this geometry
// */
// public void setMaterial(Material material,int batchIndex) {
// if (!batches.isEmpty()) {
// /**
// * Returns the material that is used for the first batch of this BatchNode
// *
// * use getMaterial(Material material,int batchIndex) to get a material from a specific batch
// *
// * @return the material that is used for the first batch of this BatchNode
// *
// * @see #setMaterial(com.jme3.material.Material)
// */
// public Material getMaterial(int batchIndex) {
// if (!batches.isEmpty()) {
// Batch b = batches.get(batches.keySet().iterator().next());
// return b.geometry.getMaterial();
// return null;//material;
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
// if (material != null) {
// oc.write(material.getAssetName(), "materialName", null);
// oc.write(material, "material", null);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
// material = null;
// String matName = ic.readString("materialName", null);
// if (matName != null) {
// // Material name is set,
// // Attempt to load material via J3M
// try {
// material = im.getAssetManager().loadMaterial(matName);
// } catch (AssetNotFoundException ex) {
// // Cannot find J3M file.
// logger.log(Level.FINE, "Could not load J3M file {0} for Geometry.",
// matName);
// // If material is NULL, try to load it from the geometry
// if (material == null) {
// material = (Material) ic.readSavable("material", null);
}
/**
* Merges all geometries in the collection into
* the output mesh. Does not take into account materials.
*
* @param geometries
* @param outMesh
*/
private void mergeGeometries(Mesh outMesh, List<Geometry> geometries) {
int[] compsForBuf = new int[VertexBuffer.Type.values().length];
VertexBuffer.Format[] formatForBuf = new VertexBuffer.Format[compsForBuf.length];
int totalVerts = 0;
int totalTris = 0;
int totalLodLevels = 0;
int maxVertCount = 0;
Mesh.Mode mode = null;
for (Geometry geom : geometries) {
totalVerts += geom.getVertexCount();
totalTris += geom.getTriangleCount();
totalLodLevels = Math.min(totalLodLevels, geom.getMesh().getNumLodLevels());
if (maxVertCount < geom.getVertexCount()) {
maxVertCount = geom.getVertexCount();
}
Mesh.Mode listMode;
int components;
switch (geom.getMesh().getMode()) {
case Points:
listMode = Mesh.Mode.Points;
components = 1;
break;
case LineLoop:
case LineStrip:
case Lines:
listMode = Mesh.Mode.Lines;
components = 2;
break;
case TriangleFan:
case TriangleStrip:
case Triangles:
listMode = Mesh.Mode.Triangles;
components = 3;
break;
default:
throw new UnsupportedOperationException();
}
for (Entry<VertexBuffer> entry : geom.getMesh().getBuffers()) {
compsForBuf[entry.getKey()] = entry.getValue().getNumComponents();
formatForBuf[entry.getKey()] = entry.getValue().getFormat();
}
if (mode != null && mode != listMode) {
throw new UnsupportedOperationException("Cannot combine different"
+ " primitive types: " + mode + " != " + listMode);
}
mode = listMode;
compsForBuf[VertexBuffer.Type.Index.ordinal()] = components;
}
outMesh.setMode(mode);
if (totalVerts >= 65536) {
// make sure we create an UnsignedInt buffer so
// we can fit all of the meshes
formatForBuf[VertexBuffer.Type.Index.ordinal()] = VertexBuffer.Format.UnsignedInt;
} else {
formatForBuf[VertexBuffer.Type.Index.ordinal()] = VertexBuffer.Format.UnsignedShort;
}
// generate output buffers based on retrieved info
for (int i = 0; i < compsForBuf.length; i++) {
if (compsForBuf[i] == 0) {
continue;
}
Buffer data;
if (i == VertexBuffer.Type.Index.ordinal()) {
data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalTris);
} else {
data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalVerts);
}
VertexBuffer vb = new VertexBuffer(VertexBuffer.Type.values()[i]);
vb.setupData(VertexBuffer.Usage.Dynamic, compsForBuf[i], formatForBuf[i], data);
outMesh.setBuffer(vb);
}
int globalVertIndex = 0;
int globalTriIndex = 0;
for (Geometry geom : geometries) {
Mesh inMesh = geom.getMesh();
geom.batch(this, globalVertIndex);
int geomVertCount = inMesh.getVertexCount();
int geomTriCount = inMesh.getTriangleCount();
for (int bufType = 0; bufType < compsForBuf.length; bufType++) {
VertexBuffer inBuf = inMesh.getBuffer(VertexBuffer.Type.values()[bufType]);
VertexBuffer outBuf = outMesh.getBuffer(VertexBuffer.Type.values()[bufType]);
if (outBuf == null) {
continue;
}
if (VertexBuffer.Type.Index.ordinal() == bufType) {
int components = compsForBuf[bufType];
IndexBuffer inIdx = inMesh.getIndicesAsList();
IndexBuffer outIdx = outMesh.getIndexBuffer();
for (int tri = 0; tri < geomTriCount; tri++) {
for (int comp = 0; comp < components; comp++) {
int idx = inIdx.get(tri * components + comp) + globalVertIndex;
outIdx.put((globalTriIndex + tri) * components + comp, idx);
}
}
} else if (VertexBuffer.Type.Position.ordinal() == bufType) {
FloatBuffer inPos = (FloatBuffer) inBuf.getData();
FloatBuffer outPos = (FloatBuffer) outBuf.getData();
doCopyBuffer(inPos, globalVertIndex, outPos);
} else if (VertexBuffer.Type.Normal.ordinal() == bufType || VertexBuffer.Type.Tangent.ordinal() == bufType) {
FloatBuffer inPos = (FloatBuffer) inBuf.getData();
FloatBuffer outPos = (FloatBuffer) outBuf.getData();
doCopyBuffer(inPos, globalVertIndex, outPos);
} else {
for (int vert = 0; vert < geomVertCount; vert++) {
int curGlobalVertIndex = globalVertIndex + vert;
inBuf.copyElement(vert, outBuf, curGlobalVertIndex);
}
}
}
globalVertIndex += geomVertCount;
globalTriIndex += geomTriCount;
}
tmpFloat = new float[maxVertCount * 3];
tmpFloatN = new float[maxVertCount * 3];
tmpFloatT = new float[maxVertCount * 4];
}
private void doTransforms(FloatBuffer bufPos, FloatBuffer bufNorm, int start, int end, Matrix4f transform) {
TempVars vars = TempVars.get();
Vector3f pos = vars.vect1;
Vector3f norm = vars.vect2;
int length = (end - start) * 3;
// offset is given in element units
// convert to be in component units
int offset = start * 3;
bufPos.position(offset);
bufNorm.position(offset);
bufPos.get(tmpFloat, 0, length);
bufNorm.get(tmpFloatN, 0, length);
int index = 0;
while (index < length) {
pos.x = tmpFloat[index];
norm.x = tmpFloatN[index++];
pos.y = tmpFloat[index];
norm.y = tmpFloatN[index++];
pos.z = tmpFloat[index];
norm.z = tmpFloatN[index];
transform.mult(pos, pos);
transform.multNormal(norm, norm);
index -= 2;
tmpFloat[index] = pos.x;
tmpFloatN[index++] = norm.x;
tmpFloat[index] = pos.y;
tmpFloatN[index++] = norm.y;
tmpFloat[index] = pos.z;
tmpFloatN[index++] = norm.z;
}
vars.release();
bufPos.position(offset);
//using bulk put as it's faster
bufPos.put(tmpFloat, 0, length);
bufNorm.position(offset);
//using bulk put as it's faster
bufNorm.put(tmpFloatN, 0, length);
}
private void doTransformsTangents(FloatBuffer bufPos, FloatBuffer bufNorm, FloatBuffer bufTangents, int start, int end, Matrix4f transform) {
TempVars vars = TempVars.get();
Vector3f pos = vars.vect1;
Vector3f norm = vars.vect2;
Vector3f tan = vars.vect3;
int length = (end - start) * 3;
int tanLength = (end - start) * 4;
// offset is given in element units
// convert to be in component units
int offset = start * 3;
int tanOffset = start * 4;
bufPos.position(offset);
bufNorm.position(offset);
bufTangents.position(tanOffset);
bufPos.get(tmpFloat, 0, length);
bufNorm.get(tmpFloatN, 0, length);
bufTangents.get(tmpFloatT, 0, tanLength);
int index = 0;
int tanIndex = 0;
while (index < length) {
pos.x = tmpFloat[index];
norm.x = tmpFloatN[index++];
pos.y = tmpFloat[index];
norm.y = tmpFloatN[index++];
pos.z = tmpFloat[index];
norm.z = tmpFloatN[index];
tan.x = tmpFloatT[tanIndex++];
tan.y = tmpFloatT[tanIndex++];
tan.z = tmpFloatT[tanIndex++];
transform.mult(pos, pos);
transform.multNormal(norm, norm);
transform.multNormal(tan, tan);
index -= 2;
tanIndex -= 3;
tmpFloat[index] = pos.x;
tmpFloatN[index++] = norm.x;
tmpFloat[index] = pos.y;
tmpFloatN[index++] = norm.y;
tmpFloat[index] = pos.z;
tmpFloatN[index++] = norm.z;
tmpFloatT[tanIndex++] = tan.x;
tmpFloatT[tanIndex++] = tan.y;
tmpFloatT[tanIndex++] = tan.z;
tanIndex++;
}
vars.release();
bufPos.position(offset);
//using bulk put as it's faster
bufPos.put(tmpFloat, 0, length);
bufNorm.position(offset);
//using bulk put as it's faster
bufNorm.put(tmpFloatN, 0, length);
bufTangents.position(tanOffset);
//using bulk put as it's faster
bufTangents.put(tmpFloatT, 0, tanLength);
}
private void doCopyBuffer(FloatBuffer inBuf, int offset, FloatBuffer outBuf) {
TempVars vars = TempVars.get();
Vector3f pos = vars.vect1;
// offset is given in element units
// convert to be in component units
offset *= 3;
for (int i = 0; i < inBuf.capacity() / 3; i++) {
pos.x = inBuf.get(i * 3 + 0);
pos.y = inBuf.get(i * 3 + 1);
pos.z = inBuf.get(i * 3 + 2);
outBuf.put(offset + i * 3 + 0, pos.x);
outBuf.put(offset + i * 3 + 1, pos.y);
outBuf.put(offset + i * 3 + 2, pos.z);
}
vars.release();
}
protected class Batch {
Geometry geometry;
boolean needMeshUpdate = false;
}
}
|
package org.apache.fop.render.pdf;
// FOP
import org.apache.fop.render.PrintRenderer;
import org.apache.fop.render.RendererContext;
import org.apache.fop.fo.FOUserAgent;
import org.apache.fop.image.FopImage;
import org.apache.fop.image.XMLImage;
import org.apache.fop.image.ImageFactory;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.Version;
import org.apache.fop.fo.properties.RuleStyle;
import org.apache.fop.fo.properties.BackgroundRepeat;
import org.apache.fop.pdf.PDFStream;
import org.apache.fop.pdf.PDFDocument;
import org.apache.fop.pdf.PDFInfo;
import org.apache.fop.pdf.PDFResources;
import org.apache.fop.pdf.PDFXObject;
import org.apache.fop.pdf.PDFPage;
import org.apache.fop.pdf.PDFState;
import org.apache.fop.pdf.PDFLink;
import org.apache.fop.pdf.PDFOutline;
import org.apache.fop.pdf.PDFAnnotList;
import org.apache.fop.pdf.PDFColor;
import org.apache.fop.extensions.BookmarkData;
import org.apache.fop.area.Trait;
import org.apache.fop.area.TreeExt;
import org.apache.fop.area.CTM;
import org.apache.fop.area.Title;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.Page;
import org.apache.fop.area.RegionReference;
import org.apache.fop.area.Area;
import org.apache.fop.area.Block;
import org.apache.fop.area.BlockViewport;
import org.apache.fop.area.LineArea;
import org.apache.fop.area.inline.Character;
import org.apache.fop.area.inline.Word;
import org.apache.fop.area.inline.Viewport;
import org.apache.fop.area.inline.ForeignObject;
import org.apache.fop.area.inline.Image;
import org.apache.fop.area.inline.Leader;
import org.apache.fop.area.inline.InlineParent;
import org.apache.fop.layout.FontState;
import org.apache.fop.layout.FontMetric;
import org.apache.fop.traits.BorderProps;
import org.apache.fop.datatypes.ColorType;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.w3c.dom.Document;
// Java
import java.io.IOException;
import java.io.OutputStream;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/*
todo:
word rendering and optimistion
pdf state optimisation
line and border
background pattern
writing mode
text decoration
*/
/**
* Renderer that renders areas to PDF
*
*/
public class PDFRenderer extends PrintRenderer {
/**
* The mime type for pdf
*/
public static final String MIME_TYPE = "application/pdf";
/**
* the PDF Document being created
*/
protected PDFDocument pdfDoc;
/**
* Map of pages using the PageViewport as the key
* this is used for prepared pages that cannot be immediately
* rendered
*/
protected HashMap pages = null;
/**
* Page references are stored using the PageViewport as the key
* when a reference is made the PageViewport is used
* for pdf this means we need the pdf page reference
*/
protected HashMap pageReferences = new HashMap();
protected HashMap pvReferences = new HashMap();
private String producer;
/**
* The output stream to write the document to
*/
protected OutputStream ostream;
/**
* the /Resources object of the PDF document being created
*/
protected PDFResources pdfResources;
/**
* the current stream to add PDF commands to
*/
protected PDFStream currentStream;
/**
* the current annotation list to add annotations to
*/
protected PDFAnnotList currentAnnotList;
/**
* the current page to add annotations to
*/
protected PDFPage currentPage;
// drawing state
protected PDFState currentState = null;
protected PDFColor currentColor;
protected String currentFontName = "";
protected int currentFontSize = 0;
protected int pageHeight;
protected HashMap filterMap = new HashMap();
/**
* true if a TJ command is left to be written
*/
protected boolean textOpen = false;
/**
* the previous Y coordinate of the last word written.
* Used to decide if we can draw the next word on the same line.
*/
protected int prevWordY = 0;
/**
* the previous X coordinate of the last word written.
* used to calculate how much space between two words
*/
protected int prevWordX = 0;
/**
* The width of the previous word. Used to calculate space between
*/
protected int prevWordWidth = 0;
/**
* reusable word area string buffer to reduce memory usage
*/
private StringBuffer wordAreaPDF = new StringBuffer();
/**
* create the PDF renderer
*/
public PDFRenderer() {
}
/**
* Configure the PDF renderer.
* Get the configuration to be used for pdf stream filters,
* fonts etc.
*/
public void configure(Configuration conf) throws ConfigurationException {
Configuration filters = conf.getChild("filterList");
Configuration[] filt = filters.getChildren("value");
ArrayList filterList = new ArrayList();
for (int i = 0; i < filt.length; i++) {
String name = filt[i].getValue();
filterList.add(name);
}
filterMap.put(PDFStream.DEFAULT_FILTER, filterList);
Configuration[] font = conf.getChildren("font");
for (int i = 0; i < font.length; i++) {
Configuration[] triple = font[i].getChildren("font-triplet");
ArrayList tripleList = new ArrayList();
for (int j = 0; j < triple.length; j++) {
tripleList.add(new FontTriplet(triple[j].getAttribute("name"),
triple[j].getAttribute("style"),
triple[j].getAttribute("weight")));
}
EmbedFontInfo efi;
efi = new EmbedFontInfo(font[i].getAttribute("metrics-url"),
font[i].getAttributeAsBoolean("kerning"),
tripleList, font[i].getAttribute("embed-url"));
if(fontList == null) {
fontList = new ArrayList();
}
fontList.add(efi);
}
}
/**
* set the PDF document's producer
*
* @param producer string indicating application producing PDF
*/
public void setProducer(String prod) {
producer = prod;
}
public void setUserAgent(FOUserAgent agent) {
super.setUserAgent(agent);
PDFXMLHandler xmlHandler = new PDFXMLHandler();
//userAgent.setDefaultXMLHandler(MIME_TYPE, xmlHandler);
String svg = "http:
userAgent.addXMLHandler(MIME_TYPE, svg, xmlHandler);
}
public void startRenderer(OutputStream stream) throws IOException {
ostream = stream;
this.pdfDoc = new PDFDocument(Version.getVersion());
this.pdfDoc.setProducer(producer);
this.pdfDoc.setFilterMap(filterMap);
pdfDoc.outputHeader(stream);
}
public void stopRenderer() throws IOException {
FontSetup.addToResources(pdfDoc, pdfDoc.getResources(), fontInfo);
pdfDoc.outputTrailer(ostream);
this.pdfDoc = null;
ostream = null;
}
public boolean supportsOutOfOrder() {
return true;
}
public void renderExtension(TreeExt ext) {
// render bookmark extension
if (ext instanceof BookmarkData) {
renderRootExtensions((BookmarkData)ext);
}
}
protected void renderRootExtensions(BookmarkData bookmarks) {
for (int i = 0; i < bookmarks.getCount(); i++) {
BookmarkData ext = bookmarks.getSubData(i);
renderOutline(ext, null);
}
}
private void renderOutline(BookmarkData outline, PDFOutline parentOutline) {
PDFOutline outlineRoot = pdfDoc.getOutlineRoot();
PDFOutline pdfOutline = null;
PageViewport pv = outline.getPage();
if(pv != null) {
Rectangle2D bounds = pv.getViewArea();
double h = bounds.getHeight();
float yoffset = (float)h / 1000f;
String intDest = (String)pageReferences.get(pv.getKey());
if (parentOutline == null) {
pdfOutline = pdfDoc.makeOutline(outlineRoot,
outline.getLabel(), intDest, yoffset);
} else {
PDFOutline pdfParentOutline = parentOutline;
pdfOutline = pdfDoc.makeOutline(pdfParentOutline,
outline.getLabel(), intDest, yoffset);
}
}
for (int i = 0; i < outline.getCount(); i++) {
renderOutline(outline.getSubData(i), pdfOutline);
}
}
public void startPageSequence(Title seqTitle) {
if (seqTitle != null) {
String str = convertTitleToString(seqTitle);
PDFInfo info = this.pdfDoc.getInfo();
info.setTitle(str);
}
}
/**
* The pdf page is prepared by making the page.
* The page is made in the pdf document without any contents
* and then stored to add the contents later.
* The page objects is stored using the area tree PageViewport
* as a key.
*/
public void preparePage(PageViewport page) {
this.pdfResources = this.pdfDoc.getResources();
Rectangle2D bounds = page.getViewArea();
double w = bounds.getWidth();
double h = bounds.getHeight();
currentPage = this.pdfDoc.makePage(this.pdfResources,
(int) Math.round(w / 1000), (int) Math.round(h / 1000));
if (pages == null) {
pages = new HashMap();
}
pages.put(page, currentPage);
pageReferences.put(page.getKey(), currentPage.referencePDF());
pvReferences.put(page.getKey(), page);
}
/**
* This method creates a pdf stream for the current page
* uses it as the contents of a new page. The page is written
* immediately to the output stream.
*/
public void renderPage(PageViewport page) throws IOException,
FOPException {
if (pages != null
&& (currentPage = (PDFPage) pages.get(page)) != null) {
pages.remove(page);
Rectangle2D bounds = page.getViewArea();
double h = bounds.getHeight();
pageHeight = (int) h;
} else {
this.pdfResources = this.pdfDoc.getResources();
Rectangle2D bounds = page.getViewArea();
double w = bounds.getWidth();
double h = bounds.getHeight();
pageHeight = (int) h;
currentPage = this.pdfDoc.makePage(this.pdfResources,
(int) Math.round(w / 1000), (int) Math.round(h / 1000));
pageReferences.put(page.getKey(), currentPage.referencePDF());
pvReferences.put(page.getKey(), page);
}
currentStream =
this.pdfDoc.makeStream(PDFStream.CONTENT_FILTER, false);
currentState = new PDFState();
currentState.setTransform(new AffineTransform(1, 0, 0, -1, 0,
(int) Math.round(pageHeight / 1000)));
// Transform origin at top left to origin at bottom left
currentStream.add("1 0 0 -1 0 "
+ (int) Math.round(pageHeight / 1000) + " cm\n");
//currentStream.add("BT\n");
currentFontName = "";
Page p = page.getPage();
renderPageAreas(p);
//currentStream.add("ET\n");
this.pdfDoc.addStream(currentStream);
currentPage.setContents(currentStream);
this.pdfDoc.addPage(currentPage);
this.pdfDoc.output(ostream);
}
protected void startVParea(CTM ctm) {
// Set the given CTM in the graphics state
currentState.push();
currentState.setTransform(
new AffineTransform(CTMHelper.toPDFArray(ctm)));
currentStream.add("q\n");
// multiply with current CTM
currentStream.add(CTMHelper.toPDFString(ctm) + " cm\n");
// Set clip?
currentStream.add("BT\n");
}
protected void endVParea() {
currentStream.add("ET\n");
currentStream.add("Q\n");
currentState.pop();
}
protected void renderRegion(RegionReference region) {
// Draw a rectangle so we can see it!
// x=0,y=0,w=ipd,h=bpd
currentFontName = "";
super.renderRegion(region);
}
/**
* Handle block traits.
* The block could be any sort of block with any positioning
* so this should render the traits such as border and background
* in its position.
*
* @param block the block to render the traits
*/
protected void handleBlockTraits(Block block) {
float startx = currentIPPosition / 1000f;
float starty = currentBPPosition / 1000f;
drawBackAndBorders(block, startx, starty,
block.getWidth() / 1000f, block.getHeight() / 1000f);
}
/**
* Draw the background and borders.
* This draws the background and border traits for an area given
* the position.
*
* @param block the area to get the traits from
* @param startx the start x position
* @param starty the start y position
* @param width the width of the area
* @param height the height of the area
*/
protected void drawBackAndBorders(Area block, float startx, float starty, float width, float height) {
// draw background then border
closeText();
boolean started = false;
Trait.Background back;
back = (Trait.Background)block.getTrait(Trait.BACKGROUND);
if(back != null) {
started = true;
currentStream.add("ET\n");
currentStream.add("q\n");
if (back.color != null) {
updateColor(back.color, true, null);
currentStream.add(startx + " " + starty + " "
+ width + " " + height + " re\n");
currentStream.add("f\n");
}
if (back.url != null) {
ImageFactory fact = ImageFactory.getInstance();
FopImage fopimage = fact.getImage(back.url, userAgent);
if (fopimage != null && fopimage.load(FopImage.DIMENSIONS, userAgent)) {
if (back.repeat == BackgroundRepeat.REPEAT) {
// create a pattern for the image
} else {
// place once
Rectangle2D pos;
pos = new Rectangle2D.Float((startx + back.horiz) * 1000,
(starty + back.vertical) * 1000,
fopimage.getWidth() * 1000,
fopimage.getHeight() * 1000);
putImage(back.url, pos);
}
}
}
}
BorderProps bps = (BorderProps)block.getTrait(Trait.BORDER_BEFORE);
if(bps != null) {
float endx = startx + width;
if(!started) {
started = true;
currentStream.add("ET\n");
currentStream.add("q\n");
}
updateColor(bps.color, false, null);
currentStream.add(bps.width / 1000f + " w\n");
drawLine(startx, starty, endx, starty);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_START);
if(bps != null) {
float endy = starty + height;
if(!started) {
started = true;
currentStream.add("ET\n");
currentStream.add("q\n");
}
updateColor(bps.color, false, null);
currentStream.add(bps.width / 1000f + " w\n");
drawLine(startx, starty, startx, endy);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_AFTER);
if(bps != null) {
float sy = starty + height;
float endx = startx + width;
if(!started) {
started = true;
currentStream.add("ET\n");
currentStream.add("q\n");
}
updateColor(bps.color, false, null);
currentStream.add(bps.width / 1000f + " w\n");
drawLine(startx, sy, endx, sy);
}
bps = (BorderProps)block.getTrait(Trait.BORDER_END);
if(bps != null) {
float sx = startx + width;
float endy = starty + height;
if(!started) {
started = true;
currentStream.add("ET\n");
currentStream.add("q\n");
}
updateColor(bps.color, false, null);
currentStream.add(bps.width / 1000f + " w\n");
drawLine(sx, starty, sx, endy);
}
if(started) {
currentStream.add("Q\n");
currentStream.add("BT\n");
// font last set out of scope in text section
currentFontName = "";
}
}
/**
* Draw a line.
*
* @param startx the start x position
* @param starty the start y position
* @param endx the x end position
* @param endy the y end position
*/
private void drawLine(float startx, float starty, float endx, float endy) {
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + endy + " l\n");
currentStream.add("S\n");
}
protected void renderBlockViewport(BlockViewport bv, List children) {
// clip and position viewport if necessary
// save positions
int saveIP = currentIPPosition;
int saveBP = currentBPPosition;
String saveFontName = currentFontName;
CTM ctm = bv.getCTM();
closeText();
if (bv.getPositioning() == Block.ABSOLUTE) {
currentIPPosition = 0;
currentBPPosition = 0;
currentStream.add("ET\n");
if (bv.getClip()) {
currentStream.add("q\n");
float x = (float)(bv.getXOffset() + containingIPPosition) / 1000f;
float y = (float)(bv.getYOffset() + containingBPPosition) / 1000f;
float width = (float)bv.getWidth() / 1000f;
float height = (float)bv.getHeight() / 1000f;
clip(x, y, width, height);
}
CTM tempctm = new CTM(containingIPPosition, containingBPPosition);
ctm = tempctm.multiply(ctm);
startVParea(ctm);
handleBlockTraits(bv);
renderBlocks(children);
endVParea();
if (bv.getClip()) {
currentStream.add("Q\n");
}
currentStream.add("BT\n");
// clip if necessary
currentIPPosition = saveIP;
currentBPPosition = saveBP;
} else {
if (ctm != null) {
currentIPPosition = 0;
currentBPPosition = 0;
currentStream.add("ET\n");
double[] vals = ctm.toArray();
boolean aclock = vals[2] == 1.0;
if (vals[2] == 1.0) {
ctm = ctm.translate(-saveBP - bv.getHeight(), -saveIP);
} else if (vals[0] == -1.0) {
ctm = ctm.translate(-saveIP - bv.getWidth(), -saveBP - bv.getHeight());
} else {
ctm = ctm.translate(saveBP, saveIP - bv.getWidth());
}
}
if (bv.getClip()) {
currentStream.add("q\n");
float x = (float)bv.getXOffset() / 1000f;
float y = (float)bv.getYOffset() / 1000f;
float width = (float)bv.getWidth() / 1000f;
float height = (float)bv.getHeight() / 1000f;
clip(x, y, width, height);
}
if (ctm != null) {
startVParea(ctm);
}
handleBlockTraits(bv);
renderBlocks(children);
if (ctm != null) {
endVParea();
}
if (bv.getClip()) {
currentStream.add("Q\n");
}
if (ctm != null) {
currentStream.add("BT\n");
}
// clip if necessary
currentIPPosition = saveIP;
currentBPPosition = saveBP;
currentBPPosition += (int)(bv.getHeight());
}
currentFontName = saveFontName;
}
/**
* Clip an area.
* write a clipping operation given coordinates in the current
* transform.
* @param x the x coordinate
* @param y the y coordinate
* @param width the width of the area
* @param height the height of the area
*/
protected void clip(float x, float y, float width, float height) {
currentStream.add(x + " " + y + " m\n");
currentStream.add((x + width) + " " + y + " l\n");
currentStream.add((x + width) + " " + (y + height) + " l\n");
currentStream.add(x + " " + (y + height) + " l\n");
currentStream.add("h\n");
currentStream.add("W\n");
currentStream.add("n\n");
}
protected void renderLineArea(LineArea line) {
super.renderLineArea(line);
closeText();
}
/**
* Render inline parent area.
* For pdf this handles the inline parent area traits such as
* links, border, background.
* @param ip the inline parent area
*/
public void renderInlineParent(InlineParent ip) {
float start = currentBlockIPPosition / 1000f;
float top = (ip.getOffset() + currentBPPosition) / 1000f;
float width = ip.getWidth() / 1000f;
float height = ip.getHeight() / 1000f;
drawBackAndBorders(ip, start, top, width, height);
// render contents
super.renderInlineParent(ip);
// place the link over the top
Object tr = ip.getTrait(Trait.INTERNAL_LINK);
boolean internal = false;
String dest = null;
float yoffset = 0;
if (tr == null) {
dest = (String)ip.getTrait(Trait.EXTERNAL_LINK);
} else {
String pvKey = (String)tr;
dest = (String)pageReferences.get(pvKey);
if(dest != null) {
PageViewport pv = (PageViewport)pvReferences.get(pvKey);
Rectangle2D bounds = pv.getViewArea();
double h = bounds.getHeight();
yoffset = (float)h / 1000f;
internal = true;
}
}
if (dest != null) {
// add link to pdf document
Rectangle2D rect = new Rectangle2D.Float(start, top, width, height);
// transform rect to absolute coords
AffineTransform transform = currentState.getTransform();
rect = transform.createTransformedShape(rect).getBounds();
int type = internal ? PDFLink.INTERNAL : PDFLink.EXTERNAL;
PDFLink pdflink = pdfDoc.makeLink(rect, dest, type, yoffset);
currentPage.addAnnotation(pdflink);
}
}
public void renderCharacter(Character ch) {
super.renderCharacter(ch);
}
public void renderWord(Word word) {
StringBuffer pdf = new StringBuffer();
String name = (String) word.getTrait(Trait.FONT_NAME);
int size = ((Integer) word.getTrait(Trait.FONT_SIZE)).intValue();
// This assumes that *all* CIDFonts use a /ToUnicode mapping
Font f = (Font) fontInfo.getFonts().get(name);
boolean useMultiByte = f.isMultiByte();
// String startText = useMultiByte ? "<FEFF" : "(";
String startText = useMultiByte ? "<" : "(";
String endText = useMultiByte ? "> " : ") ";
updateFont(name, size, pdf);
ColorType ct = (ColorType)word.getTrait(Trait.COLOR);
if(ct != null) {
updateColor(ct, true, pdf);
}
int rx = currentBlockIPPosition;
// int bl = pageHeight - currentBPPosition;
int bl = currentBPPosition + word.getOffset();
// Set letterSpacing
//float ls = fs.getLetterSpacing() / this.currentFontSize;
//pdf.append(ls).append(" Tc\n");
if (!textOpen || bl != prevWordY) {
closeText();
pdf.append("1 0 0 -1 " + (rx / 1000f) + " "
+ (bl / 1000f) + " Tm [" + startText);
prevWordY = bl;
textOpen = true;
} else {
// express the space between words in thousandths of an em
int space = prevWordX - rx + prevWordWidth;
float emDiff = (float) space / (float) currentFontSize * 1000f;
// this prevents a problem in Acrobat Reader and other viewers
// where large numbers cause text to disappear or default to
// a limit
if (emDiff < -33000) {
closeText();
pdf.append("1 0 0 1 " + (rx / 1000f) + " "
+ (bl / 1000f) + " Tm [" + startText);
textOpen = true;
} else {
pdf.append(Float.toString(emDiff));
pdf.append(" ");
pdf.append(startText);
}
}
prevWordWidth = word.getWidth();
prevWordX = rx;
String s = word.getWord();
FontMetric metrics = fontInfo.getMetricsFor(name);
FontState fs = new FontState(name, metrics, size);
escapeText(s, fs, useMultiByte, pdf);
pdf.append(endText);
currentStream.add(pdf.toString());
super.renderWord(word);
}
public void escapeText(String s, FontState fs,
boolean useMultiByte, StringBuffer pdf) {
String startText = useMultiByte ? "<" : "(";
String endText = useMultiByte ? "> " : ") ";
boolean kerningAvailable = false;
HashMap kerning = null;
kerning = fs.getKerning();
if (kerning != null && !kerning.isEmpty()) {
kerningAvailable = true;
}
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = fs.mapChar(s.charAt(i));
if (!useMultiByte) {
if (ch > 127) {
pdf.append("\\");
pdf.append(Integer.toOctalString((int) ch));
} else {
switch (ch) {
case '(':
case ')':
case '\\':
pdf.append("\\");
break;
}
pdf.append(ch);
}
} else {
pdf.append(getUnicodeString(ch));
}
if (kerningAvailable && (i + 1) < l) {
addKerning(pdf, (new Integer((int) ch)),
(new Integer((int) fs.mapChar(s.charAt(i + 1)))
), kerning, startText, endText);
}
}
}
/**
* Convert a char to a multibyte hex representation
*/
private String getUnicodeString(char c) {
StringBuffer buf = new StringBuffer(4);
byte[] uniBytes = null;
try {
char[] a = {c};
uniBytes = new String(a).getBytes("UnicodeBigUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
// This should never fail
}
for (int i = 0; i < uniBytes.length; i++) {
int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i])
: (int) uniBytes[i];
String hexString = Integer.toHexString(b);
if (hexString.length() == 1) {
buf = buf.append("0" + hexString);
} else {
buf = buf.append(hexString);
}
}
return buf.toString();
}
private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
HashMap kerning, String startText, String endText) {
HashMap kernPair = (HashMap) kerning.get(ch1);
if (kernPair != null) {
Integer width = (Integer) kernPair.get(ch2);
if (width != null) {
buf.append(endText).append(-width.intValue());
buf.append(' ').append(startText);
}
}
}
/**
* Checks to see if we have some text rendering commands open
* still and writes out the TJ command to the stream if we do
*/
private void closeText() {
if (textOpen) {
currentStream.add("] TJ\n");
textOpen = false;
prevWordX = 0;
prevWordY = 0;
}
}
private void updateColor(ColorType col, boolean fill, StringBuffer pdf) {
PDFColor areaColor = null;
//if (this.currentFill instanceof PDFColor) {
// areaColor = (PDFColor)this.currentFill;
if (areaColor == null || areaColor.red() != (double)col.red()
|| areaColor.green() != (double)col.green()
|| areaColor.blue() != (double)col.blue()) {
areaColor = new PDFColor((double)col.red(),
(double)col.green(),
(double)col.blue());
closeText();
//this.currentFill = areaColor;
if(pdf != null) {
pdf.append(areaColor.getColorSpaceOut(fill));
} else {
currentStream.add(areaColor.getColorSpaceOut(fill));
}
}
}
private void updateFont(String name, int size, StringBuffer pdf) {
if ((!name.equals(this.currentFontName))
|| (size != this.currentFontSize)) {
closeText();
this.currentFontName = name;
this.currentFontSize = size;
pdf = pdf.append("/" + name + " " + ((float) size / 1000f)
+ " Tf\n");
}
}
public void renderImage(Image image, Rectangle2D pos) {
String url = image.getURL();
putImage(url, pos);
}
protected void putImage(String url, Rectangle2D pos) {
PDFXObject xobject = pdfDoc.getImage(url);
if (xobject != null) {
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobject.getXNumber());
return;
}
ImageFactory fact = ImageFactory.getInstance();
FopImage fopimage = fact.getImage(url, userAgent);
if (fopimage == null) {
return;
}
if (!fopimage.load(FopImage.DIMENSIONS, userAgent)) {
return;
}
String mime = fopimage.getMimeType();
if ("text/xml".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
Document doc = ((XMLImage) fopimage).getDocument();
String ns = ((XMLImage) fopimage).getNameSpace();
renderDocument(doc, ns, pos);
} else if ("image/svg+xml".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
Document doc = ((XMLImage) fopimage).getDocument();
String ns = ((XMLImage) fopimage).getNameSpace();
renderDocument(doc, ns, pos);
} else if ("image/eps".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
} else if ("image/jpeg".equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobj);
} else {
if (!fopimage.load(FopImage.BITMAP, userAgent)) {
return;
}
FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
fact.releaseImage(url, userAgent);
int w = (int) pos.getWidth() / 1000;
int h = (int) pos.getHeight() / 1000;
placeImage((int) pos.getX() / 1000,
(int) pos.getY() / 1000, w, h, xobj);
}
// output new data
try {
this.pdfDoc.output(ostream);
} catch (IOException ioe) {
// ioexception will be caught later
}
}
protected void placeImage(int x, int y, int w, int h, int xobj) {
currentStream.add("q\n" + ((float) w) + " 0 0 "
+ ((float) -h) + " "
+ (((float) currentBlockIPPosition) / 1000f + x) + " "
+ (((float)(currentBPPosition + 1000 * h)) / 1000f
+ y) + " cm\n" + "/Im" + xobj + " Do\nQ\n");
}
public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
Document doc = fo.getDocument();
String ns = fo.getNameSpace();
renderDocument(doc, ns, pos);
}
public void renderDocument(Document doc, String ns, Rectangle2D pos) {
RendererContext context;
context = new RendererContext(MIME_TYPE);
context.setUserAgent(userAgent);
context.setProperty(PDFXMLHandler.PDF_DOCUMENT, pdfDoc);
context.setProperty(PDFXMLHandler.OUTPUT_STREAM, ostream);
context.setProperty(PDFXMLHandler.PDF_STATE, currentState);
context.setProperty(PDFXMLHandler.PDF_PAGE, currentPage);
context.setProperty(PDFXMLHandler.PDF_STREAM, currentStream);
context.setProperty(PDFXMLHandler.PDF_XPOS,
new Integer(currentBlockIPPosition + (int) pos.getX()));
context.setProperty(PDFXMLHandler.PDF_YPOS,
new Integer(currentBPPosition + (int) pos.getY()));
context.setProperty(PDFXMLHandler.PDF_FONT_INFO, fontInfo);
context.setProperty(PDFXMLHandler.PDF_FONT_NAME, currentFontName);
context.setProperty(PDFXMLHandler.PDF_FONT_SIZE,
new Integer(currentFontSize));
context.setProperty(PDFXMLHandler.PDF_WIDTH,
new Integer((int) pos.getWidth()));
context.setProperty(PDFXMLHandler.PDF_HEIGHT,
new Integer((int) pos.getHeight()));
userAgent.renderXML(context, doc, ns);
}
/**
* Render an inline viewport.
* This renders an inline viewport by clipping if necessary.
* @param viewport the viewport to handle
*/
public void renderViewport(Viewport viewport) {
closeText();
currentStream.add("ET\n");
if (viewport.getClip()) {
currentStream.add("q\n");
float x = currentBlockIPPosition / 1000f;
float y = (currentBPPosition + viewport.getOffset()) / 1000f;
float width = viewport.getWidth() / 1000f;
float height = viewport.getHeight() / 1000f;
clip(x, y, width, height);
}
super.renderViewport(viewport);
if (viewport.getClip()) {
currentStream.add("Q\n");
}
currentStream.add("BT\n");
}
/**
* Render leader area.
* This renders a leader area which is an area with a rule.
* @param area the leader area to render
*/
public void renderLeader(Leader area) {
closeText();
currentStream.add("ET\n");
currentStream.add("q\n");
int style = area.getRuleStyle();
boolean alt = false;
switch(style) {
case RuleStyle.SOLID:
currentStream.add("[] 0 d\n");
break;
case RuleStyle.DOTTED:
currentStream.add("[2] 0 d\n");
break;
case RuleStyle.DASHED:
currentStream.add("[6 4] 0 d\n");
break;
case RuleStyle.DOUBLE:
case RuleStyle.GROOVE:
case RuleStyle.RIDGE:
alt = true;
break;
}
float startx = ((float) currentBlockIPPosition) / 1000f;
float starty = ((currentBPPosition + area.getOffset()) / 1000f);
float endx = (currentBlockIPPosition + area.getWidth()) / 1000f;
if (!alt) {
currentStream.add(area.getRuleThickness() / 1000f + " w\n");
drawLine(startx, starty, endx, starty);
} else {
if (style == RuleStyle.DOUBLE) {
float third = area.getRuleThickness() / 3000f;
currentStream.add(third + " w\n");
drawLine(startx, starty, endx, starty);
drawLine(startx, (starty + 2 * third), endx, (starty + 2 * third));
} else {
float half = area.getRuleThickness() / 2000f;
currentStream.add("1 g\n");
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + starty + " l\n");
currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
currentStream.add("h\n");
currentStream.add("f\n");
if (style == RuleStyle.GROOVE) {
currentStream.add("0 g\n");
currentStream.add(startx + " " + starty + " m\n");
currentStream.add(endx + " " + starty + " l\n");
currentStream.add(endx + " " + (starty + half) + " l\n");
currentStream.add((startx + half) + " " + (starty + half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
} else {
currentStream.add("0 g\n");
currentStream.add(endx + " " + starty + " m\n");
currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
currentStream.add(startx + " " + (starty + half) + " l\n");
currentStream.add((endx - half) + " " + (starty + half) + " l\n");
}
currentStream.add("h\n");
currentStream.add("f\n");
}
}
currentStream.add("Q\n");
currentStream.add("BT\n");
super.renderLeader(area);
}
}
|
package org.appwork.scheduler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author daniel
*
*/
public abstract class DelayedRunnable implements Runnable {
private final ScheduledExecutorService service;
private final long delayInMS;
private long nextDelay;
private volatile long lastRunRequest = 0;
private volatile long firstRunRequest = 0;
private ScheduledFuture<?> delayer;
private final long maxInMS;
private boolean delayerEnabled = true;
public DelayedRunnable(final ScheduledExecutorService service, final long delayInMS) {
this(service, delayInMS, -1);
}
public DelayedRunnable(final ScheduledExecutorService service, final long minDelayInMS, final long maxDelayInMS) {
this.service = service;
this.nextDelay = this.delayInMS = minDelayInMS;
this.maxInMS = maxDelayInMS;
if (this.delayInMS <= 0) { throw new IllegalArgumentException("minDelay must be >0"); }
if (this.maxInMS == 0) { throw new IllegalArgumentException("maxDelay must be !=0"); }
}
abstract public void delayedrun();
public boolean isDelayerEnabled() {
return this.delayerEnabled;
}
public void resetAndStart() {
this.run();
}
@Override
public void run() {
if (this.delayerEnabled == false) {
DelayedRunnable.this.delayedrun();
return;
}
synchronized (this) {
/* lastRunRequest is updated every time */
this.lastRunRequest = System.currentTimeMillis();
if (this.delayer == null) {
if (this.firstRunRequest == 0) {
/* firstRunRequest is updated only once */
this.firstRunRequest = System.currentTimeMillis();
}
this.delayer = this.service.schedule(new Runnable() {
public void run() {
boolean doWhat = false;
synchronized (DelayedRunnable.this) {
/* do we have to run now? */
final long dif = System.currentTimeMillis() - DelayedRunnable.this.lastRunRequest;
boolean runNow = dif >= DelayedRunnable.this.nextDelay;
if (DelayedRunnable.this.maxInMS > 0) {
/* is a maxDelay set? */
if (System.currentTimeMillis() - DelayedRunnable.this.firstRunRequest > DelayedRunnable.this.maxInMS) {
/* we have to run now! */
runNow = true;
} else {
/*
* calc new nextDelay so we can reach
* maxDelay better
*/
DelayedRunnable.this.nextDelay = Math.max(DelayedRunnable.this.maxInMS - (System.currentTimeMillis() - DelayedRunnable.this.firstRunRequest), 10);
}
}
DelayedRunnable.this.delayer = null;
if (runNow) {
/* we no longer delay the run */
doWhat = true;
/* reset nextDelay and firstRunRequest */
DelayedRunnable.this.firstRunRequest = System.currentTimeMillis();
DelayedRunnable.this.nextDelay = DelayedRunnable.this.delayInMS;
} else {
/* lets delay it again */
DelayedRunnable.this.nextDelay = DelayedRunnable.this.delayInMS - dif;
doWhat = false;
DelayedRunnable.this.run();
}
}
if (doWhat) {
/* we no longer delay the run */
DelayedRunnable.this.delayedrun();
} else {
/* lets delay it again */
DelayedRunnable.this.run();
}
}
}, DelayedRunnable.this.nextDelay, TimeUnit.MILLISECONDS);
}
}
}
public void setDelayerEnabled(final boolean b) {
if (this.delayerEnabled == b) { return; }
synchronized (this) {
if (b == false) {
this.stop();
}
this.delayerEnabled = b;
}
}
public boolean stop() {
synchronized (this) {
if (this.delayer != null) {
this.delayer.cancel(false);
this.delayer = null;
return true;
}
}
return false;
}
}
|
package org.appwork.utils.swing.dialog;
import java.awt.Image;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import org.appwork.resources.AWUTheme;
import org.appwork.uio.UIOManager;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.interfaces.ValueConverter;
import org.appwork.utils.locale._AWU;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.EDTRunner;
/**
* A Dialog Instance which provides extended Dialog features and thus replaces
* JOptionPane
*/
public class Dialog {
public static final String LASTSELECTION = "LASTSELECTION_";
public static final String FILECHOOSER = "FILECHOOSER";
/**
* Icon Key for Error Icons
*
* @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String,
* int, int, boolean)
*/
public static final String ICON_ERROR = "dialog/error";
/**
* Icon Key for Information Icons
*
* @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String,
* int, int, boolean)
*/
public static final String ICON_INFO = "dialog/info";
/**
* Icon Key for Question Icons
*
* @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String,
* int, int, boolean)
*/
public static final String ICON_QUESTION = "dialog/help";
/**
* Icon Key for Warning Icons
*
* @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String,
* int, int, boolean)
*/
public static final String ICON_WARNING = "dialog/warning";
/**
* internal singleton instance to access the instance of this class
*/
private static final Dialog INSTANCE = new Dialog();
/**
*
* @deprecated Use org.appwork.uio.UIOManager Constants instead
*/
@Deprecated()
public static final int LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY = 1 << 12;
/**
* if the user pressed cancel, the return mask will contain this mask
*/
public static final int RETURN_CANCEL = 1 << 2;
/**
* if user closed the window
*/
public static final int RETURN_CLOSED = 1 << 6;
public static final int RETURN_INTERRUPT = 1 << 8;
/**
* this return flag can be set in two situations:<br>
* a) The user selected the {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option<br>
* b) The dialog has been skipped because the DO NOT SHOW AGAIN flag has
* been set previously<br>
* <br>
* Check {@link #RETURN_SKIPPED_BY_DONT_SHOW} to know if the dialog has been
* visible or autoskipped
*/
public static final int RETURN_DONT_SHOW_AGAIN = 1 << 3;
/**
* If the user pressed OK, the return mask will contain this flag
*/
public static final int RETURN_OK = 1 << 1;
/**
* If the dialog has been skipped due to previously selected
* {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option, this return flag is set.
*
* @see #RETURN_DONT_SHOW_AGAIN
*/
public static final int RETURN_SKIPPED_BY_DONT_SHOW = 1 << 4;
/**
* If the Timeout ({@link UIOManager#LOGIC_COUNTDOWN}) has run out, the
* return mask contains this flag
*/
public static final int RETURN_TIMEOUT = 1 << 5;
/**
* If the dialog has been skiped/closed by ESC key
*/
public static final int RETURN_ESC = 1 << 7;
/**
* @return
*
*/
public static Dialog I() {
return Dialog.INSTANCE;
}
public static boolean isClosed(final Object value) {
if (!(value instanceof Integer)) { return false; }
return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_CLOSED);
}
public static boolean isOK(final Object value) {
if (!(value instanceof Integer)) { return false; }
return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_OK);
}
private List<? extends Image> iconList = null;
/**
* Do Not use an Icon. By default dialogs have an Icon
*/
public static final int STYLE_HIDE_ICON = 1 << 8;
/**
* Some dialogs are able to render HTML. Use this switch to enable html
*/
public static final int STYLE_HTML = 1 << 7;
/**
* Some dialogs are able to layout themselves in a large mode. E:g. to
* display a huge text.
*/
public static final int STYLE_LARGE = 1 << 6;
/**
* Displays a Checkbox with "do not show this again" text. If the user
* selects this box, the UserInteraktion class will remember the answer and
* will not disturb the user with the same question (same title)
*/
public static final int STYLE_SHOW_DO_NOT_DISPLAY_AGAIN = 1 << 5;
/**
* Inputdialogs will use passwordfields instead of textfields
*/
public static final int STYLE_PASSWORD = 1 << 9;
/**
* tries to find some special markers in the text and selects an appropriate
* icon
*
* @param text
* @return
*/
public static ImageIcon getIconByText(final String text) {
try {
if (text != null && text.contains("?")) {
return AWUTheme.I().getIcon(Dialog.ICON_QUESTION, 32);
} else if (text != null && (text.contains("error") || text.contains("exception"))) {
return AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32);
} else if (text != null && text.contains("!")) {
return AWUTheme.I().getIcon(Dialog.ICON_WARNING, 32);
} else {
return AWUTheme.I().getIcon(Dialog.ICON_INFO, 32);
}
} catch (final Throwable e) {
Log.exception(e);
return null;
}
}
/**
* Return the singleton instance of Dialog
*
* @return
*/
public static Dialog getInstance() {
return Dialog.INSTANCE;
}
public static void main(final String[] args) throws InterruptedException {
final Thread th = new Thread() {
@Override
public void run() {
try {
Dialog.getInstance().showConfirmDialog(0, "Blabla?");
System.out.println("RETURNED OK");
} catch (final DialogClosedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final DialogCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
th.start();
Thread.sleep(5000);
th.interrupt();
}
/**
* The max counter value for a timeout Dialog
*/
private int defaultTimeout = 20000;
/**
* Parent window for all dialogs created with abstractdialog
*/
private LAFManagerInterface lafManager;
private DialogHandler handler = null;
private DialogHandler defaultHandler;
private Dialog() {
defaultHandler = new DialogHandler() {
@Override
public <T> T showDialog(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException {
return Dialog.this.showDialogRaw(dialog);
}
};
}
public DialogHandler getDefaultHandler() {
return defaultHandler;
}
/**
* @return the {@link Dialog#defaultTimeout} in ms
* @see Dialog#defaultTimeout
*/
protected int getDefaultTimeout() {
return defaultTimeout;
}
public DialogHandler getHandler() {
return handler;
}
/**
* @return
*/
public List<? extends Image> getIconList() {
return iconList;
}
public LAFManagerInterface getLafManager() {
synchronized (this) {
return lafManager;
}
}
public void initLaf() {
synchronized (this) {
if (lafManager != null) {
lafManager.init();
setLafManager(null);
}
}
}
/**
* @param countdownTime
* the {@link Dialog#defaultTimeout} to set
* @see Dialog#defaultTimeout
*/
public void setDefaultTimeout(final int countdownTime) {
defaultTimeout = countdownTime;
}
public void setHandler(DialogHandler handler) {
if (handler == null) {
handler = defaultHandler;
}
this.handler = handler;
}
@Deprecated
public void setIconList(final List<? extends Image> iconList) {
this.iconList = iconList;
}
public void setLafManager(final LAFManagerInterface lafManager) {
synchronized (this) {
this.lafManager = lafManager;
}
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param question
* The Dialog is able to show a question to the user.
* @param options
* A list of various options to select
* @param defaultSelectedIndex
* The option which is selected by default
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default]
* @param cancelOption
* Text for Cancel Button [null for default]
* @param renderer
* A renderer to customize the Dialog. Might be null
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public int showComboDialog(final int flag, final String title, final String question, final Object[] options, final int defaultSelectedIndex, final ImageIcon icon, final String okOption, final String cancelOption, final ListCellRenderer renderer) throws DialogClosedException, DialogCanceledException {
return this.showDialog(new ComboBoxDialog(flag, title, question, options, defaultSelectedIndex, icon, okOption, cancelOption, renderer));
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param question
* The Dialog is able to show a question to the user.
* @param options
* A list of various options to select
* @param defaultSelectedItem
* The option which is selected by default
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default]
* @param cancelOption
* Text for Cancel Button [null for default]
* @param renderer
* A renderer to customize the Dialog. Might be null
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public Object showComboDialog(final int flag, final String title, final String question, final Object[] options, final Object defaultSelectedItem, final ImageIcon icon, final String okOption, final String cancelOption, final ListCellRenderer renderer) throws DialogClosedException, DialogCanceledException {
int def = 0;
for (int i = 0; i < options.length; i++) {
if (options[i] == defaultSelectedItem) {
def = i;
break;
}
}
final Integer returnIndex = this.showDialog(new ComboBoxDialog(flag, title, question, options, def, icon, okOption, cancelOption, renderer));
return options[returnIndex];
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param question
* The Dialog is able to show a question to the user.
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public int showConfirmDialog(final int flag, final String question) throws DialogClosedException, DialogCanceledException {
return this.showConfirmDialog(flag, _AWU.T.DIALOG_CONFIRMDIALOG_TITLE(), question, Dialog.getIconByText(question), null, null);
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param question
* The Dialog is able to show a question to the user.
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public int showConfirmDialog(final int flag, final String title, final String question) throws DialogClosedException, DialogCanceledException {
return this.showConfirmDialog(flag, title, question, Dialog.getIconByText(title + question), null, null);
}
/**
* Keep this method for webinstaller compatibility reasons. People cannot uninstall if this method is missing
* @param flag
* @param title
* @param message
* @param tmpicon
* @param okOption
* @param cancelOption
* @return
* @throws DialogClosedException
* @throws DialogCanceledException
*/
public int showConfirmDialog(final int flag, final String title, final String message, final ImageIcon tmpicon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException {
return showConfirmDialog(flag, title, message, (Icon)tmpicon, okOption, cancelOption);
}
/**
* Requests a ConfirmDialog
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default] Text for OK Button [null
* for default]
* @param cancelOption
* Text for Cancel Button [null for default] Text for cancel
* Button [null for default]
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public int showConfirmDialog(final int flag, final String title, final String message, final Icon tmpicon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException {
final Icon icon;
if (tmpicon == null) {
icon = Dialog.getIconByText(title + message);
} else {
icon = tmpicon;
}
return this.showDialog(new ConfirmDialog(flag, title, message, icon, okOption, cancelOption));
}
/**
* note: showdialog must not call init itself!!
*
* @param <T>
* @param dialog
* @return
* @throws DialogClosedException
* @throws DialogCanceledException
*/
public <T> T showDialog(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException {
final DialogHandler lhandler = handler;
if (lhandler != null) {
return lhandler.showDialog(dialog);
}
return this.showDialogRaw(dialog);
}
/**
* @param dialog
* @throws DialogClosedException
* @throws DialogCanceledException
*/
protected <T> T showDialogRaw(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException {
if (dialog == null) { return null; }
if (SwingUtilities.isEventDispatchThread()) {
return this.showDialogRawInEDT(dialog);
} else {
return this.showDialogRawOutsideEDT(dialog);
}
}
protected <T> T showDialogRawInEDT(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException {
dialog.setCallerIsEDT(true);
dialog.displayDialog();
final T ret = dialog.getReturnValue();
final int mask = dialog.getReturnmask();
if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); }
if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); }
return ret;
}
protected <T> T showDialogRawOutsideEDT(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException {
dialog.setCallerIsEDT(false);
if (Thread.interrupted()) { throw new DialogClosedException(Dialog.RETURN_INTERRUPT, new InterruptedException()); }
final AtomicBoolean waitingLock = new AtomicBoolean(false);
final EDTRunner edth = new EDTRunner() {
@Override
protected void runInEDT() {
dialog.setDisposedCallback(new DisposeCallBack() {
@Override
public void dialogDisposed(final AbstractDialog<?> dialog) {
synchronized (waitingLock) {
waitingLock.set(true);
waitingLock.notifyAll();
}
}
});
dialog.displayDialog();
}
};
try {
if (Thread.interrupted()) { throw new InterruptedException(); }
synchronized (waitingLock) {
if (waitingLock.get() == false) {
waitingLock.wait();
}
}
} catch (final InterruptedException e) {
// Use a edtrunner here. AbstractCaptcha.dispose is edt save...
// however there may be several CaptchaDialog classes with
// overriddden unsave dispose methods...
new EDTRunner() {
@Override
protected void runInEDT() {
try {
// close dialog if open
dialog.interrupt();
} catch (final Exception e) {
}
}
};
try {
throw new DialogClosedException(dialog.getReturnmask() | Dialog.RETURN_INTERRUPT, e);
} catch (final IllegalStateException e1) {
// if we cannot get the returnmask from the dialog
throw new DialogClosedException(Dialog.RETURN_INTERRUPT, e);
}
}
final T ret = dialog.getReturnValue();
final int mask = dialog.getReturnmask();
if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); }
if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); }
return ret;
}
/**
* @param i
* @param dialog_error_title
* @param dialog_error_noconnection
* @return
*/
public int showErrorDialog(final int flags, final String title, final String message) {
try {
return this.showConfirmDialog(flags, title, message, AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32), null, null);
} catch (final DialogClosedException e) {
return Dialog.RETURN_CLOSED;
} catch (final DialogCanceledException e) {
return Dialog.RETURN_CANCEL;
}
}
public int showErrorDialog(final String s) {
try {
return this.showConfirmDialog(UIOManager.BUTTONS_HIDE_CANCEL | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN, _AWU.T.DIALOG_ERROR_TITLE(), s, AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32), null, null);
} catch (final DialogClosedException e) {
return Dialog.RETURN_CLOSED;
} catch (final DialogCanceledException e) {
return Dialog.RETURN_CANCEL;
}
}
/**
* @param string
* @param message
* @param e
*/
public int showExceptionDialog(final String title, final String message, final Throwable e) {
try {
final ExceptionDialog dialog = new ExceptionDialog(UIOManager.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT | UIOManager.BUTTONS_HIDE_CANCEL, title, message, e, null, null);
this.showDialog(dialog);
} catch (final DialogClosedException e1) {
return Dialog.RETURN_CLOSED;
} catch (final DialogCanceledException e1) {
return Dialog.RETURN_CANCEL;
}
return 0;
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog flag
* @param question
* The Dialog is able to show a question to the user. question
* @param defaultvalue
* defaultvalue
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showInputDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException {
return this.showInputDialog(flag, _AWU.T.DIALOG_INPUT_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null);
}
/**
* Requests in Inputdialog.
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @param defaultMessage
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default]
* @param cancelOption
* Text for Cancel Button [null for default]
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showInputDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException {
return this.showDialog(new InputDialog(flag, title, message, defaultMessage, icon, okOption, cancelOption));
}
/**
*
* @param message
* The Dialog is able to show a message to the user
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showInputDialog(final String message) throws DialogClosedException, DialogCanceledException {
return this.showInputDialog(0, message, null);
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param message
* The Dialog is able to show a message to the user
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public void showMessageDialog(final int flag, final String message) {
this.showMessageDialog(flag, _AWU.T.DIALOG_MESSAGE_TITLE(), message);
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public void showMessageDialog(final int flag, final String title, final String message) {
try {
this.showConfirmDialog(UIOManager.BUTTONS_HIDE_CANCEL | flag, title, message, Dialog.getIconByText(title + message), null, null);
} catch (final DialogClosedException e) {
} catch (final DialogCanceledException e) {
}
}
/**
*
* @param message
* The Dialog is able to show a message to the user
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public void showMessageDialog(final String message) {
this.showMessageDialog(0, _AWU.T.DIALOG_MESSAGE_TITLE(), message);
}
/**
*
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public void showMessageDialog(final String title, final String message) {
this.showMessageDialog(0, title, message);
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog flag
* @param question
* The Dialog is able to show 3 Passwordfields to the user.
* question
* @param defaultvalue
* defaultvalue
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showPasswordDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException {
return this.showPasswordDialog(flag, _AWU.T.DIALOG_PASSWORD_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null);
}
/**
* Requests in MultiInputdialog.
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @param defaultMessage
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default]
* @param cancelOption
* Text for Cancel Button [null for default]
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
protected String showPasswordDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException {
return this.showDialog(new PasswordDialog(flag, title, message, icon, okOption, cancelOption));
}
/**
*
* @param message
* The Dialog is able to show a message to the user
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showPasswordDialog(final String message) throws DialogClosedException, DialogCanceledException {
return this.showPasswordDialog(0, message, null);
}
/**
*
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @param def
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public String showTextAreaDialog(final String title, final String message, final String def) throws DialogClosedException, DialogCanceledException {
return this.showDialog(new TextAreaDialog(title, message, def));
}
/**
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog flag
* @param question
* The Dialog is able to show a slider to the user. question
* @param defaultvalue
* defaultvalue
* @param min
* Min slider value
* @param max
* Max slider value
* @param step
* slider step
* @param valueConverter
* TODO
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
public long showValueDialog(final int flag, final String question, final long defaultvalue, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException {
return this.showValueDialog(flag, _AWU.T.DIALOG_SLIDER_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null, min, max, step, valueConverter);
}
/**
* Requests in ValueDialog.
*
* @param flag
* see {@link Dialog} - Flags. There are various flags to
* customize the dialog
* @param title
* The Dialog's Window Title
* @param message
* The Dialog is able to show a message to the user
* @param defaultMessage
* @param icon
* The dialog is able to display an Icon If this is null, the
* dialog might select an Icon derived from the message and title
* text
* @param okOption
* Text for OK Button [null for default]
* @param cancelOption
* Text for Cancel Button [null for default]
* @param min
* Min slider value
* @param max
* Max slider value
* @param step
* slider step
* @param valueConverter
* @return
* @throws DialogCanceledException
* @throws DialogClosedException
*/
protected long showValueDialog(final int flag, final String title, final String message, final long defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException {
return this.showDialog(new ValueDialog(flag, title, message, icon, okOption, cancelOption, defaultMessage, min, max, step, valueConverter));
}
}
|
package org.barbon.mangaget.scrape;
import android.os.AsyncTask;
import android.net.http.AndroidHttpClient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.HttpGet;
public class Downloader {
protected static class CountingInputStream extends FilterInputStream {
private long byteCount = 0;
public CountingInputStream(InputStream in) {
super(in);
}
public long getCount() {
return byteCount;
}
@Override
public int read(byte[] buffer) throws IOException {
int size = in.read(buffer);
if (size != -1)
byteCount += size;
return size;
}
@Override
public int read() throws IOException {
int ch = in.read();
if (ch != -1)
byteCount += 1;
return ch;
}
@Override
public int read(byte[] buffer, int offset, int count)
throws IOException {
int size = in.read(buffer, offset, count);
if (size != -1)
byteCount += size;
return size;
}
}
public interface OnDownloadProgress {
public void downloadStarted();
public void downloadProgress(long downloaded, long total);
public void downloadComplete(boolean success);
public void downloadCompleteBackground(boolean success);
}
public interface DownloadTarget {
public void startDownload(InputStream stream, String encoding,
String baseUrl)
throws Exception;
public long downloadChunk()
throws Exception;
public void completeDownload()
throws Exception;
public void abortDownload()
throws Exception;
}
public static class OnDownloadProgressAdapter
implements OnDownloadProgress {
@Override public void downloadStarted() { }
@Override public void downloadProgress(long downloaded, long total) { }
@Override public void downloadComplete(boolean success) { }
@Override public void downloadCompleteBackground(boolean success) { }
}
public class StringDownloadTarget implements DownloadTarget {
private static final int BUFFER_SIZE = 1024;
private DownloadDestination destination;
private InputStream in;
private ByteArrayOutputStream out;
private byte[] buffer = new byte[BUFFER_SIZE];
public StringDownloadTarget(DownloadDestination _destination) {
destination = _destination;
}
@Override
public void startDownload(InputStream stream, String encoding,
String baseUrl) {
destination.encoding = encoding;
destination.baseUrl = baseUrl;
in = stream;
out = new ByteArrayOutputStream();
}
@Override
public long downloadChunk() throws IOException {
int size = in.read(buffer);
if (size != -1)
out.write(buffer, 0, size);
return size;
}
@Override
public void completeDownload() {
destination.stream = new ByteArrayInputStream(out.toByteArray());
}
@Override
public void abortDownload() { }
}
public class FileDownloadTarget implements DownloadTarget {
private static final int BUFFER_SIZE = 1024;
private DownloadDestination destination;
private InputStream in;
private OutputStream out;
private byte[] buffer = new byte[BUFFER_SIZE];
public FileDownloadTarget(DownloadDestination _destination) {
destination = _destination;
}
@Override
public void startDownload(InputStream stream, String encoding,
String baseUrl) throws IOException {
destination.encoding = encoding;
destination.baseUrl = baseUrl;
in = stream;
out = new FileOutputStream(destination.path);
}
@Override
public long downloadChunk() throws IOException {
int size = in.read(buffer);
if (size != -1)
out.write(buffer, 0, size);
return size;
}
@Override
public void completeDownload() throws IOException {
out.close();
}
@Override
public void abortDownload() throws IOException {
out.close();
// remove target path
destination.path.delete();
}
}
private class DownloadTask extends AsyncTask<String, Long, Boolean> {
private OnDownloadProgress progressListener;
private DownloadTarget downloadTarget;
private CountingInputStream byteCounter;
public DownloadTask(OnDownloadProgress listener,
DownloadTarget target) {
progressListener = listener;
downloadTarget = target;
}
@Override
public void onPreExecute() {
// nothing to do
}
public Boolean doInBackground(String... params) {
publishProgress(0L);
AndroidHttpClient client =
AndroidHttpClient.newInstance("MangaGet/1.0");
long totalSize = -1;
try {
HttpResponse response = client.execute(new HttpGet(params[0]));
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
totalSize = entity.getContentLength();
byteCounter = new CountingInputStream(content);
downloadTarget.startDownload(
byteCounter, EntityUtils.getContentCharSet(entity),
// TODO handle redirects
// http://stackoverflow.com/questions/1456987/httpclient-4-how-to-capture-last-redirect-url/1457173#1457173
params[0]);
}
catch (Exception e) {
e.printStackTrace(); // TODO better diagnostics
client.close();
// TODO handle exception
progressListener.downloadCompleteBackground(false);
return false;
}
try {
for (;;) {
long size = downloadTarget.downloadChunk();
if (size == -1)
break;
publishProgress(1L, byteCounter.getCount(), totalSize);
}
downloadTarget.completeDownload();
}
catch(Exception e) {
e.printStackTrace(); // TODO better diagnostics
try {
downloadTarget.abortDownload();
}
catch (Exception e1) {
// can only ignore the exception...
}
client.close();
// TODO handle exception
progressListener.downloadCompleteBackground(false);
return false;
}
client.close();
// TODO handle exception
progressListener.downloadCompleteBackground(true);
return true;
}
@Override
public void onProgressUpdate(Long... values) {
// TODO abort on exception
if (values[0] == 0)
progressListener.downloadStarted();
else
progressListener.downloadProgress(values[1], values[2]);
}
@Override
public void onPostExecute(Boolean result) {
progressListener.downloadComplete(result);
}
}
public static class DownloadDestination {
public File path;
public InputStream stream;
public String encoding;
public String baseUrl;
public DownloadDestination() {
}
public DownloadDestination(File _path) {
path = _path;
}
}
private static Downloader theInstance;
public static void setInstance(Downloader instance) {
theInstance = instance;
}
public static Downloader getInstance() {
if (theInstance != null)
return theInstance;
return theInstance = new Downloader();
}
protected Downloader() { }
public DownloadDestination requestDownload(
String url, OnDownloadProgress listener, File path) {
DownloadDestination destination = new DownloadDestination(path);
DownloadTarget target = new FileDownloadTarget(destination);
DownloadTask task = new DownloadTask(listener, target);
// avoid potential error condition
executeLater(task, url);
return destination;
}
public DownloadDestination requestDownload(
String url, OnDownloadProgress listener) {
DownloadDestination destination = new DownloadDestination();
DownloadTarget target = new StringDownloadTarget(destination);
DownloadTask task = new DownloadTask(listener, target);
// avoid potential error condition
executeLater(task, url);
return destination;
}
private void executeLater(final DownloadTask task, final String url) {
new android.os.Handler().post(
new Runnable() {
@Override
public void run() {
task.execute(url);
}
});
}
}
|
package org.biojava.bio.symbol;
import java.util.*;
import org.biojava.bio.seq.*;
/**
* <p>
* A factory that is used to maintain associations between alphabets and
* preferred bit-packings for them.
* </p>
*
* <p>
* There are many ways to pack the symbols for an alphabet as binary.
* Different applications will wish to have different representations for
* reasons such as integration with external formats, wether to store
* ambiguity or not and what algorithms may be used on the bit-packed
* representation. Also, it has utility methods to arrange the bit-strings
* for symbols within a Java int primative.
* </p>
*
* @author Matthew Pocock
* @author Thomas Down
*/
public class PackingFactory {
private final static Map packForAlpha;
static {
packForAlpha = new HashMap();
}
/**
* Get the default packing for an alphabet.
*
* @param alpha the FiniteAlphabet that will be bit-packed
* @param ambiguity true if the packing should store ambiguity and false
* if it can discard ambiguity information
**/
public static Packing getPacking(FiniteAlphabet alpha, boolean ambiguity)
throws IllegalAlphabetException {
Packing pack = (Packing) packForAlpha.get(alpha);
if(pack == null) {
if(alpha == DNATools.getDNA()) {
if(ambiguity) {
pack = new DNAAmbPack();
} else {
pack = new DNANoAmbPack(DNATools.a());
}
} else {
throw new IllegalAlphabetException();
}
}
return pack;
}
public static int primeWord(
SymbolList symList,
int wordLength,
Packing packing
) throws IllegalSymbolException {
int word = 0;
for(int i = 0; i < wordLength; i++) {
int p = packing.pack(symList.symbolAt(i+1));
word |= (int) ((int) p << (int) (i * packing.wordSize()));
}
return word;
}
public static int nextWord(
SymbolList symList,
int word,
int offset,
int wordLength,
Packing packing
) throws IllegalSymbolException {
word = word >> (int) packing.wordSize();
int p = packing.pack(symList.symbolAt(offset));
word |= (int) p << ((int) (wordLength - 1) * packing.wordSize());
return word;
}
public static void binary(long val) {
for(int i = 63; i >= 0; i
System.out.print( ((((val >> i) & 1) == 1) ? 1 : 0) );
}
System.out.println();
}
public static void binary(int val) {
for(int i = 31; i >= 0; i
System.out.print( ((((val >> i) & 1) == 1) ? 1 : 0) );
}
System.out.println();
}
}
|
package org.bouncycastle.asn1;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
/**
* a general purpose ASN.1 decoder - note: this class differs from the
* others in that it returns null after it has read the last object in
* the stream. If an ASN.1 NULL is encountered a DER/BER Null object is
* returned.
*/
public class ASN1InputStream
extends FilterInputStream
implements DERTags
{
private static final DERObject END_OF_STREAM = new DERObject()
{
void encode(
DEROutputStream out)
throws IOException
{
throw new IOException("Eeek!");
}
public int hashCode()
{
return 0;
}
public boolean equals(
Object o)
{
return o == this;
}
};
boolean eofFound = false;
int limit = Integer.MAX_VALUE;
public ASN1InputStream(
InputStream is)
{
super(is);
}
/**
* Create an ASN1InputStream based on the input byte array. The length of DER objects in
* the stream is automatically limited to the length of the input array.
*
* @param input array containing ASN.1 encoded data.
*/
public ASN1InputStream(
byte[] input)
{
this(new ByteArrayInputStream(input), input.length);
}
/**
* Create an ASN1InputStream where no DER object will be longer than limit.
*
* @param input stream containing ASN.1 encoded data.
* @param limit maximum size of a DER encoded object.
*/
public ASN1InputStream(
InputStream input,
int limit)
{
super(input);
this.limit = limit;
}
protected int readLength()
throws IOException
{
int length = read();
if (length < 0)
{
throw new IOException("EOF found when length expected");
}
if (length == 0x80)
{
return -1; // indefinite-length encoding
}
if (length > 127)
{
int size = length & 0x7f;
if (size > 4)
{
throw new IOException("DER length more than 4 bytes");
}
length = 0;
for (int i = 0; i < size; i++)
{
int next = read();
if (next < 0)
{
throw new IOException("EOF found reading length");
}
length = (length << 8) + next;
}
if (length < 0)
{
throw new IOException("corrupted steam - negative length found");
}
if (length >= limit) // after all we must have read at least 1 byte
{
throw new IOException("corrupted steam - out of bounds length found");
}
}
return length;
}
protected void readFully(
byte[] bytes)
throws IOException
{
int left = bytes.length;
int len;
if (left == 0)
{
return;
}
while ((len = read(bytes, bytes.length - left, left)) > 0)
{
if ((left -= len) == 0)
{
return;
}
}
if (left != 0)
{
throw new EOFException("EOF encountered in middle of object");
}
}
/**
* build an object given its tag and the number of bytes to construct it from.
*/
protected DERObject buildObject(
int tag,
int tagNo,
int length)
throws IOException
{
if ((tag & APPLICATION) != 0)
{
return new DERApplicationSpecific(tagNo, readDefiniteLengthFully(length));
}
boolean isConstructed = (tag & CONSTRUCTED) != 0;
if (isConstructed)
{
switch (tag)
{
case SEQUENCE | CONSTRUCTED:
return new DERSequence(buildDerEncodableVector(length));
case SET | CONSTRUCTED:
return new DERSet(buildDerEncodableVector(length), false);
case OCTET_STRING | CONSTRUCTED:
return buildDerConstructedOctetString(length);
default:
{
// with tagged object tag number is bottom 5 bits
if ((tag & TAGGED) != 0)
{
if (length == 0) // empty tag!
{
return new DERTaggedObject(false, tagNo, new DERSequence());
}
ASN1EncodableVector v = buildDerEncodableVector(length);
if (v.size() == 1)
{
// explicitly tagged (probably!) - if it isn't we'd have to
// tell from the context
return new DERTaggedObject(tagNo, v.get(0));
}
return new DERTaggedObject(false, tagNo, new DERSequence(v));
}
return new DERUnknownTag(tag, readDefiniteLengthFully(length));
}
}
}
byte[] bytes = readDefiniteLengthFully(length);
switch (tag)
{
case NULL:
return DERNull.INSTANCE;
case BOOLEAN:
return new DERBoolean(bytes);
case INTEGER:
return new DERInteger(bytes);
case ENUMERATED:
return new DEREnumerated(bytes);
case OBJECT_IDENTIFIER:
return new DERObjectIdentifier(bytes);
case BIT_STRING:
{
int padBits = bytes[0];
byte[] data = new byte[bytes.length - 1];
System.arraycopy(bytes, 1, data, 0, bytes.length - 1);
return new DERBitString(data, padBits);
}
case NUMERIC_STRING:
return new DERNumericString(bytes);
case UTF8_STRING:
return new DERUTF8String(bytes);
case PRINTABLE_STRING:
return new DERPrintableString(bytes);
case IA5_STRING:
return new DERIA5String(bytes);
case T61_STRING:
return new DERT61String(bytes);
case VISIBLE_STRING:
return new DERVisibleString(bytes);
case GENERAL_STRING:
return new DERGeneralString(bytes);
case UNIVERSAL_STRING:
return new DERUniversalString(bytes);
case BMP_STRING:
return new DERBMPString(bytes);
case OCTET_STRING:
return new DEROctetString(bytes);
case UTC_TIME:
return new DERUTCTime(bytes);
case GENERALIZED_TIME:
return new DERGeneralizedTime(bytes);
default:
{
// with tagged object tag number is bottom 5 bits
if ((tag & TAGGED) != 0)
{
if (bytes.length == 0) // empty tag!
{
return new DERTaggedObject(false, tagNo, DERNull.INSTANCE);
}
// simple type - implicit... return an octet string
return new DERTaggedObject(false, tagNo, new DEROctetString(bytes));
}
return new DERUnknownTag(tag, bytes);
}
}
}
private byte[] readDefiniteLengthFully(int length)
throws IOException
{
byte[] bytes = new byte[length];
readFully(bytes);
return bytes;
}
/**
* read a string of bytes representing an indefinite length object.
*/
private byte[] readIndefiniteLengthFully()
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int b, b1;
b1 = read();
while ((b = read()) >= 0)
{
if (b1 == 0 && b == 0)
{
break;
}
bOut.write(b1);
b1 = b;
}
return bOut.toByteArray();
}
private BERConstructedOctetString buildConstructedOctetString(DERObject sentinel)
throws IOException
{
Vector octs = new Vector();
DERObject o;
while ((o = readObject()) != sentinel)
{
octs.addElement(o);
}
return new BERConstructedOctetString(octs);
}
// yes, people actually do this...
private BERConstructedOctetString buildDerConstructedOctetString(int length)
throws IOException
{
DefiniteLengthInputStream dIn = new DefiniteLengthInputStream(this, length);
ASN1InputStream aIn = new ASN1InputStream(dIn, length);
return aIn.buildConstructedOctetString(null);
}
private ASN1EncodableVector buildEncodableVector(DERObject sentinel)
throws IOException
{
ASN1EncodableVector v = new ASN1EncodableVector();
DERObject o;
while ((o = readObject()) != sentinel)
{
v.add(o);
}
return v;
}
private ASN1EncodableVector buildDerEncodableVector(int length)
throws IOException
{
DefiniteLengthInputStream dIn = new DefiniteLengthInputStream(this, length);
ASN1InputStream aIn = new ASN1InputStream(dIn, length);
return aIn.buildEncodableVector(null);
}
public DERObject readObject()
throws IOException
{
int tag = read();
if (tag == -1)
{
if (eofFound)
{
throw new EOFException("attempt to read past end of file.");
}
eofFound = true;
return null;
}
int tagNo = 0;
if ((tag & TAGGED) != 0 || (tag & APPLICATION) != 0)
{
tagNo = readTagNumber(tag);
}
int length = readLength();
if (length < 0) // indefinite length method
{
switch (tag)
{
case NULL:
return BERNull.INSTANCE;
case SEQUENCE | CONSTRUCTED:
return new BERSequence(buildEncodableVector(END_OF_STREAM));
case SET | CONSTRUCTED:
return new BERSet(buildEncodableVector(END_OF_STREAM), false);
case OCTET_STRING | CONSTRUCTED:
return buildConstructedOctetString(END_OF_STREAM);
default:
{
// with tagged object tag number is bottom 5 bits
if ((tag & TAGGED) != 0)
{
// simple type - implicit... return an octet string
if ((tag & CONSTRUCTED) == 0)
{
byte[] bytes = readIndefiniteLengthFully();
return new BERTaggedObject(false, tagNo, new DEROctetString(bytes));
}
// either constructed or explicitly tagged
ASN1EncodableVector v = buildEncodableVector(END_OF_STREAM);
if (v.size() == 0) // empty tag!
{
return new DERTaggedObject(tagNo);
}
if (v.size() == 1)
{
// explicitly tagged (probably!) - if it isn't we'd have to
// tell from the context
return new BERTaggedObject(tagNo, v.get(0));
}
return new BERTaggedObject(false, tagNo, new BERSequence(v));
}
throw new IOException("unknown BER object encountered");
}
}
}
else
{
if (tag == 0 && length == 0) // end of contents marker.
{
return END_OF_STREAM;
}
return buildObject(tag, tagNo, length);
}
}
private int readTagNumber(int tag)
throws IOException
{
int tagNo = tag & 0x1f;
if (tagNo == 0x1f)
{
int b = read();
tagNo = 0;
while ((b >= 0) && ((b & 0x80) != 0))
{
tagNo |= (b & 0x7f);
tagNo <<= 7;
b = read();
}
if (b < 0)
{
eofFound = true;
throw new EOFException("EOF found inside tag value.");
}
tagNo |= (b & 0x7f);
}
return tagNo;
}
}
|
package org.bouncycastle.math.ec;
import java.math.BigInteger;
public class ECAlgorithms
{
/*
* "Shamir's Trick", originally due to E. G. Straus
* (Addition chains of vectors. American Mathematical Monthly,
* 71(7):806808, Aug./Sept. 1964)
* <pre>
* Input: The points P, Q, scalar k = (km?, ... , k1, k0)
* and scalar l = (lm?, ... , l1, l0).
* Output: R = k * P + l * Q.
* 1: Z <- P + Q
* 2: R <- O
* 3: for i from m-1 down to 0 do
* 4: R <- R + R {point doubling}
* 5: if (ki = 1) and (li = 0) then R <- R + P end if
* 6: if (ki = 0) and (li = 1) then R <- R + Q end if
* 7: if (ki = 1) and (li = 1) then R <- R + Z end if
* 8: end for
* 9: return R
* </pre>
*/
public static ECPoint shamirsTrick(ECPoint P, BigInteger k,
ECPoint Q, BigInteger l)
{
if (!P.getCurve().equals(Q.getCurve()))
{
throw new IllegalArgumentException("P and Q must be on same curve");
}
int m = Math.max(k.bitLength(), l.bitLength());
ECPoint Z = P.add(Q);
ECPoint R = P.getCurve().getInfinity();
for (int i = m - 1; i >= 0; --i)
{
R = R.twice();
if (k.testBit(i))
{
if (l.testBit(i))
{
R = R.add(Z);
}
else
{
R = R.add(P);
}
}
else
{
if (l.testBit(i))
{
R = R.add(Q);
}
}
}
return R;
}
}
|
package org.bouncycastle.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A simple collection backed store.
*/
public class CollectionStore
implements Store
{
private Collection _local;
/**
* Basic constructor.
*
* @param collection - initial contents for the store, this is copied.
*/
public CollectionStore(
Collection collection)
{
_local = new ArrayList(collection);
}
/**
* Return the matches in the collection for the passed in selector.
*
* @param selector the selector to match against.
* @return a possibly empty collection of matching objects.
*/
public Collection getMatches(Selector selector)
{
if (selector == null)
{
return new ArrayList(_local);
}
else
{
List col = new ArrayList();
Iterator iter = _local.iterator();
while (iter.hasNext())
{
Object obj = iter.next();
if (selector.match(obj))
{
col.add(obj);
}
}
return col;
}
}
}
|
package org.exist.util;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.exist.EXistException;
import org.exist.Namespaces;
import org.exist.storage.BrokerPool;
import org.exist.validation.resolver.eXistXMLCatalogResolver;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
/**
* Factory to create new XMLReader objects on demand. The factory is used
* by {@link org.exist.util.XMLReaderPool}.
*
* @author wolf
*/
public class XMLReaderObjectFactory extends BasePoolableObjectFactory {
private final static int VALIDATION_ENABLED = 0;
private final static int VALIDATION_AUTO = 1;
private final static int VALIDATION_DISABLED = 2;
public static final String CONFIGURATION_ENTITY_RESOLVER_ELEMENT_NAME = "entity-resolver";
public static final String CONFIGURATION_CATALOG_ELEMENT_NAME = "catalog";
public static final String CONFIGURATION_ELEMENT_NAME = "validation";
public final static String PROPERTY_VALIDATION = "validation.mode";
public final static String CATALOG_RESOLVER = "validation.resolver";
public final static String CATALOG_URIS = "validation.catalog_uris";
public final static String GRAMMER_POOL = "validation.grammar_pool";
public final static String PROPERTIES_RESOLVER
="http://apache.org/xml/properties/internal/entity-resolver";
private BrokerPool pool;
public XMLReaderObjectFactory(BrokerPool pool) {
super();
this.pool = pool;
}
/** (non-Javadoc)
* @see org.apache.commons.pool.BasePoolableObjectFactory#makeObject()
*/
public Object makeObject() throws Exception {
Configuration config = pool.getConfiguration();
// get validation settings
int validation = VALIDATION_AUTO;
String option = (String) config.getProperty(PROPERTY_VALIDATION);
if (option != null) {
if (option.equals("true") || option.equals("yes"))
validation = VALIDATION_ENABLED;
else if (option.equals("auto"))
validation = VALIDATION_AUTO;
else
validation = VALIDATION_DISABLED;
}
// create a SAX parser
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
if (validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED){
saxFactory.setValidating(true);
} else {
saxFactory.setValidating(false);
}
saxFactory.setNamespaceAware(true);
try {
saxFactory.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true);
try {
// TODO check does this work?
saxFactory.setFeature(Namespaces.SAX_VALIDATION,
validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED);
saxFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED);
saxFactory.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC,
validation == VALIDATION_AUTO);
saxFactory.setFeature("http://apache.org/xml/features/validation/schema",
validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED);
} catch (SAXNotRecognizedException e1) {
// ignore: feature only recognized by xerces
} catch (SAXNotSupportedException e1) {
// ignore: feature only recognized by xerces
}
SAXParser sax = saxFactory.newSAXParser();
XMLReader parser = sax.getXMLReader();
eXistXMLCatalogResolver resolver = (eXistXMLCatalogResolver) config.getProperty(CATALOG_RESOLVER);
if(resolver!=null){
parser.setProperty(PROPERTIES_RESOLVER, resolver);
}
return parser;
} catch (ParserConfigurationException e) {
throw new EXistException(e);
}
}
}
|
package org.exist.xmldb;
import java.util.Date;
import org.exist.dom.DocumentImpl;
import org.exist.security.Permission;
import org.exist.security.User;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.util.LockException;
import org.exist.xquery.Constants;
import org.w3c.dom.DocumentType;
import org.xml.sax.ext.LexicalHandler;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.XMLDBException;
/**
* Abstract base implementation of interface EXistResource.
*/
public abstract class AbstractEXistResource implements EXistResource {
protected User user;
protected BrokerPool pool;
protected LocalCollection parent;
protected String docId = null;
protected String mimeType = null;
protected boolean isNewResource = false;
public AbstractEXistResource(User user, BrokerPool pool, LocalCollection parent, String docId, String mimeType) {
this.user = user;
this.pool = pool;
this.parent = parent;
//TODO : use dedicated function in XmldbURI
if (docId.indexOf("/") != Constants.STRING_NOT_FOUND)
docId = docId.substring(docId.lastIndexOf("/") + 1);
this.docId = docId;
this.mimeType = mimeType;
}
/* (non-Javadoc)
* @see org.exist.xmldb.EXistResource#getCreationTime()
*/
public abstract Date getCreationTime() throws XMLDBException;
/* (non-Javadoc)
* @see org.exist.xmldb.EXistResource#getLastModificationTime()
*/
public abstract Date getLastModificationTime() throws XMLDBException;
public abstract Permission getPermissions() throws XMLDBException;
/* (non-Javadoc)
* @see org.exist.xmldb.EXistResource#setLexicalHandler(org.xml.sax.ext.LexicalHandler)
*/
public void setLexicalHandler(LexicalHandler handler) {
}
public void setMimeType(String mime) {
this.mimeType = mime;
}
public String getMimeType() throws XMLDBException {
return mimeType;
}
protected DocumentImpl openDocument(DBBroker broker, int lockMode) throws XMLDBException {
DocumentImpl document = null;
org.exist.collections.Collection parentCollection = null;
try {
parentCollection = parent.getCollectionWithLock(lockMode);
if(parentCollection == null)
throw new XMLDBException(ErrorCodes.INVALID_COLLECTION, "Collection " + parent.getPath() + " not found");
try {
document = parentCollection.getDocumentWithLock(broker, docId, lockMode);
} catch (LockException e) {
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"Failed to acquire lock on document " + docId);
}
if (document == null) {
throw new XMLDBException(ErrorCodes.INVALID_RESOURCE);
}
// System.out.println("Opened document " + document.getName() + " mode = " + lockMode);
return document;
} finally {
if(parentCollection != null)
parentCollection.release();
}
}
protected void closeDocument(DocumentImpl doc, int lockMode) throws XMLDBException {
if(doc == null)
return;
// System.out.println("Closed " + doc.getName() + " mode = " + lockMode);
doc.getUpdateLock().release(lockMode);
}
public DocumentType getDocType() throws XMLDBException {
return null;
}
public void setDocType(DocumentType doctype) throws XMLDBException {
}
}
|
package org.myrobotlab.service;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import org.myrobotlab.deeplearning4j.MRLLabelGenerator;
import org.myrobotlab.framework.Service;
import org.datavec.api.berkeley.StringUtils;
import org.datavec.api.io.filters.BalancedPathFilter;
import org.datavec.api.io.labels.ParentPathLabelGenerator;
import org.datavec.api.split.FileSplit;
import org.datavec.api.split.InputSplit;
import org.datavec.image.loader.NativeImageLoader;
import org.datavec.image.recordreader.ImageRecordReader;
import org.datavec.image.transform.FlipImageTransform;
import org.datavec.image.transform.ImageTransform;
import org.datavec.image.transform.WarpImageTransform;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.datasets.iterator.MultipleEpochsIterator;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.GradientNormalization;
import org.deeplearning4j.nn.conf.LearningRatePolicy;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.distribution.Distribution;
import org.deeplearning4j.nn.conf.distribution.GaussianDistribution;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.inputs.InvalidInputTypeException;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.LocalResponseNormalization;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.util.ModelSerializer;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.io.FileIO;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.complex.IComplexNDArray;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
import org.nd4j.linalg.dataset.api.preprocessor.VGG16ImagePreProcessor;
import org.nd4j.linalg.indexing.INDArrayIndex;
import org.nd4j.linalg.indexing.ShapeOffsetResolution;
import org.nd4j.linalg.indexing.conditions.Condition;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import ch.qos.logback.core.util.FileUtil;
import marytts.util.io.FileUtils;
public class Deeplearning4j extends Service {
private static final long serialVersionUID = 1L;
// TODO: update these based on the input sample data...
protected static int height = 100;
protected static int width = 100;
protected static int channels = 3;
// TODO: the number of labels for the current model
protected static int modelNumLabels = 0;
// TODO: what does this actually control?!
protected static int batchSize = 20;
protected static long seed = 42;
protected static Random rng = new Random(seed);
protected static int listenerFreq = 1;
protected static int iterations = 1;
// protected static int epochs = 50;
public static int epochs = 2;
protected static int nCores = 8;
protected static String modelType = "AlexNet"; // LeNet, AlexNet or Custom but you need to fill it out
public String modelDir = "models";
public String modelFilename = "model.bin";
// This is the "model" to be trained and used
private MultiLayerNetwork network;
// these are the labels that relate to the output of the model.
private List<String> networkLabels;
// constructor.
public Deeplearning4j(String reservedKey) {
super(reservedKey);
}
/**
* Train a model based on a directory of training data. Each subdirectory is named for it's label
* the files in that subdirectory are examples of that label. Normally a directory will contain a bunch
* of training images.
*
* @param trainingDataDir the directory that contains the subdirectories of labels.
* @throws IOException e
*/
public void trainModel(String trainingDataDir) throws IOException {
log.info("Load data....");
/**
* Data Setup -> organize and limit data file paths:
* - mainPath = path to image files
* - fileSplit = define basic dataset split with limits on format
* - pathFilter = define additional file load filter to limit size and balance batch content
**/
ParentPathLabelGenerator labelMaker = new MRLLabelGenerator();
// load up the path where the training data lives.
File mainPath = new File(trainingDataDir);
FileSplit fileSplit = new FileSplit(mainPath, NativeImageLoader.ALLOWED_FORMATS, rng);
ImageRecordReader recordReader = new ImageRecordReader(height, width, channels, labelMaker);
DataSetIterator dataIter;
/**
* Data Setup -> transformation
* - Transform = how to tranform images and generate large dataset to train on
**/
List<ImageTransform> transforms = createImageTransformList();
/**
* Data Setup -> normalization
* - how to normalize images and generate large dataset to train on
* Data Setup -> define how to load data into net:
* - recordReader = the reader that loads and converts image data pass in inputSplit to initialize
* - dataIter = a generator that only loads one batch at a time into memory to save memory
* - trainIter = uses MultipleEpochsIterator to ensure model runs through the data for all epochs
**/
MultipleEpochsIterator trainIter;
log.info("Train network....");
// Train without transformations
recordReader.initialize(fileSplit, null);
log.info("Create network....{}", networkLabels);
// training set metadata , the labels and how many there are
networkLabels = recordReader.getLabels();
int numLabels = networkLabels.size();
log.info("Network Labels: {}", networkLabels);
// an interator for that dataset.
dataIter = new RecordReaderDataSetIterator(recordReader, batchSize, 1, numLabels);
DataNormalization scaler = new ImagePreProcessingScaler(0, 1);
// pre process / fit the data with the scaler.
scaler.fit(dataIter);
// build the neural network (specify structure, etc..)
network = createNetwork(numLabels);
// our preprocessor ... TODO: is this necessary here?
dataIter.setPreProcessor(scaler);
// TODO: learn more about what this does.
trainIter = new MultipleEpochsIterator(epochs, dataIter, nCores);
// The magic.. train the model!
network.fit(trainIter);
// Train with transformations
for (ImageTransform transform : transforms) {
log.info("Training on transformation: {}" , transform.getClass().toString());
recordReader.initialize(fileSplit, transform);
dataIter = new RecordReaderDataSetIterator(recordReader, batchSize, 1, numLabels);
scaler.fit(dataIter);
dataIter.setPreProcessor(scaler);
trainIter = new MultipleEpochsIterator(epochs, dataIter, nCores);
// train the model even more with some transpositions of the original image.
network.fit(trainIter);
}
log.info("Done training model..");
}
public void trainModel() throws IOException {
trainModel("./training");
}
/*
* This provides a list of various transforms to attempt on the image as part of the training process
* this synthetically generates a larger training set. I think it's typically used to train in
* rotational and scale invariance in the matching of the network. But, that's just a guess :)
*/
private List<ImageTransform> createImageTransformList() {
// TODO: consider a bunch of opencv filter based transforms here!
ImageTransform flipTransform1 = new FlipImageTransform(rng);
ImageTransform flipTransform2 = new FlipImageTransform(new Random(123));
ImageTransform warpTransform = new WarpImageTransform(rng, 42);
List<ImageTransform> transforms = Arrays.asList(new ImageTransform[]{flipTransform1, warpTransform, flipTransform2});
return transforms;
}
private MultiLayerNetwork createNetwork(int numLabels) {
MultiLayerNetwork network = null;
switch (modelType) {
case "LeNet":
network = lenetModel(numLabels);
break;
case "AlexNet":
network = alexnetModel(numLabels);
break;
case "custom":
network = customModel(numLabels);
break;
default:
throw new InvalidInputTypeException("Incorrect model provided.");
}
network.init();
network.setListeners(new ScoreIterationListener(listenerFreq));
return network;
}
// save the current model and it's set of labels
public void saveModel(String filename) throws IOException {
File dir = new File(modelDir);
if (!dir.exists()) {
dir.mkdirs();
log.info("Creating models directory {}" , dir);
}
File f = new File(filename);
log.info("Saving DL4J model to {}", f.getAbsolutePath());
ModelSerializer.writeModel(network, filename, true);
// also need to save the labels!
String labelFilename = filename + ".labels";
FileWriter fw = new FileWriter(new File(labelFilename));
fw.write(StringUtils.join(networkLabels, "|"));
fw.flush();
fw.close();
log.info("Model saved.");
}
public void saveModel() throws IOException {
saveModel(modelDir + File.separator + modelFilename);
}
// load the default model
public void loadModel() throws IOException {
loadModel(modelDir + File.separator + modelFilename);
}
// load a model based on its filename and the labels from an associated filename.labels file..
public void loadModel(String filename) throws IOException {
File f = new File(filename);
log.info("Loading network from : {}", f.getAbsolutePath());
network = ModelSerializer.restoreMultiLayerNetwork(f, true);
log.info("Network restored. {}", network);
// TODO: there has to be a better way to manage the labels!?!?!! Gah
networkLabels = StringUtils.split(FileIO.toString(new File(filename + ".labels")), "\\|");
modelNumLabels = networkLabels.size();
log.info("Network labels {} objects", modelNumLabels);
}
public void evaluateModel(File file) throws IOException {
log.info("Evaluate model....");
NativeImageLoader nativeImageLoader = new NativeImageLoader(height, width, channels);
INDArray image = nativeImageLoader.asMatrix(file); // testImage is of Mat format
// 0-255 to 0-1
DataNormalization scaler = new ImagePreProcessingScaler(0, 1);
scaler.transform(image);
// Pass through to neural Net
INDArray output = network.output(image);
System.out.println(output);
System.out.println(networkLabels);
// TODO: I suppose we could create a map of probabilities and return that ...
// this map could be large
}
/* From the animals classification example */
public MultiLayerNetwork lenetModel(int numLabels) {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(iterations)
.regularization(false).l2(0.005) // tried 0.0001, 0.0005
.activation(Activation.RELU)
.learningRate(0.0001) // tried 0.00001, 0.00005, 0.000001
.weightInit(WeightInit.XAVIER)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(Updater.RMSPROP).momentum(0.9)
.list()
.layer(0, convInit("cnn1", channels, 50 , new int[]{5, 5}, new int[]{1, 1}, new int[]{0, 0}, 0))
.layer(1, maxPool("maxpool1", new int[]{2,2}))
.layer(2, conv5x5("cnn2", 100, new int[]{5, 5}, new int[]{1, 1}, 0))
.layer(3, maxPool("maxool2", new int[]{2,2}))
.layer(4, new DenseLayer.Builder().nOut(500).build())
.layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(numLabels)
.activation(Activation.SOFTMAX)
.build())
.backprop(true).pretrain(false)
.setInputType(InputType.convolutional(height, width, channels))
.build();
return new MultiLayerNetwork(conf);
}
/* From the animals classification example */
public MultiLayerNetwork alexnetModel(int numLabels) {
double nonZeroBias = 1;
double dropOut = 0.5;
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(seed)
.weightInit(WeightInit.DISTRIBUTION)
.dist(new NormalDistribution(0.0, 0.01))
.activation(Activation.RELU)
.updater(Updater.NESTEROVS)
.iterations(iterations)
.gradientNormalization(GradientNormalization.RenormalizeL2PerLayer) // normalize to prevent vanishing or exploding gradients
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(1e-2)
.biasLearningRate(1e-2*2)
.learningRateDecayPolicy(LearningRatePolicy.Step)
.lrPolicyDecayRate(0.1)
.lrPolicySteps(100000)
.regularization(true)
.l2(5 * 1e-4)
.momentum(0.9)
.miniBatch(false)
.list()
.layer(0, convInit("cnn1", channels, 96, new int[]{11, 11}, new int[]{4, 4}, new int[]{3, 3}, 0))
.layer(1, new LocalResponseNormalization.Builder().name("lrn1").build())
.layer(2, maxPool("maxpool1", new int[]{3,3}))
.layer(3, conv5x5("cnn2", 256, new int[] {1,1}, new int[] {2,2}, nonZeroBias))
.layer(4, new LocalResponseNormalization.Builder().name("lrn2").build())
.layer(5, maxPool("maxpool2", new int[]{3,3}))
.layer(6,conv3x3("cnn3", 384, 0))
.layer(7,conv3x3("cnn4", 384, nonZeroBias))
.layer(8,conv3x3("cnn5", 256, nonZeroBias))
.layer(9, maxPool("maxpool3", new int[]{3,3}))
.layer(10, fullyConnected("ffn1", 4096, nonZeroBias, dropOut, new GaussianDistribution(0, 0.005)))
.layer(11, fullyConnected("ffn2", 4096, nonZeroBias, dropOut, new GaussianDistribution(0, 0.005)))
.layer(12, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.name("output")
.nOut(numLabels)
.activation(Activation.SOFTMAX)
.build())
.backprop(true)
.pretrain(false)
.setInputType(InputType.convolutional(height, width, channels))
.build();
return new MultiLayerNetwork(conf);
}
/* From the animals classification example */
public static MultiLayerNetwork customModel(int numLabels) {
/**
* Use this method to build your own custom model.
**/
log.error("Not implemented!!!");
return null;
}
private ConvolutionLayer convInit(String name, int in, int out, int[] kernel, int[] stride, int[] pad, double bias) {
return new ConvolutionLayer.Builder(kernel, stride, pad).name(name).nIn(in).nOut(out).biasInit(bias).build();
}
private ConvolutionLayer conv3x3(String name, int out, double bias) {
return new ConvolutionLayer.Builder(new int[]{3,3}, new int[] {1,1}, new int[] {1,1}).name(name).nOut(out).biasInit(bias).build();
}
private ConvolutionLayer conv5x5(String name, int out, int[] stride, int[] pad, double bias) {
return new ConvolutionLayer.Builder(new int[]{5,5}, stride, pad).name(name).nOut(out).biasInit(bias).build();
}
private SubsamplingLayer maxPool(String name, int[] kernel) {
return new SubsamplingLayer.Builder(kernel, new int[]{2,2}).name(name).build();
}
private DenseLayer fullyConnected(String name, int out, double bias, double dropOut, Distribution dist) {
return new DenseLayer.Builder().name(name).nOut(out).biasInit(bias).dropOut(dropOut).dist(dist).build();
}
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Deeplearning4j.class.getCanonicalName());
meta.addDescription("A wrapper service for the Deeplearning4j framework.");
meta.addCategory("ai");
meta.addDependency("org.deeplearning4j", "0.8");
// this also depends on opencv
meta.addDependency("org.bytedeco.javacv", "1.3");
// and this is just a good frame grabber.. might as well pull it in.
meta.addDependency("pl.sarxos.webcam", "0.3.10");
return meta;
}
public static void main(String[] args) throws IOException {
Deeplearning4j dl4j = (Deeplearning4j)Runtime.createAndStart("dl4j", "Deeplearning4j");
// this is how many generations to iterate on training the dataset. larger number means longer training time.
dl4j.epochs = 50;
dl4j.trainModel("test/resources/animals");
//dl4j.trainModel("training");
// save the model out
dl4j.saveModel();
dl4j.loadModel();
//File testIm = new File("test/resources/animals/turtle/Baby_sea_turtle.jpg");
// File testIm = new File("test/resources/animals/deer/BlackTailed_Deer_Doe.jpg");
File testIm = new File("test/resources/animals/turtle/Western_Painted_Turtle.jpg");
// BufferedImage img = ImageIO.read(testIm);
// Frame frame = grabberConverter.convert(img);
dl4j.evaluateModel(testIm);
// dl4j.evaluateModel(img);
System.out.println("Done evaluating the model.");
System.exit(0);
}
}
|
package org.opencms.widgets;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.json.JSONArray;
import org.opencms.json.JSONException;
import org.opencms.json.JSONObject;
import org.opencms.loader.CmsImageScaler;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.types.CmsXmlVfsImageValue;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
/**
* Provides a widget for an extended image selection using the advanced gallery dialog.<p>
*
* @since 7.5.0
*/
public class CmsVfsImageWidget extends CmsAdeImageGalleryWidget {
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsVfsImageWidget.class);
/** Input field prefix for the description field. */
private static final String PREFIX_DESCRIPTION = "desc.";
/** Input field prefix for the format field. */
private static final String PREFIX_FORMAT = "format.";
/** Input field prefix for the hidden format value field. */
private static final String PREFIX_FORMATVALUE = "fmtval.";
/** Input field prefix for the image field. */
private static final String PREFIX_IMAGE = "img.";
/** Input field prefix for the image ratio field. */
private static final String PREFIX_IMAGERATIO = "imgrat.";
/** Input field prefix for the hidden scale field. */
private static final String PREFIX_SCALE = "scale.";
/**
* Creates a new image widget.<p>
*/
public CmsVfsImageWidget() {
// empty constructor is required for class registration
super();
}
/**
* Creates an image widget with the specified configuration options.<p>
*
* @param configuration the configuration (possible options) for the image widget
*/
public CmsVfsImageWidget(String configuration) {
super(configuration);
}
/**
* @see org.opencms.widgets.I_CmsWidget#getDialogIncludes(org.opencms.file.CmsObject,org.opencms.widgets.I_CmsWidgetDialog)
*/
@Override
public String getDialogIncludes(CmsObject cms, I_CmsWidgetDialog widgetDialog) {
StringBuffer result = new StringBuffer(256);
// import the JavaScript for the image widget
result.append(getJSIncludeFile(CmsWorkplace.getSkinUri() + "components/widgets/vfsimage.js"));
return result.toString();
}
/**
* @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public String getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
String id = param.getId();
long idHash = id.hashCode();
if (idHash < 0) {
// negative hash codes will not work as JS variable names, so convert them
idHash = -idHash;
// add 2^32 to the value to ensure that it is unique
idHash += 4294967296L;
}
// cast parameter to xml value to access the specific methods
CmsXmlVfsImageValue value = (CmsXmlVfsImageValue)param;
String imageLink = value.getRequestLink(cms);
if (imageLink == null) {
imageLink = "";
}
StringBuffer result = new StringBuffer(4096);
result.append("<td class=\"xmlTd\" style=\"height: 25px;\">");
result.append("<table class=\"xmlTableNested\">");
result.append("<tr>");
result.append("<td class=\"xmlLabel\">");
result.append(widgetDialog.getMessages().key(Messages.GUI_EDITOR_LABEL_IMAGE_PATH_0));
result.append(" </td>");
result.append("<td>");
result.append("<input class=\"xmlInputMedium\" value=\"").append(imageLink).append("\" name=\"");
result.append(PREFIX_IMAGE).append(id).append("\" id=\"");
result.append(PREFIX_IMAGE).append(id);
result.append("\" onkeyup=\"checkVfsImagePreview('");
result.append(id);
result.append("');\" />");
result.append("</td>");
result.append(widgetDialog.dialogHorizontalSpacer(10));
result.append("<td><table class=\"editorbuttonbackground\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
result.append(widgetDialog.button(getOpenGalleryCall(cms, widgetDialog, param, idHash), null, getGalleryName()
+ "gallery", Messages.getButtonName(getGalleryName()), widgetDialog.getButtonStyle()));
// create preview button
String previewClass = "hide";
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(imageLink)) {
// show button if preview is enabled
previewClass = "show";
}
result.append("<td class=\"");
result.append(previewClass);
result.append("\" id=\"preview");
result.append(id);
result.append("\">");
result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
result.append(widgetDialog.button(
getOpenPreviewCall(widgetDialog, PREFIX_IMAGE + param.getId()),
null,
"preview.png",
Messages.GUI_BUTTON_PREVIEW_0,
widgetDialog.getButtonStyle()));
result.append("</tr></table></td>");
result.append("</tr></table></td>");
result.append("</tr>");
JSONObject additional = null;
try {
additional = getAdditionalGalleryInfo(cms, widgetDialog, param);
} catch (JSONException e) {
LOG.error("Error parsing widget configuration", e);
}
if (additional != null) {
result.append("\n<script type=\"text/javascript\">\n");
result.append("var cms_additional_").append(idHash).append("=");
result.append(additional.toString()).append(";\n");
result.append("</script>");
}
CmsVfsImageWidgetConfiguration configuration = getWidgetConfiguration(cms, widgetDialog, param);
String format = value.getFormat(cms);
if (configuration.isShowFormat()) {
// show the format select box, also create hidden format value field
result.append("<tr>");
result.append("<td class=\"xmlLabel\">");
result.append(widgetDialog.getMessages().key(Messages.GUI_EDITOR_LABEL_IMAGE_FORMAT_0));
result.append(" </td>");
result.append("<td class=\"xmlTd\">");
result.append("<select class=\"xmlInput");
if (param.hasError()) {
result.append(" xmlInputError");
}
result.append("\" name=\"");
result.append(PREFIX_FORMAT).append(id);
result.append("\" id=\"");
result.append(PREFIX_FORMAT).append(id);
result.append("\"");
result.append(" onchange=\"setImageFormat(\'");
result.append(id);
result.append("\', \'imgFmts");
result.append(idHash);
result.append("\');\"");
result.append(">");
// get select box options from default value String
List<CmsSelectWidgetOption> options = configuration.getSelectFormat();
String selected = getSelectedValue(cms, options, format);
int selectedIndex = 0;
for (int i = 0; i < options.size(); i++) {
CmsSelectWidgetOption option = options.get(i);
// create the option
result.append("<option value=\"");
result.append(option.getValue());
result.append("\"");
if ((selected != null) && selected.equals(option.getValue())) {
result.append(" selected=\"selected\"");
selectedIndex = i;
}
result.append(">");
result.append(option.getOption());
result.append("</option>");
}
result.append("</select>");
result.append("</td>");
result.append("</tr>");
List<String> formatValues = configuration.getFormatValues();
String selectedFormat = "";
try {
selectedFormat = formatValues.get(selectedIndex);
} catch (Exception e) {
// ignore, just didn't find a matching format value
}
// create hidden field to store the matching image format value
result.append("<input type=\"hidden\" value=\"").append(selectedFormat).append("\" name=\"");
result.append(PREFIX_FORMATVALUE).append(id).append("\" id=\"");
result.append(PREFIX_FORMATVALUE).append(id).append("\" />");
// create hidden field to store image ratio
String ratio = "";
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(imageLink)) {
// an image is specified, calculate ratio
try {
CmsImageScaler scaler = new CmsImageScaler(cms, cms.readResource(imageLink));
float r = scaler.getWidth() / (float)scaler.getHeight();
ratio = String.valueOf(r);
} catch (CmsException e) {
// ignore, image not found in VFS
}
}
result.append("<input type=\"hidden\" value=\"").append(ratio).append("\" name=\"");
result.append(PREFIX_IMAGERATIO).append(id).append("\" id=\"");
result.append(PREFIX_IMAGERATIO).append(id).append("\" />");
// add possible format names and values as JS variables to access them from image gallery window
result.append("\n<script type=\"text/javascript\">");
JSONArray formatsJson = new JSONArray(configuration.getFormatValues());
result.append("\nvar imgFmts").append(idHash).append(" = ").append(formatsJson).append(";");
result.append("\nvar imgFmtNames").append(idHash).append(" = \"").append(
CmsEncoder.escape(configuration.getSelectFormatString(), CmsEncoder.ENCODING_UTF_8)).append("\";");
result.append("\nvar useFmts").append(idHash).append(" = true;");
result.append("\n</script>");
} else {
result.append("<input type=\"hidden\" value=\"\" name=\"");
result.append(PREFIX_IMAGERATIO).append(id).append("\" id=\"");
result.append(PREFIX_IMAGERATIO).append(id).append("\" />");
result.append("<input type=\"hidden\" value=\"").append(format).append("\" name=\"");
result.append(PREFIX_FORMAT).append(id).append("\" id=\"");
result.append(PREFIX_FORMAT).append(id).append("\" />");
result.append("\n<script type=\"text/javascript\">");
result.append("\nvar useFmts").append(idHash).append(" = false;");
result.append("\n</script>");
}
String description = value.getDescription(cms);
if (description == null) {
description = "";
}
if (configuration.isShowDescription()) {
result.append("<tr>");
result.append("<td class=\"xmlLabel\">");
result.append(widgetDialog.getMessages().key(Messages.GUI_EDITOR_LABEL_IMAGE_DESC_0));
result.append("</td>");
result.append("<td class=\"xmlTd\">");
result.append("<textarea class=\"xmlInput maxwidth");
if (param.hasError()) {
result.append(" xmlInputError");
}
result.append("\" name=\"");
result.append(PREFIX_DESCRIPTION).append(id).append("\" id=\"");
result.append(PREFIX_DESCRIPTION).append(id);
result.append("\" rows=\"");
result.append(2);
result.append("\" cols=\"60\" style=\"height: 3em; overflow:auto;\">");
result.append(CmsEncoder.escapeXml(description));
result.append("</textarea>");
result.append("</td>");
result.append("</tr>");
} else {
result.append("<input type=\"hidden\" value=\"").append(CmsEncoder.escapeXml(description)).append(
"\" name=\"");
result.append(PREFIX_DESCRIPTION).append(id).append("\" id=\"");
result.append(PREFIX_DESCRIPTION).append(id).append("\" />");
}
result.append("</table>");
String scale = value.getScaleOptions(cms);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getScaleParams())
&& (scale.indexOf(configuration.getScaleParams()) == -1)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(scale)) {
scale += ",";
}
scale += configuration.getScaleParams();
}
result.append("<input type=\"hidden\" value=\"").append(scale).append("\" name=\"");
result.append(PREFIX_SCALE).append(id).append("\" id=\"");
result.append(PREFIX_SCALE).append(id).append("\" />");
result.append("</td>");
return result.toString();
}
/**
* @see org.opencms.widgets.A_CmsWidget#getWidgetStringValue(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public String getWidgetStringValue(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
String result = super.getWidgetStringValue(cms, widgetDialog, param);
String configuration = CmsMacroResolver.resolveMacros(getConfiguration(), cms, widgetDialog.getMessages());
if (configuration == null) {
configuration = param.getDefault(cms);
}
List<CmsSelectWidgetOption> options = CmsSelectWidgetOption.parseOptions(configuration);
for (int m = 0; m < options.size(); m++) {
CmsSelectWidgetOption option = options.get(m);
if (result.equals(option.getValue())) {
result = option.getOption();
break;
}
}
return result;
}
/**
* @see org.opencms.widgets.I_CmsWidget#newInstance()
*/
@Override
public I_CmsWidget newInstance() {
return new CmsVfsImageWidget(getConfiguration());
}
/**
* @see org.opencms.widgets.I_CmsWidget#setEditorValue(org.opencms.file.CmsObject, java.util.Map, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public void setEditorValue(
CmsObject cms,
Map<String, String[]> formParameters,
I_CmsWidgetDialog widgetDialog,
I_CmsWidgetParameter param) {
String[] imgValues = formParameters.get(PREFIX_IMAGE + param.getId());
if ((imgValues != null) && (imgValues.length > 0)) {
param.setStringValue(cms, imgValues[0]);
}
CmsXmlVfsImageValue value = (CmsXmlVfsImageValue)param;
String[] descValues = formParameters.get(PREFIX_DESCRIPTION + param.getId());
value.setDescription(cms, descValues[0]);
String[] formatValues = formParameters.get(PREFIX_FORMAT + param.getId());
value.setFormat(cms, formatValues[0]);
String[] scaleValues = formParameters.get(PREFIX_SCALE + param.getId());
value.setScaleOptions(cms, scaleValues[0]);
}
/**
* @see org.opencms.widgets.CmsAdeImageGalleryWidget#getAdditionalGalleryInfo(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
protected JSONObject getAdditionalGalleryInfo(
CmsObject cms,
I_CmsWidgetDialog widgetDialog,
I_CmsWidgetParameter param) throws JSONException {
JSONObject result = super.getAdditionalGalleryInfo(cms, widgetDialog, param);
result.put("isAdvancedWidget", true);
return result;
}
/**
* @see org.opencms.widgets.A_CmsAdeGalleryWidget#getGalleryOpenParams(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter, long)
*/
@Override
protected Map<String, String> getGalleryOpenParams(
CmsObject cms,
I_CmsWidgetDialog widgetDialog,
I_CmsWidgetParameter param,
long hashId) {
Map<String, String> result = super.getGalleryOpenParams(cms, widgetDialog, param, hashId);
// the current element value will be read by java-script including the image input field and the scale input field
StringBuffer currentElement = new StringBuffer("'+document.getElementById('");
currentElement.append(PREFIX_IMAGE).append(param.getId());
currentElement.append("').getAttribute('value')+'%3F__scale%3D'+document.getElementById('");
currentElement.append(PREFIX_SCALE).append(param.getId()).append("').getAttribute('value')+'");
currentElement.append("%26__formatName%3D'+escape(document.getElementById('").append(PREFIX_FORMAT).append(
param.getId()).append("')[document.getElementById('").append(PREFIX_FORMAT).append(param.getId()).append(
"').selectedIndex].value)+'");
result.put(GALLERY_PARAM.currentelement.name(), currentElement.toString());
return result;
}
/**
* Returns the currently selected value of the select widget.<p>
*
* If a value is found in the given parameter, this is used. Otherwise
* the default value of the select options are used. If there is neither a parameter value
* nor a default value, <code>null</code> is returned.<p>
*
* @param cms the current users OpenCms context
* @param selectOptions the available select options
* @param currentValue the current value that is selected
*
* @return the currently selected value of the select widget
*/
protected String getSelectedValue(CmsObject cms, List<CmsSelectWidgetOption> selectOptions, String currentValue) {
String paramValue = currentValue;
if (CmsStringUtil.isEmpty(paramValue)) {
CmsSelectWidgetOption option = CmsSelectWidgetOption.getDefaultOption(selectOptions);
if (option != null) {
paramValue = option.getValue();
}
}
return paramValue;
}
}
|
package org.phenoscape.main;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.bbop.framework.GUIComponentFactory;
import org.bbop.framework.GUIManager;
import org.bbop.framework.GUITask;
import org.bbop.framework.VetoableShutdownListener;
import org.bbop.framework.dock.LayoutDriver;
import org.bbop.framework.dock.idw.IDWDriver;
import org.jdesktop.swingworker.SwingWorker;
import org.oboedit.gui.factory.SearchComponentFactory;
import org.oboedit.gui.factory.SearchResultsComponentFactory;
import org.oboedit.gui.tasks.DefaultGUIStartupTask;
import org.phenoscape.app.CrossPlatform;
import org.phenoscape.model.OntologyController;
import org.phenoscape.model.PhenexController;
import org.phenoscape.swing.BlockingProgressDialog;
import org.phenoscape.swing.WindowSizePrefsSaver;
import org.phenoscape.view.CharacterMatrixComponentFactory;
import org.phenoscape.view.CharacterTableComponentFactory;
import org.phenoscape.view.DataSetComponentFactory;
import org.phenoscape.view.LogViewComponentFactory;
import org.phenoscape.view.MenuFactory;
import org.phenoscape.view.PhenotypeTableComponentFactory;
import org.phenoscape.view.SessionTermInfoFactory;
import org.phenoscape.view.SpecimenTableComponentFactory;
import org.phenoscape.view.StateTableComponentFactory;
import org.phenoscape.view.TaxonTableComponentFactory;
import phenote.gui.PhenoteDockingTheme;
import phenote.gui.factories.PhenoteGraphViewFactory;
import phenote.gui.factories.PhenoteOntologyTreeEditorFactory;
import phenote.gui.selection.SelectionBridge;
/**
* This startup task does all the work of starting up Phenex.
* @author Jim Balhoff
*/
public class PhenexStartupTask extends DefaultGUIStartupTask {
private PhenexController controller;
@Override
protected Collection<GUIComponentFactory<?>> getDefaultComponentFactories() {
Collection<GUIComponentFactory<?>> factories = new ArrayList<GUIComponentFactory<?>>();
factories.add(new DataSetComponentFactory(this.controller));
factories.add(new CharacterTableComponentFactory(this.controller));
factories.add(new StateTableComponentFactory(this.controller));
factories.add(new PhenotypeTableComponentFactory(this.controller));
factories.add(new TaxonTableComponentFactory(this.controller));
factories.add(new SpecimenTableComponentFactory(this.controller));
factories.add(new CharacterMatrixComponentFactory(this.controller));
//factories.add(new OntologyPreferencesComponentFactory());
factories.add(new SessionTermInfoFactory());
factories.add(new PhenoteOntologyTreeEditorFactory());
factories.add(new PhenoteGraphViewFactory());
factories.add(new SearchComponentFactory() {
public FactoryCategory getCategory() {
return FactoryCategory.ONTOLOGY;
}
});
factories.add(new SearchResultsComponentFactory());
factories.add(new LogViewComponentFactory());
return factories;
}
@Override
protected void configureLogging() {
//TODO should the desired level be set in the configuration file?
final Logger rl = LogManager.getRootLogger();
rl.setLevel(Level.DEBUG);
}
@Override
protected void configureUI() {
try {
final String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
if (lookAndFeelClassName.equals("apple.laf.AquaLookAndFeel")) {
// We are running on Mac OS X - use the Quaqua look and feel
System.setProperty("apple.laf.useScreenMenuBar", "true");
UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
} else {
// We are on some other platform, use the system look and feel
UIManager.setLookAndFeel(lookAndFeelClassName);
}
} catch (ClassNotFoundException e) {
log().error("Look and feel class not found", e);
} catch (InstantiationException e) {
log().error("Could not instantiate look and feel", e);
} catch (IllegalAccessException e) {
log().error("Error setting look and feel", e);
} catch (UnsupportedLookAndFeelException e) {
log().error("Look and feel not supported", e);
}
}
@Override
protected void configureSystem() {
super.configureSystem();
final SwingWorker<OntologyController, Void> ontologyLoader = new SwingWorker<OntologyController, Void>() {
@Override
protected OntologyController doInBackground() {
return new OntologyController();
}
};
// you would expect that displaying the progress dialog would make the splash screen go away, but it doesn't
this.flashJFrameToMakeSplashScreenGoAway();
final BlockingProgressDialog<OntologyController, Void> dialog = new BlockingProgressDialog<OntologyController, Void>(ontologyLoader, "Phenex is checking for ontology updates. It may take some time to download and configure ontologies.");
dialog.setTitle("Launching " + this.getAppName());
dialog.setSize(400, 150);
dialog.setLocationRelativeTo(null);
dialog.run();
try {
this.controller = new PhenexController(ontologyLoader.get());
} catch (InterruptedException e) {
log().fatal("Failed to create ontology controller", e);
GUIManager.exit(1);
} catch (ExecutionException e) {
log().fatal("Failed to create ontology controller", e);
GUIManager.exit(1);
}
this.controller.setAppName(this.getAppName());
}
@Override
protected String getAppID() {
return "Phenex";
}
@Override
protected String getAppName() {
return "Phenex";
}
@Override
protected Action getAboutAction() {
//TODO make an about panel
return new AbstractAction() {
public void actionPerformed(ActionEvent e) {
}
};
}
@Override
protected JFrame createFrame() {
final JFrame frame = super.createFrame();
frame.setTitle(getAppName());
// the window prefs saver is not currently working because the BBOP MainFrame is trying to be too smart
new WindowSizePrefsSaver(frame, this.getClass().getName() + "mainwindow");
return frame;
}
@Override
protected void showFrame() {
// BBOP centers and makes frame a certain size - we are overriding this
GUIManager.getManager().getFrame().setVisible(true);
}
@Override
protected LayoutDriver createLayoutDriver() {
final LayoutDriver driver = super.createLayoutDriver();
if (driver instanceof IDWDriver) {
((IDWDriver)driver).setCustomTheme(new PhenoteDockingTheme());
}
driver.setSaveLayoutOnExit(false);
return driver;
}
@Override
protected String getPerspectiveResourceDir() {
return "org/phenoscape/view/layouts";
}
@Override
protected String getDefaultPerspectiveResourcePath() {
if (getPerspectiveResourceDir() != null)
return getPerspectiveResourceDir() + "/default.idw";
else
return null;
}
@Override
public File getPrefsDir() {
return CrossPlatform.getUserPreferencesFolder(this.getAppID());
}
@Override
protected void installSystemListeners() {
GUIManager.addVetoableShutdownListener(new VetoableShutdownListener() {
public boolean willShutdown() {
return controller.canCloseDocument();
}
});
}
@Override
protected void doOtherInstallations() {
super.doOtherInstallations();
new SelectionBridge().install();
}
@Override
protected Collection<? extends JMenuItem> getDefaultMenus() {
return (new MenuFactory(this.controller)).createMenus();
}
@Override
protected Collection<GUITask> getDefaultTasks() {
// OBO-Edit startup task adds some things we don't want
// hopefully none of these tasks are needed for operations in Phenex
return new ArrayList<GUITask>();
}
private void flashJFrameToMakeSplashScreenGoAway() {
final JFrame frame = new JFrame();
frame.setVisible(true);
frame.setVisible(false);
}
private Logger log() {
return Logger.getLogger(this.getClass());
}
}
|
/*
* $Id$
* $URL$
*/
package org.subethamail.web.action;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.java.Log;
import org.subethamail.core.lists.i.MailSummary;
import org.subethamail.web.Backend;
import org.subethamail.web.action.auth.AuthAction;
import org.subethamail.web.model.PaginateModel;
/**
* Gets one page of an archive. Model becomes a List<MessageSummary>.
*
* @author Jeff Schnitzer
*/
@Log
public class GetThreads extends AuthAction
{
public static class Model extends PaginateModel
{
public Model()
{
this.setCount(100); // default to 100
}
@Getter @Setter Long listId;
@Getter @Setter List<MailSummary> messages;
}
public void initialize()
{
this.getCtx().setModel(new Model());
}
public void execute() throws Exception
{
Model model = (Model)this.getCtx().getModel();
model.messages = Backend.instance().getArchiver().getThreads(model.listId, model.getSkip(), model.getCount());
model.setTotalCount(Backend.instance().getArchiver().countMailByList(model.listId));
}
}
|
package org.team3042.sweep.commands;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import com.sun.squawk.io.BufferedReader;
import com.sun.squawk.microedition.io.FileConnection;
public class GRTFileIO {
public GRTFileIO(){
}
public static String getFileContents(String filename) {
String url = "file:///" + filename;
String contents = "";
try {
FileConnection c = (FileConnection) Connector.open(url);
BufferedReader buf = new BufferedReader(new InputStreamReader(c
.openInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
contents += line + "\n";
}
c.close();
} catch (IOException e) {
e.printStackTrace();
}
return contents;
}
public static void writeToFile(String filename, String contents) {
System.out.println("Here");
String url = "file:///" + filename;
try {
FileConnection c = (FileConnection) Connector.open(url);
if(!c.exists()){
c.create();
}
OutputStreamWriter writer = new OutputStreamWriter(c
.openOutputStream());
writer.write(contents+"\n");
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package jenkins.util.xml;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import jenkins.util.SystemProperties;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
/**
* Utilities useful when working with various XML types.
* @since 1.596.1 and 1.600, unrestricted since TODO
*/
public final class XMLUtils {
private final static Logger LOGGER = LogManager.getLogManager().getLogger(XMLUtils.class.getName());
private final static String DISABLED_PROPERTY_NAME = XMLUtils.class.getName() + ".disableXXEPrevention";
private static final String FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities";
private static final String FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities";
/**
* Transform the source to the output in a manner that is protected against XXE attacks.
* If the transform can not be completed safely then an IOException is thrown.
* Note - to turn off safety set the system property <code>disableXXEPrevention</code> to <code>true</code>.
* @param source The XML input to transform. - This should be a <code>StreamSource</code> or a
* <code>SAXSource</code> in order to be able to prevent XXE attacks.
* @param out The Result of transforming the <code>source</code>.
*/
public static void safeTransform(@Nonnull Source source, @Nonnull Result out) throws TransformerException,
SAXException {
InputSource src = SAXSource.sourceToInputSource(source);
if (src != null) {
SAXTransformerFactory stFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
stFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_GENERAL_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_PARAMETER_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
// defend against XXE
// the above features should strip out entities - however the feature may not be supported depending
// on the xml implementation used and this is out of our control.
// So add a fallback plan if all else fails.
xmlReader.setEntityResolver(RestrictiveEntityResolver.INSTANCE);
SAXSource saxSource = new SAXSource(xmlReader, src);
_transform(saxSource, out);
}
else {
// for some reason we could not convert source
// this applies to DOMSource and StAXSource - and possibly 3rd party implementations...
// a DOMSource can already be compromised as it is parsed by the time it gets to us.
if (SystemProperties.getBoolean(DISABLED_PROPERTY_NAME)) {
LOGGER.log(Level.WARNING, "XML external entity (XXE) prevention has been disabled by the system " +
"property {0}=true Your system may be vulnerable to XXE attacks.", DISABLED_PROPERTY_NAME);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Caller stack trace: ", new Exception("XXE Prevention caller history"));
}
_transform(source, out);
}
else {
throw new TransformerException("Could not convert source of type " + source.getClass() + " and " +
"XXEPrevention is enabled.");
}
}
}
/**
* Parse the supplied XML stream data to a {@link Document}.
* <p>
* This function does not close the stream.
*
* @param stream The XML stream.
* @return The XML {@link Document}.
* @throws SAXException Error parsing the XML stream data e.g. badly formed XML.
* @throws IOException Error reading from the steam.
* @since 2.0
*/
public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException {
DocumentBuilder docBuilder;
try {
docBuilder = newDocumentBuilderFactory().newDocumentBuilder();
docBuilder.setEntityResolver(RestrictiveEntityResolver.INSTANCE);
} catch (ParserConfigurationException e) {
throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e);
}
return docBuilder.parse(new InputSource(stream));
}
/**
* Parse the supplied XML file data to a {@link Document}.
* @param file The file to parse.
* @param encoding The encoding of the XML in the file.
* @return The parsed document.
* @throws SAXException Error parsing the XML file data e.g. badly formed XML.
* @throws IOException Error reading from the file.
* @since 2.0
*/
public static @Nonnull Document parse(@Nonnull File file, @Nonnull String encoding) throws SAXException, IOException {
if (!file.exists() || !file.isFile()) {
throw new IllegalArgumentException(String.format("File %s does not exist or is not a 'normal' file.", file.getAbsolutePath()));
}
try (InputStream fileInputStream = Files.newInputStream(file.toPath());
InputStreamReader fileReader = new InputStreamReader(fileInputStream, encoding)) {
return parse(fileReader);
} catch (InvalidPathException e) {
throw new IOException(e);
}
}
/**
* The a "value" from an XML file using XPath.
* <p>
* Uses the system encoding for reading the file.
*
* @param xpath The XPath expression to select the value.
* @param file The file to read.
* @return The data value. An empty {@link String} is returned when the expression does not evaluate
* to anything in the document.
* @throws IOException Error reading from the file.
* @throws SAXException Error parsing the XML file data e.g. badly formed XML.
* @throws XPathExpressionException Invalid XPath expression.
* @since 2.0
*/
public static @Nonnull String getValue(@Nonnull String xpath, @Nonnull File file) throws IOException, SAXException, XPathExpressionException {
return getValue(xpath, file, Charset.defaultCharset().toString());
}
/**
* The a "value" from an XML file using XPath.
* @param xpath The XPath expression to select the value.
* @param file The file to read.
* @param fileDataEncoding The file data format.
* @return The data value. An empty {@link String} is returned when the expression does not evaluate
* to anything in the document.
* @throws IOException Error reading from the file.
* @throws SAXException Error parsing the XML file data e.g. badly formed XML.
* @throws XPathExpressionException Invalid XPath expression.
* @since 2.0
*/
public static @Nonnull String getValue(@Nonnull String xpath, @Nonnull File file, @Nonnull String fileDataEncoding) throws IOException, SAXException, XPathExpressionException {
Document document = parse(file, fileDataEncoding);
return getValue(xpath, document);
}
/**
* The a "value" from an XML file using XPath.
* @param xpath The XPath expression to select the value.
* @param document The document from which the value is to be extracted.
* @return The data value. An empty {@link String} is returned when the expression does not evaluate
* to anything in the document.
* @throws XPathExpressionException Invalid XPath expression.
* @since 2.0
*/
public static String getValue(String xpath, Document document) throws XPathExpressionException {
XPath xPathProcessor = XPathFactory.newInstance().newXPath();
return xPathProcessor.compile(xpath).evaluate(document);
}
/**
* potentially unsafe XML transformation.
* @param source The XML input to transform.
* @param out The Result of transforming the <code>source</code>.
*/
private static void _transform(Source source, Result out) throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// this allows us to use UTF-8 for storing data,
// plus it checks any well-formedness issue in the submitted data.
Transformer t = factory.newTransformer();
t.transform(source, out);
}
private static DocumentBuilderFactory newDocumentBuilderFactory() {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// Set parser features to prevent against XXE etc.
// Note: setting only the external entity features on DocumentBuilderFactory instance
// (ala how safeTransform does it for SAXTransformerFactory) does seem to work (was still
// processing the entities - tried Oracle JDK 7 and 8 on OSX). Setting seems a bit extreme,
// but looks like there's no other choice.
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
setDocumentBuilderFactoryFeature(documentBuilderFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
setDocumentBuilderFactoryFeature(documentBuilderFactory, FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_GENERAL_ENTITIES, false);
setDocumentBuilderFactoryFeature(documentBuilderFactory, FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_PARAMETER_ENTITIES, false);
setDocumentBuilderFactoryFeature(documentBuilderFactory, "http://apache.org/xml/features/disallow-doctype-decl", true);
return documentBuilderFactory;
}
private static void setDocumentBuilderFactoryFeature(DocumentBuilderFactory documentBuilderFactory, String feature, boolean state) {
try {
documentBuilderFactory.setFeature(feature, state);
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("Failed to set the XML Document Builder factory feature %s to %s", feature, state), e);
}
}
}
|
package com.intellij.facet.impl.autodetecting;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetType;
import com.intellij.facet.FacetTypeRegistry;
import com.intellij.facet.impl.autodetecting.model.DetectedFacetInfo;
import com.intellij.facet.pointers.FacetPointer;
import com.intellij.facet.pointers.FacetPointersManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.BidirectionalMultiMap;
import com.intellij.util.fileIndex.AbstractFileIndex;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* @author nik
*/
public class FacetDetectionIndex extends AbstractFileIndex<FacetDetectionIndexEntry> {
private static final Logger LOG = Logger.getInstance("#com.intellij.facet.impl.autodetecting.FacetDetectionIndex");
private static final byte CURRENT_VERSION = 1;
@NonNls private static final String CACHE_DIRECTORY_NAME = "facets";
private final FileTypeManager myFileTypeManager;
private final Set<FileType> myFileTypes;
private final Set<FacetType> myNewFacetTypes = new THashSet<FacetType>();
private final FacetPointersManager myFacetPointersManager;
private final FacetAutodetectingManagerImpl myAutodetectingManager;
private final BidirectionalMultiMap<String, FacetPointer> myFacets;
private final BidirectionalMultiMap<String, Integer> myDetectedFacetIds;
public FacetDetectionIndex(final Project project, final FacetAutodetectingManagerImpl autodetectingManager, Set<FileType> fileTypes) {
super(project);
myAutodetectingManager = autodetectingManager;
myFileTypes = new THashSet<FileType>(fileTypes);
myFileTypeManager = FileTypeManager.getInstance();
myFacetPointersManager = FacetPointersManager.getInstance(project);
myFacets = new BidirectionalMultiMap<String, FacetPointer>();
myDetectedFacetIds = new BidirectionalMultiMap<String, Integer>();
}
protected FacetDetectionIndexEntry createIndexEntry(final DataInputStream input) throws IOException {
return new FacetDetectionIndexEntry(input, myFacetPointersManager);
}
public boolean belongs(final VirtualFile file) {
FileType fileType = myFileTypeManager.getFileTypeByFile(file);
return myFileTypes.contains(fileType);
}
protected String getLoadingIndicesMessage() {
return ProjectBundle.message("progress.text.loading.facet.detection.indices");
}
protected String getBuildingIndicesMessage(final boolean formatChanged) {
return formatChanged ? ProjectBundle.message("progress.text.facet.indices.format.has.changed.redetecting.facets")
: ProjectBundle.message("progress.text.detecting.facets");
}
public byte getCurrentVersion() {
return CURRENT_VERSION;
}
public String getCachesDirName() {
return CACHE_DIRECTORY_NAME;
}
public static File getDetectedFacetsFile(@NotNull Project project) {
return new File(PathManager.getSystemPath() + File.separator + CACHE_DIRECTORY_NAME + File.separator + project.getName() + ".detected." + project.getLocationHash());
}
protected void readHeader(final DataInputStream input) throws IOException {
int size = input.readInt();
Set<String> facetTypesInCache = new THashSet<String>();
while (size
facetTypesInCache.add(input.readUTF());
}
Set<String> unknownTypes = new THashSet<String>(facetTypesInCache);
for (FacetType type : FacetTypeRegistry.getInstance().getFacetTypes()) {
unknownTypes.remove(type.getStringId());
if (!facetTypesInCache.contains(type.getStringId())) {
myNewFacetTypes.add(type);
}
}
if (!unknownTypes.isEmpty()) {
LOG.info("Unknown facet types in cache: " + new HashSet<String>(unknownTypes));
}
}
@Nullable
protected Set<FileType> getFileTypesToRefresh() {
if (myNewFacetTypes.isEmpty()) {
return null;
}
return myAutodetectingManager.getFileTypes(myNewFacetTypes);
}
protected void writeHeader(final DataOutputStream output) throws IOException {
FacetType[] types = FacetTypeRegistry.getInstance().getFacetTypes();
output.writeInt(types.length);
for (FacetType type : types) {
output.writeUTF(type.getStringId());
}
}
public void queueEntryUpdate(final VirtualFile file) {
myAutodetectingManager.queueUpdate(file);
}
protected void doUpdateIndexEntry(final VirtualFile file) {
myAutodetectingManager.processFile(file);
}
@Nullable
public Set<String> getFiles(Integer id) {
return myDetectedFacetIds.getKeys(id);
}
@Nullable
public Set<String> getFiles(final FacetPointer pointer) {
return myFacets.getKeys(pointer);
}
@Nullable
public Set<String> getFiles(final Facet facet) {
return myFacets.getKeys(myFacetPointersManager.create(facet));
}
protected void onEntryAdded(final String url, final FacetDetectionIndexEntry entry) {
myFacets.removeKey(url);
SmartList<FacetPointer> detectedFacets = entry.getFacets();
if (detectedFacets != null) {
for (FacetPointer detectedFacet : detectedFacets) {
myFacets.put(url, detectedFacet);
}
}
myDetectedFacetIds.removeKey(url);
SmartList<Integer> facetIds = entry.getDetectedFacetIds();
if (facetIds != null) {
for (Integer id : facetIds) {
myDetectedFacetIds.put(url, id);
}
}
}
protected void onEntryRemoved(final String url, final FacetDetectionIndexEntry entry) {
Set<Integer> ids = myDetectedFacetIds.getValues(url);
myDetectedFacetIds.removeKey(url);
if (ids != null && !ids.isEmpty()) {
myAutodetectingManager.removeObsoleteFacets(ids);
}
}
public void removeFacetFromCache(final FacetPointer<Facet> facetPointer) {
Set<String> urls = myFacets.getKeys(facetPointer);
if (urls != null) {
for (String url : urls) {
FacetDetectionIndexEntry indexEntry = getIndexEntry(url);
if (indexEntry != null) {
indexEntry.remove(facetPointer);
}
}
}
myFacets.removeValue(facetPointer);
}
public void updateIndexEntryForCreatedFacet(final DetectedFacetInfo<Module> info, final Facet facet) {
FacetPointer<Facet> pointer = FacetPointersManager.getInstance(facet.getModule().getProject()).create(facet);
Set<String> urls = myDetectedFacetIds.getKeys(info.getId());
if (urls != null) {
String[] urlsArray = ArrayUtil.toStringArray(urls);
for (String url : urlsArray) {
myDetectedFacetIds.remove(url, info.getId());
myFacets.put(url, pointer);
FacetDetectionIndexEntry indexEntry = getIndexEntry(url);
indexEntry.remove(info.getId());
indexEntry.add(pointer);
}
}
}
public boolean isEmpty() {
return myDetectedFacetIds.isEmpty() && myFacets.isEmpty();
}
public void removeFromIndex(final DetectedFacetInfo<Module> info) {
int id = info.getId();
Set<String> urls = myDetectedFacetIds.getKeys(id);
if (urls != null) {
for (String url : urls) {
FacetDetectionIndexEntry entry = getIndexEntry(url);
if (entry != null) {
entry.remove(id);
}
}
}
myDetectedFacetIds.removeValue(id);
}
}
|
package com.intellij.psi.impl.search;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.java.stubs.index.JavaAnonymousClassBaseRefOccurenceIndex;
import com.intellij.psi.impl.java.stubs.index.JavaSuperClassNameOccurenceIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.AllClassesSearch;
import com.intellij.psi.search.searches.DirectClassInheritorsSearch;
import com.intellij.util.Processor;
import com.intellij.util.QueryExecutor;
import java.util.Collection;
/**
* @author max
*/
public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, DirectClassInheritorsSearch.SearchParameters> {
public boolean execute(final DirectClassInheritorsSearch.SearchParameters p, final Processor<PsiClass> consumer) {
final PsiClass aClass = p.getClassToProcess();
final PsiManagerImpl psiManager = (PsiManagerImpl)PsiManager.getInstance(aClass.getProject());
final SearchScope useScope = ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
public SearchScope compute() {
return aClass.getUseScope();
}
});
final String qualifiedName = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
return aClass.getQualifiedName();
}
});
if (CommonClassNames.JAVA_LANG_OBJECT.equals(qualifiedName)) {
final SearchScope scope = useScope.intersectWith(GlobalSearchScope.notScope(GlobalSearchScope.getScopeRestrictedByFileTypes(
GlobalSearchScope.allScope(psiManager.getProject()), StdFileTypes.JSP, StdFileTypes.JSPX)));
return AllClassesSearch.search(scope, aClass.getProject()).forEach(new Processor<PsiClass>() {
public boolean process(final PsiClass psiClass) {
if (psiClass.isInterface()) {
return consumer.process(psiClass);
}
final PsiClass superClass = psiClass.getSuperClass();
if (superClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) {
return consumer.process(psiClass);
}
return true;
}
});
}
final GlobalSearchScope scope = useScope instanceof GlobalSearchScope ? (GlobalSearchScope)useScope : null;
final String searchKey = aClass.getName();
Collection<PsiReferenceList> candidates = ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiReferenceList>>() {
public Collection<PsiReferenceList> compute() {
return JavaSuperClassNameOccurenceIndex.getInstance().get(searchKey, psiManager.getProject(), scope);
}
});
for (PsiReferenceList referenceList : candidates) {
ProgressManager.getInstance().checkCanceled();
PsiClass candidate = (PsiClass)referenceList.getParent();
if (!consumer.process(candidate)) return false;
}
if (p.includeAnonymous()) {
Collection<PsiAnonymousClass> anonymousCandidates = ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiAnonymousClass>>() {
public Collection<PsiAnonymousClass> compute() {
return JavaAnonymousClassBaseRefOccurenceIndex.getInstance().get(searchKey, psiManager.getProject(), scope);
}
});
for (PsiAnonymousClass candidate : anonymousCandidates) {
ProgressManager.getInstance().checkCanceled();
if (!consumer.process(candidate)) return false;
}
if (aClass.isEnum()) {
// abstract enum can be subclassed in the body
PsiField[] fields = ApplicationManager.getApplication().runReadAction(new Computable<PsiField[]>() {
public PsiField[] compute() {
return aClass.getFields();
}
});
for (final PsiField field : fields) {
if (field instanceof PsiEnumConstant) {
PsiEnumConstantInitializer initializingClass =
ApplicationManager.getApplication().runReadAction(new Computable<PsiEnumConstantInitializer>() {
public PsiEnumConstantInitializer compute() {
return ((PsiEnumConstant)field).getInitializingClass();
}
});
if (initializingClass != null) {
if (!consumer.process(initializingClass)) return false;
}
}
}
}
}
return true;
}
}
|
package hudson;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.Issue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
//TODO to be merged back in FilePathTest after security release
public class FilePathSEC904Test {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
@Issue("SECURITY-904")
public void isDescendant_regularFiles() throws IOException, InterruptedException {
// root
// /workspace
// /sub
// sub-regular.txt
// regular.txt
// /protected
// secret.txt
FilePath rootFolder = new FilePath(temp.newFolder("root"));
FilePath workspaceFolder = rootFolder.child("workspace");
FilePath subFolder = workspaceFolder.child("sub");
FilePath protectedFolder = rootFolder.child("protected");
FilePath regularFile = workspaceFolder.child("regular.txt");
regularFile.write("regular-file", StandardCharsets.UTF_8.name());
FilePath subRegularFile = subFolder.child("sub-regular.txt");
subRegularFile.write("sub-regular-file", StandardCharsets.UTF_8.name());
FilePath secretFile = protectedFolder.child("secret.txt");
secretFile.write("secrets", StandardCharsets.UTF_8.name());
assertTrue(workspaceFolder.isDescendant("."));
assertTrue(workspaceFolder.isDescendant("regular.txt"));
assertTrue(workspaceFolder.isDescendant("./regular.txt"));
assertTrue(workspaceFolder.isDescendant("sub/sub-regular.txt"));
assertTrue(workspaceFolder.isDescendant("sub//sub-regular.txt"));
assertTrue(workspaceFolder.isDescendant("sub/../sub/sub-regular.txt"));
assertTrue(workspaceFolder.isDescendant("./sub/../sub/sub-regular.txt"));
// nonexistent files
assertTrue(workspaceFolder.isDescendant("nonexistent.txt"));
assertTrue(workspaceFolder.isDescendant("sub/nonexistent.txt"));
assertTrue(workspaceFolder.isDescendant("nonexistent/nonexistent.txt"));
assertFalse(workspaceFolder.isDescendant("../protected/nonexistent.txt"));
assertFalse(workspaceFolder.isDescendant("../nonexistent/nonexistent.txt"));
// the intermediate path "./.." goes out of workspace and so is refused
assertFalse(workspaceFolder.isDescendant("./../workspace"));
assertFalse(workspaceFolder.isDescendant("./../workspace/"));
assertFalse(workspaceFolder.isDescendant("./../workspace/regular.txt"));
assertFalse(workspaceFolder.isDescendant("../workspace/regular.txt"));
assertFalse(workspaceFolder.isDescendant("./../../root/workspace/regular.txt"));
// attempt to reach other folder
assertFalse(workspaceFolder.isDescendant("../protected/secret.txt"));
assertFalse(workspaceFolder.isDescendant("./../protected/secret.txt"));
}
@Test
@Issue("SECURITY-904")
public void isDescendant_regularSymlinks() throws IOException, InterruptedException {
// root
// /workspace
// a.txt
// _a => symlink to ../a
// _atxt => symlink to ../a/a.txt
// regular.txt
// _nonexistent => symlink to nonexistent (nonexistent folder)
// /protected
// secret.txt
FilePath rootFolder = new FilePath(temp.newFolder("root"));
FilePath workspaceFolder = rootFolder.child("workspace");
FilePath aFolder = workspaceFolder.child("a");
FilePath bFolder = workspaceFolder.child("b");
FilePath protectedFolder = rootFolder.child("protected");
FilePath regularFile = workspaceFolder.child("regular.txt");
regularFile.write("regular-file", StandardCharsets.UTF_8.name());
FilePath aFile = aFolder.child("a.txt");
aFile.write("a-file", StandardCharsets.UTF_8.name());
FilePath bFile = bFolder.child("a.txt");
bFile.write("b-file", StandardCharsets.UTF_8.name());
bFolder.child("_a").symlinkTo("../a", null);
bFolder.child("_atxt").symlinkTo("../a/a.txt", null);
workspaceFolder.child("_protected").symlinkTo("../protected", null);
workspaceFolder.child("_nonexistent").symlinkTo("nonexistent", null);
workspaceFolder.child("_nonexistentUp").symlinkTo("../nonexistent", null);
workspaceFolder.child("_secrettxt").symlinkTo("../protected/secret.txt", null);
FilePath secretFile = protectedFolder.child("secret.txt");
secretFile.write("secrets", StandardCharsets.UTF_8.name());
assertTrue(workspaceFolder.isDescendant("regular.txt"));
assertTrue(workspaceFolder.isDescendant("_nonexistent"));
assertTrue(workspaceFolder.isDescendant("a"));
assertTrue(workspaceFolder.isDescendant("a/a.txt"));
assertTrue(workspaceFolder.isDescendant("a/../a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b/../a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b"));
assertTrue(workspaceFolder.isDescendant("./b"));
assertTrue(workspaceFolder.isDescendant("b/_a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b/_a/../a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b/_atxt"));
assertFalse(workspaceFolder.isDescendant("_nonexistentUp"));
assertFalse(workspaceFolder.isDescendant("_protected"));
assertFalse(workspaceFolder.isDescendant("_protected/"));
assertFalse(workspaceFolder.isDescendant("_protected/secret.txt"));
assertFalse(workspaceFolder.isDescendant("./_protected/secret.txt"));
assertFalse(workspaceFolder.isDescendant("_secrettxt"));
assertFalse(workspaceFolder.isDescendant("./_secrettxt"));
}
@Test
@Issue("SECURITY-904")
public void isDescendant_windowsSpecificSymlinks() throws Exception {
assumeTrue(Functions.isWindows());
// root
// /workspace
// a.txt
// b.txt
// _a => junction to ../a
// regular.txt
// _nonexistent => junction to nonexistent (nonexistent folder)
// /protected
// secret.txt
File root = temp.newFolder("root");
FilePath rootFolder = new FilePath(root);
FilePath workspaceFolder = rootFolder.child("workspace");
FilePath aFolder = workspaceFolder.child("a");
FilePath bFolder = workspaceFolder.child("b");
FilePath protectedFolder = rootFolder.child("protected");
FilePath regularFile = workspaceFolder.child("regular.txt");
regularFile.write("regular-file", StandardCharsets.UTF_8.name());
FilePath aFile = aFolder.child("a.txt");
aFile.write("a-file", StandardCharsets.UTF_8.name());
FilePath bFile = bFolder.child("a.txt");
bFile.write("b-file", StandardCharsets.UTF_8.name());
createJunction(new File(root, "/workspace/b/_a"), new File(root, "/workspace/a"));
createJunction(new File(root, "/workspace/_nonexistent"), new File(root, "/workspace/nonexistent"));
createJunction(new File(root, "/workspace/_nonexistentUp"), new File(root, "/nonexistent"));
createJunction(new File(root, "/workspace/_protected"), new File(root, "/protected"));
FilePath secretFile = protectedFolder.child("secret.txt");
secretFile.write("secrets", StandardCharsets.UTF_8.name());
assertTrue(workspaceFolder.isDescendant("b"));
assertTrue(workspaceFolder.isDescendant("b/_a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b\\_a\\a.txt"));
assertTrue(workspaceFolder.isDescendant("b\\_a\\../a/a.txt"));
assertTrue(workspaceFolder.isDescendant("b\\_a\\..\\a\\a.txt"));
assertTrue(workspaceFolder.isDescendant(".\\b\\_a\\..\\a\\a.txt"));
assertTrue(workspaceFolder.isDescendant("b/_a/../a/a.txt"));
assertTrue(workspaceFolder.isDescendant("./b/_a/../a/a.txt"));
// by Util.resolveSymlinkToFile / neither Path.toRealPath under Windows
assertTrue(workspaceFolder.isDescendant("_nonexistent"));
assertTrue(workspaceFolder.isDescendant("_nonexistent/"));
assertTrue(workspaceFolder.isDescendant("_nonexistent/.."));
assertTrue(workspaceFolder.isDescendant("_nonexistentUp"));
assertFalse(workspaceFolder.isDescendant("_protected"));
assertFalse(workspaceFolder.isDescendant("_protected/../a"));
}
private void createJunction(File from, File to) throws Exception {
Process p = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "mklink", "/J", from.getAbsolutePath(), to.getAbsolutePath()});
p.waitFor(2, TimeUnit.SECONDS);
}
@Test(expected = IllegalArgumentException.class)
@Issue("SECURITY-904")
public void isDescendant_throwIfParentDoesNotExist_symlink() throws Exception {
FilePath rootFolder = new FilePath(temp.newFolder("root"));
FilePath aFolder = rootFolder.child("a");
aFolder.mkdirs();
FilePath linkToNonexistent = aFolder.child("linkToNonexistent");
linkToNonexistent.symlinkTo("__nonexistent__", null);
linkToNonexistent.isDescendant(".");
}
@Test(expected = IllegalArgumentException.class)
@Issue("SECURITY-904")
public void isDescendant_throwIfParentDoesNotExist_directNonexistent() throws Exception {
FilePath rootFolder = new FilePath(temp.newFolder("root"));
FilePath nonexistent = rootFolder.child("nonexistent");
nonexistent.isDescendant(".");
}
@Test(expected = IllegalArgumentException.class)
@Issue("SECURITY-904")
public void isDescendant_throwIfAbsolutePathGiven() throws Exception {
FilePath rootFolder = new FilePath(temp.newFolder("root"));
rootFolder.mkdirs();
rootFolder.isDescendant(temp.newFile().getAbsolutePath());
}
@Test
@Issue("SECURITY-904")
public void isDescendant_worksEvenInSymbolicWorkspace() throws Exception {
// root
// /_workspace => symlink to ../workspace
// /workspace
// a.txt
// _a => symlink to ../a
// _atxt => symlink to ../a/a.txt
// regular.txt
// _nonexistent => symlink to nonexistent (nonexistent folder)
// /protected
// secret.txt
FilePath rootFolder = new FilePath(temp.newFolder("root"));
FilePath wFolder = rootFolder.child("w");
FilePath workspaceFolder = rootFolder.child("workspace");
FilePath aFolder = workspaceFolder.child("a");
FilePath bFolder = workspaceFolder.child("b");
FilePath protectedFolder = rootFolder.child("protected");
FilePath regularFile = workspaceFolder.child("regular.txt");
regularFile.write("regular-file", StandardCharsets.UTF_8.name());
FilePath aFile = aFolder.child("a.txt");
aFile.write("a-file", StandardCharsets.UTF_8.name());
FilePath bFile = bFolder.child("a.txt");
bFile.write("b-file", StandardCharsets.UTF_8.name());
bFolder.child("_a").symlinkTo("../a", null);
bFolder.child("_atxt").symlinkTo("../a/a.txt", null);
workspaceFolder.child("_protected").symlinkTo("../protected", null);
workspaceFolder.child("_protected2").symlinkTo("../../protected", null);
workspaceFolder.child("_nonexistent").symlinkTo("nonexistent", null);
workspaceFolder.child("_nonexistentUp").symlinkTo("../nonexistent", null);
workspaceFolder.child("_secrettxt").symlinkTo("../protected/secret.txt", null);
workspaceFolder.child("_secrettxt2").symlinkTo("../../protected/secret.txt", null);
wFolder.mkdirs();
FilePath symbolicWorkspace = wFolder.child("_w");
symbolicWorkspace.symlinkTo("../workspace", null);
FilePath secretFile = protectedFolder.child("secret.txt");
secretFile.write("secrets", StandardCharsets.UTF_8.name());
assertTrue(symbolicWorkspace.isDescendant("regular.txt"));
assertTrue(symbolicWorkspace.isDescendant("_nonexistent"));
assertTrue(symbolicWorkspace.isDescendant("a"));
assertTrue(symbolicWorkspace.isDescendant("a/a.txt"));
assertTrue(symbolicWorkspace.isDescendant("b"));
assertTrue(symbolicWorkspace.isDescendant("b/_a/a.txt"));
assertTrue(symbolicWorkspace.isDescendant("b/_atxt"));
assertFalse(symbolicWorkspace.isDescendant("_nonexistentUp"));
assertFalse(symbolicWorkspace.isDescendant("_protected"));
assertFalse(symbolicWorkspace.isDescendant("_protected/"));
assertFalse(symbolicWorkspace.isDescendant("_protected/secret.txt"));
assertFalse(symbolicWorkspace.isDescendant("./_protected/secret.txt"));
assertFalse(symbolicWorkspace.isDescendant("_protected2"));
assertFalse(symbolicWorkspace.isDescendant("_protected2/secret.txt"));
assertFalse(symbolicWorkspace.isDescendant("_secrettxt"));
assertFalse(symbolicWorkspace.isDescendant("./_secrettxt"));
assertFalse(symbolicWorkspace.isDescendant("_secrettxt2"));
}
}
|
package org.aksw.sparqlify.qa.metrics;
import java.util.Set;
import org.aksw.sparqlify.core.algorithms.ViewQuad;
import org.aksw.sparqlify.core.domain.input.ViewDefinition;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
public class HttpUri extends PinpointMetric implements NodeMetric {
// TODO: host names up to 255 characters
public static final String httpUrlPattern = "^" +
"(?:(?:https?):
// user info, e.g. user@ or user:passwd@
"(?:\\S+(?::\\S*)?@)?" +
// host part, e.g. localhost, aksw.org, 127.0.0.1
"(?:" +
// IP address based host names, like 193.239.40.138
// exclude host names based on local IP addresses because they
// cannot be resolved in the WWW
// 10.x.x.x
"(?!10(?:\\.\\d{1,3}){3})" +
// 127.x.x.x
"(?!127(?:\\.\\d{1,3}){3})" +
// 169.254.x.x
"(?!169\\.254(?:\\.\\d{1,3}){2})" +
// 172.16.0.0/12 (172.16.0.0 to 172.31.255.255)
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\d{1,3}){2})" +
// 192.168.x.x
"(?!192\\.168(?:\\.\\d{1,3}){2})" +
// all remaining and valid IP addresses:
// first octet:
// 1-99 1xx 2xx up to 223
"(?:[1-9]\\d?|" + "1\\d\\d|" + "2[01]\\d|22[0-3])" +
// second and third octet
// 0-99 1xx 2xx up to 255
"(?:\\.(?:\\d{1,2}|" + "1\\d\\d|" + "2[0-4]\\d|25[0-5])){2}" +
// fourth octet
// omitting network (x.x.x.0) and broadcast (x.x.x.255)
// addresses
// 1-99 1xx 2xx up to 254
"(?:\\.(?:[1-9]\\d?|" + "1\\d\\d|" + "2[0-4]\\d|25[0-4]))" +
"|" +
// domain name based host names like aksw.org or
// mail.informatik.uni-leipzig.de
// TODO: add support for internationalized domain names
// domain name
// restrictions: only one hyphen *between* two chars; a char can
// be a letter or digit
"(?:(?:(?:[a-zA-Z0-9]-?)*(?:[a-zA-Z0-9])+\\.)+)" +
// TLD identifier
"(?:[a-z]{2,})" +
")" +
// port number
"(?::\\d{2,5})?" +
// path
// according to
// http://tools.ietf.org/html/draft-fielding-url-syntax-09#appendix-A :
// path = [ "/" ] path_segments
// path_segments = segment *( "/" segment )
// segment = *pchar *( ";" param )
// param = *pchar
// pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+"
// unreserved = alpha | digit | mark
// escaped = "%" hex hex
// alpha = lowalpha | upalpha
// mark = "$" | "-" | "_" | "." | "!" | "~" |
"(?:(?:/([a-zA-Z\\d_~',\\Q$-.!*()\\E]|%[a-fA-F\\d]{2})*)*)" +
// opaque URLs not considered here
// query
// http://tools.ietf.org/html/draft-fielding-url-syntax-09#appendix-A:
// rel_path = [ path_segments ] [ "?" query ]
// query = *urlc
// urlc = reserved | unreserved | escaped
// reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+"
// unreserved = alpha | digit | mark
// escaped = "%" hex hex
// http://tools.ietf.org/html/rfc3986#page-23:
// query = *( pchar / "/" / "?" )
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
"(?:\\?" +
"(?:" +
// field
"(?:([a-zA-Z\\d;/:_~',\\Q-?@$+*.!()\\E]|%[a-fA-F\\d]{2}))+" +
"(?:=" +
// value &
"(?:([a-zA-Z\\d;/:_~',\\Q-?@$+*.!()\\E]|%[a-fA-F\\d]{2}))+)?[&;]" +
")*" +
"(?:" +
// field
"(?:([a-zA-Z\\d;/:_~',\\Q-?@$+*.!()\\E]|%[a-fA-F\\d]{2}))+" +
"(?:=" +
// value
"(?:([a-zA-Z\\d;/:_~',\\Q-?@$+*.!()\\E]|%[a-fA-F\\d]{2}))+)?" +
")" +
")?" +
// fragment
"(?:#(?:([a-zA-Z\\d;/:_~',=&\\Q-?@$+*.!()\\E]|%[a-fA-F\\d]{2}))*)?" +
"$";
@Override
public void assessNodes(Triple triple) {
/* assess subject */
Node subj = triple.getSubject();
if (subj.isURI() && !subj.getURI().matches(httpUrlPattern)) {
Set<ViewQuad<ViewDefinition>> viewQuads =
pinpointer.getViewCandidates(triple);
String note1 = "subject position of " + triple.toString();
String note2 = "";
// for (ViewQuad<ViewDefinition> viewQuad : viewQuads) {
// note2 += viewQuad.getQuad() + "\n"
// + "of the following view definition:\n"
// + viewQuad.getView() + "\n";
// note2 += "\n\n";
writeToSink(0, note1, note2, viewQuads);
}
/* assess predicate */
Node pred = triple.getPredicate();
if (!pred.getURI().matches(httpUrlPattern)) {
Set<ViewQuad<ViewDefinition>> viewQuads =
pinpointer.getViewCandidates(triple);
String note1 = "predicate position of " + triple.toString();
String note2 = "";
writeToSink(0, note1, note2, viewQuads);
}
/* assess object */
Node obj = triple.getObject();
if (obj.isURI() && !obj.getURI().matches(httpUrlPattern)) {
Set<ViewQuad<ViewDefinition>> viewQuads =
pinpointer.getViewCandidates(triple);
String note1 = "object position of " + triple.toString();
String note2 = "";
writeToSink(0, note1, note2, viewQuads);
}
}
}
|
/**
* Jonathan Ramaswamy
* Dijkstra Car Strategy
* A strategy algorithm for cars that uses Dijkstra's algorithm to find
* the shortest path from the starting node to the destination node
*/
package traffic.strategy;
import java.util.ArrayList;
import java.util.List;
import traffic.graph.Graph;
import traffic.graph.GraphNode;
public class DijkstraCarStrategy implements CarStrategy {
public DijkstraCarStrategy(){}
/**
* Uses Dijkstra's algorithm to find the shortest path from one node to the end
* Returns a list corresponding to the path for the car to take
*/
public List<Integer> getPath(Graph g, int currentNode, int destNode ) {
int [] dist = new int [g.getNumNodes()];
int [] prev = new int [g.getNumNodes()];
boolean [] visited = new boolean [g.getNumNodes()];
for (int i=0; i<dist.length; i++) {
dist[i] = Integer.MAX_VALUE;
prev[i] = Integer.MAX_VALUE;
}
dist[currentNode] = 0;
for (int i=0; i<dist.length; i++) {
int next = minVertex(dist, visited);
visited[next] = true;
if(next == destNode) {
List<Integer> path = new ArrayList<Integer>();
while(next != Integer.MAX_VALUE) {
path.add(0, next);
next = prev[next];
}
path.remove(0);
return path;
}
List<GraphNode> n = g.getNeighbors(next);
for (int j=0; j<n.size(); j++) {
//TODO: the indices can no longer be the IDs
int v = n.get(j).getID();
int w = dist[next] + g.getDelayAtNode(next);
if (dist[v] > w) {
dist[v] = w;
prev[v] = next;
}
}
}
return null;
}
//Finds the closest vertex on the graph from the current one
private int minVertex (int [] dist, boolean [] v) {
int x = Integer.MAX_VALUE;
int y = -1;
for (int i=0; i<dist.length; i++) {
if (!v[i] && dist[i]<x) {
y=i;
x=dist[i];
}
}
return y;
}
}
|
package org.pentaho.di.ui.trans.steps.getxmldata;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.HashSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import javax.xml.xpath.XPath;
import org.xml.sax.InputSource;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathConstants;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.Const;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPreviewFactory;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.trans.steps.getxmldata.getXMLDataMeta;
import org.pentaho.di.trans.steps.getxmldata.getXMLDataField;
import org.pentaho.di.trans.steps.getxmldata.Messages;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.core.vfs.KettleVFS;
public class getXMLDataDialog extends BaseStepDialog implements StepDialogInterface
{
private static final String[] YES_NO_COMBO = new String[] { Messages.getString("System.Combo.No"), Messages.getString("System.Combo.Yes") };
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wFileTab, wContentTab, wFieldsTab;
private Composite wFileComp, wContentComp, wFieldsComp;
private FormData fdFileComp, fdContentComp, fdFieldsComp;
private Label wlFilename,wlXMLIsAFile;
private Button wbbFilename; // Browse: add file or directory
private Button wbdFilename; // Delete
private Button wbeFilename; // Edit
private Button wbaFilename; // Add or change
private TextVar wFilename;
private FormData fdlFilename, fdbFilename, fdbdFilename, fdbeFilename, fdbaFilename, fdFilename;
private Label wlFilenameList;
private TableView wFilenameList;
private FormData fdlFilenameList, fdFilenameList;
private Label wlFilemask;
private TextVar wFilemask;
private FormData fdlFilemask, fdFilemask;
private Button wbShowFiles;
private FormData fdbShowFiles;
private FormData fdlXMLField, fdlXMLStreamField,fdlXMLIsAFile;
private FormData fdXMLField, fdXSDFileField;
private FormData fdOutputField,fdXMLIsAFile,fdAdditionalFields,fdAddFileResult,fdXmlConf;
private Label wlXMLField, wlXmlStreamField;
private CCombo wXMLField;
private Button wXMLStreamField,wXMLIsAFile;
private Label wlInclFilename;
private Button wInclFilename,wAddResult;
private FormData fdlInclFilename, fdInclFilename,fdAddResult,fdlAddResult;
private Label wlNameSpaceAware;
private Button wNameSpaceAware;
private FormData fdlNameSpaceAware, fdNameSpaceAware;
private Label wlValidating;
private Button wValidating;
private FormData fdlValidating, fdValidating;
private Label wlInclFilenameField;
private TextVar wInclFilenameField;
private FormData fdlInclFilenameField, fdInclFilenameField;
private Label wlInclRownum,wlAddResult;
private Button wInclRownum;
private FormData fdlInclRownum, fdRownum;
private Label wlInclRownumField;
private TextVar wInclRownumField;
private FormData fdlInclRownumField, fdInclRownumField;
private Label wlLimit;
private Text wLimit;
private FormData fdlLimit, fdLimit;
private Label wlLoopXPath;
private TextVar wLoopXPath;
private FormData fdlLoopXPath, fdLoopXPath;
private Label wlEncoding;
private CCombo wEncoding;
private FormData fdlEncoding, fdEncoding;
private TableView wFields;
private FormData fdFields;
private Group wOutputField;
private Group wAdditionalFields;
private Group wAddFileResult;
private Group wXmlConf;
private getXMLDataMeta input;
private boolean gotEncodings = false;
public static final int dateLengths[] = new int[]
{
23, 19, 14, 10, 10, 10, 10, 8, 8, 8, 8, 6, 6
}
;
public getXMLDataDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(getXMLDataMeta)in;
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("getXMLDataDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right= new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
// START OF FILE TAB ///
wFileTab=new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(Messages.getString("getXMLDataDialog.File.Tab"));
wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// START OF Output Field GROUP //
wOutputField = new Group(wFileComp, SWT.SHADOW_NONE);
props.setLook(wOutputField);
wOutputField.setText(Messages.getString("getXMLDataDialog.wOutputField.Label"));
FormLayout outputfieldgroupLayout = new FormLayout();
outputfieldgroupLayout.marginWidth = 10;
outputfieldgroupLayout.marginHeight = 10;
wOutputField.setLayout(outputfieldgroupLayout);
//Is XML string defined in a Field
wlXmlStreamField = new Label(wOutputField, SWT.RIGHT);
wlXmlStreamField.setText(Messages.getString("getXMLDataDialog.wlXmlStreamField.Label"));
props.setLook(wlXmlStreamField);
fdlXMLStreamField = new FormData();
fdlXMLStreamField.left = new FormAttachment(0, 0);
fdlXMLStreamField.top = new FormAttachment(0, margin);
fdlXMLStreamField.right = new FormAttachment(middle, -margin);
wlXmlStreamField.setLayoutData(fdlXMLStreamField);
wXMLStreamField = new Button(wOutputField, SWT.CHECK);
props.setLook(wXMLStreamField);
wXMLStreamField.setToolTipText(Messages.getString("getXMLDataDialog.wXmlStreamField.Tooltip"));
fdXSDFileField = new FormData();
fdXSDFileField.left = new FormAttachment(middle, margin);
fdXSDFileField.top = new FormAttachment(0, margin);
wXMLStreamField.setLayoutData(fdXSDFileField);
SelectionAdapter lsxmlstream = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
ActivewlXmlStreamField();
input.setChanged();
}
};
wXMLStreamField.addSelectionListener(lsxmlstream);
//Is XML source is a file?
wlXMLIsAFile = new Label(wOutputField, SWT.RIGHT);
wlXMLIsAFile.setText(Messages.getString("getXMLDataDialog.XMLIsAFile.Label"));
props.setLook(wlXMLIsAFile);
fdlXMLIsAFile = new FormData();
fdlXMLIsAFile.left = new FormAttachment(0, 0);
fdlXMLIsAFile.top = new FormAttachment(wXMLStreamField, margin);
fdlXMLIsAFile.right = new FormAttachment(middle, -margin);
wlXMLIsAFile.setLayoutData(fdlXMLIsAFile);
wXMLIsAFile = new Button(wOutputField, SWT.CHECK);
props.setLook(wXMLIsAFile);
wXMLIsAFile.setToolTipText(Messages.getString("getXMLDataDialog.XMLIsAFile.Tooltip"));
fdXMLIsAFile = new FormData();
fdXMLIsAFile.left = new FormAttachment(middle, margin);
fdXMLIsAFile.top = new FormAttachment(wXMLStreamField, margin);
wXMLIsAFile.setLayoutData(fdXMLIsAFile);
SelectionAdapter lsxmlisafile = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
ActivewlXmlStreamField();
input.setChanged();
}
};
wXMLIsAFile.addSelectionListener(lsxmlisafile);
// If XML string defined in a Field
wlXMLField=new Label(wOutputField, SWT.RIGHT);
wlXMLField.setText(Messages.getString("getXMLDataDialog.wlXMLField.Label"));
props.setLook(wlXMLField);
fdlXMLField=new FormData();
fdlXMLField.left = new FormAttachment(0, 0);
fdlXMLField.top = new FormAttachment(wXMLIsAFile, margin);
fdlXMLField.right= new FormAttachment(middle, -margin);
wlXMLField.setLayoutData(fdlXMLField);
wXMLField=new CCombo(wOutputField, SWT.BORDER | SWT.READ_ONLY);
wXMLField.setEditable(true);
props.setLook(wXMLField);
wXMLField.addModifyListener(lsMod);
fdXMLField=new FormData();
fdXMLField.left = new FormAttachment(middle, margin);
fdXMLField.top = new FormAttachment(wXMLIsAFile, margin);
fdXMLField.right= new FormAttachment(100, -margin);
wXMLField.setLayoutData(fdXMLField);
wXMLField.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setXMLStreamField();
shell.setCursor(null);
busy.dispose();
}
}
);
fdOutputField = new FormData();
fdOutputField.left = new FormAttachment(0, margin);
fdOutputField.top = new FormAttachment(wFilenameList, margin);
fdOutputField.right = new FormAttachment(100, -margin);
wOutputField.setLayoutData(fdOutputField);
// / END OF Output Field GROUP
// Filename line
wlFilename=new Label(wFileComp, SWT.RIGHT);
wlFilename.setText(Messages.getString("getXMLDataDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(wOutputField, margin);
fdlFilename.right= new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbbFilename);
wbbFilename.setText(Messages.getString("getXMLDataDialog.FilenameBrowse.Button"));
wbbFilename.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(wOutputField, margin);
wbbFilename.setLayoutData(fdbFilename);
wbaFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbaFilename);
wbaFilename.setText(Messages.getString("getXMLDataDialog.FilenameAdd.Button"));
wbaFilename.setToolTipText(Messages.getString("getXMLDataDialog.FilenameAdd.Tooltip"));
fdbaFilename=new FormData();
fdbaFilename.right= new FormAttachment(wbbFilename, -margin);
fdbaFilename.top = new FormAttachment(wOutputField, margin);
wbaFilename.setLayoutData(fdbaFilename);
wFilename=new TextVar(transMeta,wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.right= new FormAttachment(wbaFilename, -margin);
fdFilename.top = new FormAttachment(wOutputField, margin);
wFilename.setLayoutData(fdFilename);
wlFilemask=new Label(wFileComp, SWT.RIGHT);
wlFilemask.setText(Messages.getString("getXMLDataDialog.RegExp.Label"));
props.setLook(wlFilemask);
fdlFilemask=new FormData();
fdlFilemask.left = new FormAttachment(0, 0);
fdlFilemask.top = new FormAttachment(wFilename, margin);
fdlFilemask.right= new FormAttachment(middle, -margin);
wlFilemask.setLayoutData(fdlFilemask);
wFilemask=new TextVar(transMeta,wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilemask);
wFilemask.addModifyListener(lsMod);
fdFilemask=new FormData();
fdFilemask.left = new FormAttachment(middle, 0);
fdFilemask.top = new FormAttachment(wFilename, margin);
fdFilemask.right= new FormAttachment(100, 0);
wFilemask.setLayoutData(fdFilemask);
// Filename list line
wlFilenameList=new Label(wFileComp, SWT.RIGHT);
wlFilenameList.setText(Messages.getString("getXMLDataDialog.FilenameList.Label"));
props.setLook(wlFilenameList);
fdlFilenameList=new FormData();
fdlFilenameList.left = new FormAttachment(0, 0);
fdlFilenameList.top = new FormAttachment(wFilemask, margin);
fdlFilenameList.right= new FormAttachment(middle, -margin);
wlFilenameList.setLayoutData(fdlFilenameList);
// Buttons to the right of the screen...
wbdFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbdFilename);
wbdFilename.setText(Messages.getString("getXMLDataDialog.FilenameRemove.Button"));
wbdFilename.setToolTipText(Messages.getString("getXMLDataDialog.FilenameRemove.Tooltip"));
fdbdFilename=new FormData();
fdbdFilename.right = new FormAttachment(100, 0);
fdbdFilename.top = new FormAttachment (wFilemask, 40);
wbdFilename.setLayoutData(fdbdFilename);
wbeFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbeFilename);
wbeFilename.setText(Messages.getString("getXMLDataDialog.FilenameEdit.Button"));
wbeFilename.setToolTipText(Messages.getString("getXMLDataDialog.FilenameEdit.Tooltip"));
fdbeFilename=new FormData();
fdbeFilename.right = new FormAttachment(100, 0);
fdbeFilename.top = new FormAttachment (wbdFilename, margin);
wbeFilename.setLayoutData(fdbeFilename);
wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(Messages.getString("getXMLDataDialog.ShowFiles.Button"));
fdbShowFiles=new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.bottom = new FormAttachment(100, 0);
wbShowFiles.setLayoutData(fdbShowFiles);
ColumnInfo[] colinfo=new ColumnInfo[3];
colinfo[ 0]=new ColumnInfo( Messages.getString("getXMLDataDialog.Files.Filename.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false);
colinfo[ 1]=new ColumnInfo( Messages.getString("getXMLDataDialog.Files.Wildcard.Column"),ColumnInfo.COLUMN_TYPE_TEXT, false );
colinfo[0].setUsingVariables(true);
colinfo[1].setUsingVariables(true);
colinfo[1].setToolTip(Messages.getString("getXMLDataDialog.Files.Wildcard.Tooltip"));
colinfo[2]=new ColumnInfo(Messages.getString("getXMLDataDialog.Required.Column"),ColumnInfo.COLUMN_TYPE_CCOMBO, YES_NO_COMBO );
colinfo[2].setToolTip(Messages.getString("getXMLDataDialog.Required.Tooltip"));
wFilenameList = new TableView(transMeta,wFileComp,
SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER,
colinfo,
2,
lsMod,
props
);
props.setLook(wFilenameList);
fdFilenameList=new FormData();
fdFilenameList.left = new FormAttachment(middle, 0);
fdFilenameList.right = new FormAttachment(wbdFilename, -margin);
fdFilenameList.top = new FormAttachment(wFilemask, margin);
fdFilenameList.bottom = new FormAttachment(wbShowFiles, -margin);
wFilenameList.setLayoutData(fdFilenameList);
fdFileComp=new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom= new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
/// END OF FILE TAB
// START OF CONTENT TAB///
wContentTab=new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(Messages.getString("getXMLDataDialog.Content.Tab"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
// START OF XmlConf Field GROUP //
wXmlConf = new Group(wContentComp, SWT.SHADOW_NONE);
props.setLook(wXmlConf);
wXmlConf.setText(Messages.getString("getXMLDataDialog.wXmlConf.Label"));
FormLayout XmlConfgroupLayout = new FormLayout();
XmlConfgroupLayout.marginWidth = 10;
XmlConfgroupLayout.marginHeight = 10;
wXmlConf.setLayout(XmlConfgroupLayout);
wlLoopXPath=new Label(wXmlConf, SWT.RIGHT);
wlLoopXPath.setText(Messages.getString("getXMLDataDialog.LoopXPath.Label"));
props.setLook(wlLoopXPath);
fdlLoopXPath=new FormData();
fdlLoopXPath.left = new FormAttachment(0, 0);
fdlLoopXPath.top = new FormAttachment(0, margin);
fdlLoopXPath.right= new FormAttachment(middle, -margin);
wlLoopXPath.setLayoutData(fdlLoopXPath);
wLoopXPath=new TextVar(transMeta,wXmlConf, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLoopXPath.setToolTipText(Messages.getString("getXMLDataDialog.LoopXPath.Tooltip"));
props.setLook(wLoopXPath);
wLoopXPath.addModifyListener(lsMod);
fdLoopXPath=new FormData();
fdLoopXPath.left = new FormAttachment(middle, 0);
fdLoopXPath.top = new FormAttachment(0, margin);
fdLoopXPath.right= new FormAttachment(100, 0);
wLoopXPath.setLayoutData(fdLoopXPath);
wlEncoding=new Label(wXmlConf, SWT.RIGHT);
wlEncoding.setText(Messages.getString("getXMLDataDialog.Encoding.Label"));
props.setLook(wlEncoding);
fdlEncoding=new FormData();
fdlEncoding.left = new FormAttachment(0, 0);
fdlEncoding.top = new FormAttachment(wLoopXPath, margin);
fdlEncoding.right= new FormAttachment(middle, -margin);
wlEncoding.setLayoutData(fdlEncoding);
wEncoding=new CCombo(wXmlConf, SWT.BORDER | SWT.READ_ONLY);
wEncoding.setEditable(true);
props.setLook(wEncoding);
wEncoding.addModifyListener(lsMod);
fdEncoding=new FormData();
fdEncoding.left = new FormAttachment(middle, 0);
fdEncoding.top = new FormAttachment(wLoopXPath, margin);
fdEncoding.right= new FormAttachment(100, 0);
wEncoding.setLayoutData(fdEncoding);
wEncoding.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setEncodings();
shell.setCursor(null);
busy.dispose();
}
}
);
// Set Namespace aware ?
wlNameSpaceAware=new Label(wXmlConf, SWT.RIGHT);
wlNameSpaceAware.setText(Messages.getString("getXMLDataDialog.NameSpaceAware.Label"));
props.setLook(wlNameSpaceAware);
fdlNameSpaceAware=new FormData();
fdlNameSpaceAware.left = new FormAttachment(0, 0);
fdlNameSpaceAware.top = new FormAttachment(wEncoding, margin);
fdlNameSpaceAware.right= new FormAttachment(middle, -margin);
wlNameSpaceAware.setLayoutData(fdlNameSpaceAware);
wNameSpaceAware=new Button(wXmlConf, SWT.CHECK );
props.setLook(wNameSpaceAware);
wNameSpaceAware.setToolTipText(Messages.getString("getXMLDataDialog.NameSpaceAware.Tooltip"));
fdNameSpaceAware=new FormData();
fdNameSpaceAware.left = new FormAttachment(middle, 0);
fdNameSpaceAware.top = new FormAttachment(wEncoding, margin);
wNameSpaceAware.setLayoutData(fdNameSpaceAware);
// Validate XML?
wlValidating=new Label(wXmlConf, SWT.RIGHT);
wlValidating.setText(Messages.getString("getXMLDataDialog.Validating.Label"));
props.setLook(wlValidating);
fdlValidating=new FormData();
fdlValidating.left = new FormAttachment(0, 0);
fdlValidating.top = new FormAttachment(wNameSpaceAware, margin);
fdlValidating.right= new FormAttachment(middle, -margin);
wlValidating.setLayoutData(fdlValidating);
wValidating=new Button(wXmlConf, SWT.CHECK );
props.setLook(wValidating);
wValidating.setToolTipText(Messages.getString("getXMLDataDialog.Validating.Tooltip"));
fdValidating=new FormData();
fdValidating.left = new FormAttachment(middle, 0);
fdValidating.top = new FormAttachment(wNameSpaceAware, margin);
wValidating.setLayoutData(fdValidating);
wlLimit=new Label(wXmlConf, SWT.RIGHT);
wlLimit.setText(Messages.getString("getXMLDataDialog.Limit.Label"));
props.setLook(wlLimit);
fdlLimit=new FormData();
fdlLimit.left = new FormAttachment(0, 0);
fdlLimit.top = new FormAttachment(wValidating, margin);
fdlLimit.right= new FormAttachment(middle, -margin);
wlLimit.setLayoutData(fdlLimit);
wLimit=new Text(wXmlConf, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLimit);
wLimit.addModifyListener(lsMod);
fdLimit=new FormData();
fdLimit.left = new FormAttachment(middle, 0);
fdLimit.top = new FormAttachment(wValidating, margin);
fdLimit.right= new FormAttachment(100, 0);
wLimit.setLayoutData(fdLimit);
fdXmlConf = new FormData();
fdXmlConf.left = new FormAttachment(0, margin);
fdXmlConf.top = new FormAttachment(0, margin);
fdXmlConf.right = new FormAttachment(100, -margin);
wXmlConf.setLayoutData(fdXmlConf);
// / END OF XmlConf Field GROUP
// START OF Additional Fields GROUP //
wAdditionalFields = new Group(wContentComp, SWT.SHADOW_NONE);
props.setLook(wAdditionalFields);
wAdditionalFields.setText(Messages.getString("getXMLDataDialog.wAdditionalFields.Label"));
FormLayout AdditionalFieldsgroupLayout = new FormLayout();
AdditionalFieldsgroupLayout.marginWidth = 10;
AdditionalFieldsgroupLayout.marginHeight = 10;
wAdditionalFields.setLayout(AdditionalFieldsgroupLayout);
wlInclFilename=new Label(wAdditionalFields, SWT.RIGHT);
wlInclFilename.setText(Messages.getString("getXMLDataDialog.InclFilename.Label"));
props.setLook(wlInclFilename);
fdlInclFilename=new FormData();
fdlInclFilename.left = new FormAttachment(0, 0);
fdlInclFilename.top = new FormAttachment(wXmlConf, 4*margin);
fdlInclFilename.right= new FormAttachment(middle, -margin);
wlInclFilename.setLayoutData(fdlInclFilename);
wInclFilename=new Button(wAdditionalFields, SWT.CHECK );
props.setLook(wInclFilename);
wInclFilename.setToolTipText(Messages.getString("getXMLDataDialog.InclFilename.Tooltip"));
fdInclFilename=new FormData();
fdInclFilename.left = new FormAttachment(middle, 0);
fdInclFilename.top = new FormAttachment(wXmlConf, 4*margin);
wInclFilename.setLayoutData(fdInclFilename);
wlInclFilenameField=new Label(wAdditionalFields, SWT.LEFT);
wlInclFilenameField.setText(Messages.getString("getXMLDataDialog.InclFilenameField.Label"));
props.setLook(wlInclFilenameField);
fdlInclFilenameField=new FormData();
fdlInclFilenameField.left = new FormAttachment(wInclFilename, margin);
fdlInclFilenameField.top = new FormAttachment(wLimit, 4*margin);
wlInclFilenameField.setLayoutData(fdlInclFilenameField);
wInclFilenameField=new TextVar(transMeta,wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wInclFilenameField);
wInclFilenameField.addModifyListener(lsMod);
fdInclFilenameField=new FormData();
fdInclFilenameField.left = new FormAttachment(wlInclFilenameField, margin);
fdInclFilenameField.top = new FormAttachment(wLimit, 4*margin);
fdInclFilenameField.right= new FormAttachment(100, 0);
wInclFilenameField.setLayoutData(fdInclFilenameField);
wlInclRownum=new Label(wAdditionalFields, SWT.RIGHT);
wlInclRownum.setText(Messages.getString("getXMLDataDialog.InclRownum.Label"));
props.setLook(wlInclRownum);
fdlInclRownum=new FormData();
fdlInclRownum.left = new FormAttachment(0, 0);
fdlInclRownum.top = new FormAttachment(wInclFilenameField, margin);
fdlInclRownum.right= new FormAttachment(middle, -margin);
wlInclRownum.setLayoutData(fdlInclRownum);
wInclRownum=new Button(wAdditionalFields, SWT.CHECK );
props.setLook(wInclRownum);
wInclRownum.setToolTipText(Messages.getString("getXMLDataDialog.InclRownum.Tooltip"));
fdRownum=new FormData();
fdRownum.left = new FormAttachment(middle, 0);
fdRownum.top = new FormAttachment(wInclFilenameField, margin);
wInclRownum.setLayoutData(fdRownum);
wlInclRownumField=new Label(wAdditionalFields, SWT.RIGHT);
wlInclRownumField.setText(Messages.getString("getXMLDataDialog.InclRownumField.Label"));
props.setLook(wlInclRownumField);
fdlInclRownumField=new FormData();
fdlInclRownumField.left = new FormAttachment(wInclRownum, margin);
fdlInclRownumField.top = new FormAttachment(wInclFilenameField, margin);
wlInclRownumField.setLayoutData(fdlInclRownumField);
wInclRownumField=new TextVar(transMeta,wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wInclRownumField);
wInclRownumField.addModifyListener(lsMod);
fdInclRownumField=new FormData();
fdInclRownumField.left = new FormAttachment(wlInclRownumField, margin);
fdInclRownumField.top = new FormAttachment(wInclFilenameField, margin);
fdInclRownumField.right= new FormAttachment(100, 0);
wInclRownumField.setLayoutData(fdInclRownumField);
fdAdditionalFields = new FormData();
fdAdditionalFields.left = new FormAttachment(0, margin);
fdAdditionalFields.top = new FormAttachment(wXmlConf, margin);
fdAdditionalFields.right = new FormAttachment(100, -margin);
wAdditionalFields.setLayoutData(fdAdditionalFields);
// / END OF Additional Fields GROUP
// START OF AddFileResult GROUP //
wAddFileResult = new Group(wContentComp, SWT.SHADOW_NONE);
props.setLook(wAddFileResult);
wAddFileResult.setText(Messages.getString("getXMLDataDialog.wAddFileResult.Label"));
FormLayout AddFileResultgroupLayout = new FormLayout();
AddFileResultgroupLayout.marginWidth = 10;
AddFileResultgroupLayout.marginHeight = 10;
wAddFileResult.setLayout(AddFileResultgroupLayout);
wlAddResult=new Label(wAddFileResult, SWT.RIGHT);
wlAddResult.setText(Messages.getString("getXMLDataDialog.AddResult.Label"));
props.setLook(wlAddResult);
fdlAddResult=new FormData();
fdlAddResult.left = new FormAttachment(0, 0);
fdlAddResult.top = new FormAttachment(wAdditionalFields, margin);
fdlAddResult.right= new FormAttachment(middle, -margin);
wlAddResult.setLayoutData(fdlAddResult);
wAddResult=new Button(wAddFileResult, SWT.CHECK );
props.setLook(wAddResult);
wAddResult.setToolTipText(Messages.getString("getXMLDataDialog.AddResult.Tooltip"));
fdAddResult=new FormData();
fdAddResult.left = new FormAttachment(middle, 0);
fdAddResult.top = new FormAttachment(wAdditionalFields, margin);
wAddResult.setLayoutData(fdAddResult);
fdAddFileResult = new FormData();
fdAddFileResult.left = new FormAttachment(0, margin);
fdAddFileResult.top = new FormAttachment(wAdditionalFields, margin);
fdAddFileResult.right = new FormAttachment(100, -margin);
wAddFileResult.setLayoutData(fdAddFileResult);
// / END OF AddFileResult GROUP
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom= new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
// / END OF CONTENT TAB
// Fields tab...
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(Messages.getString("getXMLDataDialog.Fields.Tab"));
FormLayout fieldsLayout = new FormLayout ();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet=new Button(wFieldsComp, SWT.PUSH);
wGet.setText(Messages.getString("getXMLDataDialog.GetFields.Button"));
fdGet=new FormData();
fdGet.left=new FormAttachment(50, 0);
fdGet.bottom =new FormAttachment(100, 0);
wGet.setLayoutData(fdGet);
final int FieldsRows=input.getInputFields().length;
// Prepare a list of possible formats...
String dats[] = Const.getDateFormats();
String nums[] = Const.getNumberFormats();
int totsize = dats.length + nums.length;
String formats[] = new String[totsize];
for (int x=0;x<dats.length;x++) formats[x] = dats[x];
for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x];
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Name.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.XPath.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Element.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
getXMLDataField.ElementTypeDesc,
true ),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Type.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMeta.getTypes(),
true ),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Format.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
formats),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Length.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Precision.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Currency.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Decimal.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Group.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.TrimType.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
getXMLDataField.trimTypeDesc,
true ),
new ColumnInfo(
Messages.getString("getXMLDataDialog.FieldsTable.Repeat.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
new String[] { Messages.getString("System.Combo.Yes"), Messages.getString("System.Combo.No") },
true ),
};
colinf[0].setUsingVariables(true);
colinf[0].setToolTip(Messages.getString("getXMLDataDialog.FieldsTable.Name.Column.Tooltip"));
colinf[1].setUsingVariables(true);
colinf[1].setToolTip(Messages.getString("getXMLDataDialog.FieldsTable.XPath.Column.Tooltip"));
wFields=new TableView(transMeta,wFieldsComp,
SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
fdFieldsComp=new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom= new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK"));
wPreview=new Button(shell, SWT.PUSH);
wPreview.setText(Messages.getString("getXMLDataDialog.Button.PreviewRows"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wPreview, wCancel }, margin, wTabFolder);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsPreview = new Listener() { public void handleEvent(Event e) { preview(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wPreview.addListener(SWT.Selection, lsPreview);
wCancel.addListener (SWT.Selection, lsCancel );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wLimit.addSelectionListener( lsDef );
wInclRownumField.addSelectionListener( lsDef );
wInclFilenameField.addSelectionListener( lsDef );
// Add the file to the list of files...
SelectionAdapter selA = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
wFilenameList.add(new String[] { wFilename.getText(), wFilemask.getText() } );
wFilename.setText("");
wFilemask.setText("");
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth(true);
}
};
wbaFilename.addSelectionListener(selA);
wFilename.addSelectionListener(selA);
// Delete files from the list of files...
wbdFilename.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
int idx[] = wFilenameList.getSelectionIndices();
wFilenameList.remove(idx);
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
}
});
// Edit the selected file & remove from the list...
wbeFilename.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
int idx = wFilenameList.getSelectionIndex();
if (idx>=0)
{
String string[] = wFilenameList.getItem(idx);
wFilename.setText(string[0]);
wFilemask.setText(string[1]);
wFilenameList.remove(idx);
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
}
});
// Show the files that are selected at this time...
wbShowFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
try
{
getXMLDataMeta tfii = new getXMLDataMeta();
getInfo(tfii);
FileInputList fileInputList = tfii.getFiles(transMeta);
String files[] = fileInputList.getFileStrings();
if (files!=null && files.length>0)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, files, Messages.getString("getXMLDataDialog.FilesReadSelection.DialogTitle"), Messages.getString("getXMLDataDialog.FilesReadSelection.DialogMessage"));
esd.setViewOnly();
esd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("getXMLDataDialog.NoFileFound.DialogMessage"));
mb.setText(Messages.getString("System.Dialog.Error.Title"));
mb.open();
}
}
catch(KettleException ex)
{
new ErrorDialog(shell, Messages.getString("getXMLDataDialog.ErrorParsingData.DialogTitle"), Messages.getString("getXMLDataDialog.ErrorParsingData.DialogMessage"), ex);
}
}
}
);
// Enable/disable the right fields to allow a filename to be added to each row...
wInclFilename.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
setIncludeFilename();
}
}
);
// Enable/disable the right fields to allow a row number to be added to each row...
wInclRownum.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
setIncludeRownum();
}
}
);
// Whenever something changes, set the tooltip to the expanded version of the filename:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(wFilename.getText());
}
}
);
// Listen to the Browse... button
wbbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
if (wFilemask.getText()!=null && wFilemask.getText().length()>0) // A mask: a directory!
{
DirectoryDialog dialog = new DirectoryDialog(shell, SWT.OPEN);
if (wFilename.getText()!=null)
{
String fpath = transMeta.environmentSubstitute(wFilename.getText());
dialog.setFilterPath( fpath );
}
if (dialog.open()!=null)
{
String str= dialog.getFilterPath();
wFilename.setText(str);
}
}
else
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.xml;*.XML", "*"});
if (wFilename.getText()!=null)
{
String fname = transMeta.environmentSubstitute(wFilename.getText());
dialog.setFileName( fname );
}
dialog.setFilterNames(new String[] {Messages.getString("System.FileType.XMLFiles"), Messages.getString("System.FileType.AllFiles")});
if (dialog.open()!=null)
{
String str = dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName();
wFilename.setText(str);
}
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData(input);
ActivewlXmlStreamField();
input.setChanged(changed);
wFields.optWidth(true);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void setXMLStreamField()
{
try{
wXMLField.removeAll();
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null)
{
r.getFieldNames();
for (int i=0;i<r.getFieldNames().length;i++)
{
wXMLField.add(r.getFieldNames()[i]);
}
}
}catch(KettleException ke){
new ErrorDialog(shell, Messages.getString("GenerateAirDialog.FailedToGetFields.DialogTitle"), Messages.getString("GenerateAirDialogMod.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void ActivewlXmlStreamField()
{
wlXMLField.setEnabled(wXMLStreamField.getSelection());
wXMLField.setEnabled(wXMLStreamField.getSelection());
wlXMLIsAFile.setEnabled(wXMLStreamField.getSelection());
wXMLIsAFile.setEnabled(wXMLStreamField.getSelection());
wlFilename.setEnabled(!wXMLStreamField.getSelection());
wbbFilename.setEnabled(!wXMLStreamField.getSelection());
wbaFilename.setEnabled(!wXMLStreamField.getSelection());
wFilename.setEnabled(!wXMLStreamField.getSelection());
wlFilemask.setEnabled(!wXMLStreamField.getSelection());
wFilemask.setEnabled(!wXMLStreamField.getSelection());
wlFilenameList.setEnabled(!wXMLStreamField.getSelection());
wbdFilename.setEnabled(!wXMLStreamField.getSelection());
wbeFilename.setEnabled(!wXMLStreamField.getSelection());
wbShowFiles.setEnabled(!wXMLStreamField.getSelection());
wlFilenameList.setEnabled(!wXMLStreamField.getSelection());
wFilenameList.setEnabled(!wXMLStreamField.getSelection());
wInclFilename.setEnabled(!wXMLStreamField.getSelection());
wlInclFilename.setEnabled(!wXMLStreamField.getSelection());
if(wXMLStreamField.getSelection() && !wXMLIsAFile.getSelection())
{
wEncoding.setEnabled(false);
wlEncoding.setEnabled(false);
}
else
{
wEncoding.setEnabled(true);
wlEncoding.setEnabled(true);
}
wAddResult.setEnabled(!wXMLStreamField.getSelection());
wlAddResult.setEnabled(!wXMLStreamField.getSelection());
wLimit.setEnabled(!wXMLStreamField.getSelection());
wPreview.setEnabled(!wXMLStreamField.getSelection());
wGet.setEnabled(!wXMLStreamField.getSelection());
}
private void get()
{
try
{
getXMLDataMeta meta = new getXMLDataMeta();
getInfo(meta);
// check if the path is given
if (!checkLoopXPath(meta)) return;
FileInputList inputList = meta.getFiles(transMeta);
if(meta.getIsInFields())
{
}
else if (inputList.getFiles().size()>0)
{
//Clear Fields Grid
wFields.removeAll();
// get encoding. By default UTF-8
String encodage="UTF-8";
if (!Const.isEmpty(meta.getEncoding()))
{
encodage=meta.getEncoding();
}
// Get Fields from the first file
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(KettleVFS.getFilename(inputList.getFile(0))), encodage)));
XPath xpath =XPathFactory.newInstance().newXPath();
NodeList widgetNodes = (NodeList) xpath.evaluate(meta.getLoopXPath(), document,XPathConstants.NODESET);
HashSet<String> list = new HashSet<String> ();
if (widgetNodes.getLength() >0)
{
for (int n = 0; n < widgetNodes.getLength(); n++)
{
// Let's take the node
Node widgetNode = widgetNodes.item(n);
String valueNode=null;
for (int i = 0; i < widgetNode.getChildNodes().getLength(); i++)
{
// Get Node Name
String nodename=widgetNode.getChildNodes().item(i).getNodeName();
if(!list.contains(nodename) && !nodename.equals("#text"))
{
TableItem item = new TableItem(wFields.table, SWT.NONE);
item.setText(1, nodename);
item.setText(2, nodename);
item.setText(3, getXMLDataField.ElementTypeDesc[0]);
// Get Node value
valueNode=XMLHandler.getNodeValue( widgetNode.getChildNodes().item(i) );
// Try to get the Type
if(IsDate(valueNode))
{
item.setText(4, "Date");
item.setText(5, "yyyy/MM/dd");
}
else if(IsInteger(valueNode))
item.setText(4, "Integer");
else if(IsNumber(valueNode))
item.setText(4, "Number");
else
item.setText(4, "String");
list.add(nodename);
}
}
list.clear();
for (int i = 0; i < widgetNode.getAttributes().getLength(); i++)
{
// Get Attribute Name
String attributname=widgetNode.getAttributes().item(i).getNodeName();
if(!list.contains(attributname))
{
TableItem item = new TableItem(wFields.table, SWT.NONE);
item.setText(1, attributname);
item.setText(2, attributname);
item.setText(3, getXMLDataField.ElementTypeDesc[1]);
// Get attribute value
valueNode = widgetNode.getAttributes().item(i).getNodeValue();
// Try to get the Type
if(IsDate(valueNode))
{
item.setText(4, "Date");
item.setText(5, "yyyy/MM/dd");
}
else if(IsInteger(valueNode))
item.setText(4, "Integer");
else if(IsNumber(valueNode))
item.setText(4, "Number");
else
item.setText(4, "String");
list.add(attributname);
}
}
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("getXMLDataDialog.ErrorParsingData.DialogTitle"), Messages.getString("getXMLDataDialog.ErrorParsingData.DialogMessage"), e);
}
}
private boolean IsInteger(String str)
{
try
{
Integer.parseInt(str);
}
catch(NumberFormatException e) {return false; }
return true;
}
private boolean IsNumber(String str)
{
try
{
Float.parseFloat(str);
}
catch(Exception e) {return false; }
return true;
}
private boolean IsDate(String str)
{
// TODO: What about other dates? Maybe something for a CRQ
try
{
SimpleDateFormat fdate = new SimpleDateFormat("yyyy/MM/dd");
fdate.setLenient(false);
fdate.parse(str);
}
catch(Exception e) {return false; }
return true;
}
private void setEncodings()
{
// Encoding of the text file:
if (!gotEncodings)
{
gotEncodings = true;
wEncoding.removeAll();
ArrayList<Charset> values = new ArrayList<Charset>(Charset.availableCharsets().values());
for (int i=0;i<values.size();i++)
{
Charset charSet = (Charset)values.get(i);
wEncoding.add( charSet.displayName() );
}
// Now select the default!
String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8");
int idx = Const.indexOfString(defEncoding, wEncoding.getItems() );
if (idx>=0) wEncoding.select( idx );
}
}
public void setIncludeFilename()
{
wlInclFilenameField.setEnabled(wInclFilename.getSelection());
wInclFilenameField.setEnabled(wInclFilename.getSelection());
}
public void setIncludeRownum()
{
wlInclRownumField.setEnabled(wInclRownum.getSelection());
wInclRownumField.setEnabled(wInclRownum.getSelection());
}
/**
* Read the data from the TextFileInputMeta object and show it in this dialog.
*
* @param in The TextFileInputMeta object to obtain the data from.
*/
public void getData(getXMLDataMeta in)
{
if (in.getFileName() !=null)
{
wFilenameList.removeAll();
for (int i=0;i<in.getFileName().length;i++)
{
wFilenameList.add(new String[] { in.getFileName()[i], in.getFileMask()[i],in.getFileRequired()[i] } );
}
wFilenameList.removeEmptyRows();
wFilenameList.setRowNums();
wFilenameList.optWidth(true);
}
wInclFilename.setSelection(in.includeFilename());
wInclRownum.setSelection(in.includeRowNumber());
wAddResult.setSelection(in.addResultFile());
wNameSpaceAware.setSelection(in.isNamespaceAware());
wValidating.setSelection(in.isValidating());
wXMLStreamField.setSelection(in.getIsInFields());
wXMLIsAFile.setSelection(in.getIsAFile());
if (in.getXMLField()!=null) wXMLField.setText(in.getXMLField());
if (in.getFilenameField()!=null) wInclFilenameField.setText(in.getFilenameField());
if (in.getRowNumberField()!=null) wInclRownumField.setText(in.getRowNumberField());
wLimit.setText(""+in.getRowLimit());
if(in.getLoopXPath()!=null) wLoopXPath.setText(in.getLoopXPath());
if (in.getEncoding()!=null)
{
wEncoding.setText(""+in.getEncoding());
}else {
wEncoding.setText("UTF-8");
}
log.logDebug(toString(), Messages.getString("getXMLDataDialog.Log.GettingFieldsInfo"));
for (int i=0;i<in.getInputFields().length;i++)
{
getXMLDataField field = in.getInputFields()[i];
if (field!=null)
{
TableItem item = wFields.table.getItem(i);
String name = field.getName();
String xpath = field.getXPath();
String element = field.getElementTypeDesc();
String type = field.getTypeDesc();
String format = field.getFormat();
String length = ""+field.getLength();
String prec = ""+field.getPrecision();
String curr = field.getCurrencySymbol();
String group = field.getGroupSymbol();
String decim = field.getDecimalSymbol();
String trim = field.getTrimTypeDesc();
String rep = field.isRepeated()?Messages.getString("System.Combo.Yes"):Messages.getString("System.Combo.No");
if (name !=null) item.setText( 1, name);
if (xpath !=null) item.setText( 2, xpath);
if (element !=null) item.setText( 3, element);
if (type !=null) item.setText( 4, type );
if (format !=null) item.setText( 5, format );
if (length !=null && !"-1".equals(length )) item.setText( 7, length );
if (prec !=null && !"-1".equals(prec )) item.setText( 8, prec );
if (curr !=null) item.setText( 8, curr );
if (decim !=null) item.setText( 9, decim );
if (group !=null) item.setText( 10, group );
if (trim !=null) item.setText( 11, trim );
if (rep !=null) item.setText(12, rep );
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
setIncludeFilename();
setIncludeRownum();
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(changed);
dispose();
}
private void ok()
{
try
{
getInfo(input);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("getXMLDataDialog.ErrorParsingData.DialogTitle"), Messages.getString("getXMLDataDialog.ErrorParsingData.DialogMessage"), e);
}
dispose();
}
private void getInfo(getXMLDataMeta in) throws KettleException
{
stepname = wStepname.getText(); // return value
// copy info to TextFileInputMeta class (input)
in.setRowLimit( Const.toLong(wLimit.getText(), 0L) );
in.setLoopXPath(wLoopXPath.getText());
in.setEncoding(wEncoding.getText());
in.setFilenameField( wInclFilenameField.getText() );
in.setRowNumberField( wInclRownumField.getText() );
in.setAddResultFile( wAddResult.getSelection() );
in.setIncludeFilename( wInclFilename.getSelection() );
in.setIncludeRowNumber( wInclRownum.getSelection() );
//in.setNamespaceAwre( wNameSpaceAware.getSelection() );
//in.setValidating( wValidating.getSelection() );
in.setIsInFields(wXMLStreamField.getSelection());
in.setIsAFile(wXMLIsAFile.getSelection());
in.setXMLField(wXMLField.getText());
int nrFiles = wFilenameList.getItemCount();
int nrFields = wFields.nrNonEmpty();
in.allocate(nrFiles, nrFields);
in.setFileName( wFilenameList.getItems(0) );
in.setFileMask( wFilenameList.getItems(1) );
in.setFileRequired( wFilenameList.getItems(2) );
for (int i=0;i<nrFields;i++)
{
getXMLDataField field = new getXMLDataField();
TableItem item = wFields.getNonEmpty(i);
field.setName( item.getText(1) );
field.setXPath( item.getText(2) );
field.setElementType( getXMLDataField.getElementTypeByDesc(item.getText(3)) );
field.setType( ValueMeta.getType(item.getText(4)) );
field.setFormat( item.getText(5) );
field.setLength( Const.toInt(item.getText(6), -1) );
field.setPrecision( Const.toInt(item.getText(7), -1) );
field.setCurrencySymbol( item.getText(8) );
field.setDecimalSymbol( item.getText(9) );
field.setGroupSymbol( item.getText(10) );
field.setTrimType( getXMLDataField.getTrimTypeByDesc(item.getText(11)) );
field.setRepeated( Messages.getString("System.Combo.Yes").equalsIgnoreCase(item.getText(12)) );
in.getInputFields()[i] = field;
}
}
// check if the loop xpath is given
private boolean checkLoopXPath(getXMLDataMeta meta){
if (meta.getLoopXPath()==null || meta.getLoopXPath().length()<1)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("getXMLDataDialog.SpecifyRepeatingElement.DialogMessage"));
mb.setText(Messages.getString("System.Dialog.Error.Title"));
mb.open();
return false;
}
else
{
return true;
}
}
// Preview the data
private void preview()
{
try
{
// Create the XML input step
getXMLDataMeta oneMeta = new getXMLDataMeta();
getInfo(oneMeta);
// check if the path is given
if (!checkLoopXPath(oneMeta)) return;
TransMeta previewMeta = TransPreviewFactory.generatePreviewTransformation(transMeta, oneMeta, wStepname.getText());
EnterNumberDialog numberDialog = new EnterNumberDialog(shell, props.getDefaultPreviewSize(), Messages.getString("getXMLDataDialog.NumberRows.DialogTitle"), Messages.getString("getXMLDataDialog.NumberRows.DialogMessage"));
int previewSize = numberDialog.open();
if (previewSize>0)
{
TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog(shell, previewMeta, new String[] { wStepname.getText() }, new int[] { previewSize } );
progressDialog.open();
if (!progressDialog.isCancelled())
{
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if (trans.getResult()!=null && trans.getResult().getNrErrors()>0)
{
EnterTextDialog etd = new EnterTextDialog(shell, Messages.getString("System.Dialog.PreviewError.Title"),
Messages.getString("System.Dialog.PreviewError.Message"), loggingText, true );
etd.setReadOnly();
etd.open();
}
PreviewRowsDialog prd = new PreviewRowsDialog(shell, transMeta, SWT.NONE, wStepname.getText(),
progressDialog.getPreviewRowsMeta(wStepname.getText()), progressDialog
.getPreviewRows(wStepname.getText()), loggingText);
prd.open();
}
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("getXMLDataDialog.ErrorPreviewingData.DialogTitle"), Messages.getString("getXMLDataDialog.ErrorPreviewingData.DialogMessage"), e);
}
}
public String toString()
{
return this.getClass().getName();
}
}
|
package processing.command;
import java.util.concurrent.BlockingQueue;
import logger.Logger;
import messaging.OutgoingMessage;
import messaging.OutgoingMessage.OutType;
import processing.CommandBase;
import users.PermissionClass;
public class CommandCommandView extends CommandBase {
@Override
public boolean isMatch() {
if (!getToken("alias").startsWith(":")) return false;
return true;
}
@Override
public boolean isValid(BlockingQueue<OutgoingMessage> listOut) {
String command = ((ProcCommand)parent).getCommand(getToken("alias").substring(1), getUser());
if (command != null && command != "") return true;
return false;
}
@Override
public boolean execute(BlockingQueue<OutgoingMessage> listOut) {
String commandStr = ((ProcCommand)parent).getCommand(getToken("alias").substring(1), getUser());
String[] args = getToken("...").split(" ");
String[] commandSplitStr = commandStr.split("");
for (String t : commandSplitStr) {
if (t.contains("%arg")) {
for (int argCounter = 1; argCounter < args.length; argCounter++) {
t = t.replace("%arg" + argCounter, args[argCounter]);
}
if (t.contains("%arg")) {
t = "";
}
}
}
commandStr = commandStr.replaceAll("%me", getUser());
return listOut.add(new OutgoingMessage(OutType.CHAT, commandStr, parent.channel));
}
@Override public String getPermissionString() { return "command.view"; }
@Override public PermissionClass getPermissionClass() { return PermissionClass.User; }
@Override public String getFormatString() { return ":<alias> ..."; }
@Override public String getHelpString() { return "This command views the response <alias>"; }
}
|
package org.sagebionetworks.bridge;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Integer.parseInt;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.springframework.util.StringUtils.commaDelimitedListToSet;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.sagebionetworks.bridge.exceptions.BadRequestException;
import org.sagebionetworks.bridge.exceptions.BridgeServiceException;
import org.sagebionetworks.bridge.json.BridgeTypeName;
import org.sagebionetworks.bridge.json.DateUtils;
import org.sagebionetworks.bridge.models.schedules.Activity;
import org.sagebionetworks.bridge.models.schedules.ActivityType;
import org.sagebionetworks.bridge.models.studies.PasswordPolicy;
import org.sagebionetworks.bridge.models.studies.Study;
import org.springframework.core.annotation.AnnotationUtils;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class BridgeUtils {
public static final Joiner COMMA_SPACE_JOINER = Joiner.on(", ");
public static final Joiner COMMA_JOINER = Joiner.on(",");
public static final Joiner SEMICOLON_SPACE_JOINER = Joiner.on("; ");
public static final Joiner SPACE_JOINER = Joiner.on(" ");
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
/**
* Create a variable map for the <code>resolveTemplate</code> method that includes common values from
* a study that used in most of our templates. The map is mutable. Variables include:
* <ul>
* <li>studyName = study.getName()</li>
* <li>studyId = study.getIdentifier()</li>
* <li>sponsorName = study.getSponsorName()</li>
* <li>supportEmail = study.getSupportEmail()</li>
* <li>technicalEmail = study.getTechnicalEmail()</li>
* <li>consentEmail = study.getConsentNotificationEmail()</li>
* </ul>
*/
public static Map<String,String> studyTemplateVariables(Study study, Function<String,String> escaper) {
Map<String,String> map = Maps.newHashMap();
map.put("studyName", study.getName());
map.put("studyId", study.getIdentifier());
map.put("sponsorName", study.getSponsorName());
map.put("supportEmail", study.getSupportEmail());
map.put("technicalEmail", study.getTechnicalEmail());
map.put("consentEmail", study.getConsentNotificationEmail());
if (escaper != null) {
for (Map.Entry<String,String> entry : map.entrySet()) {
map.put(entry.getKey(), escaper.apply(entry.getValue()));
}
}
return map;
}
public static Map<String,String> studyTemplateVariables(Study study) {
return studyTemplateVariables(study, null);
}
public static String resolveTemplate(String template, Map<String,String> values) {
checkNotNull(template);
checkNotNull(values);
for (Map.Entry<String,String> entry : values.entrySet()) {
if (entry.getValue() != null) {
String var = "${"+entry.getKey()+"}";
template = template.replace(var, entry.getValue());
}
}
return template;
}
public static String generateGuid() {
return UUID.randomUUID().toString();
}
/** Generate a random 16-byte salt, using a {@link SecureRandom}. */
public static byte[] generateSalt() {
byte[] salt = new byte[16];
SECURE_RANDOM.nextBytes(salt);
return salt;
}
/**
* Searches for a @BridgeTypeName annotation on this or any parent class in the class hierarchy, returning
* that value as the type name. If none exists, defaults to the simple class name.
* @param clazz
* @return
*/
public static String getTypeName(Class<?> clazz) {
BridgeTypeName att = AnnotationUtils.findAnnotation(clazz,BridgeTypeName.class);
if (att != null) {
return att.value();
}
return clazz.getSimpleName();
}
/**
* All batch methods in Dynamo return a list of failures rather than
* throwing an exception. We should have an exception specifically for
* these so the caller gets a list of items back, but for now, convert
* to a generic exception;
* @param failures
*/
public static void ifFailuresThrowException(List<FailedBatch> failures) {
if (!failures.isEmpty()) {
List<String> messages = Lists.newArrayList();
for (FailedBatch failure : failures) {
String message = failure.getException().getMessage();
messages.add(message);
String ids = Joiner.on("; ").join(failure.getUnprocessedItems().keySet());
messages.add(ids);
}
throw new BridgeServiceException(Joiner.on(", ").join(messages));
}
}
public static boolean isEmpty(Collection<?> coll) {
return (coll == null || coll.isEmpty());
}
public static <S,T> Map<S,T> asMap(List<T> list, Function<T,S> function) {
Map<S,T> map = Maps.newHashMap();
if (list != null && function != null) {
for (T item : list) {
map.put(function.apply(item), item);
}
}
return map;
}
public static Long parseLong(String value) {
try {
return Long.parseLong(value);
} catch(NumberFormatException e) {
throw new RuntimeException("'" + value + "' is not a valid integer");
}
}
public static Set<String> commaListToOrderedSet(String commaList) {
if (commaList != null) {
// This implementation must return a LinkedHashSet. This is a set
// with ordered keys, in the order they were in the string, as some
// set serializations depend on the order of the keys (languages).
return commaDelimitedListToSet(commaList).stream()
.map(string -> string.trim())
.filter(StringUtils::isNotBlank)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
// Cannot make this immutable without losing the concrete type we rely
// upon to ensure they keys are in the order they are inserted.
return new LinkedHashSet<String>();
}
public static String setToCommaList(Set<String> set) {
if (set != null) {
// User LinkedHashSet because some supplied sets will have ordered keys
// and we want to preserve that order while processing the set.
Set<String> result = set.stream()
.filter(StringUtils::isNotBlank)
.collect(Collectors.toCollection(LinkedHashSet::new));
return (result.isEmpty()) ? null : COMMA_JOINER.join(result);
}
return null;
}
/**
* Wraps a set in an immutable set, or returns an empty immutable set if null.
* @param set
* @return
*/
public @Nonnull static <T> ImmutableSet<T> nullSafeImmutableSet(Set<T> set) {
return (set == null) ? ImmutableSet.of() : ImmutableSet.copyOf(set.stream()
.filter(element -> element != null).collect(Collectors.toSet()));
}
public @Nonnull static <T> ImmutableList<T> nullSafeImmutableList(List<T> list) {
return (list == null) ? ImmutableList.of() : ImmutableList.copyOf(list.stream()
.filter(element -> element != null).collect(Collectors.toList()));
}
public @Nonnull static <S,T> ImmutableMap<S,T> nullSafeImmutableMap(Map<S,T> map) {
ImmutableMap.Builder<S, T> builder = new ImmutableMap.Builder<>();
if (map != null) {
for (S key : map.keySet()) {
if (map.get(key) != null) {
builder.put(key, map.get(key));
}
}
}
return builder.build();
}
public static String textToErrorKey(String text) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("String is not translatable to an error key: " + text);
}
return text.toLowerCase().replaceAll(" ", "_").replaceAll("[^a-zA-Z0-9_-]", "");
}
/**
* Parse the string as an integer value, or return the defaultValue if it is null.
* If the value is provided but not a parseable integer, thrown a BadRequestException.
*/
public static int getIntOrDefault(String value, int defaultValue) {
if (isBlank(value)) {
return defaultValue;
}
try {
return parseInt(value);
} catch(NumberFormatException e) {
throw new BadRequestException(value + " is not an integer");
}
}
/**
* Parse the string as a long value, or return the defaultValue if it is null.
* If the value is provided but not a parseable long, thrown a BadRequestException.
*/
public static Long getLongOrDefault(String value, Long defaultValue) {
if (isBlank(value)) {
return defaultValue;
}
try {
return parseLong(value);
} catch(RuntimeException e) {
throw new BadRequestException(value + " is not a long");
}
}
/**
* Parse the string as a DateTime value, or return the defaultValue if it is null.
* If the value is provided but not a parseable DateTime, thrown a BadRequestException.
*/
public static DateTime getDateTimeOrDefault(String value, DateTime defaultValue) {
if (isBlank(value)) {
return defaultValue;
}
try {
return DateTime.parse(value);
} catch(Exception e) {
throw new BadRequestException(value + " is not a DateTime value");
}
}
public static LocalDate getLocalDateOrDefault(String value, LocalDate defaultValue) {
if (isBlank(value)) {
return defaultValue;
} else {
try {
return DateUtils.parseCalendarDate(value);
} catch (RuntimeException ex) {
throw new BadRequestException(value + " is not a LocalDate value");
}
}
}
/**
* Creates a new copy of the map, removing any entries that have a null value (particularly easy to do this in
* JSON).
*/
public static <K,V> Map<K,V> withoutNullEntries(Map<K,V> map) {
checkNotNull(map);
return map.entrySet().stream().filter(e -> e.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));
}
/** Helper method which puts something to a map, or removes it from the map if the value is null. */
public static <K,V> void putOrRemove(Map<K,V> map, K key, V value) {
checkNotNull(map);
checkNotNull(key);
if (value != null) {
map.put(key, value);
} else {
map.remove(key);
}
}
public static String encodeURIComponent(String component) {
String encoded = null;
if (component != null) {
try {
encoded = URLEncoder.encode(component, "UTF-8");
} catch (UnsupportedEncodingException e) {
// UTF-8 is always supported, so this should never happen.
throw new BridgeServiceException(e.getMessage());
}
}
return encoded;
}
public static String passwordPolicyDescription(PasswordPolicy policy) {
StringBuilder sb = new StringBuilder();
sb.append("Password must be ").append(policy.getMinLength()).append(" or more characters");
if (policy.isLowerCaseRequired() || policy.isNumericRequired() || policy.isSymbolRequired() || policy.isUpperCaseRequired()) {
sb.append(", and must contain at least ");
List<String> phrases = new ArrayList<>();
if (policy.isLowerCaseRequired()) {
phrases.add("one lower-case letter");
}
if (policy.isUpperCaseRequired()) {
phrases.add("one upper-case letter");
}
if (policy.isNumericRequired()) {
phrases.add("one number");
}
if (policy.isSymbolRequired()) {
// !\"
phrases.add("one symbolic character (non-alphanumerics like
}
for (int i=0; i < phrases.size(); i++) {
if (i == phrases.size()-1) {
sb.append(", and ");
} else if (i > 0) {
sb.append(", ");
}
sb.append(phrases.get(i));
}
}
sb.append(".");
return sb.toString();
}
public static String extractPasswordFromURI(URI uri) {
boolean hasPassword = (uri.getUserInfo() != null && uri.getUserInfo().contains(":"));
return (hasPassword) ? uri.getUserInfo().split(":")[1] : null;
}
public static String createReferentGuidIndex(ActivityType type, String guid, String localDateTime) {
checkNotNull(type);
checkNotNull(guid);
checkNotNull(localDateTime);
return String.format("%s:%s:%s", guid , type.name().toLowerCase(), localDateTime);
}
public static String createReferentGuidIndex(Activity activity, LocalDateTime localDateTime) {
checkNotNull(activity);
checkNotNull(localDateTime);
ActivityType type = activity.getActivityType();
String timestamp = localDateTime.toString();
switch(type) {
case COMPOUND:
return createReferentGuidIndex(type, activity.getCompoundActivity().getTaskIdentifier(), timestamp);
case SURVEY:
return createReferentGuidIndex(type, activity.getSurvey().getGuid(), timestamp);
case TASK:
return createReferentGuidIndex(type, activity.getTask().getIdentifier(), timestamp);
}
throw new BridgeServiceException("Invalid activityType specified");
}
public static String toSynapseFriendlyName(String input) {
checkNotNull(input);
String value = input.replaceAll("[^a-zA-Z0-9\\.\\-_\\s]", " ").replaceAll("\\s+", " ").trim();
checkArgument(StringUtils.isNotBlank(value));
return value;
}
}
|
package android.view;
public class View
implements android.graphics.drawable.Drawable.Callback, android.view.KeyEvent.Callback, android.view.accessibility.AccessibilityEventSource
{
public static interface OnLayoutChangeListener
{
public abstract void onLayoutChange(android.view.View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom);
}
public static class DragShadowBuilder
{
public DragShadowBuilder(android.view.View view) { throw new RuntimeException("Stub!"); }
public DragShadowBuilder() { throw new RuntimeException("Stub!"); }
@java.lang.SuppressWarnings(value={})
public final android.view.View getView() { throw new RuntimeException("Stub!"); }
public void onProvideShadowMetrics(android.graphics.Point shadowSize, android.graphics.Point shadowTouchPoint) { throw new RuntimeException("Stub!"); }
public void onDrawShadow(android.graphics.Canvas canvas) { throw new RuntimeException("Stub!"); }
}
public static class MeasureSpec
{
public MeasureSpec() { throw new RuntimeException("Stub!"); }
public static int makeMeasureSpec(int size, int mode) { throw new RuntimeException("Stub!"); }
public static int getMode(int measureSpec) { throw new RuntimeException("Stub!"); }
public static int getSize(int measureSpec) { throw new RuntimeException("Stub!"); }
public static java.lang.String toString(int measureSpec) { throw new RuntimeException("Stub!"); }
public static final int UNSPECIFIED = 0;
public static final int EXACTLY = 1073741824;
public static final int AT_MOST = -2147483648;
}
public static interface OnKeyListener
{
public abstract boolean onKey(android.view.View v, int keyCode, android.view.KeyEvent event);
}
public static interface OnTouchListener
{
public abstract boolean onTouch(android.view.View v, android.view.MotionEvent event);
}
public static interface OnHoverListener
{
public abstract boolean onHover(android.view.View v, android.view.MotionEvent event);
}
public static interface OnGenericMotionListener
{
public abstract boolean onGenericMotion(android.view.View v, android.view.MotionEvent event);
}
public static interface OnLongClickListener
{
public abstract boolean onLongClick(android.view.View v);
}
public static interface OnDragListener
{
public abstract boolean onDrag(android.view.View v, android.view.DragEvent event);
}
public static interface OnFocusChangeListener
{
public abstract void onFocusChange(android.view.View v, boolean hasFocus);
}
public static interface OnClickListener
{
public abstract void onClick(android.view.View v);
}
public static interface OnCreateContextMenuListener
{
public abstract void onCreateContextMenu(android.view.ContextMenu menu, android.view.View v, android.view.ContextMenu.ContextMenuInfo menuInfo);
}
public static interface OnSystemUiVisibilityChangeListener
{
public abstract void onSystemUiVisibilityChange(int visibility);
}
public static interface OnAttachStateChangeListener
{
public abstract void onViewAttachedToWindow(android.view.View v);
public abstract void onViewDetachedFromWindow(android.view.View v);
}
public static class BaseSavedState
extends android.view.AbsSavedState
{
public BaseSavedState(android.os.Parcel source) { super((android.os.Parcel)null); throw new RuntimeException("Stub!"); }
public BaseSavedState(android.os.Parcelable superState) { super((android.os.Parcel)null); throw new RuntimeException("Stub!"); }
public static final android.os.Parcelable.Creator<android.view.View.BaseSavedState> CREATOR;
static { CREATOR = null; }
}
public static class AccessibilityDelegate
{
public AccessibilityDelegate() { throw new RuntimeException("Stub!"); }
public void sendAccessibilityEvent(android.view.View host, int eventType) { throw new RuntimeException("Stub!"); }
public boolean performAccessibilityAction(android.view.View host, int action, android.os.Bundle args) { throw new RuntimeException("Stub!"); }
public void sendAccessibilityEventUnchecked(android.view.View host, android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchPopulateAccessibilityEvent(android.view.View host, android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public void onPopulateAccessibilityEvent(android.view.View host, android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public void onInitializeAccessibilityEvent(android.view.View host, android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public void onInitializeAccessibilityNodeInfo(android.view.View host, android.view.accessibility.AccessibilityNodeInfo info) { throw new RuntimeException("Stub!"); }
public boolean onRequestSendAccessibilityEvent(android.view.ViewGroup host, android.view.View child, android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public android.view.accessibility.AccessibilityNodeProvider getAccessibilityNodeProvider(android.view.View host) { throw new RuntimeException("Stub!"); }
}
public View(android.content.Context context) { throw new RuntimeException("Stub!"); }
public View(android.content.Context context, android.util.AttributeSet attrs) { throw new RuntimeException("Stub!"); }
public View(android.content.Context context, android.util.AttributeSet attrs, int defStyle) { throw new RuntimeException("Stub!"); }
protected void initializeFadingEdge(android.content.res.TypedArray a) { throw new RuntimeException("Stub!"); }
public int getVerticalFadingEdgeLength() { throw new RuntimeException("Stub!"); }
public void setFadingEdgeLength(int length) { throw new RuntimeException("Stub!"); }
public int getHorizontalFadingEdgeLength() { throw new RuntimeException("Stub!"); }
public int getVerticalScrollbarWidth() { throw new RuntimeException("Stub!"); }
protected int getHorizontalScrollbarHeight() { throw new RuntimeException("Stub!"); }
protected void initializeScrollbars(android.content.res.TypedArray a) { throw new RuntimeException("Stub!"); }
public void setVerticalScrollbarPosition(int position) { throw new RuntimeException("Stub!"); }
public int getVerticalScrollbarPosition() { throw new RuntimeException("Stub!"); }
public void setOnFocusChangeListener(android.view.View.OnFocusChangeListener l) { throw new RuntimeException("Stub!"); }
public void addOnLayoutChangeListener(android.view.View.OnLayoutChangeListener listener) { throw new RuntimeException("Stub!"); }
public void removeOnLayoutChangeListener(android.view.View.OnLayoutChangeListener listener) { throw new RuntimeException("Stub!"); }
public void addOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener listener) { throw new RuntimeException("Stub!"); }
public void removeOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener listener) { throw new RuntimeException("Stub!"); }
public android.view.View.OnFocusChangeListener getOnFocusChangeListener() { throw new RuntimeException("Stub!"); }
public void setOnClickListener(android.view.View.OnClickListener l) { throw new RuntimeException("Stub!"); }
public boolean hasOnClickListeners() { throw new RuntimeException("Stub!"); }
public void setOnLongClickListener(android.view.View.OnLongClickListener l) { throw new RuntimeException("Stub!"); }
public void setOnCreateContextMenuListener(android.view.View.OnCreateContextMenuListener l) { throw new RuntimeException("Stub!"); }
public boolean performClick() { throw new RuntimeException("Stub!"); }
public boolean callOnClick() { throw new RuntimeException("Stub!"); }
public boolean performLongClick() { throw new RuntimeException("Stub!"); }
public boolean showContextMenu() { throw new RuntimeException("Stub!"); }
public android.view.ActionMode startActionMode(android.view.ActionMode.Callback callback) { throw new RuntimeException("Stub!"); }
public void setOnKeyListener(android.view.View.OnKeyListener l) { throw new RuntimeException("Stub!"); }
public void setOnTouchListener(android.view.View.OnTouchListener l) { throw new RuntimeException("Stub!"); }
public void setOnGenericMotionListener(android.view.View.OnGenericMotionListener l) { throw new RuntimeException("Stub!"); }
public void setOnHoverListener(android.view.View.OnHoverListener l) { throw new RuntimeException("Stub!"); }
public void setOnDragListener(android.view.View.OnDragListener l) { throw new RuntimeException("Stub!"); }
public boolean requestRectangleOnScreen(android.graphics.Rect rectangle) { throw new RuntimeException("Stub!"); }
public boolean requestRectangleOnScreen(android.graphics.Rect rectangle, boolean immediate) { throw new RuntimeException("Stub!"); }
public void clearFocus() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="focus")
public boolean hasFocus() { throw new RuntimeException("Stub!"); }
public boolean hasFocusable() { throw new RuntimeException("Stub!"); }
protected void onFocusChanged(boolean gainFocus, int direction, android.graphics.Rect previouslyFocusedRect) { throw new RuntimeException("Stub!"); }
public void sendAccessibilityEvent(int eventType) { throw new RuntimeException("Stub!"); }
public void announceForAccessibility(java.lang.CharSequence text) { throw new RuntimeException("Stub!"); }
public void sendAccessibilityEventUnchecked(android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public void onPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public void onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent event) { throw new RuntimeException("Stub!"); }
public android.view.accessibility.AccessibilityNodeInfo createAccessibilityNodeInfo() { throw new RuntimeException("Stub!"); }
public void onInitializeAccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo info) { throw new RuntimeException("Stub!"); }
public void setAccessibilityDelegate(android.view.View.AccessibilityDelegate delegate) { throw new RuntimeException("Stub!"); }
public android.view.accessibility.AccessibilityNodeProvider getAccessibilityNodeProvider() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="accessibility")
public java.lang.CharSequence getContentDescription() { throw new RuntimeException("Stub!"); }
public void setContentDescription(java.lang.CharSequence contentDescription) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="focus")
public boolean isFocused() { throw new RuntimeException("Stub!"); }
public android.view.View findFocus() { throw new RuntimeException("Stub!"); }
public boolean isScrollContainer() { throw new RuntimeException("Stub!"); }
public void setScrollContainer(boolean isScrollContainer) { throw new RuntimeException("Stub!"); }
public int getDrawingCacheQuality() { throw new RuntimeException("Stub!"); }
public void setDrawingCacheQuality(int quality) { throw new RuntimeException("Stub!"); }
public boolean getKeepScreenOn() { throw new RuntimeException("Stub!"); }
public void setKeepScreenOn(boolean keepScreenOn) { throw new RuntimeException("Stub!"); }
public int getNextFocusLeftId() { throw new RuntimeException("Stub!"); }
public void setNextFocusLeftId(int nextFocusLeftId) { throw new RuntimeException("Stub!"); }
public int getNextFocusRightId() { throw new RuntimeException("Stub!"); }
public void setNextFocusRightId(int nextFocusRightId) { throw new RuntimeException("Stub!"); }
public int getNextFocusUpId() { throw new RuntimeException("Stub!"); }
public void setNextFocusUpId(int nextFocusUpId) { throw new RuntimeException("Stub!"); }
public int getNextFocusDownId() { throw new RuntimeException("Stub!"); }
public void setNextFocusDownId(int nextFocusDownId) { throw new RuntimeException("Stub!"); }
public int getNextFocusForwardId() { throw new RuntimeException("Stub!"); }
public void setNextFocusForwardId(int nextFocusForwardId) { throw new RuntimeException("Stub!"); }
public boolean isShown() { throw new RuntimeException("Stub!"); }
protected boolean fitSystemWindows(android.graphics.Rect insets) { throw new RuntimeException("Stub!"); }
public void setFitsSystemWindows(boolean fitSystemWindows) { throw new RuntimeException("Stub!"); }
public boolean getFitsSystemWindows() { throw new RuntimeException("Stub!"); }
public void requestFitSystemWindows() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(mapping={@android.view.ViewDebug.IntToString(from=0,to="VISIBLE"),@android.view.ViewDebug.IntToString(from=4,to="INVISIBLE"),@android.view.ViewDebug.IntToString(from=8,to="GONE")})
public int getVisibility() { throw new RuntimeException("Stub!"); }
public void setVisibility(int visibility) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isEnabled() { throw new RuntimeException("Stub!"); }
public void setEnabled(boolean enabled) { throw new RuntimeException("Stub!"); }
public void setFocusable(boolean focusable) { throw new RuntimeException("Stub!"); }
public void setFocusableInTouchMode(boolean focusableInTouchMode) { throw new RuntimeException("Stub!"); }
public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isSoundEffectsEnabled() { throw new RuntimeException("Stub!"); }
public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isHapticFeedbackEnabled() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="layout")
public boolean hasTransientState() { throw new RuntimeException("Stub!"); }
public void setHasTransientState(boolean hasTransientState) { throw new RuntimeException("Stub!"); }
public void setWillNotDraw(boolean willNotDraw) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public boolean willNotDraw() { throw new RuntimeException("Stub!"); }
public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public boolean willNotCacheDrawing() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isClickable() { throw new RuntimeException("Stub!"); }
public void setClickable(boolean clickable) { throw new RuntimeException("Stub!"); }
public boolean isLongClickable() { throw new RuntimeException("Stub!"); }
public void setLongClickable(boolean longClickable) { throw new RuntimeException("Stub!"); }
public void setPressed(boolean pressed) { throw new RuntimeException("Stub!"); }
protected void dispatchSetPressed(boolean pressed) { throw new RuntimeException("Stub!"); }
public boolean isPressed() { throw new RuntimeException("Stub!"); }
public boolean isSaveEnabled() { throw new RuntimeException("Stub!"); }
public void setSaveEnabled(boolean enabled) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean getFilterTouchesWhenObscured() { throw new RuntimeException("Stub!"); }
public void setFilterTouchesWhenObscured(boolean enabled) { throw new RuntimeException("Stub!"); }
public boolean isSaveFromParentEnabled() { throw new RuntimeException("Stub!"); }
public void setSaveFromParentEnabled(boolean enabled) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="focus")
public final boolean isFocusable() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public final boolean isFocusableInTouchMode() { throw new RuntimeException("Stub!"); }
public android.view.View focusSearch(int direction) { throw new RuntimeException("Stub!"); }
public boolean dispatchUnhandledMove(android.view.View focused, int direction) { throw new RuntimeException("Stub!"); }
public java.util.ArrayList<android.view.View> getFocusables(int direction) { throw new RuntimeException("Stub!"); }
public void addFocusables(java.util.ArrayList<android.view.View> views, int direction) { throw new RuntimeException("Stub!"); }
public void addFocusables(java.util.ArrayList<android.view.View> views, int direction, int focusableMode) { throw new RuntimeException("Stub!"); }
public void findViewsWithText(java.util.ArrayList<android.view.View> outViews, java.lang.CharSequence searched, int flags) { throw new RuntimeException("Stub!"); }
public java.util.ArrayList<android.view.View> getTouchables() { throw new RuntimeException("Stub!"); }
public void addTouchables(java.util.ArrayList<android.view.View> views) { throw new RuntimeException("Stub!"); }
public final boolean requestFocus() { throw new RuntimeException("Stub!"); }
public final boolean requestFocus(int direction) { throw new RuntimeException("Stub!"); }
public boolean requestFocus(int direction, android.graphics.Rect previouslyFocusedRect) { throw new RuntimeException("Stub!"); }
public final boolean requestFocusFromTouch() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="accessibility",mapping={@android.view.ViewDebug.IntToString(from=0,to="auto"),@android.view.ViewDebug.IntToString(from=1,to="yes"),@android.view.ViewDebug.IntToString(from=2,to="no")})
public int getImportantForAccessibility() { throw new RuntimeException("Stub!"); }
public void setImportantForAccessibility(int mode) { throw new RuntimeException("Stub!"); }
public android.view.ViewParent getParentForAccessibility() { throw new RuntimeException("Stub!"); }
public void addChildrenForAccessibility(java.util.ArrayList<android.view.View> children) { throw new RuntimeException("Stub!"); }
public boolean performAccessibilityAction(int action, android.os.Bundle arguments) { throw new RuntimeException("Stub!"); }
public void onStartTemporaryDetach() { throw new RuntimeException("Stub!"); }
public void onFinishTemporaryDetach() { throw new RuntimeException("Stub!"); }
public android.view.KeyEvent.DispatcherState getKeyDispatcherState() { throw new RuntimeException("Stub!"); }
public boolean dispatchKeyEventPreIme(android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchKeyEvent(android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchKeyShortcutEvent(android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchTouchEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public boolean onFilterTouchEventForSecurity(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchTrackballEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchGenericMotionEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
protected boolean dispatchHoverEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
protected boolean dispatchGenericPointerEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
protected boolean dispatchGenericFocusedEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public void dispatchWindowFocusChanged(boolean hasFocus) { throw new RuntimeException("Stub!"); }
public void onWindowFocusChanged(boolean hasWindowFocus) { throw new RuntimeException("Stub!"); }
public boolean hasWindowFocus() { throw new RuntimeException("Stub!"); }
protected void dispatchVisibilityChanged(android.view.View changedView, int visibility) { throw new RuntimeException("Stub!"); }
protected void onVisibilityChanged(android.view.View changedView, int visibility) { throw new RuntimeException("Stub!"); }
public void dispatchDisplayHint(int hint) { throw new RuntimeException("Stub!"); }
protected void onDisplayHint(int hint) { throw new RuntimeException("Stub!"); }
public void dispatchWindowVisibilityChanged(int visibility) { throw new RuntimeException("Stub!"); }
protected void onWindowVisibilityChanged(int visibility) { throw new RuntimeException("Stub!"); }
public int getWindowVisibility() { throw new RuntimeException("Stub!"); }
public void getWindowVisibleDisplayFrame(android.graphics.Rect outRect) { throw new RuntimeException("Stub!"); }
public void dispatchConfigurationChanged(android.content.res.Configuration newConfig) { throw new RuntimeException("Stub!"); }
protected void onConfigurationChanged(android.content.res.Configuration newConfig) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isInTouchMode() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public android.content.Context getContext() { //throw new RuntimeException("Stub!");
return null;}
public boolean onKeyPreIme(int keyCode, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onKeyLongPress(int keyCode, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onKeyUp(int keyCode, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onKeyMultiple(int keyCode, int repeatCount, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onKeyShortcut(int keyCode, android.view.KeyEvent event) { throw new RuntimeException("Stub!"); }
public boolean onCheckIsTextEditor() { throw new RuntimeException("Stub!"); }
public android.view.inputmethod.InputConnection onCreateInputConnection(android.view.inputmethod.EditorInfo outAttrs) { throw new RuntimeException("Stub!"); }
public boolean checkInputConnectionProxy(android.view.View view) { throw new RuntimeException("Stub!"); }
public void createContextMenu(android.view.ContextMenu menu) { throw new RuntimeException("Stub!"); }
protected android.view.ContextMenu.ContextMenuInfo getContextMenuInfo() { throw new RuntimeException("Stub!"); }
protected void onCreateContextMenu(android.view.ContextMenu menu) { throw new RuntimeException("Stub!"); }
public boolean onTrackballEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public boolean onGenericMotionEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public boolean onHoverEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isHovered() { throw new RuntimeException("Stub!"); }
public void setHovered(boolean hovered) { throw new RuntimeException("Stub!"); }
public void onHoverChanged(boolean hovered) { throw new RuntimeException("Stub!"); }
public boolean onTouchEvent(android.view.MotionEvent event) { throw new RuntimeException("Stub!"); }
public void cancelLongPress() { throw new RuntimeException("Stub!"); }
public void setTouchDelegate(android.view.TouchDelegate delegate) { throw new RuntimeException("Stub!"); }
public android.view.TouchDelegate getTouchDelegate() { throw new RuntimeException("Stub!"); }
public void bringToFront() { throw new RuntimeException("Stub!"); }
protected void onScrollChanged(int l, int t, int oldl, int oldt) { throw new RuntimeException("Stub!"); }
protected void onSizeChanged(int w, int h, int oldw, int oldh) { throw new RuntimeException("Stub!"); }
protected void dispatchDraw(android.graphics.Canvas canvas) { throw new RuntimeException("Stub!"); }
public final android.view.ViewParent getParent() { throw new RuntimeException("Stub!"); }
public void setScrollX(int value) { throw new RuntimeException("Stub!"); }
public void setScrollY(int value) { throw new RuntimeException("Stub!"); }
public final int getScrollX() { throw new RuntimeException("Stub!"); }
public final int getScrollY() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="layout")
public final int getWidth() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="layout")
public final int getHeight() { throw new RuntimeException("Stub!"); }
public void getDrawingRect(android.graphics.Rect outRect) { throw new RuntimeException("Stub!"); }
public final int getMeasuredWidth() { throw new RuntimeException("Stub!"); }
public final int getMeasuredWidthAndState() { throw new RuntimeException("Stub!"); }
public final int getMeasuredHeight() { throw new RuntimeException("Stub!"); }
public final int getMeasuredHeightAndState() { throw new RuntimeException("Stub!"); }
public final int getMeasuredState() { throw new RuntimeException("Stub!"); }
public android.graphics.Matrix getMatrix() { throw new RuntimeException("Stub!"); }
public float getCameraDistance() { throw new RuntimeException("Stub!"); }
public void setCameraDistance(float distance) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getRotation() { throw new RuntimeException("Stub!"); }
public void setRotation(float rotation) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getRotationY() { throw new RuntimeException("Stub!"); }
public void setRotationY(float rotationY) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getRotationX() { throw new RuntimeException("Stub!"); }
public void setRotationX(float rotationX) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getScaleX() { throw new RuntimeException("Stub!"); }
public void setScaleX(float scaleX) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getScaleY() { throw new RuntimeException("Stub!"); }
public void setScaleY(float scaleY) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getPivotX() { throw new RuntimeException("Stub!"); }
public void setPivotX(float pivotX) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getPivotY() { throw new RuntimeException("Stub!"); }
public void setPivotY(float pivotY) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getAlpha() { throw new RuntimeException("Stub!"); }
public boolean hasOverlappingRendering() { throw new RuntimeException("Stub!"); }
public void setAlpha(float alpha) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public final int getTop() { throw new RuntimeException("Stub!"); }
public final void setTop(int top) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public final int getBottom() { throw new RuntimeException("Stub!"); }
public boolean isDirty() { throw new RuntimeException("Stub!"); }
public final void setBottom(int bottom) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public final int getLeft() { throw new RuntimeException("Stub!"); }
public final void setLeft(int left) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public final int getRight() { throw new RuntimeException("Stub!"); }
public final void setRight(int right) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getX() { throw new RuntimeException("Stub!"); }
public void setX(float x) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getY() { throw new RuntimeException("Stub!"); }
public void setY(float y) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getTranslationX() { throw new RuntimeException("Stub!"); }
public void setTranslationX(float translationX) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public float getTranslationY() { throw new RuntimeException("Stub!"); }
public void setTranslationY(float translationY) { throw new RuntimeException("Stub!"); }
public void getHitRect(android.graphics.Rect outRect) { throw new RuntimeException("Stub!"); }
public void getFocusedRect(android.graphics.Rect r) { throw new RuntimeException("Stub!"); }
public boolean getGlobalVisibleRect(android.graphics.Rect r, android.graphics.Point globalOffset) { throw new RuntimeException("Stub!"); }
public final boolean getGlobalVisibleRect(android.graphics.Rect r) { throw new RuntimeException("Stub!"); }
public final boolean getLocalVisibleRect(android.graphics.Rect r) { throw new RuntimeException("Stub!"); }
public void offsetTopAndBottom(int offset) { throw new RuntimeException("Stub!"); }
public void offsetLeftAndRight(int offset) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(deepExport=true,prefix="layout_")
public android.view.ViewGroup.LayoutParams getLayoutParams() { throw new RuntimeException("Stub!"); }
public void setLayoutParams(android.view.ViewGroup.LayoutParams params) { throw new RuntimeException("Stub!"); }
public void scrollTo(int x, int y) { throw new RuntimeException("Stub!"); }
public void scrollBy(int x, int y) { throw new RuntimeException("Stub!"); }
protected boolean awakenScrollBars() { throw new RuntimeException("Stub!"); }
protected boolean awakenScrollBars(int startDelay) { throw new RuntimeException("Stub!"); }
protected boolean awakenScrollBars(int startDelay, boolean invalidate) { throw new RuntimeException("Stub!"); }
public void invalidate(android.graphics.Rect dirty) { throw new RuntimeException("Stub!"); }
public void invalidate(int l, int t, int r, int b) { throw new RuntimeException("Stub!"); }
public void invalidate() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public boolean isOpaque() { throw new RuntimeException("Stub!"); }
public android.os.Handler getHandler() { throw new RuntimeException("Stub!"); }
public boolean post(java.lang.Runnable action) { throw new RuntimeException("Stub!"); }
public boolean postDelayed(java.lang.Runnable action, long delayMillis) { throw new RuntimeException("Stub!"); }
public void postOnAnimation(java.lang.Runnable action) { throw new RuntimeException("Stub!"); }
public void postOnAnimationDelayed(java.lang.Runnable action, long delayMillis) { throw new RuntimeException("Stub!"); }
public boolean removeCallbacks(java.lang.Runnable action) { throw new RuntimeException("Stub!"); }
public void postInvalidate() { throw new RuntimeException("Stub!"); }
public void postInvalidate(int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); }
public void postInvalidateDelayed(long delayMilliseconds) { throw new RuntimeException("Stub!"); }
public void postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); }
public void postInvalidateOnAnimation() { throw new RuntimeException("Stub!"); }
public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); }
public void computeScroll() { throw new RuntimeException("Stub!"); }
public boolean isHorizontalFadingEdgeEnabled() { throw new RuntimeException("Stub!"); }
public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { throw new RuntimeException("Stub!"); }
public boolean isVerticalFadingEdgeEnabled() { throw new RuntimeException("Stub!"); }
public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { throw new RuntimeException("Stub!"); }
protected float getTopFadingEdgeStrength() { throw new RuntimeException("Stub!"); }
protected float getBottomFadingEdgeStrength() { throw new RuntimeException("Stub!"); }
protected float getLeftFadingEdgeStrength() { throw new RuntimeException("Stub!"); }
protected float getRightFadingEdgeStrength() { throw new RuntimeException("Stub!"); }
public boolean isHorizontalScrollBarEnabled() { throw new RuntimeException("Stub!"); }
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { throw new RuntimeException("Stub!"); }
public boolean isVerticalScrollBarEnabled() { throw new RuntimeException("Stub!"); }
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { throw new RuntimeException("Stub!"); }
public void setScrollbarFadingEnabled(boolean fadeScrollbars) { throw new RuntimeException("Stub!"); }
public boolean isScrollbarFadingEnabled() { throw new RuntimeException("Stub!"); }
public int getScrollBarDefaultDelayBeforeFade() { throw new RuntimeException("Stub!"); }
public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { throw new RuntimeException("Stub!"); }
public int getScrollBarFadeDuration() { throw new RuntimeException("Stub!"); }
public void setScrollBarFadeDuration(int scrollBarFadeDuration) { throw new RuntimeException("Stub!"); }
public int getScrollBarSize() { throw new RuntimeException("Stub!"); }
public void setScrollBarSize(int scrollBarSize) { throw new RuntimeException("Stub!"); }
public void setScrollBarStyle(int style) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(mapping={@android.view.ViewDebug.IntToString(from=0,to="INSIDE_OVERLAY"),@android.view.ViewDebug.IntToString(from=16777216,to="INSIDE_INSET"),@android.view.ViewDebug.IntToString(from=33554432,to="OUTSIDE_OVERLAY"),@android.view.ViewDebug.IntToString(from=50331648,to="OUTSIDE_INSET")})
public int getScrollBarStyle() { throw new RuntimeException("Stub!"); }
protected int computeHorizontalScrollRange() { throw new RuntimeException("Stub!"); }
protected int computeHorizontalScrollOffset() { throw new RuntimeException("Stub!"); }
protected int computeHorizontalScrollExtent() { throw new RuntimeException("Stub!"); }
protected int computeVerticalScrollRange() { throw new RuntimeException("Stub!"); }
protected int computeVerticalScrollOffset() { throw new RuntimeException("Stub!"); }
protected int computeVerticalScrollExtent() { throw new RuntimeException("Stub!"); }
public boolean canScrollHorizontally(int direction) { throw new RuntimeException("Stub!"); }
public boolean canScrollVertically(int direction) { throw new RuntimeException("Stub!"); }
protected final void onDrawScrollBars(android.graphics.Canvas canvas) { throw new RuntimeException("Stub!"); }
protected void onDraw(android.graphics.Canvas canvas) { throw new RuntimeException("Stub!"); }
protected void onAttachedToWindow() { throw new RuntimeException("Stub!"); }
public void onScreenStateChanged(int screenState) { throw new RuntimeException("Stub!"); }
protected void onDetachedFromWindow() { throw new RuntimeException("Stub!"); }
protected int getWindowAttachCount() { throw new RuntimeException("Stub!"); }
public android.os.IBinder getWindowToken() { throw new RuntimeException("Stub!"); }
public android.os.IBinder getApplicationWindowToken() { throw new RuntimeException("Stub!"); }
public void saveHierarchyState(android.util.SparseArray<android.os.Parcelable> container) { throw new RuntimeException("Stub!"); }
protected void dispatchSaveInstanceState(android.util.SparseArray<android.os.Parcelable> container) { throw new RuntimeException("Stub!"); }
protected android.os.Parcelable onSaveInstanceState() { throw new RuntimeException("Stub!"); }
public void restoreHierarchyState(android.util.SparseArray<android.os.Parcelable> container) { throw new RuntimeException("Stub!"); }
protected void dispatchRestoreInstanceState(android.util.SparseArray<android.os.Parcelable> container) { throw new RuntimeException("Stub!"); }
protected void onRestoreInstanceState(android.os.Parcelable state) { throw new RuntimeException("Stub!"); }
public long getDrawingTime() { throw new RuntimeException("Stub!"); }
public void setDuplicateParentStateEnabled(boolean enabled) { throw new RuntimeException("Stub!"); }
public boolean isDuplicateParentStateEnabled() { throw new RuntimeException("Stub!"); }
public void setLayerType(int layerType, android.graphics.Paint paint) { throw new RuntimeException("Stub!"); }
public int getLayerType() { throw new RuntimeException("Stub!"); }
public void buildLayer() { throw new RuntimeException("Stub!"); }
public void setDrawingCacheEnabled(boolean enabled) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public boolean isDrawingCacheEnabled() { throw new RuntimeException("Stub!"); }
public android.graphics.Bitmap getDrawingCache() { throw new RuntimeException("Stub!"); }
public android.graphics.Bitmap getDrawingCache(boolean autoScale) { throw new RuntimeException("Stub!"); }
public void destroyDrawingCache() { throw new RuntimeException("Stub!"); }
public void setDrawingCacheBackgroundColor(int color) { throw new RuntimeException("Stub!"); }
public int getDrawingCacheBackgroundColor() { throw new RuntimeException("Stub!"); }
public void buildDrawingCache() { throw new RuntimeException("Stub!"); }
public void buildDrawingCache(boolean autoScale) { throw new RuntimeException("Stub!"); }
public boolean isInEditMode() { throw new RuntimeException("Stub!"); }
protected boolean isPaddingOffsetRequired() { throw new RuntimeException("Stub!"); }
protected int getLeftPaddingOffset() { throw new RuntimeException("Stub!"); }
protected int getRightPaddingOffset() { throw new RuntimeException("Stub!"); }
protected int getTopPaddingOffset() { throw new RuntimeException("Stub!"); }
protected int getBottomPaddingOffset() { throw new RuntimeException("Stub!"); }
public boolean isHardwareAccelerated() { throw new RuntimeException("Stub!"); }
public void draw(android.graphics.Canvas canvas) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="drawing")
public int getSolidColor() { throw new RuntimeException("Stub!"); }
public boolean isLayoutRequested() { throw new RuntimeException("Stub!"); }
@java.lang.SuppressWarnings(value={})
public void layout(int l, int t, int r, int b) { throw new RuntimeException("Stub!"); }
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); }
protected void onFinishInflate() { throw new RuntimeException("Stub!"); }
public android.content.res.Resources getResources() { throw new RuntimeException("Stub!"); }
public void invalidateDrawable(android.graphics.drawable.Drawable drawable) { throw new RuntimeException("Stub!"); }
public void scheduleDrawable(android.graphics.drawable.Drawable who, java.lang.Runnable what, long when) { throw new RuntimeException("Stub!"); }
public void unscheduleDrawable(android.graphics.drawable.Drawable who, java.lang.Runnable what) { throw new RuntimeException("Stub!"); }
public void unscheduleDrawable(android.graphics.drawable.Drawable who) { throw new RuntimeException("Stub!"); }
protected boolean verifyDrawable(android.graphics.drawable.Drawable who) { throw new RuntimeException("Stub!"); }
protected void drawableStateChanged() { throw new RuntimeException("Stub!"); }
public void refreshDrawableState() { throw new RuntimeException("Stub!"); }
public final int[] getDrawableState() { throw new RuntimeException("Stub!"); }
protected int[] onCreateDrawableState(int extraSpace) { throw new RuntimeException("Stub!"); }
protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { throw new RuntimeException("Stub!"); }
public void jumpDrawablesToCurrentState() { throw new RuntimeException("Stub!"); }
public void setBackgroundColor(int color) { throw new RuntimeException("Stub!"); }
public void setBackgroundResource(int resid) { throw new RuntimeException("Stub!"); }
public void setBackground(android.graphics.drawable.Drawable background) { throw new RuntimeException("Stub!"); }
@java.lang.Deprecated()
public void setBackgroundDrawable(android.graphics.drawable.Drawable background) { throw new RuntimeException("Stub!"); }
public android.graphics.drawable.Drawable getBackground() { throw new RuntimeException("Stub!"); }
public void setPadding(int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); }
public int getPaddingTop() { throw new RuntimeException("Stub!"); }
public int getPaddingBottom() { throw new RuntimeException("Stub!"); }
public int getPaddingLeft() { throw new RuntimeException("Stub!"); }
public int getPaddingRight() { throw new RuntimeException("Stub!"); }
public void setSelected(boolean selected) { throw new RuntimeException("Stub!"); }
protected void dispatchSetSelected(boolean selected) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isSelected() { throw new RuntimeException("Stub!"); }
public void setActivated(boolean activated) { throw new RuntimeException("Stub!"); }
protected void dispatchSetActivated(boolean activated) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public boolean isActivated() { throw new RuntimeException("Stub!"); }
public android.view.ViewTreeObserver getViewTreeObserver() { throw new RuntimeException("Stub!"); }
public android.view.View getRootView() { throw new RuntimeException("Stub!"); }
public void getLocationOnScreen(int[] location) { throw new RuntimeException("Stub!"); }
public void getLocationInWindow(int[] location) { throw new RuntimeException("Stub!"); }
public final android.view.View findViewById(int id) { throw new RuntimeException("Stub!"); }
public final android.view.View findViewWithTag(java.lang.Object tag) { throw new RuntimeException("Stub!"); }
public void setId(int id) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.CapturedViewProperty()
public int getId() { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty()
public java.lang.Object getTag() { throw new RuntimeException("Stub!"); }
public void setTag(java.lang.Object tag) { throw new RuntimeException("Stub!"); }
public java.lang.Object getTag(int key) { throw new RuntimeException("Stub!"); }
public void setTag(int key, java.lang.Object tag) { throw new RuntimeException("Stub!"); }
@android.view.ViewDebug.ExportedProperty(category="layout")
public int getBaseline() { throw new RuntimeException("Stub!"); }
public void requestLayout() { throw new RuntimeException("Stub!"); }
public void forceLayout() { throw new RuntimeException("Stub!"); }
public final void measure(int widthMeasureSpec, int heightMeasureSpec) { throw new RuntimeException("Stub!"); }
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { throw new RuntimeException("Stub!"); }
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { throw new RuntimeException("Stub!"); }
public static int combineMeasuredStates(int curState, int newState) { throw new RuntimeException("Stub!"); }
public static int resolveSize(int size, int measureSpec) { throw new RuntimeException("Stub!"); }
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { throw new RuntimeException("Stub!"); }
public static int getDefaultSize(int size, int measureSpec) { throw new RuntimeException("Stub!"); }
protected int getSuggestedMinimumHeight() { throw new RuntimeException("Stub!"); }
protected int getSuggestedMinimumWidth() { throw new RuntimeException("Stub!"); }
public int getMinimumHeight() { throw new RuntimeException("Stub!"); }
public void setMinimumHeight(int minHeight) { throw new RuntimeException("Stub!"); }
public int getMinimumWidth() { throw new RuntimeException("Stub!"); }
public void setMinimumWidth(int minWidth) { throw new RuntimeException("Stub!"); }
public android.view.animation.Animation getAnimation() { throw new RuntimeException("Stub!"); }
public void startAnimation(android.view.animation.Animation animation) { throw new RuntimeException("Stub!"); }
public void clearAnimation() { throw new RuntimeException("Stub!"); }
public void setAnimation(android.view.animation.Animation animation) { throw new RuntimeException("Stub!"); }
protected void onAnimationStart() { throw new RuntimeException("Stub!"); }
protected void onAnimationEnd() { throw new RuntimeException("Stub!"); }
protected boolean onSetAlpha(int alpha) { throw new RuntimeException("Stub!"); }
public void playSoundEffect(int soundConstant) { throw new RuntimeException("Stub!"); }
public boolean performHapticFeedback(int feedbackConstant) { throw new RuntimeException("Stub!"); }
public boolean performHapticFeedback(int feedbackConstant, int flags) { throw new RuntimeException("Stub!"); }
public void setSystemUiVisibility(int visibility) { throw new RuntimeException("Stub!"); }
public int getSystemUiVisibility() { throw new RuntimeException("Stub!"); }
public int getWindowSystemUiVisibility() { throw new RuntimeException("Stub!"); }
public void onWindowSystemUiVisibilityChanged(int visible) { throw new RuntimeException("Stub!"); }
public void dispatchWindowSystemUiVisiblityChanged(int visible) { throw new RuntimeException("Stub!"); }
public void setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener l) { throw new RuntimeException("Stub!"); }
public void dispatchSystemUiVisibilityChanged(int visibility) { throw new RuntimeException("Stub!"); }
public final boolean startDrag(android.content.ClipData data, android.view.View.DragShadowBuilder shadowBuilder, java.lang.Object myLocalState, int flags) { throw new RuntimeException("Stub!"); }
public boolean onDragEvent(android.view.DragEvent event) { throw new RuntimeException("Stub!"); }
public boolean dispatchDragEvent(android.view.DragEvent event) { throw new RuntimeException("Stub!"); }
public static android.view.View inflate(android.content.Context context, int resource, android.view.ViewGroup root) { throw new RuntimeException("Stub!"); }
@java.lang.SuppressWarnings(value={})
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { throw new RuntimeException("Stub!"); }
protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { throw new RuntimeException("Stub!"); }
public int getOverScrollMode() { throw new RuntimeException("Stub!"); }
public void setOverScrollMode(int overScrollMode) { throw new RuntimeException("Stub!"); }
public android.view.ViewPropertyAnimator animate() { throw new RuntimeException("Stub!"); }
protected static final java.lang.String VIEW_LOG_TAG = "View";
public static final int NO_ID = -1;
public static final int VISIBLE = 0;
public static final int INVISIBLE = 4;
public static final int GONE = 8;
public static final int DRAWING_CACHE_QUALITY_LOW = 524288;
public static final int DRAWING_CACHE_QUALITY_HIGH = 1048576;
public static final int DRAWING_CACHE_QUALITY_AUTO = 0;
public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
public static final int SCROLLBARS_INSIDE_INSET = 16777216;
public static final int SCROLLBARS_OUTSIDE_OVERLAY = 33554432;
public static final int SCROLLBARS_OUTSIDE_INSET = 50331648;
public static final int KEEP_SCREEN_ON = 67108864;
public static final int SOUND_EFFECTS_ENABLED = 134217728;
public static final int HAPTIC_FEEDBACK_ENABLED = 268435456;
public static final int FOCUSABLES_ALL = 0;
public static final int FOCUSABLES_TOUCH_MODE = 1;
public static final int FOCUS_BACKWARD = 1;
public static final int FOCUS_FORWARD = 2;
public static final int FOCUS_LEFT = 17;
public static final int FOCUS_UP = 33;
public static final int FOCUS_RIGHT = 66;
public static final int FOCUS_DOWN = 130;
public static final int MEASURED_SIZE_MASK = 16777215;
public static final int MEASURED_STATE_MASK = -16777216;
public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
public static final int MEASURED_STATE_TOO_SMALL = 16777216;
protected static final int[] EMPTY_STATE_SET = null;
protected static final int[] ENABLED_STATE_SET = null;
protected static final int[] FOCUSED_STATE_SET = null;
protected static final int[] SELECTED_STATE_SET = null;
protected static final int[] WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] ENABLED_FOCUSED_STATE_SET = null;
protected static final int[] ENABLED_SELECTED_STATE_SET = null;
protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] FOCUSED_SELECTED_STATE_SET = null;
protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET = null;
protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_SELECTED_STATE_SET = null;
protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET = null;
protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = null;
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = null;
public static final int TEXT_ALIGNMENT_INHERIT = 0;
public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = 131072;
public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0;
public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 1;
public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 2;
public static final int OVER_SCROLL_ALWAYS = 0;
public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
public static final int OVER_SCROLL_NEVER = 2;
public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 1;
public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2;
public static final int SYSTEM_UI_FLAG_FULLSCREEN = 4;
public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 256;
public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512;
public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024;
@Deprecated
public static final int STATUS_BAR_HIDDEN = 1;
@Deprecated
public static final int STATUS_BAR_VISIBLE = 0;
public static final int SYSTEM_UI_LAYOUT_FLAGS = 1536;
public static final int FIND_VIEWS_WITH_TEXT = 1;
public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 2;
public static final int SCREEN_STATE_OFF = 0;
public static final int SCREEN_STATE_ON = 1;
public static final int SCROLLBAR_POSITION_DEFAULT = 0;
public static final int SCROLLBAR_POSITION_LEFT = 1;
public static final int SCROLLBAR_POSITION_RIGHT = 2;
public static final int LAYER_TYPE_NONE = 0;
public static final int LAYER_TYPE_SOFTWARE = 1;
public static final int LAYER_TYPE_HARDWARE = 2;
public static final android.util.Property<android.view.View, java.lang.Float> ALPHA;
public static final android.util.Property<android.view.View, java.lang.Float> TRANSLATION_X;
public static final android.util.Property<android.view.View, java.lang.Float> TRANSLATION_Y;
public static final android.util.Property<android.view.View, java.lang.Float> X;
public static final android.util.Property<android.view.View, java.lang.Float> Y;
public static final android.util.Property<android.view.View, java.lang.Float> ROTATION;
public static final android.util.Property<android.view.View, java.lang.Float> ROTATION_X;
public static final android.util.Property<android.view.View, java.lang.Float> ROTATION_Y;
public static final android.util.Property<android.view.View, java.lang.Float> SCALE_X;
public static final android.util.Property<android.view.View, java.lang.Float> SCALE_Y;
static { ALPHA = null; TRANSLATION_X = null; TRANSLATION_Y = null; X = null; Y = null; ROTATION = null; ROTATION_X = null; ROTATION_Y = null; SCALE_X = null; SCALE_Y = null; }
}
|
package resources.encodables;
import network.packets.Packet;
import resources.objects.waypoint.WaypointObject;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class OutOfBandPackage implements Encodable, Serializable {
private static final long serialVersionUID = 1L;
private List<OutOfBandData> packages;
private transient List<byte[]> data;
private transient int dataSize;
public OutOfBandPackage() {
packages = new ArrayList<>(5);
}
public OutOfBandPackage(OutOfBandData... outOfBandData) {
this();
Collections.addAll(packages, outOfBandData);
}
public List<OutOfBandData> getPackages() {
return packages;
}
@Override
public byte[] encode() {
if (packages.size() == 0)
return new byte[4];
if (data == null) {
data = new LinkedList<>();
for (OutOfBandData outOfBandData : packages) {
byte[] bytes = packOutOfBandData(outOfBandData);
dataSize += bytes.length;
data.add(bytes);
}
}
ByteBuffer bb = ByteBuffer.allocate(4 + dataSize).order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(dataSize / 2);
data.forEach(bb::put);
return bb.array();
}
@Override
public void decode(ByteBuffer data) {
int size = data.getInt() * 2;
int padding;
int start;
for (int read = 0; read < size; read++) {
start = data.position();
padding = data.getShort();
unpackOutOfBandData(data, Type.valueOf(data.get()));
data.position(data.position() + padding);
read += data.position() - start;
}
}
private void unpackOutOfBandData(ByteBuffer data, Type type) {
// Position doesn't seem to be reflective of it's spot in the package list, not sure if this can be automated
// as the client will send -3 for multiple waypoints in a mail, so could be static for each OutOfBandData
// If that's the case, then we can move the position variable to the Type enum instead of a method return statement
/* int position =*/ data.getInt();
switch(type) {
case PROSE_PACKAGE:
ProsePackage prose = Packet.getEncodable(data, ProsePackage.class);
packages.add(prose);
break;
case WAYPOINT:
WaypointObject waypoint = new WaypointObject(-1);
waypoint.decode(data);
packages.add(waypoint);
break;
case STRING_ID:
StringId stringId = Packet.getEncodable(data, StringId.class);
packages.add(stringId);
break;
default:
System.err.println("Tried to decode an unsupported OutOfBandData Type: " + type);
break;
}
}
private byte[] packOutOfBandData(OutOfBandData data) {
byte[] base = data.encode();
// Type and position is included in the padding size
int paddingSize = (base.length + 5) % 2;
ByteBuffer bb = ByteBuffer.allocate(7 + paddingSize + base.length);
Packet.addShort(bb, paddingSize); // Number of bytes for decoding to skip over when reading
Packet.addByte(bb, data.getOobType().getType());
Packet.addInt(bb, data.getOobPosition());
Packet.addData(bb, base);
for (int i = 0; i < paddingSize; i++) {
Packet.addByte(bb, 0);
}
return bb.array();
}
@Override
public String toString() {
return "OutOfBandPackage[packages=" + packages + "]";
}
public enum Type {
UNDEFINED(Byte.MIN_VALUE),
OBJECT(0),
PROSE_PACKAGE(1),
UNKNOWN(2),
AUCTION_TOKEN(3),
WAYPOINT(4),
STRING_ID(5),
STRING(6),
UNKNOWN_2(7);
byte type;
Type(int type) {
this.type = (byte) type;
}
public byte getType() {
return type;
}
public static Type valueOf(byte typeByte) {
for (Type type : Type.values()) {
if (type.getType() == typeByte)
return type;
}
return Type.UNDEFINED;
}
}
}
|
package ro.undef.patois;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
/**
* Activity for editting the list of languages.
*/
public class EditLanguagesActivity extends Activity implements View.OnClickListener {
private final static String TAG = "EditLanguagesActivity";
private LinearLayout mLayout;
private LayoutInflater mInflater;
private PatoisDatabase mDb;
private ArrayList<LanguageEntry> mLanguages;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInflater = getLayoutInflater();
setContentView(R.layout.edit_languages);
mLayout = (LinearLayout) findViewById(R.id.list);
mDb = new PatoisDatabase(this);
mDb.open();
if (savedInstanceState != null) {
loadLanguagesFromBundle(savedInstanceState);
} else {
loadLanguagesFromDatabase(mDb);
}
buildViews();
}
@Override
protected void onDestroy() {
super.onDestroy();
mDb.close();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
for (LanguageEntry language : mLanguages) {
language.syncFromView();
}
outState.putParcelableArrayList("languages", mLanguages);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
doSaveAction();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_language: {
addNewLanguage();
break;
}
case R.id.done: {
doSaveAction();
break;
}
case R.id.revert: {
doRevertAction();
break;
}
}
}
private void loadLanguagesFromDatabase(PatoisDatabase db) {
ArrayList<LanguageEntry> languages = new ArrayList<LanguageEntry>();
Cursor cursor = db.getLanguages();
while (cursor.moveToNext()) {
languages.add(new LanguageEntry(cursor));
}
mLanguages = languages;
}
private void loadLanguagesFromBundle(Bundle savedInstanceState) {
mLanguages = savedInstanceState.getParcelableArrayList("languages");
}
private void addNewLanguage() {
LanguageEntry language = new LanguageEntry();
mLanguages.add(language);
mLayout.addView(language.buildView(mInflater, mLayout));
}
private void buildViews() {
LayoutInflater inflater = mInflater;
LinearLayout layout = mLayout;
layout.removeAllViews();
for (LanguageEntry language : mLanguages) {
if (!language.isDeleted())
layout.addView(language.buildView(inflater, layout));
}
View view = findViewById(R.id.add_language);
view.setOnClickListener(this);
view = findViewById(R.id.done);
view.setOnClickListener(this);
view = findViewById(R.id.revert);
view.setOnClickListener(this);
}
private void doSaveAction() {
for (LanguageEntry language : mLanguages) {
language.saveToDatabase(mDb);
}
finish();
}
private void doRevertAction() {
finish();
}
private static class LanguageEntry implements Parcelable, View.OnClickListener {
// These fields are saved in the parcel.
/**
* ID number of the the language row in the database.
*/
private long mId;
/**
* Short code for the language (e.g., "EN" for "English").
*/
private String mCode;
/**
* Language name (e.g., "English").
*/
private String mName;
/**
* True if the data in the LanguageEntry is different from what's
* stored in the database.
*/
private boolean mModified;
/**
* True if the user pressed the 'delete' button on this LanguageEntry.
*/
private boolean mDeleted;
public boolean isDeleted() {
return mDeleted;
}
/**
* Position of the beginning of the selection in the "code" EditText
* (-1 if there is no selection).
*/
private int mCodeSelectionStart;
/**
* Position of the end of the selection in the "code" EditText
* (-1 if there is no selection).
*/
private int mCodeSelectionEnd;
/**
* Position of the beginning of the selection in the "name" EditText
* (-1 if there is no selection).
*/
private int mNameSelectionStart;
/**
* Position of the end of the selection in the "name" EditText
* (-1 if there is no selection).
*/
private int mNameSelectionEnd;
// These fields are NOT saved in the parcel.
private View mView;
private EditText mCodeEditText;
private EditText mNameEditText;
public LanguageEntry(long id, String code, String name) {
mId = id;
mCode = code;
mName = name;
mModified = false;
mDeleted = false;
mCodeSelectionStart = -1;
mCodeSelectionStart = -1;
mNameSelectionEnd = -1;
mNameSelectionEnd = -1;
}
public LanguageEntry() {
this(-1, "", "");
}
public LanguageEntry(Cursor cursor) {
this(cursor.getInt(PatoisDatabase.LANGUAGE_ID_COLUMN),
cursor.getString(PatoisDatabase.LANGUAGE_CODE_COLUMN),
cursor.getString(PatoisDatabase.LANGUAGE_NAME_COLUMN));
}
public View buildView(LayoutInflater inflater, LinearLayout parent) {
View view = inflater.inflate(R.layout.edit_language_entry, parent, false);
mView = view;
mCodeEditText = (EditText) view.findViewById(R.id.language_code);
mNameEditText = (EditText) view.findViewById(R.id.language_name);
mCodeEditText.setText(mCode);
mNameEditText.setText(mName);
if (mCodeSelectionStart != -1 && mCodeSelectionEnd != -1) {
mCodeEditText.requestFocus();
mCodeEditText.setSelection(mCodeSelectionStart, mCodeSelectionEnd);
}
if (mNameSelectionStart != -1 && mNameSelectionEnd != -1) {
mNameEditText.requestFocus();
mNameEditText.setSelection(mNameSelectionStart, mNameSelectionEnd);
}
View deleteButton = view.findViewById(R.id.delete_language);
deleteButton.setOnClickListener(this);
return view;
}
public void syncFromView() {
String new_code = mCodeEditText.getText().toString();
String new_name = mNameEditText.getText().toString();
if (new_code != mCode || new_name != mName)
mModified = true;
mCode = new_code;
mName = new_name;
if (mCodeEditText.hasFocus()) {
mCodeSelectionStart = mCodeEditText.getSelectionStart();
mCodeSelectionEnd = mCodeEditText.getSelectionEnd();
} else {
mCodeSelectionStart = -1;
mCodeSelectionEnd = -1;
}
if (mNameEditText.hasFocus()) {
mNameSelectionStart = mNameEditText.getSelectionStart();
mNameSelectionEnd = mNameEditText.getSelectionEnd();
} else {
mNameSelectionStart = -1;
mNameSelectionEnd = -1;
}
}
private void markAsDeleted() {
// TODO: Count the number of words in this language, and if not
// zero, ask the user to confirm the deletion.
LinearLayout layout = (LinearLayout) mView.getParent();
layout.removeView(mView);
mDeleted = true;
}
public void saveToDatabase(PatoisDatabase db) {
syncFromView();
if (mId == -1 && !mDeleted) {
mId = db.insertLanguage(mCode, mName);
} else if (mModified && !mDeleted) {
db.updateLanguage(mId, mCode, mName);
} else if (mDeleted) {
db.deleteLanguage(mId);
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete_language: {
markAsDeleted();
break;
}
}
}
// The Parcelable interface implementation.
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeLong(mId);
out.writeString(mCode);
out.writeString(mName);
out.writeInt(mModified ? 1 : 0);
out.writeInt(mDeleted ? 1 : 0);
out.writeInt(mCodeSelectionStart);
out.writeInt(mCodeSelectionEnd);
out.writeInt(mNameSelectionStart);
out.writeInt(mNameSelectionEnd);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public LanguageEntry createFromParcel(Parcel in) {
LanguageEntry language = new LanguageEntry(in.readLong(),
in.readString(),
in.readString());
language.mModified = in.readInt() == 1;
language.mDeleted = in.readInt() == 1;
language.mCodeSelectionStart = in.readInt();
language.mCodeSelectionEnd = in.readInt();
language.mNameSelectionStart = in.readInt();
language.mNameSelectionEnd = in.readInt();
return language;
}
public LanguageEntry[] newArray(int size) {
return new LanguageEntry[size];
}
};
}
}
|
package org.jasig.portal.services;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import org.jasig.portal.AuthorizationException;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.UserIdentityStoreFactory;
import org.jasig.portal.security.IAdditionalDescriptor;
import org.jasig.portal.security.IOpaqueCredentials;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.IPrincipal;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.security.PortalSecurityException;
/**
* Attempts to authenticate a user and retrieve attributes
* associated with the user.
* @author Ken Weiner, kweiner@interactivebusiness.com
* @author Don Fracapane (df7@columbia.edu)
* Added properties in the security properties file that hold the tokens used to
* represent the principal and credential for each security context. This version
* differs in the way the principal and credentials are set (all contexts are set
* up front after evaluating the tokens). See setContextParameters() also.
* @version $Revision$
* Changes put in to allow credentials and principals to be defined and held by each
* context.
*/
public class Authentication {
protected org.jasig.portal.security.IPerson m_Person = null;
protected ISecurityContext ic = null;
/**
* Attempts to authenticate a given IPerson based on a set of principals and credentials
* @param principals
* @param credentials
* @param person
* @exception PortalSecurityException
*/
public void authenticate (HashMap principals, HashMap credentials, IPerson person) throws PortalSecurityException {
// Retrieve the security context for the user
ISecurityContext securityContext = person.getSecurityContext();
Enumeration subCtxNames = securityContext.getSubContextNames();
// NOTE: The LoginServlet looks in the security.properties file to
// determine what tokens to look for that represent the principals and
// credentials for each context. It then retrieves the values from the request
// and stores the values in the principals and credentials HashMaps that are
// passed to the Authentication service.
// Set the principals and credentials for the root context first.
setContextParameters (principals, credentials, "root", securityContext, person);
// load principals and credentials for the subContexts
while (subCtxNames.hasMoreElements()) {
String subCtxName = (String)subCtxNames.nextElement();
// root context is handled above
if (!subCtxName.equals("root")){
// strip off "root." part of name
String subCtxNameWithoutPrefix = (subCtxName.startsWith("root.") ? subCtxName.substring(5) : subCtxName);
ISecurityContext sc = securityContext.getSubContext(subCtxNameWithoutPrefix);
setContextParameters (principals, credentials, subCtxName, sc, person);
}
}
// Attempt to authenticate the user
securityContext.authenticate();
// Check to see if the user was authenticated
if (securityContext.isAuthenticated()) {
// Add the authenticated username to the person object
// the login name may have been provided or reset by the security provider
// so this needs to be done after authentication.
person.setAttribute(IPerson.USERNAME, securityContext.getPrincipal().getUID());
// Retrieve the additional descriptor from the security context
IAdditionalDescriptor addInfo = person.getSecurityContext().getAdditionalDescriptor();
// Process the additional descriptor if one was created
if (addInfo != null) {
// Replace the passed in IPerson with the additional descriptor if the
// NOTE: This is not the preferred method, creation of IPerson objects should be
// handled by the PersonManager.
if (addInfo instanceof IPerson) {
IPerson newPerson = (IPerson)addInfo;
person.setFullName(newPerson.getFullName());
for (Enumeration e = newPerson.getAttributeNames(); e.hasMoreElements();) {
String attributeName = (String)e.nextElement();
person.setAttribute(attributeName, newPerson.getAttribute(attributeName));
}
}
// If the additional descriptor is a map then we can
// simply copy all of these additional attributes into the IPerson
else if (addInfo instanceof Map) {
// Cast the additional descriptor as a Map
Map additionalAttributes = (Map)addInfo;
// Copy each additional attribute into the person object
for (Iterator keys = additionalAttributes.keySet().iterator(); keys.hasNext();) {
// Get a key
String key = (String)keys.next();
// Set the attribute
person.setAttribute(key, additionalAttributes.get(key));
}
}
else {
LogService.log(LogService.WARN, "Authentication Service recieved unknown additional descriptor");
}
}
// Populate the person object using the PersonDirectory if applicable
if (PropertiesManager.getPropertyAsBoolean("org.jasig.portal.services.Authentication.usePersonDirectory")) {
// Retrieve all of the attributes associated with the person logging in
Hashtable attribs = (new PersonDirectory()).getUserDirectoryInformation((String)person.getAttribute(IPerson.USERNAME));
// Add each of the attributes to the IPerson
Enumeration en = attribs.keys();
while (en.hasMoreElements()) {
String key = (String)en.nextElement();
// String value = (String)attribs.get(key);
// person.setAttribute(key, value);
person.setAttribute(key, attribs.get(key));
}
}
// Make sure the the user's fullname is set
if (person.getFullName() == null) {
// Use portal display name if one exists
if (person.getAttribute("portalDisplayName") != null) {
person.setFullName((String)person.getAttribute("portalDisplayName"));
}
// If not try the eduPerson displyName
else if (person.getAttribute("displayName") != null) {
person.setFullName((String)person.getAttribute("displayName"));
}
// If still no FullName use an unrecognized string
if (person.getFullName() == null) {
person.setFullName("Unrecognized person: " + person.getAttribute(IPerson.USERNAME));
}
}
// Find the uPortal userid for this user or flunk authentication if not found
// The template username should actually be derived from directory information.
// The reference implemenatation sets the uPortalTemplateUserName to the default in
// the portal.properties file.
// A more likely template would be staff or faculty or undergraduate.
boolean autocreate = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.services.Authentication.autoCreateUsers");
// If we are going to be auto creating accounts then we must find the default template to use
if (autocreate && person.getAttribute("uPortalTemplateUserName") == null) {
String defaultTemplateUserName = PropertiesManager.getProperty("org.jasig.portal.services.Authentication.defaultTemplateUserName");
person.setAttribute("uPortalTemplateUserName", defaultTemplateUserName);
}
try {
// Attempt to retrieve the UID
int newUID = UserIdentityStoreFactory.getUserIdentityStoreImpl().getPortalUID(person,
autocreate);
person.setID(newUID);
} catch (AuthorizationException ae) {
LogService.log(LogService.ERROR, ae);
throw new PortalSecurityException("Authentication Service: Exception retrieving UID");
}
// Record the successful authentication
StatsRecorder.recordLogin(person);
}
}
/**
* Returns an IPerson object that can be used to hold site-specific attributes
* about the logged on user. This information is established during
* authentication.
* @return An object that implements the
* <code>org.jasig.portal.security.IPerson</code> interface.
*/
public IPerson getPerson () {
return m_Person;
}
/**
* Returns an ISecurityContext object that can be used
* later. This object is passed as part of the IChannel Interface.
* The security context may be used to gain authorized access to
* services.
* @return An object that implements the
* <code>org.jasig.portal.security.ISecurityContext</code> interface.
*/
public ISecurityContext getSecurityContext () {
return ic;
}
/**
* Get the principal and credential for a specific context and store them in
* the context.
* @param principals
* @param credentials
* @param ctxName
* @param securityContext
* @param person
*/
public void setContextParameters (HashMap principals, HashMap credentials, String ctxName,
ISecurityContext securityContext, IPerson person) {
String username = (String)principals.get(ctxName);
String credential = (String)credentials.get(ctxName);
// If username or credential are null, this indicates that the token was not
// set in security properties. We will then use the value for root.
username = (username != null ? username : (String)principals.get("root"));
credential = (credential != null ? credential : (String)credentials.get("root"));
LogService.log(LogService.DEBUG, "Authentication::setContextParameters() username: " + username);
// Retrieve and populate an instance of the principal object
IPrincipal principalInstance = securityContext.getPrincipalInstance();
if (username != null && !username.equals("")) {
principalInstance.setUID(username);
}
// Retrieve and populate an instance of the credentials object
IOpaqueCredentials credentialsInstance = securityContext.getOpaqueCredentialsInstance();
credentialsInstance.setCredentials(credential);
}
}
|
package jwtc.android.chess;
import jwtc.android.chess.puzzle.practice;
import jwtc.android.chess.puzzle.puzzle;
import jwtc.android.chess.tools.pgntool;
import jwtc.android.chess.ics.*;
import jwtc.chess.JNI;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import android.support.v7.app.MediaRouteActionProvider;
import android.support.v7.media.MediaRouteSelector;
import android.support.v7.media.MediaRouter;
import android.support.v7.media.MediaRouter.RouteInfo;
import com.google.android.gms.cast.ApplicationMetadata;
import com.google.android.gms.cast.Cast;
import com.google.android.gms.cast.CastDevice;
import com.google.android.gms.cast.CastMediaControlIntent;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
public class start extends AppCompatActivity {
//private ListView _lvStart;
public static final String TAG = "start";
private MediaRouter mMediaRouter;
private MediaRouteSelector mMediaRouteSelector;
private MediaRouter.Callback mMediaRouterCallback;
private CastDevice mSelectedDevice;
private GoogleApiClient mApiClient;
private Cast.Listener mCastListener;
private ConnectionCallbacks mConnectionCallbacks;
private ConnectionFailedListener mConnectionFailedListener;
private HelloWorldChannel mHelloWorldChannel;
private boolean mApplicationStarted;
private boolean mWaitingForReconnect;
private String mSessionId;
private ListView _list;
private JNI _jni;
private Timer _timer;
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences getData = getSharedPreferences("ChessPlayer", Context.MODE_PRIVATE);
String myLanguage = getData.getString("localelanguage", "");
Locale current = getResources().getConfiguration().locale;
String language = current.getLanguage();
if(myLanguage.equals("")){ // localelanguage not used yet? then use device default locale
myLanguage = language;
}
Locale locale = new Locale(myLanguage); // myLanguage is current language
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
setContentView(R.layout.start);
if (getIntent().getBooleanExtra("RESTART", false)) {
finish();
Intent intent = new Intent(this, start.class);
startActivity(intent);
}
_jni = new JNI();
_timer = new Timer(true);
_timer.schedule(new TimerTask() {
@Override
public void run() {
sendMessage(_jni.toFEN());
}
}, 1000, 1000);
_list = (ListView)findViewById(R.id.ListStart);
_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = parent.getItemAtPosition(position).toString();
try {
Intent i = new Intent();
Log.i("start", s);
if (s.equals(getString(R.string.start_play))) {
i.setClass(start.this, main.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
} else if (s.equals(getString(R.string.start_practice))) {
i.setClass(start.this, practice.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
} else if (s.equals(getString(R.string.start_puzzles))) {
i.setClass(start.this, puzzle.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
} else if (s.equals(getString(R.string.start_about))) {
i.setClass(start.this, HtmlActivity.class);
i.putExtra(HtmlActivity.HELP_MODE, "about");
startActivity(i);
} else if (s.equals(getString(R.string.start_ics))) {
i.setClass(start.this, ICSClient.class);
startActivity(i);
} else if (s.equals(getString(R.string.start_pgn))) {
i.setClass(start.this, pgntool.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
} else if (s.equals(getString(R.string.start_donate))) {
i.setClass(start.this, Donate.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
} else if (s.equals(getString(R.string.start_globalpreferences))) {
i.setClass(start.this, ChessPreferences.class);
startActivityForResult(i, 0);
} else if (s.equals(getString(R.string.menu_help))) {
i.setClass(start.this, HtmlActivity.class);
i.putExtra(HtmlActivity.HELP_MODE, "help");
startActivity(i);
}
} catch (Exception ex) {
Toast t = Toast.makeText(start.this, R.string.toast_could_not_start_activity, Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM, 0, 0);
t.show();
}
}
});
// Configure Cast device discovery
mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector = new MediaRouteSelector.Builder()
.addControlCategory(CastMediaControlIntent.categoryForCast("05EB93C6")).build();
mMediaRouterCallback = new MyMediaRouterCallback();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 1){
Log.i(TAG, "finish and restart");
Intent intent = new Intent(this, start.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("RESTART", true);
startActivity(intent);
}
}
@Override
protected void onStart() {
super.onStart();
// Start media router discovery
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
@Override
protected void onStop() {
// End media router discovery
mMediaRouter.removeCallback(mMediaRouterCallback);
super.onStop();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
teardown(true);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.start_topmenu, menu);
MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
MediaRouteActionProvider mediaRouteActionProvider
= (MediaRouteActionProvider) MenuItemCompat
.getActionProvider(mediaRouteMenuItem);
// Set the MediaRouteActionProvider selector for device discovery.
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
return true;
}
/**
* Send a text message to the receiver
*/
private void sendMessage(String message) {
if (mApiClient != null && mHelloWorldChannel != null) {
try {
//Log.i(TAG, "Try to send " + message);
Cast.CastApi.sendMessage(mApiClient,
mHelloWorldChannel.getNamespace(), message).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status result) {
if (!result.isSuccess()) {
Log.e(TAG, "Sending message failed");
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception while sending message", e);
}
}
}
/**
* Callback for MediaRouter events
*/
private class MyMediaRouterCallback extends MediaRouter.Callback {
@Override
public void onRouteSelected(MediaRouter router, RouteInfo info) {
Log.d(TAG, "onRouteSelected");
// Handle the user route selection.
mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
launchReceiver();
}
@Override
public void onRouteUnselected(MediaRouter router, RouteInfo info) {
Log.d(TAG, "onRouteUnselected: info=" + info);
teardown(false);
mSelectedDevice = null;
}
}
/**
* Google Play services callbacks
*/
private class ConnectionCallbacks implements
GoogleApiClient.ConnectionCallbacks {
@Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected");
if (mApiClient == null) {
// We got disconnected while this runnable was pending
// execution.
return;
}
try {
if (mWaitingForReconnect) {
mWaitingForReconnect = false;
// Check if the receiver app is still running
if ((connectionHint != null)
&& connectionHint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) {
Log.d(TAG, "App is no longer running");
teardown(true);
} else {
// Re-create the custom message channel
try {
Cast.CastApi.setMessageReceivedCallbacks(
mApiClient,
mHelloWorldChannel.getNamespace(),
mHelloWorldChannel);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
}
} else {
// Launch the receiver app
Cast.CastApi.launchApplication(mApiClient, "05EB93C6", false)
.setResultCallback(
new ResultCallback<Cast.ApplicationConnectionResult>() {
@Override
public void onResult(
Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
Log.d(TAG,
"ApplicationConnectionResultCallback.onResult:"
+ status.getStatusCode());
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result
.getApplicationMetadata();
mSessionId = result.getSessionId();
String applicationStatus = result
.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
Log.d(TAG, "application name: "
+ applicationMetadata.getName()
+ ", status: " + applicationStatus
+ ", sessionId: " + mSessionId
+ ", wasLaunched: " + wasLaunched);
mApplicationStarted = true;
// Create the custom message
// channel
mHelloWorldChannel = new HelloWorldChannel();
try {
Cast.CastApi.setMessageReceivedCallbacks(
mApiClient,
mHelloWorldChannel.getNamespace(),
mHelloWorldChannel);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel",
e);
}
} else {
Log.e(TAG, "application could not launch");
teardown(true);
}
}
});
}
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
@Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended");
mWaitingForReconnect = true;
}
}
/**
* Google Play services callbacks
*/
private class ConnectionFailedListener implements
GoogleApiClient.OnConnectionFailedListener {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.e(TAG, "onConnectionFailed ");
teardown(false);
}
}
/**
* Start the receiver app
*/
private void launchReceiver() {
try {
mCastListener = new Cast.Listener() {
@Override
public void onApplicationDisconnected(int errorCode) {
Log.d(TAG, "application has stopped");
teardown(true);
}
};
// Connect to Google Play services
mConnectionCallbacks = new ConnectionCallbacks();
mConnectionFailedListener = new ConnectionFailedListener();
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
.builder(mSelectedDevice, mCastListener);
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mConnectionFailedListener)
.build();
mApiClient.connect();
} catch (Exception e) {
Log.e(TAG, "Failed launchReceiver", e);
}
}
/**
* Custom message channel
*/
class HelloWorldChannel implements Cast.MessageReceivedCallback {
/**
* @return custom namespace
*/
public String getNamespace() {
return "urn:x-cast:nl.jwtc.chess.channel";
}
/*
* Receive message from the receiver app
*/
@Override
public void onMessageReceived(CastDevice castDevice, String namespace,
String message) {
//Log.d(TAG, "onMessageReceived: " + message);
}
}
/**
* Tear down the connection to the receiver
*/
private void teardown(boolean selectDefaultRoute) {
Log.d(TAG, "teardown");
if (mApiClient != null) {
if (mApplicationStarted) {
if (mApiClient.isConnected() || mApiClient.isConnecting()) {
try {
Cast.CastApi.stopApplication(mApiClient, mSessionId);
if (mHelloWorldChannel != null) {
Cast.CastApi.removeMessageReceivedCallbacks(
mApiClient,
mHelloWorldChannel.getNamespace());
mHelloWorldChannel = null;
}
} catch (IOException e) {
Log.e(TAG, "Exception while removing channel", e);
}
mApiClient.disconnect();
}
mApplicationStarted = false;
}
mApiClient = null;
}
if (selectDefaultRoute) {
mMediaRouter.selectRoute(mMediaRouter.getDefaultRoute());
}
mSelectedDevice = null;
mWaitingForReconnect = false;
mSessionId = null;
}
}
|
package kittentrate;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
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.view.MenuItem;
import com.crashlytics.android.Crashlytics;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.fabric.sdk.android.Fabric;
import kittentrate.game.GameFragment;
import kittentrate.navigation.Navigator;
import kittentrate.navigation.Screen;
import kittentrate.score.ScoresFragment;
import manulorenzo.me.kittentrate.BuildConfig;
import manulorenzo.me.kittentrate.R;
public class MainActivity extends AppCompatActivity implements Navigator {
@BindView(R.id.drawer_layout)
DrawerLayout drawerLayout;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.navigation_view)
NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setStrictMode();
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
// Set a Toolbar to replace the ActionBar.
setSupportActionBar(toolbar);
// Find our drawer view
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
drawerLayout.addDrawerListener(drawerToggle);
setupDrawerContent(navigationView);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_content);
if (fragment == null) {
loadFragment(GameFragment.newInstance(), navigationView.getMenu().getItem(0));
}
}
public void loadFragment(Fragment fragment, MenuItem menuItem) {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_content, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
}
// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE 1: Make sure to override the method with only a single `Bundle` argument
// Note 2: Make sure you implement the correct `onPostCreate(Bundle savedInstanceState)` method.
// There are 2 signatures and only `onPostCreate(Bundle state)` shows the hamburger icon.
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
menuItem -> {
selectDrawerItem(menuItem);
return true;
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.game_menu_item:
fragmentClass = GameFragment.class;
break;
case R.id.scores_menu_item:
fragmentClass = ScoresFragment.class;
break;
default:
fragmentClass = GameFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
loadFragment(fragment, menuItem);
// Close the navigation drawer
drawerLayout.closeDrawers();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void navigateTo(Screen screen) {
switch (screen) {
case GAME:
loadFragment(GameFragment.newInstance(), navigationView.getMenu().getItem(0));
break;
case SCORES:
loadFragment(ScoresFragment.newInstance(), navigationView.getMenu().getItem(0));
break;
default:
break;
}
}
private void setStrictMode() {
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
}
}
}
|
package com.kuxhausen.huemore;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.PriorityQueue;
import java.util.Stack;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.Pair;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.kuxhausen.huemore.automation.FireReceiver;
import com.kuxhausen.huemore.network.BulbAttributesSuccessListener.OnBulbAttributesReturnedListener;
import com.kuxhausen.huemore.network.ConnectionMonitor;
import com.kuxhausen.huemore.network.NetworkMethods;
import com.kuxhausen.huemore.network.OnConnectionStatusChangedListener;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments;
import com.kuxhausen.huemore.persistence.FutureEncodingException;
import com.kuxhausen.huemore.persistence.HueUrlEncoder;
import com.kuxhausen.huemore.persistence.InvalidEncodingException;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.QueueEvent;
import com.kuxhausen.huemore.state.api.BulbAttributes;
import com.kuxhausen.huemore.state.api.BulbState;
import com.kuxhausen.huemore.timing.AlarmReciever;
public class MoodExecuterService extends Service implements ConnectionMonitor, OnBulbAttributesReturnedListener{
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MoodExecuterService getService() {
// Return this instance of LocalService so clients can call public
// methods
return MoodExecuterService.this;
}
}
MoodExecuterService me = this;
private RequestQueue volleyRQ;
int notificationId = 1337;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
private static CountDownTimer countDownTimer;
Long moodLoopIterationEndNanoTime = 0l;
WakeLock wakelock;
private boolean hasHubConnection = false;
private final static int MAX_STOP_SELF_COUNDOWN = 45;
private static int countDownToStopSelf = MAX_STOP_SELF_COUNDOWN;
public ArrayList<OnConnectionStatusChangedListener> connectionListeners = new ArrayList<OnConnectionStatusChangedListener>();
public MoodExecuterService() {
}
PriorityQueue<QueueEvent> queue = new PriorityQueue<QueueEvent>();
int transientIndex = 0;
public enum KnownState {Unknown, ToSend, Getting, Synched};
public Integer maxBrightness;
public int[] group;
public int[] bulbBri;
public int[] bulbRelBri;
public KnownState[] bulbKnown;
public Mood mood;
private static int MAX_REL_BRI = 255;
public ArrayList<OnBrightnessChangedListener> brightnessListeners = new ArrayList<OnBrightnessChangedListener>();
public void onGroupSelected(int[] bulbs, Integer optionalBri){
group = bulbs;
maxBrightness = null;
bulbBri = new int[group.length];
bulbRelBri = new int[group.length];
bulbKnown = new KnownState[group.length];
for(int i = 0; i < bulbRelBri.length; i++){
bulbRelBri[i] = MAX_REL_BRI;
bulbKnown[i] = KnownState.Unknown;
}
if(optionalBri==null){
for(int i = 0; i< group.length; i++){
bulbKnown[i] = KnownState.Getting;
NetworkMethods.PreformGetBulbAttributes(me, me, group[i]);
}
} else {
maxBrightness = optionalBri;
for(int i = 0; i< group.length; i++)
bulbKnown[i] = KnownState.ToSend;
onBrightnessChanged();
}
}
/** doesn't notify listeners **/
public synchronized void setBrightness(int brightness){
Log.e("bri",""+brightness);
maxBrightness = brightness;
for(int i = 0; i< group.length; i++){
bulbBri[i] = (maxBrightness * bulbRelBri[i])/MAX_REL_BRI;
bulbKnown[i] = KnownState.ToSend;
}
}
public interface OnBrightnessChangedListener {
public void onBrightnessChanged(int brightness);
}
/** announce brightness to any listeners **/
public void onBrightnessChanged(){
for(OnBrightnessChangedListener l : brightnessListeners){
l.onBrightnessChanged(maxBrightness);
}
}
public void registerBrightnessListener(OnBrightnessChangedListener l){
if(maxBrightness!=null)
l.onBrightnessChanged(maxBrightness);
brightnessListeners.add(l);
}
public void removeBrightnessListener(OnBrightnessChangedListener l){
brightnessListeners.remove(l);
}
public void startMood(Mood m, String moodName){
mood = m;
createNotification(moodName);
queue.clear();
loadMoodIntoQueue();
restartCountDownTimer();
}
public void stopMood(){
mood = null;
queue.clear();
}
@Override
public void onAttributesReturned(BulbAttributes result, int bulbNumber) {
//figure out which bulb in group (if that group is still selected)
int index = calculateBulbPositionInGroup(bulbNumber);
//if group is still expected this, save
if(index>-1 && bulbKnown[index]==KnownState.Getting){
bulbKnown[index] = KnownState.Synched;
bulbBri[index] = result.state.bri;
//if all expected get brightnesses have returned, compute maxbri and notify listeners
boolean anyOutstandingGets = false;
for(KnownState ks : bulbKnown)
anyOutstandingGets |= (ks == KnownState.Getting);
if(!anyOutstandingGets){
//todo calc more intelligent bri when mood known
int briSum = 0;
for(int bri : bulbBri)
briSum +=bri;
maxBrightness = briSum/group.length;
for(int i = 0; i< group.length; i++){
bulbBri[i]= maxBrightness;
bulbRelBri[i] = MAX_REL_BRI;
}
onBrightnessChanged();
}
}
}
/** finds bulb index within group[] **/
private int calculateBulbPositionInGroup(int bulbNumber){
int index = -1;
for(int j = 0; j< group.length; j++){
if(group[j]==bulbNumber)
index = j;
}
return index;
}
@Override
public void setHubConnectionState(boolean connected){
if(hasHubConnection!=connected){
hasHubConnection = connected;
for(OnConnectionStatusChangedListener l : connectionListeners)
l.onConnectionStatusChanged(connected);
}
if(!connected){
//TODO rate limit
NetworkMethods.PreformGetBulbList(this, null);
}
Log.e("setHubConnection", ""+connected);
}
public boolean hasHubConnection(){
return hasHubConnection;
}
public void createNotification(String secondaryText) {
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.huemore)
.setContentTitle(
this.getResources().getString(R.string.app_name))
.setContentText(secondaryText)
.setContentIntent(resultPendingIntent);
this.startForeground(notificationId, mBuilder.build());
}
public RequestQueue getRequestQueue() {
return volleyRQ;
}
private boolean hasTransientChanges() {
if(bulbKnown==null)
return false;
boolean result = false;
for (KnownState ks : bulbKnown)
result |= (ks==KnownState.ToSend);
return result;
}
private void loadMoodIntoQueue() {
ArrayList<Integer>[] channels = new ArrayList[mood.getNumChannels()];
for (int i = 0; i < channels.length; i++)
channels[i] = new ArrayList<Integer>();
for (int i = 0; i < group.length; i++) {
channels[i % mood.getNumChannels()].add(group[i]);
}
if(mood.timeAddressingRepeatPolicy){
Stack<QueueEvent> pendingEvents = new Stack<QueueEvent>();
long earliestEventStillApplicable = Long.MIN_VALUE;
for (int i= mood.events.length-1; i>=0; i
Event e = mood.events[i];
for (Integer bNum : channels[e.channel]) {
QueueEvent qe = new QueueEvent(e);
qe.bulb = bNum;
Calendar current = Calendar.getInstance();
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);
startOfDay.getTimeInMillis();
Long offsetWithinTheDayInNanos = (current.getTimeInMillis() - startOfDay.getTimeInMillis())*1000000l;
Long startOfDayInNanos = System.nanoTime() - offsetWithinTheDayInNanos;
qe.nanoTime = startOfDayInNanos+(e.time*100000000l);
if(qe.nanoTime>0l)
pendingEvents.add(qe);
else if(qe.nanoTime>=earliestEventStillApplicable){
earliestEventStillApplicable = qe.nanoTime;
qe.nanoTime = 0l;
pendingEvents.add(qe);
}
}
}
while(!pendingEvents.empty()){
queue.add(pendingEvents.pop());
}
}else{
for (Event e : mood.events) {
for (Integer bNum : channels[e.channel]) {
QueueEvent qe = new QueueEvent(e);
qe.bulb = bNum;
// 10^8 * e.time
qe.nanoTime = System.nanoTime()+(e.time*100000000l);
queue.add(qe);
}
}
}
moodLoopIterationEndNanoTime = System.nanoTime()+(mood.loopIterationTimeLength*100000000l);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
volleyRQ = Volley.newRequestQueue(this);
restartCountDownTimer();
createNotification("");
//acquire wakelock
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
wakelock.acquire();
//start pinging to test connectivity
NetworkMethods.PreformGetBulbList(this, null);
}
@Override
public void onDestroy() {
countDownTimer.cancel();
volleyRQ.cancelAll(InternalArguments.TRANSIENT_NETWORK_REQUEST);
volleyRQ.cancelAll(InternalArguments.PERMANENT_NETWORK_REQUEST);
wakelock.release();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
//remove any possible launched wakelocks
AlarmReciever.completeWakefulIntent(intent);
FireReceiver.completeWakefulIntent(intent);
String encodedMood = intent
.getStringExtra(InternalArguments.ENCODED_MOOD);
try{
if (encodedMood != null) {
Pair<Integer[], Pair<Mood, Integer>> moodPairs = HueUrlEncoder.decode(encodedMood);
String moodName = intent.getStringExtra(InternalArguments.MOOD_NAME);
moodName = (moodName == null) ? "Unknown Mood" : moodName;
if(moodPairs.first!=null && moodPairs.first.length>0){
int[] bulbs = new int[moodPairs.first.length];
for(int i = 0; i< bulbs.length; i++)
bulbs[i] = moodPairs.first[i];
onGroupSelected(bulbs, moodPairs.second.second);
}
if(moodPairs.second.first!=null)
startMood(moodPairs.second.first, moodName);
}
} catch (InvalidEncodingException e) {
Intent i = new Intent(this,DecodeErrorActivity.class);
i.putExtra(InternalArguments.DECODER_ERROR_UPGRADE, false);
startActivity(i);
} catch (FutureEncodingException e) {
Intent i = new Intent(this,DecodeErrorActivity.class);
i.putExtra(InternalArguments.DECODER_ERROR_UPGRADE, true);
startActivity(i);
}
}
return super.onStartCommand(intent, flags, startId);
}
public void restartCountDownTimer() {
if (countDownTimer != null)
countDownTimer.cancel();
countDownToStopSelf = MAX_STOP_SELF_COUNDOWN;
// runs at the rate to execute 15 op/sec
countDownTimer = new CountDownTimer(Integer.MAX_VALUE, (1000 / 15)) {
@Override
public void onFinish() {
}
@Override
public void onTick(long millisUntilFinished) {
if (queue.peek()!=null && queue.peek().nanoTime <= System.nanoTime()) {
QueueEvent e = queue.poll();
int bulbInGroup = calculateBulbPositionInGroup(e.bulb);
if(bulbInGroup>-1 && maxBrightness!=null){
//convert relative brightness into absolute brightness
if(e.event.state.bri!=null)
bulbRelBri[bulbInGroup] = e.event.state.bri;
else
bulbRelBri[bulbInGroup] = MAX_REL_BRI;
bulbBri[bulbInGroup] = (bulbRelBri[bulbInGroup] * maxBrightness)/ MAX_REL_BRI;
e.event.state.bri = bulbBri[bulbInGroup];
bulbKnown[bulbInGroup] = KnownState.Synched;
}
NetworkMethods.PreformTransmitGroupMood(me, e.bulb, e.event.state);
} else if (queue.peek() == null && mood != null && mood.isInfiniteLooping() && System.nanoTime()>moodLoopIterationEndNanoTime) {
loadMoodIntoQueue();
} else if (hasTransientChanges()) {
boolean sentSomething = false;
while (!sentSomething) {
if(bulbKnown[transientIndex] == KnownState.ToSend){
BulbState bs = new BulbState();
bulbBri[transientIndex] = (bulbRelBri[transientIndex] * maxBrightness)/ MAX_REL_BRI;
bs.bri = bulbBri[transientIndex];
NetworkMethods.PreformTransmitGroupMood(me, group[transientIndex], bs);
bulbKnown[transientIndex] = KnownState.Synched;
sentSomething = true;
}
transientIndex = (transientIndex + 1) % group.length;
}
} else if (queue.peek() == null && (mood ==null || !mood.isInfiniteLooping())){
createNotification("");
if(countDownToStopSelf<=0)
me.stopSelf();
else
countDownToStopSelf
}
}
};
countDownTimer.start();
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.AlphaComposite;
import java.awt.RenderingHints;
import org.jdesktop.swingx.BeanInfoSupport;
import org.jdesktop.swingx.EnumerationValue;
import org.jdesktop.swingx.editors.EnumerationValuePropertyEditor;
import org.jdesktop.swingx.util.Resize;
/**
*
* @author Richard
*/
public class AbstractPainterBeanInfo extends BeanInfoSupport {
/** Creates a new instance of BackgroundPainterBeanInfo */
public AbstractPainterBeanInfo() {
super(AbstractPainter.class);
}
public AbstractPainterBeanInfo(Class clazz) {
super(clazz);
}
protected void initialize() {
setHidden(true, "class", "propertyChangeListeners", "renderingHints");
//set editor for the clip shape
//set editor for the effects (not sure how to do this one)
//TODO
//set editor for resizeClip
setPropertyEditor(ResizeClipPropertyEditor.class, "resizeClip");
//set editor for composite (incl. Alpha composites by default)
setPropertyEditor(CompositePropertyEditor.class, "composite");
//set editors for the various rendering hints
setPropertyEditor(AlphaInterpolationPropertyEditor.class, "alphaInterpolation");
setPropertyEditor(AntialiasingPropertyEditor.class, "antialiasing");
setPropertyEditor(ColorRenderingPropertyEditor.class, "colorRendering");
setPropertyEditor(DitheringPropertyEditor.class, "dithering");
setPropertyEditor(FractionalMetricsPropertyEditor.class, "fractionalMetrics");
setPropertyEditor(InterpolationPropertyEditor.class, "interpolation");
setPropertyEditor(RenderingPropertyEditor.class, "rendering");
setPropertyEditor(StrokeControlPropertyEditor.class, "strokeControl");
setPropertyEditor(TextAntialiasingPropertyEditor.class, "textAntialiasing");
//move some items into "Appearance" and some into "Behavior"
setCategory("Rendering Hints", "alphaInterpolation", "antialiasing",
"colorRendering", "dithering", "fractionalMetrics", "interpolation",
"rendering", "strokeControl", "textAntialiasing");
setCategory("Appearance", "clip", "composite", "effects");
setCategory("Behavior", "resizeClip", "useCache");
}
public static final class ResizeClipPropertyEditor extends EnumerationValuePropertyEditor {
public ResizeClipPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("None", Resize.NONE, "Resize.NONE"),
new EnumerationValue("Horizontal", Resize.HORIZONTAL, "Resize.HORIZONTAL"),
new EnumerationValue("Vertical", Resize.VERTICAL, "Resize.VERTICAL"),
new EnumerationValue("Both", Resize.BOTH, "Resize.BOTH")
});
}
}
public static final class CompositePropertyEditor extends EnumerationValuePropertyEditor {
public CompositePropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Clear", AlphaComposite.Clear, "AlphaComposite.Clear"),
new EnumerationValue("Destination", AlphaComposite.Dst, "AlphaComposite.Dst"),
new EnumerationValue("Destination Atop", AlphaComposite.DstAtop, "AlphaComposite.DstAtop"),
new EnumerationValue("Destination In", AlphaComposite.DstIn, "AlphaComposite.DstIn"),
new EnumerationValue("Destination Out", AlphaComposite.DstOut, "AlphaComposite.DstOut"),
new EnumerationValue("Destination Over", AlphaComposite.DstOver, "AlphaComposite.DstOver"),
new EnumerationValue("Source", AlphaComposite.Src, "AlphaComposite.Src"),
new EnumerationValue("Source Atop", AlphaComposite.SrcAtop, "AlphaComposite.SrcAtop"),
new EnumerationValue("Source In", AlphaComposite.SrcIn, "AlphaComposite.SrcIn"),
new EnumerationValue("Source Out", AlphaComposite.SrcOut, "AlphaComposite.SrcOut"),
new EnumerationValue("Source Over", AlphaComposite.SrcOver, "AlphaComposite.SrcOver"),
new EnumerationValue("Xor", AlphaComposite.Xor, "AlphaComposite.Xor")
});
}
}
public static final class AlphaInterpolationPropertyEditor extends EnumerationValuePropertyEditor {
public AlphaInterpolationPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT, "RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT"),
new EnumerationValue("Quality", RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY, "RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY"),
new EnumerationValue("Speed", RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED, "RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED")
});
}
}
public static final class AntialiasingPropertyEditor extends EnumerationValuePropertyEditor {
public AntialiasingPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_ANTIALIAS_DEFAULT, "RenderingHints.VALUE_ANTIALIAS_DEFAULT"),
new EnumerationValue("On", RenderingHints.VALUE_ANTIALIAS_ON, "RenderingHints.VALUE_ANTIALIAS_ON"),
new EnumerationValue("Off", RenderingHints.VALUE_ANTIALIAS_OFF, "RenderingHints.VALUE_ANTIALIAS_OFF")
});
}
}
public static final class ColorRenderingPropertyEditor extends EnumerationValuePropertyEditor {
public ColorRenderingPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_COLOR_RENDER_DEFAULT, "RenderingHints.VALUE_COLOR_RENDER_DEFAULT"),
new EnumerationValue("Quality", RenderingHints.VALUE_COLOR_RENDER_QUALITY, "RenderingHints.VALUE_COLOR_RENDER_QUALITY"),
new EnumerationValue("Speed", RenderingHints.VALUE_COLOR_RENDER_SPEED, "RenderingHints.VALUE_COLOR_RENDER_SPEED")
});
}
}
public static final class DitheringPropertyEditor extends EnumerationValuePropertyEditor {
public DitheringPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_DITHER_DEFAULT, "RenderingHints.VALUE_DITHER_DEFAULT"),
new EnumerationValue("Enable", RenderingHints.VALUE_DITHER_ENABLE, "RenderingHints.VALUE_DITHER_ENABLE"),
new EnumerationValue("Disable", RenderingHints.VALUE_DITHER_DISABLE, "RenderingHints.VALUE_DITHER_DISABLE")
});
}
}
public static final class FractionalMetricsPropertyEditor extends EnumerationValuePropertyEditor {
public FractionalMetricsPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT, "RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT"),
new EnumerationValue("On", RenderingHints.VALUE_FRACTIONALMETRICS_ON, "RenderingHints.VALUE_FRACTIONALMETRICS_ON"),
new EnumerationValue("Off", RenderingHints.VALUE_FRACTIONALMETRICS_OFF, "RenderingHints.VALUE_FRACTIONALMETRICS_OFF")
});
}
}
public static final class InterpolationPropertyEditor extends EnumerationValuePropertyEditor {
public InterpolationPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Bicubic", RenderingHints.VALUE_INTERPOLATION_BICUBIC, "RenderingHints.VALUE_INTERPOLATION_BICUBIC"),
new EnumerationValue("Bilinear", RenderingHints.VALUE_INTERPOLATION_BILINEAR, "RenderingHints.VALUE_INTERPOLATION_BILINEAR"),
new EnumerationValue("Nearest Neighbor", RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR, "RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR")
});
}
}
public static final class RenderingPropertyEditor extends EnumerationValuePropertyEditor {
public RenderingPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_RENDER_DEFAULT, "RenderingHints.VALUE_RENDER_DEFAULT"),
new EnumerationValue("Quality", RenderingHints.VALUE_RENDER_QUALITY, "RenderingHints.VALUE_RENDER_QUALITY"),
new EnumerationValue("Speed", RenderingHints.VALUE_RENDER_SPEED, "RenderingHints.VALUE_RENDER_SPEED")
});
}
}
public static final class StrokeControlPropertyEditor extends EnumerationValuePropertyEditor {
public StrokeControlPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_STROKE_DEFAULT, "RenderingHints.VALUE_STROKE_DEFAULT"),
new EnumerationValue("Normalize", RenderingHints.VALUE_STROKE_NORMALIZE, "RenderingHints.VALUE_STROKE_NORMALIZE"),
new EnumerationValue("Pure", RenderingHints.VALUE_STROKE_PURE, "RenderingHints.VALUE_STROKE_PURE")
});
}
}
public static final class TextAntialiasingPropertyEditor extends EnumerationValuePropertyEditor {
public TextAntialiasingPropertyEditor() {
super(null, new EnumerationValue[] {
new EnumerationValue("", null, "null"),
new EnumerationValue("Default", RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, "RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT"),
new EnumerationValue("On", RenderingHints.VALUE_TEXT_ANTIALIAS_ON, "RenderingHints.VALUE_TEXT_ANTIALIAS_ON"),
new EnumerationValue("Off", RenderingHints.VALUE_TEXT_ANTIALIAS_OFF, "RenderingHints.VALUE_TEXT_ANTIALIAS_OFF")
});
}
}
}
|
package com.a3louq.sci_tab;
import android.animation.Animator;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends AppCompatActivity {
final TextView[] textViews = new TextView[118];
ImageView tab, tab2, arrow, arrow2;
Button start;
Boolean longClicked=false;
RelativeLayout details, intro;
TextView introTxt, introTxt2, selectedElement, nametxt, categorytxt, colortxt, electronPerShelltxt, phasetxt;
boolean reactionGet = false;
String rw = "0";
ArrayList<Integer> reactionWith = new ArrayList<Integer>();
int state = 0;
String[] eqTest = {"Reaction1","Reaction2","Reaction3","Reaction4","Reaction5"};
String[] eqDetails = {"Details1","Details2","Details3","Details4","Details5"};
String firstElement;
String secondElement;
String test;
String[] tests;
String eq;
String equationDetails;
List<Integer> allElements = Arrays.asList(R.id.e1,R.id.e2,R.id.e3,R.id.e4,R.id.e5,R.id.e6,R.id.e7,R.id.e8,R.id.e9,R.id.e10,
R.id.e11,R.id.e12,R.id.e13,R.id.e14,R.id.e15,R.id.e16,R.id.e17,R.id.e18,R.id.e19,R.id.e20,
R.id.e21,R.id.e22,R.id.e23,R.id.e24,R.id.e25,R.id.e26,R.id.e27,R.id.e28,R.id.e29,R.id.e30,
R.id.e31,R.id.e32,R.id.e33,R.id.e34,R.id.e35,R.id.e36,R.id.e37,R.id.e38,R.id.e39,R.id.e40,
R.id.e41,R.id.e42,R.id.e43,R.id.e44,R.id.e45,R.id.e46,R.id.e47,R.id.e48,R.id.e49,R.id.e50,
R.id.e51,R.id.e52,R.id.e53,R.id.e54,R.id.e55,R.id.e56,R.id.e57,R.id.e58,R.id.e59,R.id.e60,
R.id.e61,R.id.e62,R.id.e63,R.id.e64,R.id.e65,R.id.e66,R.id.e67,R.id.e68,R.id.e69,R.id.e70,
R.id.e71,R.id.e72,R.id.e73,R.id.e74,R.id.e75,R.id.e76,R.id.e77,R.id.e78,R.id.e79,R.id.e80,
R.id.e81,R.id.e82,R.id.e83,R.id.e84,R.id.e85,R.id.e86,R.id.e87,R.id.e88,R.id.e89,R.id.e90,
R.id.e91,R.id.e92,R.id.e93,R.id.e94,R.id.e95,R.id.e96,R.id.e97,R.id.e98,R.id.e99,R.id.e100,
R.id.e101,R.id.e102,R.id.e103,R.id.e104,R.id.e105,R.id.e106,R.id.e107,R.id.e108,R.id.e109,R.id.e110,
R.id.e111,R.id.e112,R.id.e113,R.id.e114,R.id.e115,R.id.e116,R.id.e117,R.id.e118);
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
defElements();
}
public void defElements(){
details = (RelativeLayout) findViewById(R.id.details);
intro = (RelativeLayout) findViewById(R.id.intro);
tab = (ImageView) findViewById(R.id.tab);
tab2 = (ImageView) findViewById(R.id.tab2);
arrow = (ImageView) findViewById(R.id.arrow);
arrow2 = (ImageView) findViewById(R.id.arrow2);
start = (Button) findViewById(R.id.start);
introTxt = (TextView)findViewById(R.id.introText);
introTxt2 = (TextView) findViewById(R.id.introText2);
selectedElement = (TextView)findViewById(R.id.selctedElement);
nametxt = (TextView)findViewById(R.id.name);
categorytxt = (TextView)findViewById(R.id.category);
colortxt = (TextView)findViewById(R.id.color);
phasetxt = (TextView)findViewById(R.id.phase);
electronPerShelltxt = (TextView)findViewById(R.id.electrons);
for(int i=0; i<textViews.length;i++){
textViews[i]= (TextView) findViewById(allElements.get(i));
}
for(int i=0; i<allElements.size();i++){
final int finalI = i;
textViews[i].setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
longClicked=true;
setContentView(R.layout.activity_main);
defElements();
getReactions(textViews[finalI]);
return true;
}
});
final int finalI1 = i;
textViews[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(longClicked) {
setContentView(R.layout.activity_main);
defElements();
longClicked=false;
}
ColorDrawable viewColor = (ColorDrawable) textViews[finalI1].getBackground();
int colorId = viewColor.getColor();
if (state == 0) {
getDetails(textViews[finalI1], colorId);
}else if (state == 1){
secondElement = textViews[finalI].getText().toString().split("\n")[1];
for (int i=0;i<5;i++){
final int finalI2 = i;
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
test = dataSnapshot.child(firstElement).child(eqTest[finalI2]).getValue().toString();
if (test.length()>0) {
tests = test.split("\\+|→|1|2|3|4|5|6|7|8|9|0| |\\(");
for (int j=0;j<tests.length;j++){
System.out.println(tests[j] + " " + secondElement);
if ((secondElement.toLowerCase()).equals(tests[j].toLowerCase())){
eq = dataSnapshot.child(firstElement).child(eqTest[finalI2]).getValue().toString();
equationDetails = dataSnapshot.child(firstElement).child(eqDetails[finalI2]).getValue().toString();
react();
break;
}
}
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
}
}
});
}
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstLaunch = preferences.getBoolean("firstLaunch", true);
if(firstLaunch){
intro.setVisibility(View.VISIBLE);
final Animation pulse = AnimationUtils.loadAnimation(this, R.anim.pulse);
tab.startAnimation(pulse);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
TextView e22 = (TextView) findViewById(R.id.e22);
ColorDrawable viewColor = (ColorDrawable) e22.getBackground();
int colorId = viewColor.getColor();
arrow.setVisibility(View.VISIBLE);
getDetails(e22,colorId);
start.setEnabled(true);
}
},5000);
final int[] step = {1};
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(start.getText().toString().equals("next")) {
if (step[0] == 1) {
step[0]++;
details.setVisibility(View.GONE);
start.setEnabled(false);
arrow.setVisibility(View.GONE);
introTxt.setText("Long Tab on Element to show Elments which can react with");
final Animation pulse = AnimationUtils.loadAnimation(getApplication(), R.anim.long_pulse);
tab.startAnimation(pulse);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
final TextView e22 = (TextView) findViewById(R.id.e22);
getReactions(e22);
}
}, 5000);
start.setEnabled(true);
tab.setVisibility(View.INVISIBLE);
} else {
start.setEnabled(false);
start.setText("Start");
tab.setVisibility(View.INVISIBLE);
introTxt.setVisibility(View.INVISIBLE);
tab2.setVisibility(View.VISIBLE);
tab2.startAnimation(pulse);
arrow2.setVisibility(View.VISIBLE);
introTxt2.setVisibility(View.VISIBLE);
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
@Override
public void run() {
final TextView e22 = (TextView) findViewById(R.id.e22);
TextView e17 = (TextView) findViewById(R.id.e17);
firstElement = e22.getText().toString().split("\n")[1];
secondElement = e17.getText().toString().split("\n")[1];
for (int i = 0; i < 5; i++) {
final int finalI2 = i;
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
test = dataSnapshot.child(firstElement).child(eqTest[finalI2]).getValue().toString();
if (test.length() > 0) {
tests = test.split("\\+|→|1|2|3|4|5|6|7|8|9|0| |\\(");
for (int j = 0; j < tests.length; j++) {
System.out.println(tests[j] + " " + secondElement);
if ((secondElement.toLowerCase()).equals(tests[j].toLowerCase())) {
eq = dataSnapshot.child(firstElement).child(eqTest[finalI2]).getValue().toString();
equationDetails = dataSnapshot.child(firstElement).child(eqDetails[finalI2]).getValue().toString();
react();
break;
}
}
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
start.setEnabled(true);
state = 0;
}
}, 5000);
}
}else {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch",false);
editor.apply();
setContentView(R.layout.activity_main);
defElements();
}
}
});
}
}
public void react (){
new SweetAlertDialog(this)
.setTitleText("Reaction Equation")
.setContentText(eq + "\n" + equationDetails)
.show();
state = 0;
}
public void getReactions(TextView txt) {
final Animation pulse = AnimationUtils.loadAnimation(this, R.anim.pulse);
final String symbol = txt.getText().toString().split("\n")[1];
final int number = Integer.parseInt( txt.getText().toString().split("\n")[0]);
firstElement = txt.getText().toString().split("\n")[1];
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Loading...");
Dialog.show();
final TextView[] txtView = new TextView[1];
if (number == 118) {
txtView[0] = (TextView) findViewById(R.id.e118);
} else {
txtView[0] = (TextView) findViewById(allElements.get(number));
}
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
rw = dataSnapshot.child(symbol).child("Reaction with").getValue().toString();
if (rw.equals("0")){
Toast.makeText(getApplicationContext(),"No elements can react with " + symbol,Toast.LENGTH_LONG).show();
state = 0;
}else {
String[] RW = rw.split(",");
for (int i=0;i<RW.length;i++){
reactionWith.add(Integer.parseInt(RW[i]));
}
a:
for(int i =0; i<allElements.size(); i++){
for (int j=0; j<reactionWith.size();j++){
if((i==reactionWith.get(j)-1)){
txtView[0] = (TextView) findViewById(allElements.get(i));
txtView[0].startAnimation(pulse);
if (i < 117) {
continue a;
} else {
break a;
}
}
else if (i==number-1){
if (i < 117) {
continue a;
} else {
break a;
}
}
}
txtView[0] = (TextView) findViewById(allElements.get(i));
txtView[0].setBackgroundColor(getResources().getColor(R.color.numBack));
txtView[0].setTextColor(Color.GRAY);
}
}
reactionWith.clear();
Dialog.hide();
reactionGet = true;
}
@Override
public void onCancelled(DatabaseError error) {
}
});
state = 1;
}
public void getDetails(TextView element, int colorID){
final String symbol = element.getText().toString().split("\n")[1];
details.setVisibility(View.VISIBLE);
int cx = (details.getLeft() + details.getRight()) / 2;
int cy = details.getTop();
int finalRadius = Math.max(details.getWidth(), details.getHeight());
Animator anim = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
anim = ViewAnimationUtils.createCircularReveal(details, cx, cy, 0, finalRadius);
}
details.setBackgroundColor(colorID);
anim.setDuration(500);
anim.start();
selectedElement.setText(element.getText().toString());
final String[] name = {null};
final String[] category = {null};
final String[] color={null};
final String[] phase={null};
final String[] electrons={null};
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Loading...");
Dialog.show();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
name[0] =dataSnapshot.child(symbol).child("Name").getValue().toString();
category[0] =dataSnapshot.child(symbol).child("Category").getValue().toString();
color[0] =dataSnapshot.child(symbol).child("Color").getValue().toString();
phase[0] =dataSnapshot.child(symbol).child("Phase").getValue().toString();
electrons[0] =dataSnapshot.child(symbol).child("Electrons per shell").getValue().toString();
nametxt.setText(name[0]);
categorytxt.setText(category[0]);
colortxt.setText(color[0]);
phasetxt.setText(phase[0]);
electronPerShelltxt.setText(electrons[0]);
Dialog.hide();
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
public void outSide(View view) {
setContentView(R.layout.activity_main);
defElements();
state =0;
details.setVisibility(View.GONE);
}
@Override
public void onBackPressed() {
setContentView(R.layout.activity_main);
defElements();
state = 0;
details.setVisibility(View.GONE);
}
}
|
// $OldId: ExplicitOuterClasses.java,v 1.22 2002/10/17 12:31:56 schinz Exp $
package scalac.transformer;
import java.util.*;
import scalac.*;
import scalac.ast.*;
import scalac.util.*;
import scalac.parser.*;
import scalac.symtab.*;
import scalac.typechecker.*;
import Tree.*;
/**
* Make links from nested classes to their enclosing class explicit.
*
* @author Michel Schinz
* @version 1.0
*/
public class ExplicitOuterClasses extends Transformer {
// Mapping from class constructor symbols to owner field symbols.
protected HashMap/*<Symbol,Symbol>*/ outerMap = new HashMap();
public ExplicitOuterClasses(Global global, PhaseDescriptor descr) {
super(global, descr);
}
protected Type addValueParam(Type oldType, Symbol newValueParam) {
switch (oldType) {
case MethodType(Symbol[] vparams, Type result): {
Symbol[] newVParams = new Symbol[vparams.length + 1];
newVParams[0] = newValueParam;
System.arraycopy(vparams, 0, newVParams, 1, vparams.length);
return new Type.MethodType(newVParams, result);
}
case PolyType(Symbol[] tparams, Type result):
return new Type.PolyType(tparams, addValueParam(result, newValueParam));
default:
throw global.fail("invalid type", oldType);
}
}
protected Symbol outerSym(Symbol constSym) {
if (! outerMap.containsKey(constSym)) {
Symbol ownerSym = constSym.enclClass();
Symbol outerSym =
new TermSymbol(constSym.pos, freshOuterName(), constSym, 0);
outerSym.setInfo(ownerSym.type());
outerMap.put(constSym, outerSym);
}
return (Symbol)outerMap.get(constSym);
}
protected Type newConstType(Symbol constSym) {
return addValueParam(constSym.info(), outerSym(constSym));
}
protected LinkedList/*<Symbol>*/ classStack = new LinkedList();
protected LinkedList/*<Symbol>*/ outerLinks = new LinkedList();
protected Name freshOuterName() {
return global.freshNameCreator.newName(Names.OUTER_PREFIX);
}
// Return the given class with an explicit link to its outer
// class, if any.
protected Tree addOuterLink(ClassDef classDef) {
Symbol classSym = classDef.symbol();
Symbol constSym = classSym.constructor();
Symbol outerSym = outerSym(constSym);
assert (outerSym.owner() == constSym) : outerSym;
outerLinks.addFirst(outerSym);
// Add the outer parameter, both to the type and the tree.
Type newConstType = newConstType(constSym);
ValDef[][] vparams = classDef.vparams;
ValDef[] newVParamsI;
if (vparams.length == 0)
newVParamsI = new ValDef[] { gen.ValDef(outerSym) };
else {
newVParamsI = new ValDef[vparams[0].length + 1];
newVParamsI[0] = gen.ValDef(outerSym);
System.arraycopy(vparams[0], 0, newVParamsI, 1, vparams[0].length);
}
ValDef[][] newVParams = new ValDef[][] { newVParamsI };
constSym.updateInfo(newConstType);
int newMods = classDef.mods | Modifiers.STATIC;
classSym.flags |= Modifiers.STATIC;
return copy.ClassDef(classDef,
newMods,
classDef.name,
transform(classDef.tparams),
transform(newVParams),
transform(classDef.tpe),
(Template)transform((Tree)classDef.impl));
}
// Return the number of outer links to follow to find the given
// symbol.
protected int outerLevel(Symbol sym) {
Iterator classIt = classStack.iterator();
for (int level = 0; classIt.hasNext(); ++level) {
Symbol classSym = (Symbol)classIt.next();
if (classSym.closurePos(sym) != -1)
return level;
}
return -1;
}
// Return a tree referencing the "level"th outer class.
protected Tree outerRef(int level) {
assert level >= 0 : level;
if (level == 0) {
Symbol thisSym = (Symbol)classStack.getFirst();
return gen.This(thisSym.pos, thisSym);
} else {
Iterator outerIt = outerLinks.iterator();
Tree root = gen.Ident((Symbol)outerIt.next());
for (int l = 1; l < level; ++l) {
Symbol outerSym = (Symbol)outerIt.next();
root = gen.mkStable(gen.Select(root, outerSym));
}
return root;
}
}
public Tree transform(Tree tree) {
switch (tree) {
case ClassDef(int mods, _, _, _, _, _) : {
// Add outer link
ClassDef classDef = (ClassDef) tree;
Symbol sym = classDef.symbol();
Tree newTree;
classStack.addFirst(sym);
if (classStack.size() == 1 || Modifiers.Helper.isStatic(mods)) {
outerLinks.addFirst(null);
newTree = super.transform(tree);
} else
newTree = addOuterLink(classDef);
outerLinks.removeFirst();
classStack.removeFirst();
return newTree;
}
case Ident(Name name): {
if (! name.isTermName())
return super.transform(tree);
// Follow "outer" links to fetch data in outer classes.
int level = outerLevel(tree.symbol().classOwner());
if (level > 0) {
Tree root = outerRef(level);
return gen.mkStable(gen.Select(root, tree.symbol()));
} else {
return super.transform(tree);
}
}
case This(Tree qualifier): {
// If "this" refers to some outer class, replace it by
// explicit reference to it.
int level = qualifier.hasSymbol() ? outerLevel(qualifier.symbol()) : 0;
if (level > 0)
return outerRef(level);
else
return super.transform(tree);
}
case Apply(Tree fun, Tree[] args): {
// Add outer parameter to constructor calls.
Tree realFun;
Tree[] typeArgs;
switch (fun) {
case TypeApply(Tree fun2, Tree[] tArgs):
realFun = fun2; typeArgs = tArgs; break;
default:
realFun = fun; typeArgs = null; break;
}
Tree newFun = null, newArg = null;
if (realFun.hasSymbol() && realFun.symbol().isPrimaryConstructor()) {
switch (transform(realFun)) {
case Select(Tree qualifier, Name selector): {
if (! (qualifier.hasSymbol()
&& Modifiers.Helper.isNoVal(qualifier.symbol().flags))) {
newFun = make.Ident(qualifier.pos, selector)
.setType(realFun.type())
.setSymbol(realFun.symbol());
newArg = qualifier;
}
} break;
case Ident(Name name): {
int level = outerLevel(realFun.symbol().owner());
if (level >= 0) {
newFun = realFun;
newArg = outerRef(level);
}
} break;
default:
throw global.fail("unexpected node in constructor call");
}
if (newFun != null && newArg != null) {
Tree[] newArgs = new Tree[args.length + 1];
newArgs[0] = newArg;
System.arraycopy(args, 0, newArgs, 1, args.length);
Tree finalFun;
if (typeArgs != null)
finalFun = copy.TypeApply(fun, newFun, typeArgs);
else
finalFun = newFun;
finalFun.type = addValueParam(finalFun.type,
outerSym(realFun.symbol()));
return copy.Apply(tree, finalFun, transform(newArgs));
} else
return super.transform(tree);
} else
return super.transform(tree);
}
default:
return super.transform(tree);
}
}
}
|
package com.bkp.minerva.realm;
import com.bkp.minerva.C;
import com.google.common.math.LongMath;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
/**
* Represents a book list in Realm.
*/
public class RBookList extends RealmObject {
/**
* Book list name. This must be unique!
*/
@PrimaryKey
private String name;
/**
* TODO This is a work-around until Realm can do case-insensitive sorting.
* Same as {@link #name}, but in lower-case.
*/
@Index
private String sortName;
/**
* Position number for the next item to be added to this list.
*/
private Long nextPos;
/**
* References to the {@link RBookListItem}s that this list contains.
*/
private RealmList<RBookListItem> listItems;
/**
* Create a default {@link RBookList}.
* <p>
* Note: There's nothing necessarily <i>bad</i> about using this constructor, but using one with parameters is still
* a better choice.
*/
public RBookList() {
this.name = null;
this.sortName = null;
this.nextPos = 0L;
this.listItems = null;
}
/**
* Create a new {@link RBookList} with the given {@code name}.
* @param name Name of the book list. This MUST be unique!
*/
public RBookList(String name) {
this.name = name;
this.sortName = name.toLowerCase();
this.nextPos = 0L;
this.listItems = null;
}
/**
* Reset the positions of the given list's items so that they are spaced evenly using the standard position gap
* (which can be found at {@link com.bkp.minerva.C#LIST_ITEM_GAP}).
* <p>
* Note that this can take a bit, since it must iterate through all items in the list.
* @param bookList The list whose items will be re-spaced.
*/
public static void resetPositions(RBookList bookList) {
if (bookList == null) throw new IllegalArgumentException("bookList is null.");
// Get Realm and the list's items.
Realm realm = Realm.getDefaultInstance();
RealmResults<RBookListItem> items = bookList.getListItems().where().findAllSorted("pos");
// Since the list will be rearranging itself on the fly, we must iterate it backwards. This also means we need
// to know in advance what our largest position number will be. Since the first item is 0, the last item will be
// numItems * gap - gap. The value we store in the list for the nextPos field is numItems * gap.
Long nextPos = LongMath.checkedMultiply(items.size(), C.LIST_ITEM_GAP);
realm.beginTransaction();
// Change list's nextPos.
bookList.setNextPos(nextPos);
// Loop through items backwards and set their positions.
// TODO I can easily see this breaking because it makes the assumption that all of the current positions are
// TODO less than or equal to numItems * gap - gap. If we had even two items greater than that, and the items
// TODO get rearranged as we set the positions, we'll end up setting something twice and breaking the
// TODO order... need to unit test this!
for (int i = items.size() - 1; i >= 0; i
nextPos -= C.LIST_ITEM_GAP;
items.get(i).setPos(nextPos);
}
realm.commitTransaction();
// Close Realm instance.
realm.close();
}
/**
* Moves {@code itemToMove} to between {@code item1} and {@code item2} in the given {@code list}. If {@code item1}
* and {@code item2} aren't consecutive items, behavior is undefined.
* <p>
* If {@code itemToMove} is the same as either {@code item1} or {@code item2} then this does nothing.<br/>If {@code
* item1} is {@code null}, then {@code itemToMove} will be put after {@code item1} with the standard position
* gap.<br/>If {@code item2} is null, then {@code itemToMove} will be put before {@code item2} with the standard
* position gap.
* <p>
* Please note that passing {@code null} for one of the items assumes that the non-null item is either the first (if
* it's {@code item2}), or the last (if it's {@code item1}) item in the list. If this isn't the case, you'll likely
* end up with multiple items in the same list in the same position!
* <p>
* If there's no space between {@code item1} and {@code item2}, the whole list will have its items re-spaced before
* moving the item.
* <p>
* The current spacing gap can be found at {@link com.bkp.minerva.C#LIST_ITEM_GAP}.
* @param list List that all of the given items are a part of.
* @param itemToMove The item which is being moved.
* @param item1 The item which will now precede {@code itemToMove}.
* @param item2 The item which will now follow {@code itemToMove}.
*/
public static void moveItemToBetween(RBookList list, RBookListItem itemToMove, RBookListItem item1,
RBookListItem item2) {
// Check nulls.
if (list == null || itemToMove == null || (item1 == null && item2 == null))
throw new IllegalArgumentException("list, itemToMove, or both of item1 and item2 are null.");
// Check if itemToMove is the same as either item1 or item2.
if ((item1 != null && itemToMove.getKey().equals(item1.getKey()))
|| (item2 != null && itemToMove.getKey().equals(item2.getKey()))) return;
// Try to find the new position for the item, and make sure we didn't get a null back.
Long newPos = findMiddlePos(list, item1, item2);
if (newPos == null) {
// If newPos is null, we need to re-sort the items before moving itemToMove.
resetPositions(list);
newPos = findMiddlePos(list, item1, item2);
if (newPos == null)
throw new IllegalArgumentException("Couldn't find space between item1 and item2 after re-spacing");
}
// Get Realm, update itemToMove, then close Realm.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
itemToMove.setPos(newPos);
realm.commitTransaction();
realm.close();
}
/**
* Find the position number that is between the two given items. If there are no positions between the items, {@code
* null} is returned. If {@code item1} and {@code item2} aren't consecutive items, this will potentially result in
* the returned position already being taken.
* <p>
* {@code null} can be passed for ONE of {@code item1} or {@code item2}:<br/>If {@code item1} is null, the number
* returned will be {@code item1.getPos() + gap}<br/>If {@code item2} is null, the number returned will be {@code
* item2.getPos() - gap}.<br/>(The current spacing gap can be found at {@link com.bkp.minerva.C#LIST_ITEM_GAP}.)
* <p>
* Please note that passing {@code null} for one of the items assumes that the non-null item is either the first (if
* it's {@code item2}), or the last (if it's {@code item1}) item in the list. If this isn't the case, the returned
* position might already be taken!
* @param list The list which the items belong to.
* @param item1 The earlier item (which the returned position will follow).
* @param item2 The later item (which the returned position will precede).
* @return The position number between the two items, or {@code null} if there's no space between the items.
*/
public static Long findMiddlePos(RBookList list, RBookListItem item1, RBookListItem item2) {
if (list == null || (item1 == null && item2 == null))
throw new IllegalArgumentException("Null list or both items are null.");
// Handle acceptable nulls.
if (item1 == null) return LongMath.checkedSubtract(item2.getPos(), C.LIST_ITEM_GAP);
if (item2 == null) return LongMath.checkedAdd(item1.getPos(), C.LIST_ITEM_GAP);
// Get positions, make sure that item2 doesn't precede item1 and isn't in the same position as item1.
Long p1 = item1.getPos(), p2 = item2.getPos();
if (p2 <= p1) throw new IllegalArgumentException("item2 was before or at the same position as item1.");
// Calculate middle.
Long pos = LongMath.mean(p1, p2);
// Make sure there isn't an item in the calculated position. If there is, return null.
return list.getListItems().where().equalTo("pos", pos).findFirst() == null ? pos : null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSortName() {
return sortName;
}
public void setSortName(String sortName) {
this.sortName = sortName;
}
public Long getNextPos() {
return nextPos;
}
public void setNextPos(Long nextPos) {
this.nextPos = nextPos;
}
public RealmList<RBookListItem> getListItems() {
return listItems;
}
public void setListItems(RealmList<RBookListItem> listItems) {
this.listItems = listItems;
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Contains utility methods for the checks.
*
* @author Oliver Burn
* @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
* @author o_sukhodolsky
*/
public final class CheckUtils
{
/** prevent instances */
private CheckUtils()
{
throw new UnsupportedOperationException();
}
/**
* Tests whether a method definition AST defines an equals covariant.
* @param aAST the method definition AST to test.
* Precondition: aAST is a TokenTypes.METHOD_DEF node.
* @return true if aAST defines an equals covariant.
*/
public static boolean isEqualsMethod(DetailAST aAST)
{
if (aAST.getType() != TokenTypes.METHOD_DEF) {
// A node must be method def
return false;
}
// non-static, non-abstract?
final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS);
if (modifiers.branchContains(TokenTypes.LITERAL_STATIC)
|| modifiers.branchContains(TokenTypes.ABSTRACT))
{
return false;
}
// named "equals"?
final DetailAST nameNode = aAST.findFirstToken(TokenTypes.IDENT);
final String name = nameNode.getText();
if (!"equals".equals(name)) {
return false;
}
// one parameter?
final DetailAST paramsNode = aAST.findFirstToken(TokenTypes.PARAMETERS);
return (paramsNode.getChildCount() == 1);
}
// public static boolean isFinal(DetailAST detailAST) {
// DetailAST modifiersAST =
//detailAST.findFirstToken(TokenTypes.MODIFIERS);
// return modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
// public static boolean isInObjBlock(DetailAST detailAST) {
// return detailAST.getParent().getType() == TokenTypes.OBJBLOCK;
// public static String getIdentText(DetailAST detailAST) {
// return detailAST.findFirstToken(TokenTypes.IDENT).getText();
/**
* Returns whether a token represents an ELSE as part of an ELSE / IF set.
* @param aAST the token to check
* @return whether it is
*/
public static boolean isElseIf(DetailAST aAST)
{
final DetailAST parentAST = aAST.getParent();
return (aAST.getType() == TokenTypes.LITERAL_IF)
&& (isElse(parentAST) || isElseWithCurlyBraces(parentAST));
}
/**
* Returns whether a token represents an ELSE.
* @param aAST the token to check
* @return whether the token represents an ELSE
*/
private static boolean isElse(DetailAST aAST)
{
return aAST.getType() == TokenTypes.LITERAL_ELSE;
}
/**
* Returns whether a token represents an SLIST as part of an ELSE
* statement.
* @param aAST the token to check
* @return whether the toke does represent an SLIST as part of an ELSE
*/
private static boolean isElseWithCurlyBraces(DetailAST aAST)
{
return (aAST.getType() == TokenTypes.SLIST)
&& (aAST.getChildCount() == 2)
&& isElse(aAST.getParent());
}
/**
* Creates <code>FullIdent</code> for given type node.
* @param aTypeAST a type node.
* @return <code>FullIdent</code> for given type.
*/
public static FullIdent createFullType(DetailAST aTypeAST)
{
final DetailAST arrayDeclAST =
aTypeAST.findFirstToken(TokenTypes.ARRAY_DECLARATOR);
return createFullTypeNoArrays(arrayDeclAST == null ? aTypeAST
: arrayDeclAST);
}
/**
* @param aTypeAST a type node (no array)
* @return <code>FullIdent</code> for given type.
*/
private static FullIdent createFullTypeNoArrays(DetailAST aTypeAST)
{
return FullIdent.createFullIdent((DetailAST) aTypeAST.getFirstChild());
}
// constants for parseDouble()
/** octal radix */
private static final int BASE_8 = 8;
/** decimal radix */
private static final int BASE_10 = 10;
/** hex radix */
private static final int BASE_16 = 16;
/**
* Returns the value represented by the specified string of the specified
* type. Returns 0 for types other than float, double, int, and long.
* @param aText the string to be parsed.
* @param aType the token type of the text. Should be a constant of
* {@link com.puppycrawl.tools.checkstyle.api.TokenTypes}.
* @return the double value represented by the string argument.
*/
public static double parseDouble(String aText, int aType)
{
double result = 0;
switch (aType) {
case TokenTypes.NUM_FLOAT:
case TokenTypes.NUM_DOUBLE:
result = Double.parseDouble(aText);
break;
case TokenTypes.NUM_INT:
case TokenTypes.NUM_LONG:
int radix = BASE_10;
if (aText.startsWith("0x") || aText.startsWith("0X")) {
radix = BASE_16;
aText = aText.substring(2);
}
else if (aText.charAt(0) == '0') {
radix = BASE_8;
aText = aText.substring(1);
}
if ((aText.endsWith("L")) || (aText.endsWith("l"))) {
aText = aText.substring(0, aText.length() - 1);
}
if (aText.length() > 0) {
if (aType == TokenTypes.NUM_INT) {
result = parseInt(aText, radix);
}
else {
result = parseLong(aText, radix);
}
}
break;
default:
break;
}
return result;
}
/**
* Parses the string argument as a signed integer in the radix specified by
* the second argument. The characters in the string must all be digits of
* the specified radix. Handles negative values, which method
* java.lang.Integer.parseInt(String, int) does not.
* @param aText the String containing the integer representation to be
* parsed. Precondition: aText contains a parsable int.
* @param aRadix the radix to be used while parsing aText.
* @return the integer represented by the string argument in the specified
* radix.
*/
public static int parseInt(String aText, int aRadix)
{
int result = 0;
final int max = aText.length();
for (int i = 0; i < max; i++) {
final int digit = Character.digit(aText.charAt(i), aRadix);
result *= aRadix;
result += digit;
}
return result;
}
/**
* Parses the string argument as a signed long in the radix specified by
* the second argument. The characters in the string must all be digits of
* the specified radix. Handles negative values, which method
* java.lang.Integer.parseInt(String, int) does not.
* @param aText the String containing the integer representation to be
* parsed. Precondition: aText contains a parsable int.
* @param aRadix the radix to be used while parsing aText.
* @return the long represented by the string argument in the specified
* radix.
*/
public static long parseLong(String aText, int aRadix)
{
long result = 0;
final int max = aText.length();
for (int i = 0; i < max; i++) {
final int digit = Character.digit(aText.charAt(i), aRadix);
result *= aRadix;
result += digit;
}
return result;
}
/**
* Returns the value represented by the specified string of the specified
* type. Returns 0 for types other than float, double, int, and long.
* @param aText the string to be parsed.
* @param aType the token type of the text. Should be a constant of
* {@link com.puppycrawl.tools.checkstyle.api.TokenTypes}.
* @return the float value represented by the string argument.
*/
public static double parseFloat(String aText, int aType)
{
return (float) parseDouble(aText, aType);
}
/**
* Finds sub-node for given node minimal (line, column) pair.
* @param aNode the root of tree for search.
* @return sub-node with minimal (line, column) pair.
*/
public static DetailAST getFirstNode(final DetailAST aNode)
{
DetailAST currentNode = aNode;
DetailAST child = (DetailAST) aNode.getFirstChild();
while (child != null) {
final DetailAST newNode = getFirstNode(child);
if (newNode.getLineNo() < currentNode.getLineNo()
|| (newNode.getLineNo() == currentNode.getLineNo()
&& newNode.getColumnNo() < currentNode.getColumnNo()))
{
currentNode = newNode;
}
child = (DetailAST) child.getNextSibling();
}
return currentNode;
}
/**
* Tests whether {@link TokenTypes.LT LT}, {@link TokenTypes.GT GT},
* {@link TokenTypes.QUESTION QUESTION} or {@link TokenTypes.BAND BAND}
* token types are part of a generic declaration or not (in which case they
* are operators).
* @param aNode the token node
* @return true if {@link TokenTypes.LT LT}, {@link TokenTypes.GT GT},
* {@link TokenTypes.QUESTION QUESTION} or
* {@link TokenTypes.BAND BAND}
* tokens and is part of a generic declaration, false otherwise
*
*/
public static boolean isOperatorTokenPartOfGenericDeclaration(
final DetailAST aNode)
{
int type = aNode.getType();
int parentType = aNode.getParent().getType();
// Comparable < String >
if (((type == TokenTypes.GT) || (type == TokenTypes.LT))
&& ((parentType == TokenTypes.TYPE_ARGUMENTS)
|| (parentType == TokenTypes.TYPE_PARAMETERS)))
{
return true;
}
// Comparable < ? extends Serializable & CharSequence >
return (type == TokenTypes.BAND)
&& ((parentType == TokenTypes.TYPE_UPPER_BOUNDS)
|| (parentType == TokenTypes.TYPE_LOWER_BOUNDS));
}
}
|
package com.kickstarter.models;
import android.net.Uri;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import com.kickstarter.libs.qualifiers.AutoGson;
import org.joda.time.DateTime;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import auto.parcel.AutoParcel;
@AutoGson
@AutoParcel
public abstract class Activity implements Parcelable {
@Category public abstract String category();
public abstract DateTime createdAt();
public abstract long id();
@Nullable public abstract Project project();
@Nullable public abstract Update update();
public abstract DateTime updatedAt();
@Nullable public abstract User user();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder category(@Category String __);
public abstract Builder createdAt(DateTime __);
public abstract Builder id(long __);
public abstract Builder project(Project __);
public abstract Builder update(Update __);
public abstract Builder updatedAt(DateTime __);
public abstract Builder user(User __);
public abstract Activity build();
}
public static Builder builder() {
return new AutoParcel_Activity.Builder();
}
public abstract Builder toBuilder();
public static final String CATEGORY_WATCH = "watch";
public static final String CATEGORY_RESUME = "resume";
public static final String CATEGORY_UPDATE = "update";
public static final String CATEGORY_COMMENT_PROJECT = "comment-project";
public static final String CATEGORY_BACKING = "backing";
public static final String CATEGORY_COMMENT_POST = "comment-post";
public static final String CATEGORY_CANCELLATION = "cancellation";
public static final String CATEGORY_SUCCESS = "success";
public static final String CATEGORY_SUSPENSION = "suspension";
public static final String CATEGORY_LAUNCH = "launch";
public static final String CATEGORY_FAILURE = "failure";
public static final String CATEGORY_FUNDING = "funding";
public static final String CATEGORY_BACKING_CANCELED = "backing-canceled";
public static final String CATEGORY_BACKING_DROPPED = "backing-dropped";
public static final String CATEGORY_BACKING_REWARD = "backing-reward";
public static final String CATEGORY_BACKING_AMOUNT = "backing-amount";
public static final String CATEGORY_COMMENT_PROPOSAL = "comment-proposal";
public static final String CATEGORY_FOLLOW = "follow";
@Retention(RetentionPolicy.SOURCE)
@StringDef({CATEGORY_WATCH, CATEGORY_RESUME, CATEGORY_UPDATE, CATEGORY_COMMENT_PROJECT, CATEGORY_BACKING,
CATEGORY_COMMENT_POST, CATEGORY_CANCELLATION, CATEGORY_SUCCESS, CATEGORY_SUSPENSION, CATEGORY_LAUNCH,
CATEGORY_FAILURE, CATEGORY_FUNDING, CATEGORY_BACKING_CANCELED, CATEGORY_BACKING_DROPPED, CATEGORY_BACKING_REWARD,
CATEGORY_BACKING_AMOUNT, CATEGORY_COMMENT_PROPOSAL, CATEGORY_FOLLOW})
public @interface Category {}
public String projectUpdateUrl() {
return Uri.parse(project().webProjectUrl()).buildUpon()
.appendEncodedPath("posts")
.appendPath(Long.toString(update().id()))
.toString();
}
}
|
package com.daveme.intellij.organizephpimports;
import com.intellij.lang.LanguageImportStatements;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiUtilCore;
import com.jetbrains.php.lang.psi.PhpFile;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class OrganizeImportsAction extends AnAction {
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
final VirtualFile[] virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
final Project project = e.getData(CommonDataKeys.PROJECT);
final PsiFile[] psiFiles = convertToPsiFiles(virtualFiles, project);
boolean visible = containsAtLeastOnePhpFile(psiFiles);
boolean enabled = visible && hasImportStatements(psiFiles);
e.getPresentation().setVisible(visible);
e.getPresentation().setEnabled(enabled);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
final VirtualFile[] virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
final PsiFile[] psiFiles = convertToPsiFiles(virtualFiles, project);
new OrganizeImportsProcessor(project, psiFiles).execute();
}
private static boolean hasImportStatements(final PsiFile[] files) {
// @todo account for multiple projects?
for (PsiFile file : files) {
if (!LanguageImportStatements.INSTANCE.forFile(file).isEmpty()) {
return true;
}
}
return false;
}
private static boolean containsAtLeastOnePhpFile(final PsiFile[] files) {
if (files == null) return false;
if (files.length < 1) return false;
for (PsiFile file : files) {
if (file.getVirtualFile().isDirectory()) continue;
if (!(file instanceof PhpFile)) continue;
return true;
}
return false;
}
private static PsiFile[] convertToPsiFiles(final VirtualFile[] files, Project project) {
final PsiManager manager = PsiManager.getInstance(project);
final ArrayList<PsiFile> result = new ArrayList<PsiFile>();
for (VirtualFile virtualFile : files) {
final PsiFile psiFile = manager.findFile(virtualFile);
if (psiFile instanceof PhpFile) result.add(psiFile);
}
return PsiUtilCore.toPsiFileArray(result);
}
}
|
package com.dmdirc.addons.ui_swing.dialogs.prefs;
import com.dmdirc.addons.ui_swing.Apple;
import com.dmdirc.addons.ui_swing.PrefsComponentFactory;
import com.dmdirc.addons.ui_swing.UIUtilities;
import com.dmdirc.addons.ui_swing.components.colours.ColourChooser;
import com.dmdirc.addons.ui_swing.components.colours.OptionalColourChooser;
import com.dmdirc.addons.ui_swing.components.durationeditor.DurationDisplay;
import com.dmdirc.addons.ui_swing.components.text.TextLabel;
import com.dmdirc.config.prefs.PreferencesCategory;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.ReturnableThread;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import net.miginfocom.layout.PlatformDefaults;
import net.miginfocom.swing.MigLayout;
/**
* Loads a preferences panel for a specified preferences category in the
* background.
*/
public class PrefsCategoryLoader extends SwingWorker<JPanel, Object> {
/** Panel gap. */
private final int padding = (int) PlatformDefaults.getUnitValueX("related").
getValue();
/** Panel left padding. */
private final int leftPadding = (int) PlatformDefaults.getPanelInsets(1).
getValue();
/** Panel right padding. */
private final int rightPadding = (int) PlatformDefaults.getPanelInsets(3).
getValue();
/** Error panel. */
private JPanel errorCategory;
private CategoryPanel categoryPanel;
private PreferencesCategory category;
/**
* Instantiates a new preferences category loader.
*
* @param categoryPanel Parent Category panel
* @param category Preferences Category to load
*/
public PrefsCategoryLoader(final CategoryPanel categoryPanel,
final PreferencesCategory category) {
this.categoryPanel = categoryPanel;
this.category = category;
UIUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
errorCategory = new JPanel(new MigLayout("fillx"));
errorCategory.add(new TextLabel(
"There was an error loading this category."));
}
});
}
/**
* {@inheritDoc}
*
* @throws Exception if unable to compute a result
*/
@Override
protected JPanel doInBackground() throws Exception {
return addCategory(category);
}
/** {@inheritDoc} */
@Override
protected void done() {
categoryPanel.categoryLoaded(this, category);
}
/**
* Returns the panel for this loader.
*
* @return Loaded panel
*/
public JPanel getPanel() {
JPanel panel;
try {
panel = super.get();
} catch (InterruptedException ex) {
panel = errorCategory;
} catch (ExecutionException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Error loading prefs panel", ex);
panel = errorCategory;
}
return panel;
}
/**
* Initialises the specified category.
*
* @since 0.6.3m1
* @param category The category that is being initialised
* @param panel The panel to which we're adding its contents
* @param path The textual path of this category
*/
private void initCategory(final PreferencesCategory category,
final JPanel panel, final String path) {
if (!category.getDescription().isEmpty()) {
panel.add(new TextLabel(category.getDescription()), "span, " +
"growx, pushx, wrap 2*unrel");
}
for (PreferencesCategory child : category.getSubcats()) {
if (child.isInline() && category.isInlineBefore()) {
addInlineCategory(child, panel);
} else if (!child.isInline()) {
addCategory(child);
}
}
if (category.hasObject()) {
if (!(category.getObject() instanceof JPanel)) {
throw new IllegalArgumentException(
"Custom preferences objects" +
" for this UI must extend JPanel.");
}
panel.add((JPanel) category.getObject(), "growx, pushx");
return;
}
for (PreferencesSetting setting : category.getSettings()) {
addComponent(category, setting, panel);
}
if (!category.isInlineBefore()) {
for (PreferencesCategory child : category.getSubcats()) {
if (child.isInline()) {
addInlineCategory(child, panel);
}
}
}
}
/**
* Initialises and adds a component to a panel.
*
* @param category The category the setting is being added to
* @param setting The setting to be used
* @param panel The panel to add the component to
*/
private void addComponent(final PreferencesCategory category,
final PreferencesSetting setting,
final JPanel panel) {
final TextLabel label = getLabel(setting);
JComponent option = UIUtilities.invokeAndWait(
new ReturnableThread<JComponent>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(PrefsComponentFactory.getComponent(setting));
}
});
option.setToolTipText(null);
categoryPanel.getToolTipPanel().registerTooltipHandler(label,
getTooltipText(setting));
categoryPanel.getToolTipPanel().registerTooltipHandler(option,
getTooltipText(setting));
if (option instanceof DurationDisplay) {
((DurationDisplay) option).setWindow(categoryPanel.getParentWindow());
} else if (option instanceof ColourChooser) {
((ColourChooser) option).setWindow(categoryPanel.getParentWindow());
} else if (option instanceof OptionalColourChooser) {
((OptionalColourChooser) option).setWindow(categoryPanel.
getParentWindow());
}
if (Apple.isAppleUI()) {
panel.add(label, "align right, wmax 40%");
} else {
panel.add(label, "align left, wmax 40%");
}
panel.add(option, "growx, pushx, w 60%");
}
/**
* Returns the tooltip text for a preferences setting.
*
* @param setting Setting to get text for
*
* @return Tooltip text for the setting
*/
private String getTooltipText(final PreferencesSetting setting) {
if (setting.isRestartNeeded()) {
return "<html>" + setting.getHelptext() + "<br><img src=\"" +
"dmdirc://com/dmdirc/res/restart-needed.png\">Restart needed " +
"if changed</html>";
}
return setting.getHelptext();
}
/**
* Retrieves the title label for the specified setting.
*
* @param setting The setting whose label is being requested
* @return A TextLabel with the appropriate text and tooltip
*/
private TextLabel getLabel(final PreferencesSetting setting) {
final TextLabel label = new TextLabel(setting.getTitle() + ": ", false);
if (setting.getHelptext().isEmpty()) {
label.setToolTipText("No help available.");
} else {
label.setToolTipText(setting.getHelptext());
}
return label;
}
/**
* Adds a new inline category.
*
* @param category The category to be added
* @param parent The panel to add the category to
*/
private void addInlineCategory(final PreferencesCategory category,
final JPanel parent) {
final JPanel panel =
new NoRemovePanel(new MigLayout("fillx, gap unrel, wrap 2, " +
"hidemode 3, pack, wmax 470-" + leftPadding + "-" +
rightPadding + "-2*" + padding));
panel.setName(category.getPath());
panel.setBorder(BorderFactory.createTitledBorder(UIManager.getBorder(
"TitledBorder.border"), category.getTitle()));
parent.add(panel, "span, growx, pushx, wrap");
initCategory(category, panel, "");
}
/**
* Adds the specified category to the preferences dialog.
*
* @since 0.6.3m1
* @param category The category to be added
* @param namePrefix Category name prefix
*/
private JPanel addCategory(final PreferencesCategory category) {
final JPanel panel =
new NoRemovePanel(new MigLayout("fillx, gap unrel, " +
"wrap 2, hidemode 3, wmax 470-" + leftPadding + "-" +
rightPadding + "-2*" + padding));
panel.setName(category.getPath());
final String path = category.getPath();
initCategory(category, panel, path);
return panel;
}
}
|
package com.tytanapps.ptsd;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageRequest;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
/**
* The only activity in the app. Each screen of the app is a fragment. The user can switch
* between them using the navigation view.
*/
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.OnConnectionFailedListener {
private final static String LOG_TAG = MainActivity.class.getSimpleName();
// The connection to the Google API
private static GoogleApiClient mGoogleApiClient;
// Whether the user is signed in to the app with their Google Account
private boolean isUserSignedIn = false;
// The header image on top of the navigation view containing the user's information
private ViewGroup navHeader;
// The request queue used to connect with APIs in the background
private RequestQueue requestQueue;
private static final int RC_SIGN_IN = 1;
private static final int PICK_CONTACT_REQUEST = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate() called with: " + "savedInstanceState = [" + savedInstanceState + "]");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState == null) {
// Create a new Fragment to be placed in the activity layout
MainFragment firstFragment = new MainFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
// Set up the side drawer layout containing the user's information and navigation items
setupDrawerLayout();
// Set up the trusted contact button
setupFAB();
// Set up the connection to the Google API Client. This does not sign in the user.
setupGoogleSignIn();
}
@Override
public void onStart() {
//Log.d(LOG_TAG, "onStart() called with: " + "");
super.onStart();
AlarmService alarmService = new AlarmService(getBaseContext());
alarmService.cancelAlarm();
}
@Override
public void onResume() {
super.onResume();
// Attempt to sign the user in automatically
silentSignIn();
}
@Override
public void onStop() {
//Log.d(LOG_TAG, "onStop() called with: " + "");
AlarmService alarmService = new AlarmService(getBaseContext());
alarmService.startAlarm(24);
super.onStop();
}
/**
* When the back button is pressed, close the layout drawer or exit the app
*/
@Override
public void onBackPressed() {
// Close the drawer layout if it is open
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
// Result returned when launching the pick trusted contact request
else if(requestCode == PICK_CONTACT_REQUEST) {
if(resultCode == RESULT_OK) {
Uri contactUri = data.getData();
handlePickContractRequest(contactUri);
}
}
}
/**
* Set up the floating action button in the bottom of the app
* When pressed, call the trusted contact if it exists. If not, show the create contact dialog
*/
private void setupFAB() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if(fab != null) {
// Call the trusted contact if it exists, otherwise show the create contact dialog
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phoneNumber = getSharedPreferenceString(getString(R.string.pref_trusted_phone_key), "");
if (!phoneNumber.equals(""))
openDialer(phoneNumber);
else
showCreateTrustedContactDialog();
}
});
// If you press and hold on the button, change the trusted contact
fab.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showChangeTrustedContactDialog();
return true;
}
});
}
}
/**
* Create the client to connect with the Google sign in API
*/
private void setupGoogleSignIn() {
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
/**
* Set up the side drawer layout and populate it with the header and navigation items
*/
private void setupDrawerLayout() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
// The navigation view is contained within the drawer layout
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Add the header view containing the user's information
LayoutInflater inflater = LayoutInflater.from(this);
ViewGroup navigationHeader = (ViewGroup) inflater.inflate(R.layout.nav_header_main, null, false);
navigationHeader.findViewById(R.id.button_sign_in).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
navigationView.addHeaderView(navigationHeader);
navHeader = navigationHeader;
}
/**
* Sign in to the user's Google Account
*/
public void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
/**
* When the user has been logged in, update the UI
* @param result The result of signing into your account
*/
private void handleSignInResult(GoogleSignInResult result) {
if (result != null && result.isSuccess()) {
isUserSignedIn = true;
GoogleSignInAccount googleAccount = result.getSignInAccount();
String name = googleAccount.getDisplayName();
String email = googleAccount.getEmail();
Uri profilePicture = googleAccount.getPhotoUrl();
View signInButton = findViewById(R.id.button_sign_in);
if(signInButton != null)
signInButton.setVisibility(View.INVISIBLE);
updateNavigationHeader(name, email, profilePicture);
}
}
/**
* Sign in to the user's Google Account in the background
* Only signs the user in if they have previously granted access
*/
private void silentSignIn() {
OptionalPendingResult<GoogleSignInResult> pendingResult =
Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (pendingResult.isDone()) {
// There's immediate result available.
GoogleSignInResult googleAccount = pendingResult.get();
handleSignInResult(googleAccount);
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
pendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(@NonNull GoogleSignInResult result) {
handleSignInResult(result);
}
});
}
}
/**
* Is the user signed in to the app with their Google Account
* @return Whether the user is signed in to the app
*/
protected boolean isUserSignedIn() {
return isUserSignedIn;
}
/**
* Update the header on the navigation view with the user's information
* @param name The name to display on the navigation view
* @param email The email subtext to show on the navigation view
* @param profilePicture A url of the user's profile picture
*/
private void updateNavigationHeader(String name, String email, Uri profilePicture) {
// Update the name
TextView drawerNameTextView = (TextView) navHeader.findViewById(R.id.drawer_name);
drawerNameTextView.setText(name);
// Update the email address
TextView drawerEmailTextView = (TextView) navHeader.findViewById(R.id.drawer_subtext);
drawerEmailTextView.setVisibility(View.VISIBLE);
drawerEmailTextView.setText(email);
// Show the profile picture. If the user doesn't have one, use the app logo instead
ImageView profileImageView = (ImageView) navHeader.findViewById(R.id.drawer_imageview);
loadProfilePicture(profileImageView, profilePicture);
// Hide the sign in button
View signInButton = navHeader.findViewById(R.id.button_sign_in);
if(signInButton != null)
signInButton.setVisibility(View.GONE);
}
/**
* Load the street view imagery for the given address.
* If there is no street view imagery, it uses the map view instead.
* You should not call this directly. Call loadFacilityImage instead
* @param imageView The ImageView to place the image into
* @param profilePictureUri The uri of the image to load
*/
private void loadProfilePicture(final ImageView imageView, Uri profilePictureUri) {
if(profilePictureUri == null || imageView == null)
return;
String url = profilePictureUri.toString();
// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(Utilities.getCircularBitmap(bitmap, 200, 200));
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.d(LOG_TAG, "Street View Image errorListener: " + error.toString());
}
});
// Start loading the image in the background
getRequestQueue().add(request);
}
/**
* Display a dialog explaining a trusted contact and allow the user to make one
*/
protected void showCreateTrustedContactDialog() {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setPositiveButton(R.string.add_trusted_contact, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pickTrustedContact();
}
});
alertDialogBuilder.setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
LayoutInflater inflater = LayoutInflater.from(this);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.create_trusted_contact_layout, null, false);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setView(layout);
alertDialog.show();
}
/**
* Display a dialog explaining a trusted contact and allow the user to make one
*/
protected void showChangeTrustedContactDialog() {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setPositiveButton(R.string.change_trusted_contact, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pickTrustedContact();
}
});
LayoutInflater inflater = LayoutInflater.from(this);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.change_trusted_contact_layout, null, false);
TextView currentContactTextView = (TextView) layout.findViewById(R.id.current_contact_textview);
String contactName = getSharedPreferenceString(getString(R.string.pref_trusted_name_key), "");
String contactPhone = getSharedPreferenceString(getString(R.string.pref_trusted_phone_key), "");
if(contactPhone.equals("")) {
currentContactTextView.setText("Your trusted contact is\n" + contactName + "\n" + contactPhone);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setView(layout);
alertDialog.show();
}
else
showCreateTrustedContactDialog();
}
/**
* Read a shared preference string from memory
* @param prefKey The key of the shared preference
* @param defaultValue The value to return if the key does not exist
* @return The shared preference with the given key
*/
private String getSharedPreferenceString(String prefKey, String defaultValue) {
return getPreferences(Context.MODE_PRIVATE).getString(prefKey, defaultValue);
}
/**
* Open the dialer with a phone number entered
* This does not call the number directly, the user needs to press the call button
* @param phoneNumber The phone number to call
*/
protected void openDialer(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(intent);
}
/**
* Open an intent to allow the user to pick one of their contacts
*/
protected void pickTrustedContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
/**
* Handle the result of choosing a trusted contact
* @param trustedContactUri The response from the contact picker activity
*/
private void handlePickContractRequest(Uri trustedContactUri) {
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(trustedContactUri, projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phoneNumber = cursor.getString(column);
cursor.close();
String name = getContactName(phoneNumber);
saveSharedPreference(getString(R.string.pref_trusted_name_key), name);
saveSharedPreference(getString(R.string.pref_trusted_phone_key), phoneNumber);
Log.d(LOG_TAG, "Trusted contact changed: NAME: " + name + " PHONENUMBER: " + phoneNumber);
}
}
/**
* Get a contact's name given their phone number
* @param phoneNumber The phone number of the contact
* @return The contact's name
*/
public String getContactName(String phoneNumber) {
Log.d(LOG_TAG, "getContactName() called with: " + "phoneNumber = [" + phoneNumber + "]");
ContentResolver cr = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
Log.d(LOG_TAG, "getContactName() returned: " + contactName);
return contactName;
}
/**
* Save a String to a SharedPreference
* @param prefKey The key of the shared preference
* @param value The value to save in the shared preference
*/
private void saveSharedPreference(String prefKey, String value) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(prefKey, value);
editor.apply();
}
/**
* Get the request queue. Creates it if it has not yet been instantiated
* @return The request queue for connecting with an API
*/
protected RequestQueue getRequestQueue() {
if(requestQueue == null)
instantiateRequestQueue();
return requestQueue;
}
/**
* Create the request queue. This is used to connect to the API in the background
*/
protected void instantiateRequestQueue() {
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);
// Start the queue
requestQueue.start();
}
/**
* Switch the fragment when a navigation item in the navigation pane is selected
*/
@Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment newFragment = null;
// Switch to the appropriate fragment
int id = item.getItemId();
switch(id) {
case R.id.nav_simple_test:
newFragment = new MainFragment();
break;
case R.id.nav_test:
newFragment = new PTSDTestFragment();
break;
case R.id.nav_resources:
newFragment = new ResourcesFragment();
break;
case R.id.nav_hotline:
newFragment = new PhoneFragment();
break;
case R.id.nav_websites:
newFragment = new WebsiteFragment();
break;
case R.id.nav_nearby:
newFragment = new NearbyFacilitiesFragment();
break;
}
if(newFragment != null) {
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
// Close the drawer layout
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Purposely crash the app to test debugging
*/
private void crashApp() {
Log.e(LOG_TAG, "The crash app method has been called.");
throw new RuntimeException("The crash app method has been called. What did you expect to happen?");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
}
|
package com.haxademic.sketch.hardware.kinect_openni;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.poly2tri.Poly2Tri;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PVector;
import blobDetection.Blob;
import blobDetection.BlobDetection;
import blobDetection.EdgeVertex;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.util.OpenGLUtil;
import com.haxademic.core.hardware.kinect.KinectWrapper;
import com.haxademic.core.image.filters.FastBlurFilter;
import com.haxademic.core.math.MathUtil;
@SuppressWarnings("serial")
public class KinectSilhouette
extends PAppletHax {
protected int PIXEL_SIZE = 5;
protected final int KINECT_CLOSE = 500;
protected final int KINECT_FAR = 2000;
protected PGraphics _kinectPixelated;
protected Vector<FloatParticle> _particles;
protected Vector<FloatParticle> _inactiveParticles;
protected PGraphics _silhouette;
BlobDetection theBlobDetection;
PImage blobBufferImg;
protected ArrayList<PVector> _curEdgeList;
protected ArrayList<PVector> _lastEdgeList;
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>();
List<DelaunayTriangle> triangles;
public static void main(String args[]) {
_isFullScreen = false;
PApplet.main(new String[] { "--hide-stop", "--bgcolor=000000", "com.haxademic.sketch.hardware.kinect_openni.KinectSilhouette" });
}
protected void overridePropsFile() {
_appConfig.setProperty( "width", "1024" );
_appConfig.setProperty( "height", "768" );
_appConfig.setProperty( "rendering", "false" );
_appConfig.setProperty( "kinect_active", "true" );
_appConfig.setProperty( "kinect_mirrored", "true" );
_appConfig.setProperty( "fullscreen", "false" );
}
public void setup() {
super.setup();
initBlobDetection();
_kinectPixelated = createGraphics( KinectWrapper.KWIDTH, KinectWrapper.KHEIGHT, P.OPENGL );
_particles = new Vector<FloatParticle>();
_inactiveParticles = new Vector<FloatParticle>();
_curEdgeList = new ArrayList<PVector>();
_lastEdgeList = new ArrayList<PVector>();
}
protected void initBlobDetection() {
_silhouette = p.createGraphics( p.width, p.height, P.OPENGL );
// BlobDetection
// img which will be sent to detection (a smaller copy of the image frame);
blobBufferImg = new PImage( (int)(p.width * 0.2f), (int)(p.height * 0.2f) );
theBlobDetection = new BlobDetection( blobBufferImg.width, blobBufferImg.height );
theBlobDetection.setPosDiscrimination(true); // true if looking for bright areas
theBlobDetection.setThreshold(0.5f); // will detect bright areas whose luminosity > threshold
}
public void drawApp() {
p.background(0);
drawKinect();
runBlobDetection( _kinectPixelated );
getEdges();
drawEdges();
updateParticles();
}
protected void drawKinect() {
// loop through kinect data within player's control range
_kinectPixelated.beginDraw();
_kinectPixelated.clear();
_kinectPixelated.noStroke();
float pixelDepth;
for ( int x = 0; x < KinectWrapper.KWIDTH; x += PIXEL_SIZE ) {
for ( int y = 0; y < KinectWrapper.KHEIGHT; y += PIXEL_SIZE ) {
pixelDepth = p.kinectWrapper.getMillimetersDepthForKinectPixel( x, y );
if( pixelDepth != 0 && pixelDepth > KINECT_CLOSE && pixelDepth < KINECT_FAR ) {
// _kinectPixelated.fill(((pixelDepth - KINECT_CLOSE) / (KINECT_FAR - KINECT_CLOSE)) * 255f);
_kinectPixelated.fill(255f);
_kinectPixelated.rect(x, y, PIXEL_SIZE, PIXEL_SIZE);
}
}
}
_kinectPixelated.endDraw();
}
protected void runBlobDetection( PImage source ) {
blobBufferImg.copy(source, 0, 0, source.width, source.height, 0, 0, blobBufferImg.width, blobBufferImg.height);
FastBlurFilter.blur(blobBufferImg, 3);
theBlobDetection.computeBlobs(blobBufferImg.pixels);
}
protected void drawEdges() {
_silhouette.beginDraw();
_silhouette.clear();
_silhouette.smooth(OpenGLUtil.SMOOTH_LOW);
_silhouette.stroke(255);
_silhouette.noFill();
if (_curEdgeList != null && _lastEdgeList != null && _curEdgeList.size() > 0 && _lastEdgeList.size() > 0) {
// find closest point from each current point to last points
PVector curEdgeVector;
for(int i=0; i < _curEdgeList.size(); i++) {
curEdgeVector = _curEdgeList.get(i);
float dist = 0f;
float minDist = 100f;
int closestLastIndex = -1;
float oldX, newX, oldY, newY;
// int plusFrame = (p.frameCount % 2 == 0) ? 0 : 1; // swap between even and odd vertices each frame
// find closest last vertex
for(int j=0; j < _lastEdgeList.size(); j++) {
dist = MathUtil.getDistance(curEdgeVector.x, curEdgeVector.y, _lastEdgeList.get(j).x, _lastEdgeList.get(j).y);
if(dist < minDist) {
minDist = dist;
closestLastIndex = j;
}
}
// upon finding closest last, draw a line for now, if close enough
if (minDist < 0.2f && i % 4 == 0) {
newX = curEdgeVector.x * p.width;
newY = curEdgeVector.y * p.height;
oldX = _lastEdgeList.get(closestLastIndex).x * p.width;
oldY = _lastEdgeList.get(closestLastIndex).y * p.height;
_silhouette.line(newX, newY, oldX, oldY);
// _silhouette.ellipse( newX, newY, 6, 6 );
// float angle = -MathUtil.getAngleToTarget(curEdgeVector.x, curEdgeVector.y, _lastEdgeList.get(closestLastIndex).x, _lastEdgeList.get(closestLastIndex).y);
// float outerX = curEdgeVector.x + P.sin( MathUtil.degreesToRadians(angle) ) * minDist;
// float outerY = curEdgeVector.y + P.cos( MathUtil.degreesToRadians(angle) ) * minDist;
newParticle(
newX,
newY,
(newX - oldX) * 0.05f,
(newY - oldY) * 0.05f,
255
);
// draw 'mesh' between every few points
if( i > 20 ) {
PVector lastFewEdgeVector = _curEdgeList.get(i-20);
if ( MathUtil.getDistance(curEdgeVector.x, curEdgeVector.y, lastFewEdgeVector.x, lastFewEdgeVector.y) < 0.2f ) {
_silhouette.stroke(255);
_silhouette.line(curEdgeVector.x * p.width, curEdgeVector.y * p.height, lastFewEdgeVector.x * p.width, lastFewEdgeVector.y * p.height);
}
}
}
}
}
_silhouette.endDraw();
p.image(_silhouette,0,0);
}
protected void getEdges() {
_lastEdgeList.clear();
_lastEdgeList = _curEdgeList;
_curEdgeList = new ArrayList<PVector>();
p.stroke(255);
p.fill(255);
// do edge detection
Blob b;
EdgeVertex eA,eB;
for (int n=0 ; n < theBlobDetection.getBlobNb() ; n++) {
b = theBlobDetection.getBlob(n);
if ( b!= null ) {
for (int m=0;m<b.getEdgeNb();m++) {
eA = b.getEdgeVertexA(m);
eB = b.getEdgeVertexB(m); // should store these too?
if (eA !=null && eB !=null) {
_curEdgeList.add( new PVector(eA.x, eA.y) );
}
}
// drawTrianglesForBlob(b);
}
}
}
protected void updateParticles() {
// update particles
FloatParticle particle;
int particlesLen = _particles.size() - 1;
for( int i = particlesLen; i > 0; i
particle = _particles.get(i);
if( particle.active == true ) {
particle.update();
} else {
_particles.remove(i);
_inactiveParticles.add(particle);
}
}
}
protected void newParticle( float x, float y, float speedX, float speedY, int color ) {
FloatParticle particle;
if( _inactiveParticles.size() > 0 ) {
particle = _inactiveParticles.remove( _inactiveParticles.size() - 1 );
} else {
particle = new FloatParticle();
}
particle.startAt( x, y, speedX, speedY, color );
_particles.add( particle );
}
public class FloatParticle {
PVector _position = new PVector();
PVector _speed = new PVector();
PVector _gravity = new PVector(0,0.31f);
int _color = 0;
float _size = 8;
float _opacity = 1;
float _opacityFadeSpeed = 0.03f;
public boolean active = false;
protected int _audioIndex;
public FloatParticle() {
}
public void startAt( float x, float y, float speedX, float speedY, int color ) {
_position.set( x, y );
_speed.set( speedX * 15f * p.random(2f) + p.random(-0.2f,0.2f), speedY * 5f * p.random(3f) ); // add a little extra x variance
// _speed.mult( 1 + p._audioInput.getFFT().spectrum[_audioIndex] ); // speed multiplied by audio
_color = color;
_opacity = 0.8f;
// _opacityFadeSpeed = p.random(400f, 800f) / 10000f; // 0.005 - 0.05
active = true;
_size = P.max(6,(P.abs(_speed.x) + P.abs(_speed.y))*0.3f);
_audioIndex = MathUtil.randRange(0, 511);
}
public void update() {
_position.add( _speed );
_speed.add( _gravity );
_speed.set( _speed.x * 0.98f, _speed.y );
_size *= 0.98f;
// bounce
if (_position.y > p.height) {
_position.sub( _speed );
_speed.set( _speed.x, _speed.y * -0.4f );
}
_opacity -= _opacityFadeSpeed;
if( _opacity <= 0 ) {
active = false;
} else {
p.fill( _color, 200f * _opacity );
p.noStroke();
// float size = _size; // 1 + p._audioInput.getFFT().spectrum[_audioIndex] * 10; // was 3
p.rect( _position.x, _position.y, _size, _size );
}
}
}
public void drawTrianglesForBlob(Blob b) {
// create points array, skipping over blob edge vertices
points.clear();
EdgeVertex eA;
for (int m=0;m<b.getEdgeNb();m+=10) {
eA = b.getEdgeVertexA(m);
if (eA != null) {
PolygonPoint point = new PolygonPoint(eA.x * p.width, eA.y * p.height);
points.add(point);
}
}
if (points.size() < 10) return;
// calculate triangles
doTriangulation();
// draw it
p.stroke(0,255,0);
p.strokeWeight(2);
p.fill(255, 120);
TriangulationPoint point1, point2, point3;
for (DelaunayTriangle triangle : triangles) {
point1 = triangle.points[0];
point2 = triangle.points[1];
point3 = triangle.points[2];
if( point1.getYf() > 0 && point1.getYf() < p.height &&
point2.getYf() > 0 && point2.getYf() < p.height &&
point3.getYf() > 0 && point3.getYf() < p.height &&
point1.getXf() > 0 && point1.getXf() < p.width &&
point2.getXf() > 0 && point2.getXf() < p.width &&
point3.getXf() > 0 && point3.getXf() < p.width) {
p.line( point1.getXf(), point1.getYf(), point2.getXf(), point2.getYf() );
p.line( point3.getXf(), point3.getYf(), point2.getXf(), point2.getYf() );
p.line( point1.getXf(), point1.getYf(), point3.getXf(), point3.getYf() );
// sometimes fill triangles
if (MathUtil.randBoolean(p) == true ) {
p.beginShape();
p.vertex( point1.getXf(), point1.getYf() );
p.vertex( point2.getXf(), point2.getYf() );
p.vertex( point3.getXf(), point3.getYf() );
p.endShape();
}
}
}
}
void doTriangulation() {
Polygon polygon = new Polygon(points);
// polygon.
try {
Poly2Tri.triangulate(polygon);
triangles = polygon.getTriangles();
// println("DT: " + triangles);
} catch(NullPointerException e) {
}
}
}
|
package com.jcwhatever.bukkit.generic.scripting.api;
import com.jcwhatever.bukkit.generic.GenericsLib;
import com.jcwhatever.bukkit.generic.GenericsPlugin;
import com.jcwhatever.bukkit.generic.scripting.IEvaluatedScript;
import com.jcwhatever.bukkit.generic.scripting.IScriptApiInfo;
import com.jcwhatever.bukkit.generic.utils.Scheduler;
import com.jcwhatever.bukkit.generic.utils.Scheduler.ScheduledTask;
import com.jcwhatever.bukkit.generic.utils.Scheduler.TaskHandler;
import com.jcwhatever.bukkit.generic.utils.TextUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@IScriptApiInfo(
variableName = "depends",
description = "Handle script plugin dependencies.")
public class ScriptApiDepends extends GenericsScriptApi {
private static ApiObject _api;
/**
* Constructor.
*
* @param plugin The owning plugin
*/
public ScriptApiDepends(Plugin plugin) {
super(plugin);
}
@Override
public IScriptApiObject getApiObject(IEvaluatedScript script) {
if (_api == null)
_api = new ApiObject();
return _api;
}
@Override
public void reset() {
if (_api == null)
return;
_api.reset();
}
public static class ApiObject implements IScriptApiObject {
private List<DependsWrapper> _wrappers = new ArrayList<>(10);
private ScheduledTask _task;
@Override
public void reset() {
if (_task != null)
_task.cancel();
_wrappers.clear();
}
/**
* Provide a runnable function to be run once the specified
* plugin is loaded.
*
* @param pluginName The name of the plugin or multiple comma delimited names.
* @param runnable The function to run.
*/
public void on(String pluginName, Runnable runnable) {
if (runDepends(pluginName, runnable))
return;
DependsWrapper wrapper = new DependsWrapper(pluginName, runnable);
_wrappers.add(wrapper);
if (_task == null || _task.isCancelled())
_task = Scheduler.runTaskRepeat(GenericsLib.getLib(), 20, 20, new DependsChecker());
}
/*
* Attempt to run runnable if dependency plugin is loaded.
*/
private boolean runDepends(String pluginNames, Runnable runnable) {
String[] names = TextUtils.PATTERN_COMMA.split(pluginNames);
for (String pluginName : names) {
Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName.trim());
if (plugin == null)
return false;
if (!plugin.isEnabled())
return false;
if (plugin instanceof GenericsPlugin && !((GenericsPlugin) plugin).isLoaded())
return false;
}
runnable.run();
return true;
}
private class DependsChecker extends TaskHandler {
@Override
public void run() {
if (_wrappers.isEmpty()) {
cancelTask();
return;
}
Iterator<DependsWrapper> iterator = _wrappers.iterator();
while (iterator.hasNext()) {
DependsWrapper wrapper = iterator.next();
if (wrapper.getTotalChecks() > 60 ||
runDepends(wrapper.getPluginName(), wrapper.getRunnable())) {
iterator.remove();
}
else {
wrapper.incrementCheck();
}
}
}
}
}
private static class DependsWrapper {
private final String _pluginName;
private final Runnable _runnable;
private int _totalChecks;
DependsWrapper(String pluginName, Runnable runnable) {
_pluginName = pluginName;
_runnable = runnable;
}
public int getTotalChecks() {
return _totalChecks;
}
public void incrementCheck() {
_totalChecks++;
}
public String getPluginName() {
return _pluginName;
}
public Runnable getRunnable() {
return _runnable;
}
}
}
|
package ir.parsoa.rippleview ;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.RelativeLayout;
public class RippleView extends View
{
private static final String DEBUG_TAG = "RippleView" ;
private int maxRadius = 80 ;
private float outerAlpha = 0 ;
private float innerAlpha = 0 ;
private float outerRadius = 0 ;
private float innerRadius = 0 ;
private int width ;
private int height ;
private int rippleColorID ;
private RippleViewCallback callback ;
private static final long RIPPLE_DURATION = 300 ;
private Path outerPath = new Path() ;
private Paint outerPaint;
private Path innerPath = new Path() ;
private Paint innerPaint ;
public static void DrawRippleAtPosition(Activity context , int rippleCenterX , int rippleCenterY ,
int rippleRadius , int colorID , ViewGroup rootLayout ,
RippleViewCallback callback)
{
RippleView rippleView = new RippleView(context , callback);
rippleView.setRippleRadius(rippleRadius);
rootLayout.addView(rippleView);
rippleView.init(rippleCenterX , rippleCenterY , colorID) ;
}
public static void DrawRippleAtPosition(Activity context , int rippleCenterX , int rippleCenterY ,
int colorID , ViewGroup rootLayout , RippleViewCallback callback)
{
RippleView rippleView = new RippleView(context , callback);
rootLayout.addView(rippleView);
rippleView.init(rippleCenterX , rippleCenterY , colorID) ;
}
public static void DrawRippleAtPosition(Activity context , View targetView , int colorID ,
ViewGroup rootLayout , RippleViewCallback callback)
{
RippleView rippleView = new RippleView(context , callback);
rootLayout.addView(rippleView);
int[] coordinates = new int[2] ;
targetView.getLocationInWindow(coordinates);
rippleView.init(coordinates[0] + targetView.getWidth() / 2,
coordinates[1] + targetView.getHeight() / 2 - getStatusBarHeight(context), colorID) ;
}
private static int getStatusBarHeight(Activity context)
{
Rect rectangle= new Rect();
Window window= context.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
return rectangle.top ;
}
public RippleView(Context context , RippleViewCallback callback)
{
super(context);
this.callback = callback ;
}
public void init(float rippleCenterX , float rippleCenterY , int color)
{
rippleColorID = color ;
init(rippleCenterX , rippleCenterY);
}
public void init(float rippleCenterX , float rippleCenterY)
{
outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
outerPaint.setAlpha(100);
innerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
innerPaint.setAlpha(100);
width = maxRadius * 2 ;
height = maxRadius * 2 ;
setX(rippleCenterX - width / 2);
setY(rippleCenterY - height / 2);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) getLayoutParams() ;
params.width = width ;
params.height = height ;
this.setLayoutParams(params);
startAnimation();
}
private void startAnimation()
{
OuterRippleAnimator outerRippleAnimator = new OuterRippleAnimator() ;
outerRippleAnimator.setDuration(RIPPLE_DURATION);
startAnimation(outerRippleAnimator);
InnerRippleAnimator innerRippleAnimator = new InnerRippleAnimator() ;
innerRippleAnimator.setAnimationListener(new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
((ViewGroup) getParent()).removeView(RippleView.this);
if(callback != null)
{
callback.onAnimationFinished();
}
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
});
innerRippleAnimator.setDuration(RIPPLE_DURATION);
innerRippleAnimator.setStartOffset(RIPPLE_DURATION / 4);
startAnimation(innerRippleAnimator);
}
private void setRadius(Paint paint , float radius , int color , float alphaFactor)
{
if(outerRadius > 0)
{
RadialGradient radialGradient = new RadialGradient(width / 2 , height / 2 , radius,
adjustAlpha(getResources().getColor(color), alphaFactor),
getResources().getColor(color), Shader.TileMode.MIRROR);
paint.setShader(radialGradient);
}
else
{
RadialGradient radialGradient = new RadialGradient(width / 2 , height / 2 , 1 ,
adjustAlpha(getResources().getColor(color), alphaFactor),
getResources().getColor(color), Shader.TileMode.MIRROR);
paint.setShader(radialGradient);
}
}
public int adjustAlpha(int color, float factor)
{
int alpha = Math.round(Color.alpha(color) * factor);
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return Color.argb(alpha, red, green, blue);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
outerPath.reset();
outerPath.addCircle(getWidth() / 2, getHeight() / 2, outerRadius, Path.Direction.CW);
canvas.clipPath(outerPath);
innerPath.reset();
innerPath.addCircle(getWidth() / 2, getHeight() / 2, innerRadius, Path.Direction.CW);
canvas.clipPath(innerPath);
canvas.restore() ;
canvas.drawCircle(getWidth() / 2, getHeight() / 2, outerRadius, outerPaint);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, innerRadius, innerPaint);
}
public class OuterRippleAnimator extends Animation
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
super.applyTransformation(interpolatedTime, t);
outerAlpha = interpolatedTime * 255.f ;
outerRadius = interpolatedTime * maxRadius ;
setRadius(outerPaint, outerRadius , rippleColorID , interpolatedTime);
invalidate();
}
@Override
public boolean willChangeBounds() {
return false;
}
@Override
public boolean willChangeTransformationMatrix() {
return false;
}
}
public class InnerRippleAnimator extends Animation
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
super.applyTransformation(interpolatedTime, t);
innerAlpha = interpolatedTime * 255.f ;
innerRadius = interpolatedTime * maxRadius ;
setRadius(innerPaint, innerRadius, rippleColorID , interpolatedTime);
invalidate();
}
@Override
public boolean willChangeBounds() {
return false;
}
@Override
public boolean willChangeTransformationMatrix() {
return false;
}
}
public void setRippleRadius(int radius)
{
maxRadius = radius ;
}
}
|
package som.interpreter.nodes;
import som.interpreter.SArguments;
import som.interpreter.TruffleCompiler;
import som.interpreter.TypesGen;
import som.interpreter.nodes.dispatch.AbstractDispatchNode;
import som.interpreter.nodes.dispatch.GenericDispatchNode;
import som.interpreter.nodes.dispatch.SuperDispatchNode;
import som.interpreter.nodes.dispatch.UninitializedDispatchNode;
import som.interpreter.nodes.literals.BlockNode;
import som.interpreter.nodes.specialized.IfFalseMessageNodeFactory;
import som.interpreter.nodes.specialized.IfTrueIfFalseMessageNodeFactory;
import som.interpreter.nodes.specialized.IfTrueMessageNodeFactory;
import som.interpreter.nodes.specialized.IntToDoMessageNodeFactory;
import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileFalseStaticBlocksNode;
import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileTrueStaticBlocksNode;
import som.vm.Universe;
import som.vmobjects.SBlock;
import som.vmobjects.SSymbol;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.NodeInfo;
public final class MessageSendNode {
public static AbstractMessageSendNode create(final SSymbol selector,
final ExpressionNode receiver, final ExpressionNode[] arguments) {
return new UninitializedMessageSendNode(selector, receiver, arguments);
}
@NodeInfo(shortName = "send")
public abstract static class AbstractMessageSendNode extends ExpressionNode
implements PreevaluatedExpression {
@Child protected ExpressionNode receiverNode;
@Children protected final ExpressionNode[] argumentNodes;
protected AbstractMessageSendNode(final ExpressionNode receiver,
final ExpressionNode[] arguments) {
this.receiverNode = adoptChild(receiver);
this.argumentNodes = adoptChildren(arguments);
}
@Override
public final Object executeGeneric(final VirtualFrame frame) {
Object rcvr = receiverNode.executeGeneric(frame);
Object[] arguments = evaluateArguments(frame);
return executeEvaluated(frame, rcvr, arguments);
}
@ExplodeLoop
private Object[] evaluateArguments(final VirtualFrame frame) {
Object[] arguments = new Object[argumentNodes.length];
for (int i = 0; i < argumentNodes.length; i++) {
arguments[i] = argumentNodes[i].executeGeneric(frame);
}
return arguments;
}
}
private static final class UninitializedMessageSendNode
extends AbstractMessageSendNode {
private final SSymbol selector;
protected UninitializedMessageSendNode(final SSymbol selector,
final ExpressionNode receiver, final ExpressionNode[] arguments) {
super(receiver, arguments);
this.selector = selector;
}
@Override
public Object executeEvaluated(final VirtualFrame frame,
final Object receiver, final Object[] arguments) {
return specialize(receiver, arguments).executeEvaluated(frame, receiver,
arguments);
}
private PreevaluatedExpression specialize(final Object receiver,
final Object[] arguments) {
TruffleCompiler.transferToInterpreterAndInvalidate("Specialize Message Node");
// first option is a super send, super sends are treated specially because
// the receiver class is lexically determined
if (receiverNode instanceof ISuperReadNode) {
GenericMessageSendNode node = new GenericMessageSendNode(selector,
receiverNode, argumentNodes, SuperDispatchNode.create(selector,
(ISuperReadNode) receiverNode));
return replace(node);
}
// We treat super sends separately for simplicity, might not be the
// optimal solution, especially in cases were the knowledge of the
// receiver class also allows us to do more specific things, but for the
// moment we will leave it at this.
// TODO: revisit, and also do more specific optimizations for super sends.
// let's organize the specializations by number of arguments
// perhaps not the best, but one simple way to just get some order into
// the chaos.
switch (argumentNodes.length) {
// case 0: return specializeUnary( receiver, arguments); // don't have any at the moment
case 1: return specializeBinary(receiver, arguments);
case 2: return specializeTernary(receiver, arguments);
}
return makeGenericSend();
}
private GenericMessageSendNode makeGenericSend() {
return new GenericMessageSendNode(selector, receiverNode, argumentNodes,
new UninitializedDispatchNode(selector, Universe.current()));
}
private PreevaluatedExpression specializeBinary(final Object receiver,
final Object[] arguments) {
switch (selector.getString()) {
case "whileTrue:": {
if (argumentNodes[0] instanceof BlockNode &&
receiverNode instanceof BlockNode) {
BlockNode argBlockNode = (BlockNode) argumentNodes[0];
SBlock argBlock = (SBlock) arguments[0];
return replace(new WhileTrueStaticBlocksNode(
(BlockNode) receiverNode, argBlockNode, (SBlock) receiver,
argBlock, Universe.current()));
}
break; // use normal send
}
case "whileFalse:":
if (argumentNodes[0] instanceof BlockNode &&
receiverNode instanceof BlockNode) {
BlockNode argBlockNode = (BlockNode) argumentNodes[0];
SBlock argBlock = (SBlock) arguments[0];
return replace(new WhileFalseStaticBlocksNode(
(BlockNode) receiverNode, argBlockNode,
(SBlock) receiver, argBlock, Universe.current()));
}
break; // use normal send
case "ifTrue:":
return replace(IfTrueMessageNodeFactory.create(receiver, arguments[0],
Universe.current(), receiverNode, argumentNodes[0]));
case "ifFalse:":
return replace(IfFalseMessageNodeFactory.create(receiver, arguments[0],
Universe.current(), receiverNode, argumentNodes[0]));
}
return makeGenericSend();
}
private PreevaluatedExpression specializeTernary(final Object receiver,
final Object[] arguments) {
switch (selector.getString()) {
case "ifTrue:ifFalse:":
return replace(IfTrueIfFalseMessageNodeFactory.create(receiver,
arguments[0], arguments[1], Universe.current(), receiverNode,
argumentNodes[0], argumentNodes[1]));
case "to:do:":
if (TypesGen.TYPES.isImplicitInteger(receiver) &&
TypesGen.TYPES.isImplicitInteger(arguments[0]) &&
TypesGen.TYPES.isSBlock(arguments[1])) {
return replace(IntToDoMessageNodeFactory.create(this,
(SBlock) arguments[1], receiverNode, argumentNodes[0],
argumentNodes[1]));
}
break;
}
return makeGenericSend();
}
}
public static final class GenericMessageSendNode
extends AbstractMessageSendNode {
@Child private AbstractDispatchNode dispatchNode;
private GenericMessageSendNode(final SSymbol selector,
final ExpressionNode receiver, final ExpressionNode[] arguments,
final AbstractDispatchNode dispatchNode) {
super(receiver, arguments);
this.dispatchNode = adoptChild(dispatchNode);
}
@Override
public Object executeEvaluated(final VirtualFrame frame,
final Object receiver, final Object[] arguments) {
SArguments args = new SArguments(receiver, arguments);
return dispatchNode.executeDispatch(frame, args);
}
public void replaceDispatchNodeBecauseCallSiteIsMegaMorphic(
final GenericDispatchNode replacement) {
dispatchNode.replace(replacement);
}
}
}
|
package soot.jimple.infoflow.data;
import java.util.LinkedList;
import soot.SootField;
import soot.Unit;
import soot.Value;
import soot.jimple.Stmt;
public class Abstraction implements Cloneable {
private final AccessPath accessPath;
private final Value source;
private final Stmt sourceContext;
private Unit activationUnit;
private Unit activationUnitOnCurrentLevel;
private boolean isActive = true;
private final boolean exceptionThrown;
private int hashCode;
private Abstraction abstractionFromCallEdge;
private DirectionChangeInfo directionChangeInfo;
public Abstraction(Value taint, Value src, Stmt srcContext, boolean exceptionThrown, boolean isActive, Unit activationUnit){
this.source = src;
this.accessPath = new AccessPath(taint);
this.activationUnit = activationUnit;
this.sourceContext = srcContext;
this.exceptionThrown = exceptionThrown;
this.isActive = isActive;
}
protected Abstraction(AccessPath p, Value src, Stmt srcContext, boolean exceptionThrown, boolean isActive){
this.source = src;
this.sourceContext = srcContext;
this.accessPath = p.clone();
this.activationUnit = null;
this.exceptionThrown = exceptionThrown;
this.isActive = isActive;
}
/**
* Creates an abstraction as a copy of an existing abstraction,
* only exchanging the access path.
* @param p The value to be used as the new access path
* @param original The original abstraction to copy
*/
public Abstraction(Value p, Abstraction original){
this(new AccessPath(p), original);
}
/**
* Creates an abstraction as a copy of an existing abstraction,
* only exchanging the access path. -> only used by AbstractionWithPath
* @param p The access path for the new abstraction
* @param original The original abstraction to copy
*/
public Abstraction(AccessPath p, Abstraction original){
if (original == null) {
source = null;
sourceContext = null;
}
else {
source = original.source;
sourceContext = original.sourceContext;
}
accessPath = p.clone();
exceptionThrown = original.exceptionThrown;
activationUnit = original.activationUnit;
activationUnitOnCurrentLevel = original.activationUnitOnCurrentLevel;
if(directionChangeInfo != null)
directionChangeInfo = original.directionChangeInfo.clone();
isActive = original.isActive;
}
public Abstraction deriveInactiveAbstraction(){
Abstraction a = clone();
a.isActive = false;
return a;
}
//should be only called by call-/returnFunctions!
public Abstraction deriveNewAbstraction(AccessPath p){
Abstraction a = new Abstraction(p.clone(), source, sourceContext, exceptionThrown, isActive);
a.abstractionFromCallEdge = abstractionFromCallEdge;
a.activationUnit = activationUnit;
a.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
if(directionChangeInfo != null)
a.directionChangeInfo = directionChangeInfo.clone();
return a;
}
public Abstraction deriveNewAbstraction(AccessPath p, Unit newActUnit){
Abstraction a = new Abstraction(p.clone(), source, sourceContext, exceptionThrown, isActive);
a.abstractionFromCallEdge = abstractionFromCallEdge;
if(isActive){
a.activationUnit = newActUnit;
}else{
a.activationUnit = activationUnit;
a.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
}
if(directionChangeInfo != null)
a.directionChangeInfo = directionChangeInfo.clone();
return a;
}
public Abstraction deriveNewAbstraction(AccessPath p, Unit srcUnit, boolean isActive){
Abstraction a = new Abstraction(p.clone(), source, sourceContext, exceptionThrown, isActive);
a.abstractionFromCallEdge = abstractionFromCallEdge;
if(isActive){
a.activationUnit = srcUnit;
}else{
a.activationUnit = activationUnit;
a.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
}
if(directionChangeInfo != null)
a.directionChangeInfo = directionChangeInfo.clone();
return a;
}
public Abstraction deriveNewAbstraction(Value taint, Unit activationUnit){
return this.deriveNewAbstraction(taint, false, activationUnit);
}
public Abstraction deriveNewAbstraction(Value taint, Unit srcUnit, boolean isActive){
return this.deriveNewAbstraction(taint, false, srcUnit, isActive);
}
public Abstraction deriveNewAbstraction(Value taint, boolean cutFirstField, Unit newActUnit){
return deriveNewAbstraction(taint, cutFirstField, newActUnit, isActive);
}
public Abstraction deriveNewAbstraction(Value taint, boolean cutFirstField, Unit newActUnit, boolean isActive){
Abstraction a;
LinkedList<SootField> tempList = new LinkedList<SootField>(accessPath.getFields());
if(cutFirstField){
tempList.removeFirst();
}
a = new Abstraction(new AccessPath(taint, tempList), source, sourceContext, exceptionThrown, isActive);
a.abstractionFromCallEdge = abstractionFromCallEdge;
if(directionChangeInfo != null)
a.directionChangeInfo = directionChangeInfo.clone();
if(isActive){
a.activationUnit = newActUnit;
}else{
a.activationUnit = activationUnit;
a.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
}
return a;
}
/**
* Derives a new abstraction that models the current local being thrown as
* an exception
* @return The newly derived abstraction
*/
public Abstraction deriveNewAbstractionOnThrow(){
assert !this.exceptionThrown;
Abstraction abs = new Abstraction(accessPath, source, sourceContext, true, isActive);
abs.abstractionFromCallEdge = abstractionFromCallEdge;
abs.activationUnit = activationUnit;
abs.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
if(directionChangeInfo != null)
abs.directionChangeInfo = directionChangeInfo.clone();
return abs;
}
/**
* Derives a new abstraction that models the current local being caught as
* an exception
* @param taint The value in which the tainted exception is stored
* @return The newly derived abstraction
*/
public Abstraction deriveNewAbstractionOnCatch(Value taint, Unit newActivationUnit){
assert this.exceptionThrown;
Abstraction abs = new Abstraction(new AccessPath(taint), source, sourceContext, false, isActive);
if(isActive){
abs.activationUnit = newActivationUnit;
}else{
abs.activationUnit = activationUnit;
abs.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
}
abs.abstractionFromCallEdge = abstractionFromCallEdge;
if(directionChangeInfo != null)
abs.directionChangeInfo = directionChangeInfo.clone();
return abs;
}
public Value getSource() {
return source;
}
public Stmt getSourceContext() {
return this.sourceContext;
}
public boolean isAbstractionActive(){
return isActive;
}
@Override
public String toString(){
if(accessPath != null && source != null){
return (isActive?"":"_")+accessPath.toString() + " | "+(activationUnit==null?"":activationUnit.toString()) + ">>"+ (activationUnitOnCurrentLevel==null?"":activationUnitOnCurrentLevel.toString());
}
if(accessPath != null){
return accessPath.toString();
}
return "Abstraction (null)";
}
public AccessPath getAccessPath(){
return accessPath;
}
public Unit getActivationUnit(){
return activationUnit;
}
public Abstraction getAbstractionWithNewActivationUnitOnCurrentLevel(Unit u){
Abstraction a = this.clone();
a.activationUnitOnCurrentLevel = u;
return a;
}
public Unit getActivationUnitOnCurrentLevel(){
return activationUnitOnCurrentLevel;
}
public Abstraction getAbstractionFromCallEdge(){
return abstractionFromCallEdge;
}
/**
* best-effort approach: if we are at level 0 and have not seen a call edge, we just take the abstraction which is imprecise
* null is not allowed
* @return
*/
public Abstraction getNotNullAbstractionFromCallEdge(){
if(abstractionFromCallEdge == null)
return this;
return abstractionFromCallEdge;
}
public void usePredAbstractionOfCG(){
if(abstractionFromCallEdge == null)
return;
abstractionFromCallEdge = abstractionFromCallEdge.abstractionFromCallEdge;
}
public void setAbstractionFromCallEdge(Abstraction abs){
abstractionFromCallEdge = abs;
}
public Abstraction getActiveCopy(boolean dropAbstractionFromCallEdge){
Abstraction a = clone();
a.isActive = true;
a.activationUnit = null;
a.activationUnitOnCurrentLevel = null;
if(dropAbstractionFromCallEdge){
if(a.abstractionFromCallEdge != null){
a.abstractionFromCallEdge = a.abstractionFromCallEdge.abstractionFromCallEdge;
}
}
return a;
}
/**
* Gets whether this value has been thrown as an exception
* @return True if this value has been thrown as an exception, otherwise
* false
*/
public boolean getExceptionThrown() {
return this.exceptionThrown;
}
@Override
public Abstraction clone(){
Abstraction a = new Abstraction(accessPath.clone(), source, sourceContext, exceptionThrown, isActive);
a.activationUnit = activationUnit;
a.activationUnitOnCurrentLevel = activationUnitOnCurrentLevel;
a.abstractionFromCallEdge = abstractionFromCallEdge;
if(directionChangeInfo != null)
a.directionChangeInfo = directionChangeInfo.clone();
return a;
}
public Abstraction cloneUsePredAbstractionOfCG(){
Abstraction a = clone();
if(a.abstractionFromCallEdge != null){
a.abstractionFromCallEdge = a.abstractionFromCallEdge.abstractionFromCallEdge;
}
return a;
}
public boolean isLoop(Unit u) {
if(directionChangeInfo == null)
return false;
return directionChangeInfo.isLoop(u, this);
}
public void setDirectionChange(Unit unitOfDirectionChange) {
this.directionChangeInfo = new DirectionChangeInfo();
directionChangeInfo.setUnitOfDirectionChange(unitOfDirectionChange);
directionChangeInfo.setAccessPathOfDirectionChange(accessPath);
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj))
return true;
if (obj == null || !(obj instanceof Abstraction))
return false;
Abstraction other = (Abstraction) obj;
if (accessPath == null) {
if (other.accessPath != null)
return false;
} else if (!accessPath.equals(other.accessPath))
return false;
if (source == null) {
if (other.source != null)
return false;
} else if (!source.equals(other.source))
return false;
if (sourceContext == null) {
if (other.sourceContext != null)
return false;
} else if (!sourceContext.equals(other.sourceContext))
return false;
// if (activationUnit == null) {
// if (other.activationUnit != null)
// return false;
// } else if (!activationUnit.equals(other.activationUnit))
// return false;
// if (activationUnitOnCurrentLevel == null) {
// if (other.activationUnitOnCurrentLevel != null)
// return false;
// } else if (!activationUnitOnCurrentLevel.equals(other.activationUnitOnCurrentLevel))
// return false;
if (this.exceptionThrown != other.exceptionThrown)
return false;
if(this.isActive != other.isActive)
return false;
assert this.hashCode() == obj.hashCode(); // make sure nothing all wonky is going on
return true;
}
@Override
public int hashCode() {
final int prime = 31;
if (this.hashCode == 0) {
this.hashCode = 1;
this.hashCode = prime * this.hashCode + ((accessPath == null) ? 0 : accessPath.hashCode());
this.hashCode = prime * this.hashCode + ((source == null) ? 0 : source.hashCode());
this.hashCode = prime * this.hashCode + ((sourceContext == null) ? 0 : sourceContext.hashCode());
// this.hashCode = prime * this.hashCode + ((activationUnit == null) ? 0 : activationUnit.hashCode());
// this.hashCode = prime * this.hashCode + ((activationUnitOnCurrentLevel == null) ? 0 : activationUnitOnCurrentLevel.hashCode());
this.hashCode = prime * this.hashCode + (exceptionThrown ? 1231 : 1237);
this.hashCode = prime * this.hashCode + (isActive ? 1231 : 1237);
}
return this.hashCode;
}
}
|
package soot.jimple.spark.solver;
import soot.jimple.spark.pag.*;
import soot.jimple.spark.sets.*;
import soot.*;
import soot.util.IdentityHashSet;
import soot.util.queue.*;
import java.util.*;
/** Propagates points-to sets along pointer assignment graph using a worklist.
* @author Ondrej Lhotak
*/
public final class PropWorklist extends Propagator {
protected final Set<VarNode> varNodeWorkList = new TreeSet<VarNode>();
public PropWorklist( PAG pag ) { this.pag = pag; }
/** Actually does the propagation. */
public final void propagate() {
ofcg = pag.getOnFlyCallGraph();
new TopoSorter( pag, false ).sort();
for (Object object : pag.allocSources()) {
handleAllocNode( (AllocNode) object );
}
boolean verbose = pag.getOpts().verbose();
do {
if( verbose ) {
G.v().out.println( "Worklist has "+varNodeWorkList.size()+
" nodes." );
}
while( !varNodeWorkList.isEmpty() ) {
VarNode src = varNodeWorkList.iterator().next();
varNodeWorkList.remove( src );
handleVarNode( src );
}
if( verbose ) {
G.v().out.println( "Now handling field references" );
}
for (Object object : pag.storeSources()) {
final VarNode src = (VarNode) object;
Node[] targets = pag.storeLookup( src );
for (Node element0 : targets) {
final FieldRefNode target = (FieldRefNode) element0;
target.getBase().makeP2Set().forall( new P2SetVisitor() {
public final void visit( Node n ) {
AllocDotField nDotF = pag.makeAllocDotField(
(AllocNode) n, target.getField() );
nDotF.makeP2Set().addAll( src.getP2Set(), null );
}
} );
}
}
HashSet<Object[]> edgesToPropagate = new HashSet<Object[]>();
for (Object object : pag.loadSources()) {
handleFieldRefNode( (FieldRefNode) object, edgesToPropagate );
}
IdentityHashSet<PointsToSetInternal> nodesToFlush = new IdentityHashSet<PointsToSetInternal>();
for (Object[] pair : edgesToPropagate) {
PointsToSetInternal nDotF = (PointsToSetInternal) pair[0];
PointsToSetInternal newP2Set = nDotF.getNewSet();
VarNode loadTarget = (VarNode) pair[1];
if( loadTarget.makeP2Set().addAll( newP2Set, null ) ) {
varNodeWorkList.add( loadTarget );
}
nodesToFlush.add( nDotF );
}
for (PointsToSetInternal nDotF : nodesToFlush) {
nDotF.flushNew();
}
} while( !varNodeWorkList.isEmpty() );
}
/* End of public methods. */
/* End of package methods. */
/** Propagates new points-to information of node src to all its
* successors. */
protected final boolean handleAllocNode( AllocNode src ) {
boolean ret = false;
Node[] targets = pag.allocLookup( src );
for (Node element : targets) {
if( element.makeP2Set().add( src ) ) {
varNodeWorkList.add( (VarNode) element );
ret = true;
}
}
return ret;
}
/** Propagates new points-to information of node src to all its
* successors. */
protected final boolean handleVarNode( final VarNode src ) {
boolean ret = false;
boolean flush = true;
if( src.getReplacement() != src ) throw new RuntimeException(
"Got bad node "+src+" with rep "+src.getReplacement() );
final PointsToSetInternal newP2Set = src.getP2Set().getNewSet();
if( newP2Set.isEmpty() ) return false;
if( ofcg != null ) {
QueueReader addedEdges = pag.edgeReader();
ofcg.updatedNode( src );
ofcg.build();
while(addedEdges.hasNext()) {
Node addedSrc = (Node) addedEdges.next();
Node addedTgt = (Node) addedEdges.next();
ret = true;
if( addedSrc instanceof VarNode ) {
if( addedTgt instanceof VarNode ) {
VarNode edgeSrc = (VarNode) addedSrc.getReplacement();
VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
if( edgeTgt.makeP2Set().addAll( edgeSrc.getP2Set(), null ) ) {
varNodeWorkList.add( edgeTgt );
if(edgeTgt == src) flush = false;
}
}
} else if( addedSrc instanceof AllocNode ) {
AllocNode edgeSrc = (AllocNode) addedSrc;
VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
if( edgeTgt.makeP2Set().add( edgeSrc ) ) {
varNodeWorkList.add( edgeTgt );
if(edgeTgt == src) flush = false;
}
}
}
}
Node[] simpleTargets = pag.simpleLookup( src );
for (Node element : simpleTargets) {
if( element.makeP2Set().addAll( newP2Set, null ) ) {
varNodeWorkList.add( (VarNode) element );
if(element == src) flush = false;
ret = true;
}
}
Node[] storeTargets = pag.storeLookup( src );
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
final SparkField f = fr.getField();
ret = fr.getBase().getP2Set().forall( new P2SetVisitor() {
public final void visit( Node n ) {
AllocDotField nDotF = pag.makeAllocDotField(
(AllocNode) n, f );
if( nDotF.makeP2Set().addAll( newP2Set, null ) ) {
returnValue = true;
}
}
} ) | ret;
}
final HashSet<Node[]> storesToPropagate = new HashSet<Node[]>();
final HashSet<Node[]> loadsToPropagate = new HashSet<Node[]>();
for( final FieldRefNode fr : src.getAllFieldRefs()) {
final SparkField field = fr.getField();
final Node[] storeSources = pag.storeInvLookup( fr );
if( storeSources.length > 0 ) {
newP2Set.forall( new P2SetVisitor() {
public final void visit( Node n ) {
AllocDotField nDotF = pag.makeAllocDotField(
(AllocNode) n, field );
for (Node element : storeSources) {
Node[] pair = { element,
nDotF.getReplacement() };
storesToPropagate.add( pair );
}
}
} );
}
final Node[] loadTargets = pag.loadLookup( fr );
if( loadTargets.length > 0 ) {
newP2Set.forall( new P2SetVisitor() {
public final void visit( Node n ) {
AllocDotField nDotF = pag.makeAllocDotField(
(AllocNode) n, field );
if( nDotF != null ) {
for (Node element : loadTargets) {
Node[] pair = { nDotF.getReplacement(),
element };
loadsToPropagate.add( pair );
}
}
}
} );
}
}
if(flush) src.getP2Set().flushNew();
for (Node[] p : storesToPropagate) {
VarNode storeSource = (VarNode) p[0];
AllocDotField nDotF = (AllocDotField) p[1];
if( nDotF.makeP2Set().addAll( storeSource.getP2Set(), null ) ) {
ret = true;
}
}
for (Node[] p : loadsToPropagate) {
AllocDotField nDotF = (AllocDotField) p[0];
VarNode loadTarget = (VarNode) p[1];
if( loadTarget.makeP2Set().
addAll( nDotF.getP2Set(), null ) ) {
varNodeWorkList.add( loadTarget );
ret = true;
}
}
return ret;
}
/** Propagates new points-to information of node src to all its
* successors. */
protected final void handleFieldRefNode( FieldRefNode src,
final HashSet<Object[]> edgesToPropagate ) {
final Node[] loadTargets = pag.loadLookup( src );
if( loadTargets.length == 0 ) return;
final SparkField field = src.getField();
src.getBase().getP2Set().forall( new P2SetVisitor() {
public final void visit( Node n ) {
AllocDotField nDotF = pag.makeAllocDotField(
(AllocNode) n, field );
if( nDotF != null ) {
PointsToSetInternal p2Set = nDotF.getP2Set();
if( !p2Set.getNewSet().isEmpty() ) {
for (Node element : loadTargets) {
Object[] pair = { p2Set, element };
edgesToPropagate.add( pair );
}
}
}
}
} );
}
protected PAG pag;
protected OnFlyCallGraph ofcg;
}
|
package org.wikipedia.page;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.BackPressedHandler;
import org.wikipedia.Constants;
import org.wikipedia.Constants.InvokeSource;
import org.wikipedia.LongPressHandler;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.analytics.FindInPageFunnel;
import org.wikipedia.analytics.GalleryFunnel;
import org.wikipedia.analytics.LoginFunnel;
import org.wikipedia.analytics.PageScrollFunnel;
import org.wikipedia.analytics.TabFunnel;
import org.wikipedia.auth.AccountUtil;
import org.wikipedia.bridge.CommunicationBridge;
import org.wikipedia.bridge.JavaScriptActionHandler;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.okhttp.OkHttpWebViewClient;
import org.wikipedia.descriptions.DescriptionEditActivity;
import org.wikipedia.descriptions.DescriptionEditTutorialActivity;
import org.wikipedia.edit.EditHandler;
import org.wikipedia.gallery.GalleryActivity;
import org.wikipedia.history.HistoryEntry;
import org.wikipedia.history.UpdateHistoryTask;
import org.wikipedia.language.LangLinksActivity;
import org.wikipedia.login.LoginActivity;
import org.wikipedia.media.AvPlayer;
import org.wikipedia.media.DefaultAvPlayer;
import org.wikipedia.media.MediaPlayerImplementation;
import org.wikipedia.page.action.PageActionTab;
import org.wikipedia.page.leadimages.LeadImagesHandler;
import org.wikipedia.page.leadimages.PageHeaderView;
import org.wikipedia.page.shareafact.ShareHandler;
import org.wikipedia.page.tabs.Tab;
import org.wikipedia.readinglist.ReadingListBookmarkMenu;
import org.wikipedia.readinglist.database.ReadingListDbHelper;
import org.wikipedia.readinglist.database.ReadingListPage;
import org.wikipedia.settings.Prefs;
import org.wikipedia.suggestededits.SuggestedEditsSummary;
import org.wikipedia.util.ActiveTimer;
import org.wikipedia.util.AnimationUtil;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ShareUtil;
import org.wikipedia.util.StringUtil;
import org.wikipedia.util.ThrowableUtil;
import org.wikipedia.util.UriUtil;
import org.wikipedia.util.log.L;
import org.wikipedia.views.ObservableWebView;
import org.wikipedia.views.SwipeRefreshLayoutWithScroll;
import org.wikipedia.views.WikiPageErrorView;
import java.util.Date;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import static android.app.Activity.RESULT_OK;
import static org.wikipedia.Constants.ACTIVITY_REQUEST_GALLERY;
import static org.wikipedia.Constants.InvokeSource.BOOKMARK_BUTTON;
import static org.wikipedia.Constants.InvokeSource.PAGE_ACTIVITY;
import static org.wikipedia.descriptions.DescriptionEditTutorialActivity.DESCRIPTION_SELECTED_TEXT;
import static org.wikipedia.page.PageActivity.ACTION_RESUME_READING;
import static org.wikipedia.page.PageCacher.loadIntoCache;
import static org.wikipedia.settings.Prefs.getTextSizeMultiplier;
import static org.wikipedia.settings.Prefs.isDescriptionEditTutorialEnabled;
import static org.wikipedia.settings.Prefs.isLinkPreviewEnabled;
import static org.wikipedia.util.DimenUtil.getContentTopOffset;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
import static org.wikipedia.util.DimenUtil.leadImageHeightForDevice;
import static org.wikipedia.util.ResourceUtil.getThemedAttributeId;
import static org.wikipedia.util.ResourceUtil.getThemedColor;
import static org.wikipedia.util.StringUtil.addUnderscores;
import static org.wikipedia.util.ThrowableUtil.isOffline;
import static org.wikipedia.util.UriUtil.decodeURL;
import static org.wikipedia.util.UriUtil.visitInExternalBrowser;
public class PageFragment extends Fragment implements BackPressedHandler {
public interface Callback {
void onPageShowBottomSheet(@NonNull BottomSheetDialog dialog);
void onPageShowBottomSheet(@NonNull BottomSheetDialogFragment dialog);
void onPageDismissBottomSheet();
void onPageLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry);
void onPageInitWebView(@NonNull ObservableWebView v);
void onPageShowLinkPreview(@NonNull HistoryEntry entry);
void onPageLoadMainPageInForegroundTab();
void onPageUpdateProgressBar(boolean visible, boolean indeterminate, int value);
void onPageShowThemeChooser();
void onPageStartSupportActionMode(@NonNull ActionMode.Callback callback);
void onPageHideSoftKeyboard();
void onPageAddToReadingList(@NonNull PageTitle title, @NonNull InvokeSource source);
void onPageRemoveFromReadingLists(@NonNull PageTitle title);
void onPageLoadError(@NonNull PageTitle title);
void onPageLoadErrorBackPressed();
void onPageHideAllContent();
void onPageSetToolbarFadeEnabled(boolean enabled);
void onPageSetToolbarElevationEnabled(boolean enabled);
}
private boolean pageRefreshed;
private boolean errorState = false;
private static final int REFRESH_SPINNER_ADDITIONAL_OFFSET = (int) (16 * DimenUtil.getDensityScalar());
private PageFragmentLoadState pageFragmentLoadState;
private PageViewModel model;
@NonNull private TabFunnel tabFunnel = new TabFunnel();
private PageScrollFunnel pageScrollFunnel;
private LeadImagesHandler leadImagesHandler;
private PageHeaderView pageHeaderView;
private ObservableWebView webView;
private CoordinatorLayout containerView;
private SwipeRefreshLayoutWithScroll refreshView;
private WikiPageErrorView errorView;
private PageActionTabLayout tabLayout;
private ToCHandler tocHandler;
private WebViewScrollTriggerListener scrollTriggerListener = new WebViewScrollTriggerListener();
private CommunicationBridge bridge;
private LinkHandler linkHandler;
private EditHandler editHandler;
private ActionMode findInPageActionMode;
private ShareHandler shareHandler;
private CompositeDisposable disposables = new CompositeDisposable();
private ActiveTimer activeTimer = new ActiveTimer();
@Nullable private AvPlayer avPlayer;
@Nullable private AvCallback avCallback;
private WikipediaApp app;
@NonNull
private final SwipeRefreshLayout.OnRefreshListener pageRefreshListener = this::refreshPage;
private PageActionTab.Callback pageActionTabsCallback = new PageActionTab.Callback() {
@Override
public void onAddToReadingListTabSelected() {
Prefs.shouldShowBookmarkToolTip(false);
if (model.isInReadingList()) {
new ReadingListBookmarkMenu(tabLayout, new ReadingListBookmarkMenu.Callback() {
@Override
public void onAddRequest(@Nullable ReadingListPage page) {
addToReadingList(getTitle(), BOOKMARK_BUTTON);
}
@Override
public void onDeleted(@Nullable ReadingListPage page) {
if (callback() != null) {
callback().onPageRemoveFromReadingLists(getTitle());
}
}
@Override
public void onShare() {
// ignore
}
}).show(getTitle());
} else {
addToReadingList(getTitle(), BOOKMARK_BUTTON);
}
}
@Override
public void onSharePageTabSelected() {
sharePageLink();
}
@Override
public void onChooseLangTabSelected() {
startLangLinksActivity();
}
@Override
public void onFindInPageTabSelected() {
showFindInPage();
}
@Override
public void onFontAndThemeTabSelected() {
showThemeChooser();
}
@Override
public void onViewToCTabSelected() {
tocHandler.show();
}
@Override
public void updateBookmark(boolean pageSaved) {
setBookmarkIconForPageSavedState(pageSaved);
}
};
public ObservableWebView getWebView() {
return webView;
}
public PageTitle getTitle() {
return model.getTitle();
}
@Nullable public PageTitle getTitleOriginal() {
return model.getTitleOriginal();
}
@NonNull public ShareHandler getShareHandler() {
return shareHandler;
}
@Nullable public Page getPage() {
return model.getPage();
}
public HistoryEntry getHistoryEntry() {
return model.getCurEntry();
}
public EditHandler getEditHandler() {
return editHandler;
}
public ViewGroup getContainerView() {
return containerView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AnimationUtil.setSharedElementTransitions(requireActivity());
app = (WikipediaApp) requireActivity().getApplicationContext();
model = new PageViewModel();
pageFragmentLoadState = new PageFragmentLoadState();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
pageHeaderView = rootView.findViewById(R.id.page_header_view);
DimenUtil.setViewHeight(pageHeaderView, leadImageHeightForDevice());
webView = rootView.findViewById(R.id.page_web_view);
initWebViewListeners();
containerView = rootView.findViewById(R.id.page_contents_container);
refreshView = rootView.findViewById(R.id.page_refresh_container);
int swipeOffset = getContentTopOffsetPx(requireActivity()) + REFRESH_SPINNER_ADDITIONAL_OFFSET;
refreshView.setProgressViewOffset(false, -swipeOffset, swipeOffset);
refreshView.setColorSchemeResources(getThemedAttributeId(requireContext(), R.attr.colorAccent));
refreshView.setScrollableChild(webView);
refreshView.setOnRefreshListener(pageRefreshListener);
tabLayout = rootView.findViewById(R.id.page_actions_tab_layout);
tabLayout.setPageActionTabsCallback(pageActionTabsCallback);
errorView = rootView.findViewById(R.id.page_error);
return rootView;
}
@Override
public void onDestroyView() {
if (avPlayer != null) {
avPlayer.deinit();
avPlayer = null;
}
//uninitialize the bridge, so that no further JS events can have any effect.
bridge.cleanup();
tocHandler.log();
shareHandler.dispose();
leadImagesHandler.dispose();
disposables.clear();
webView.clearAllListeners();
((ViewGroup) webView.getParent()).removeView(webView);
webView = null;
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
app.getRefWatcher().watch(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
if (callback() != null) {
callback().onPageInitWebView(webView);
}
updateFontSize();
// Explicitly set background color of the WebView (independently of CSS, because
// the background may be shown momentarily while the WebView loads content,
// creating a seizure-inducing effect, or at the very least, a migraine with aura).
webView.setBackgroundColor(getThemedColor(requireActivity(), R.attr.paper_color));
bridge = new CommunicationBridge(webView);
setupMessageHandlers();
sendDecorOffsetMessage();
errorView.setRetryClickListener((v) -> refreshPage());
errorView.setBackClickListener((v) -> {
boolean back = onBackPressed();
// Needed if we're coming from another activity or fragment
if (!back && callback() != null) {
// noinspection ConstantConditions
callback().onPageLoadErrorBackPressed();
}
});
editHandler = new EditHandler(this, bridge);
pageFragmentLoadState.setEditHandler(editHandler);
tocHandler = new ToCHandler(this, requireActivity().getWindow().getDecorView().findViewById(R.id.toc_container),
requireActivity().getWindow().getDecorView().findViewById(R.id.page_scroller_button), bridge);
// TODO: initialize View references in onCreateView().
leadImagesHandler = new LeadImagesHandler(this, bridge, webView, pageHeaderView);
shareHandler = new ShareHandler(this, bridge);
if (callback() != null) {
new LongPressHandler(webView, HistoryEntry.SOURCE_INTERNAL_LINK, new PageContainerLongPressHandler(this));
}
pageFragmentLoadState.setUp(model, this, refreshView, webView, bridge, leadImagesHandler, getCurrentTab());
if (shouldLoadFromBackstack(requireActivity()) || savedInstanceState != null) {
reloadFromBackstack();
}
}
public void reloadFromBackstack() {
pageFragmentLoadState.setTab(getCurrentTab());
if (!pageFragmentLoadState.backStackEmpty()) {
pageFragmentLoadState.loadFromBackStack();
} else {
loadMainPageInForegroundTab();
}
}
void setToolbarFadeEnabled(boolean enabled) {
if (callback() != null) {
callback().onPageSetToolbarFadeEnabled(enabled);
}
}
private boolean shouldLoadFromBackstack(@NonNull Activity activity) {
return activity.getIntent() != null
&& (ACTION_RESUME_READING.equals(activity.getIntent().getAction())
|| activity.getIntent().hasExtra(Constants.INTENT_APP_SHORTCUT_CONTINUE_READING));
}
private void initWebViewListeners() {
webView.addOnUpOrCancelMotionEventListener(() -> {
// update our session, since it's possible for the user to remain on the page for
// a long time, and we wouldn't want the session to time out.
app.getSessionFunnel().touchSession();
});
webView.addOnScrollChangeListener((int oldScrollY, int scrollY, boolean isHumanScroll) -> {
if (pageScrollFunnel != null) {
pageScrollFunnel.onPageScrolled(oldScrollY, scrollY, isHumanScroll);
}
});
webView.addOnContentHeightChangedListener(scrollTriggerListener);
webView.setWebViewClient(new OkHttpWebViewClient() {
@NonNull @Override public PageViewModel getModel() {
return model;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!isAdded()) {
return;
}
bridge.onPageFinished();
updateProgressBar(false, true, 0);
bridge.execute(JavaScriptActionHandler.setMulti(requireContext(), app.getCurrentTheme().getFunnelName().toUpperCase(), app.getCurrentTheme().isDark() && Prefs.shouldDimDarkModeImages(), Prefs.isCollapseTablesEnabled()));
}
});
}
private void handleInternalLink(@NonNull PageTitle title) {
if (!isResumed()) {
return;
}
// If it's a Special page, launch it in an external browser, since mobileview
// doesn't support the Special namespace.
// TODO: remove when Special pages are properly returned by the server
// If this is a Talk page also show in external browser since we don't handle those pages
// in the app very well at this time.
if (title.isSpecial() || title.isTalkPage()) {
visitInExternalBrowser(requireActivity(), Uri.parse(title.getMobileUri()));
return;
}
dismissBottomSheet();
HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK);
if (model.getTitle() != null) {
historyEntry.setReferrer(model.getTitle().getCanonicalUri());
}
if (title.namespace() != Namespace.MAIN || !isLinkPreviewEnabled()) {
loadPage(title, historyEntry);
} else {
Callback callback = callback();
if (callback != null) {
callback.onPageShowLinkPreview(historyEntry);
}
}
}
@Override
public void onPause() {
super.onPause();
activeTimer.pause();
addTimeSpentReading(activeTimer.getElapsedSec());
pageFragmentLoadState.updateCurrentBackStackItem();
app.commitTabState();
closePageScrollFunnel();
long time = app.getTabList().size() >= 1 && !pageFragmentLoadState.backStackEmpty()
? System.currentTimeMillis()
: 0;
Prefs.pageLastShown(time);
}
@Override
public void onResume() {
super.onResume();
initPageScrollFunnel();
activeTimer.resume();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
sendDecorOffsetMessage();
// if the screen orientation changes, then re-layout the lead image container,
// but only if we've finished fetching the page.
if (!pageFragmentLoadState.isLoading() && !errorState) {
pageFragmentLoadState.layoutLeadImage();
}
}
public Tab getCurrentTab() {
return app.getTabList().get(app.getTabList().size() - 1);
}
private void setCurrentTabAndReset(int position) {
// move the selected tab to the bottom of the list, and navigate to it!
// (but only if it's a different tab than the one currently in view!
if (position < app.getTabList().size() - 1) {
Tab tab = app.getTabList().remove(position);
app.getTabList().add(tab);
pageFragmentLoadState.setTab(tab);
}
if (app.getTabCount() > 0) {
app.getTabList().get(app.getTabList().size() - 1).squashBackstack();
pageFragmentLoadState.loadFromBackStack();
}
}
public void openInNewBackgroundTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
if (app.getTabCount() == 0) {
openInNewTab(title, entry, getForegroundTabPosition());
pageFragmentLoadState.loadFromBackStack();
} else {
openInNewTab(title, entry, getBackgroundTabPosition());
((PageActivity) requireActivity()).animateTabsButton();
}
}
public void openInNewForegroundTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
openInNewTab(title, entry, getForegroundTabPosition());
pageFragmentLoadState.loadFromBackStack();
}
private void openInNewTab(@NonNull PageTitle title, @NonNull HistoryEntry entry, int position) {
int selectedTabPosition = -1;
for (Tab tab : app.getTabList()) {
if (tab.getBackStackPositionTitle() != null && tab.getBackStackPositionTitle().equals(title)) {
selectedTabPosition = app.getTabList().indexOf(tab);
break;
}
}
if (selectedTabPosition >= 0) {
setCurrentTabAndReset(selectedTabPosition);
return;
}
tabFunnel.logOpenInNew(app.getTabList().size());
if (shouldCreateNewTab()) {
// create a new tab
Tab tab = new Tab();
boolean isForeground = position == getForegroundTabPosition();
// if the requested position is at the top, then make its backstack current
if (isForeground) {
pageFragmentLoadState.setTab(tab);
}
// put this tab in the requested position
app.getTabList().add(position, tab);
trimTabCount();
// add the requested page to its backstack
tab.getBackStack().add(new PageBackStackItem(title, entry));
if (!isForeground) {
loadIntoCache(title);
}
requireActivity().invalidateOptionsMenu();
} else {
getCurrentTab().getBackStack().add(new PageBackStackItem(title, entry));
}
}
public void openFromExistingTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
// find the tab in which this title appears...
int selectedTabPosition = -1;
for (Tab tab : app.getTabList()) {
if (tab.getBackStackPositionTitle() != null && tab.getBackStackPositionTitle().equals(title)) {
selectedTabPosition = app.getTabList().indexOf(tab);
break;
}
}
if (selectedTabPosition == -1) {
loadPage(title, entry, true, true);
return;
}
setCurrentTabAndReset(selectedTabPosition);
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, boolean pushBackStack, boolean squashBackstack) {
//is the new title the same as what's already being displayed?
if (!getCurrentTab().getBackStack().isEmpty()
&& getCurrentTab().getBackStack().get(getCurrentTab().getBackStackPosition()).getTitle().equals(title)) {
if (model.getPage() == null) {
pageFragmentLoadState.loadFromBackStack();
} else if (!TextUtils.isEmpty(title.getFragment())) {
scrollToSection(title.getFragment());
}
return;
}
if (squashBackstack) {
if (app.getTabCount() > 0) {
app.getTabList().get(app.getTabList().size() - 1).clearBackstack();
}
}
loadPage(title, entry, pushBackStack, 0);
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry,
boolean pushBackStack, int stagedScrollY) {
loadPage(title, entry, pushBackStack, stagedScrollY, false);
}
/**
* Load a new page into the WebView in this fragment.
* This shall be the single point of entry for loading content into the WebView, whether it's
* loading an entirely new page, refreshing the current page, retrying a failed network
* request, etc.
* @param title Title of the new page to load.
* @param entry HistoryEntry associated with the new page.
* @param pushBackStack Whether to push the new page onto the backstack.
*/
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry,
boolean pushBackStack, int stagedScrollY, boolean isRefresh) {
// clear the title in case the previous page load had failed.
clearActivityActionBarTitle();
// update the time spent reading of the current page, before loading the new one
addTimeSpentReading(activeTimer.getElapsedSec());
activeTimer.reset();
// disable sliding of the ToC while sections are loading
tocHandler.setEnabled(false);
errorState = false;
errorView.setVisibility(View.GONE);
tabLayout.enableAllTabs();
model.setTitle(title);
model.setTitleOriginal(title);
model.setCurEntry(entry);
model.setReadingListPage(null);
model.setForceNetwork(isRefresh);
updateProgressBar(true, true, 0);
this.pageRefreshed = isRefresh;
closePageScrollFunnel();
pageFragmentLoadState.load(pushBackStack);
scrollTriggerListener.setStagedScrollY(stagedScrollY);
updateBookmarkAndMenuOptions();
}
public Bitmap getLeadImageBitmap() {
return leadImagesHandler.getLeadImageBitmap();
}
/**
* Update the WebView's font size, based on the specified font size multiplier from the app
* preferences. The default text zoom starts from 100, which is by percentage.
*/
@SuppressWarnings("checkstyle:magicnumber")
public void updateFontSize() {
webView.getSettings().setTextZoom(100 + getTextSizeMultiplier() * 10);
}
public void updateBookmarkAndMenuOptions() {
if (!isAdded()) {
return;
}
pageActionTabsCallback.updateBookmark(model.isInReadingList());
requireActivity().invalidateOptionsMenu();
}
public void updateBookmarkAndMenuOptionsFromDao() {
disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageInAnyList(getTitle())).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally(() -> {
pageActionTabsCallback.updateBookmark(model.getReadingListPage() != null);
requireActivity().invalidateOptionsMenu();
})
.subscribe(page -> model.setReadingListPage(page),
throwable -> model.setReadingListPage(null)));
}
public void onActionModeShown(ActionMode mode) {
// make sure we have a page loaded, since shareHandler makes references to it.
if (model.getPage() != null) {
shareHandler.onTextSelected(mode);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.ACTIVITY_REQUEST_EDIT_SECTION
&& resultCode == EditHandler.RESULT_REFRESH_PAGE) {
pageFragmentLoadState.backFromEditing(data);
FeedbackUtil.showMessage(requireActivity(), R.string.edit_saved_successfully);
// and reload the page...
loadPage(model.getTitleOriginal(), model.getCurEntry(), false, false);
} else if (requestCode == Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL
&& resultCode == RESULT_OK) {
Prefs.setDescriptionEditTutorialEnabled(false);
startDescriptionEditActivity(data.getStringExtra(DESCRIPTION_SELECTED_TEXT));
} else if (requestCode == Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT
&& resultCode == RESULT_OK) {
refreshPage();
FeedbackUtil.showMessage(requireActivity(), R.string.description_edit_success_saved_snackbar);
}
}
public void sharePageLink() {
if (getPage() != null) {
ShareUtil.shareText(requireActivity(), getPage().getTitle());
}
}
@NonNull public ViewGroup getTabLayout() {
return tabLayout;
}
public View getHeaderView() {
return pageHeaderView;
}
public void showFindInPage() {
if (model.getPage() == null) {
return;
}
final FindInPageFunnel funnel = new FindInPageFunnel(app, model.getTitle().getWikiSite(),
model.getPage().getPageProperties().getPageId());
final FindInWebPageActionProvider findInPageActionProvider
= new FindInWebPageActionProvider(this, funnel);
startSupportActionMode(new ActionMode.Callback() {
private final String actionModeTag = "actionModeFindInPage";
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
findInPageActionMode = mode;
MenuItem menuItem = menu.add(R.string.menu_page_find_in_page);
menuItem.setActionProvider(findInPageActionProvider);
menuItem.expandActionView();
setToolbarElevationEnabled(false);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mode.setTag(actionModeTag);
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
if (webView == null || !isAdded()) {
return;
}
findInPageActionMode = null;
funnel.setPageHeight(webView.getContentHeight());
funnel.logDone();
webView.clearMatches();
hideSoftKeyboard();
setToolbarElevationEnabled(true);
}
});
}
public boolean closeFindInPage() {
if (findInPageActionMode != null) {
findInPageActionMode.finish();
return true;
}
return false;
}
/**
* Scroll to a specific section in the WebView.
* @param sectionAnchor Anchor link of the section to scroll to.
*/
public void scrollToSection(@NonNull String sectionAnchor) {
if (!isAdded() || tocHandler == null) {
return;
}
tocHandler.scrollToSection(sectionAnchor);
}
public void onPageLoadComplete() {
refreshView.setEnabled(true);
requireActivity().invalidateOptionsMenu();
setupToC(model, pageFragmentLoadState.isFirstPage());
editHandler.setPage(model.getPage());
initPageScrollFunnel();
if (model.getReadingListPage() != null) {
final ReadingListPage page = model.getReadingListPage();
final PageTitle title = model.getTitle();
disposables.add(Completable.fromAction(() -> {
if (!TextUtils.equals(page.thumbUrl(), title.getThumbUrl())
|| !TextUtils.equals(page.description(), title.getDescription())) {
page.thumbUrl(title.getThumbUrl());
page.description(title.getDescription());
ReadingListDbHelper.instance().updatePage(page);
}
}).subscribeOn(Schedulers.io()).subscribe());
}
checkAndShowBookmarkOnboarding();
}
public void onPageLoadError(@NonNull Throwable caught) {
if (!isAdded()) {
return;
}
updateProgressBar(false, true, 0);
refreshView.setRefreshing(false);
if (pageRefreshed) {
pageRefreshed = false;
}
hidePageContent();
errorView.setError(caught);
errorView.setVisibility(View.VISIBLE);
View contentTopOffset = errorView.findViewById(R.id.view_wiki_error_article_content_top_offset);
View tabLayoutOffset = errorView.findViewById(R.id.view_wiki_error_article_tab_layout_offset);
contentTopOffset.setLayoutParams(getContentTopOffsetParams(requireContext()));
contentTopOffset.setVisibility(View.VISIBLE);
tabLayoutOffset.setLayoutParams(getTabLayoutOffsetParams());
tabLayoutOffset.setVisibility(View.VISIBLE);
disableActionTabs(caught);
refreshView.setEnabled(!ThrowableUtil.is404(caught));
errorState = true;
if (callback() != null) {
callback().onPageLoadError(getTitle());
}
}
public void refreshPage() {
refreshPage(0);
}
public void refreshPage(int stagedScrollY) {
if (pageFragmentLoadState.isLoading()) {
refreshView.setRefreshing(false);
return;
}
errorView.setVisibility(View.GONE);
tabLayout.enableAllTabs();
errorState = false;
model.setCurEntry(new HistoryEntry(model.getTitle(), HistoryEntry.SOURCE_HISTORY));
loadPage(model.getTitle(), model.getCurEntry(), false, stagedScrollY, app.isOnline());
}
boolean isLoading() {
return pageFragmentLoadState.isLoading();
}
CommunicationBridge getBridge() {
return bridge;
}
private void setupToC(@NonNull PageViewModel model, boolean isFirstPage) {
tocHandler.setupToC(model.getPage(), model.getTitle().getWikiSite(), isFirstPage);
tocHandler.setEnabled(true);
}
private void setBookmarkIconForPageSavedState(boolean pageSaved) {
View bookmarkTab = tabLayout.getChildAt(PageActionTab.ADD_TO_READING_LIST.code());
if (bookmarkTab != null) {
((ImageView) bookmarkTab).setImageResource(pageSaved ? R.drawable.ic_bookmark_white_24dp
: R.drawable.ic_bookmark_border_white_24dp);
}
}
protected void clearActivityActionBarTitle() {
FragmentActivity currentActivity = requireActivity();
if (currentActivity instanceof PageActivity) {
((PageActivity) currentActivity).clearActionBarTitle();
}
}
private boolean shouldCreateNewTab() {
return !getCurrentTab().getBackStack().isEmpty();
}
private int getBackgroundTabPosition() {
return Math.max(0, getForegroundTabPosition() - 1);
}
private int getForegroundTabPosition() {
return app.getTabList().size();
}
private void setupMessageHandlers() {
linkHandler = new LinkHandler(requireActivity()) {
@Override public void onPageLinkClicked(@NonNull String anchor, @NonNull String linkText) {
dismissBottomSheet();
JSONObject payload = new JSONObject();
try {
payload.put("anchor", anchor);
payload.put("text", linkText);
} catch (JSONException e) {
throw new RuntimeException(e);
}
bridge.sendMessage("handleReference", payload);
}
@Override public void onInternalLinkClicked(@NonNull PageTitle title) {
handleInternalLink(title);
}
@Override public WikiSite getWikiSite() {
return model.getTitle().getWikiSite();
}
};
bridge.addListener("link_clicked", linkHandler);
bridge.addListener("reference_clicked", new ReferenceHandler() {
@Override
protected void onReferenceClicked(int selectedIndex, @NonNull List<Reference> adjacentReferences) {
if (!isAdded()) {
L.d("Detached from activity, so stopping reference click.");
return;
}
showBottomSheet(new ReferenceDialog(requireActivity(), selectedIndex, adjacentReferences, linkHandler));
}
});
bridge.addListener("image_clicked", (String messageType, JSONObject messagePayload) -> {
try {
String href = decodeURL(messagePayload.getString("src"));
if (href.startsWith("/wiki/")) {
String filename = UriUtil.removeInternalLinkPrefix(href);
String fileUrl = null;
// Set the lead image url manually if the filename equals to the lead image file name.
if (getPage() != null && !TextUtils.isEmpty(getPage().getPageProperties().getLeadImageName())) {
String leadImageName = addUnderscores(getPage().getPageProperties().getLeadImageName());
String leadImageUrl = getPage().getPageProperties().getLeadImageUrl();
if (filename.contains(leadImageName) && leadImageUrl != null) {
fileUrl = UriUtil.resolveProtocolRelativeUrl(leadImageUrl);
}
}
WikiSite wiki = model.getTitle().getWikiSite();
requireActivity().startActivityForResult(GalleryActivity.newIntent(requireActivity(),
model.getTitleOriginal(), filename, fileUrl, wiki,
GalleryFunnel.SOURCE_NON_LEAD_IMAGE),
ACTIVITY_REQUEST_GALLERY);
} else {
linkHandler.onUrlClick(href, messagePayload.optString("title"), "");
}
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
});
bridge.addListener("media_clicked", (String messageType, JSONObject messagePayload) -> {
try {
String href = decodeURL(messagePayload.getString("href"));
String filename = StringUtil.removeUnderscores(UriUtil.removeInternalLinkPrefix(href));
WikiSite wiki = model.getTitle().getWikiSite();
requireActivity().startActivityForResult(GalleryActivity.newIntent(requireActivity(),
model.getTitleOriginal(), filename, wiki,
GalleryFunnel.SOURCE_NON_LEAD_IMAGE),
ACTIVITY_REQUEST_GALLERY);
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
});
bridge.addListener("pronunciation_clicked", (String messageType, JSONObject messagePayload) -> {
if (avPlayer == null) {
avPlayer = new DefaultAvPlayer(new MediaPlayerImplementation());
avPlayer.init();
}
if (avCallback == null) {
avCallback = new AvCallback();
}
if (!avPlayer.isPlaying()) {
updateProgressBar(true, true, 0);
avPlayer.play(getPage().getTitlePronunciationUrl(), avCallback, avCallback);
} else {
updateProgressBar(false, true, 0);
avPlayer.stop();
}
});
}
public void verifyBeforeEditingDescription(@Nullable String text) {
if (getPage() != null && getPage().getPageProperties().canEdit()) {
if (!AccountUtil.isLoggedIn() && Prefs.getTotalAnonDescriptionsEdited() >= getResources().getInteger(R.integer.description_max_anon_edits)) {
new AlertDialog.Builder(requireActivity())
.setMessage(R.string.description_edit_anon_limit)
.setPositiveButton(R.string.page_editing_login, (DialogInterface dialogInterface, int i) ->
startActivity(LoginActivity.newIntent(requireContext(), LoginFunnel.SOURCE_EDIT)))
.setNegativeButton(R.string.description_edit_login_cancel_button_text, null)
.show();
} else {
startDescriptionEditActivity(text);
}
} else {
getEditHandler().showUneditableDialog();
}
}
private void startDescriptionEditActivity(@Nullable String text) {
if (isDescriptionEditTutorialEnabled()) {
startActivityForResult(DescriptionEditTutorialActivity.newIntent(requireContext(), text),
Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL);
} else {
SuggestedEditsSummary sourceSummary = new SuggestedEditsSummary(getTitle().getPrefixedText(), getTitle().getWikiSite().languageCode(), getTitle(),
getTitle().getDisplayText(), getTitle().getDisplayText(), getTitle().getDescription(), getTitle().getThumbUrl(),
null, null, null, null);
startActivityForResult(DescriptionEditActivity.newIntent(requireContext(), getTitle(), text, sourceSummary, null, PAGE_ACTIVITY),
Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT);
}
}
/**
* Convenience method for hiding all the content of a page.
*/
private void hidePageContent() {
leadImagesHandler.hide();
webView.setVisibility(View.INVISIBLE);
if (callback() != null) {
callback().onPageHideAllContent();
}
}
@Override
public boolean onBackPressed() {
if (tocHandler != null && tocHandler.isVisible()) {
tocHandler.hide();
return true;
}
if (closeFindInPage()) {
return true;
}
if (pageFragmentLoadState.goBack()) {
return true;
}
return false;
}
public void goForward() {
pageFragmentLoadState.goForward();
}
private void checkAndShowBookmarkOnboarding() {
if (Prefs.shouldShowBookmarkToolTip() && Prefs.getOverflowReadingListsOptionClickCount() == 2) {
View targetView = tabLayout.getChildAt(PageActionTab.ADD_TO_READING_LIST.code());
FeedbackUtil.showTapTargetView(requireActivity(), targetView,
R.string.tool_tip_bookmark_icon_title, R.string.tool_tip_bookmark_icon_text, null);
Prefs.shouldShowBookmarkToolTip(false);
}
}
private void sendDecorOffsetMessage() {
JSONObject payload = new JSONObject();
try {
payload.put("offset", getContentTopOffset(requireActivity()));
} catch (JSONException e) {
throw new RuntimeException(e);
}
bridge.sendMessage("setDecorOffset", payload);
}
private void initPageScrollFunnel() {
if (model.getPage() != null) {
pageScrollFunnel = new PageScrollFunnel(app, model.getPage().getPageProperties().getPageId());
}
}
private void closePageScrollFunnel() {
if (pageScrollFunnel != null && webView.getContentHeight() > 0) {
pageScrollFunnel.setViewportHeight(webView.getHeight());
pageScrollFunnel.setPageHeight(webView.getContentHeight());
pageScrollFunnel.logDone();
}
pageScrollFunnel = null;
}
public void showBottomSheet(@NonNull BottomSheetDialog dialog) {
Callback callback = callback();
if (callback != null) {
callback.onPageShowBottomSheet(dialog);
}
}
public void showBottomSheet(@NonNull BottomSheetDialogFragment dialog) {
Callback callback = callback();
if (callback != null) {
callback.onPageShowBottomSheet(dialog);
}
}
private void dismissBottomSheet() {
Callback callback = callback();
if (callback != null) {
callback.onPageDismissBottomSheet();
}
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
Callback callback = callback();
if (callback != null) {
callback.onPageLoadPage(title, entry);
}
}
private void loadMainPageInForegroundTab() {
Callback callback = callback();
if (callback != null) {
callback.onPageLoadMainPageInForegroundTab();
}
}
private void updateProgressBar(boolean visible, boolean indeterminate, int value) {
Callback callback = callback();
if (callback != null) {
callback.onPageUpdateProgressBar(visible, indeterminate, value);
}
}
private void showThemeChooser() {
Callback callback = callback();
if (callback != null) {
callback.onPageShowThemeChooser();
}
}
public void startSupportActionMode(@NonNull ActionMode.Callback actionModeCallback) {
if (callback() != null) {
callback().onPageStartSupportActionMode(actionModeCallback);
}
}
public void hideSoftKeyboard() {
Callback callback = callback();
if (callback != null) {
callback.onPageHideSoftKeyboard();
}
}
public void setToolbarElevationEnabled(boolean enabled) {
Callback callback = callback();
if (callback != null) {
callback.onPageSetToolbarElevationEnabled(enabled);
}
}
public void addToReadingList(@NonNull PageTitle title, @NonNull InvokeSource source) {
Callback callback = callback();
if (callback != null) {
callback.onPageAddToReadingList(title, source);
}
}
public void startLangLinksActivity() {
Intent langIntent = new Intent();
langIntent.setClass(requireActivity(), LangLinksActivity.class);
langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE);
langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle());
requireActivity().startActivityForResult(langIntent, Constants.ACTIVITY_REQUEST_LANGLINKS);
}
private void trimTabCount() {
while (app.getTabList().size() > Constants.MAX_TABS) {
app.getTabList().remove(0);
}
}
@SuppressLint("CheckResult")
private void addTimeSpentReading(int timeSpentSec) {
if (model.getCurEntry() == null) {
return;
}
model.setCurEntry(new HistoryEntry(model.getCurEntry().getTitle(),
new Date(),
model.getCurEntry().getSource(),
timeSpentSec));
Completable.fromAction(new UpdateHistoryTask(model.getCurEntry()))
.subscribeOn(Schedulers.io())
.subscribe(() -> { }, L::e);
}
private LinearLayout.LayoutParams getContentTopOffsetParams(@NonNull Context context) {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getContentTopOffsetPx(context));
}
private LinearLayout.LayoutParams getTabLayoutOffsetParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, tabLayout.getHeight());
}
private void disableActionTabs(@Nullable Throwable caught) {
boolean offline = isOffline(caught);
for (int i = 0; i < tabLayout.getChildCount(); i++) {
if (!(offline && PageActionTab.of(i).equals(PageActionTab.ADD_TO_READING_LIST))) {
tabLayout.disableTab(i);
}
}
}
private class AvCallback implements AvPlayer.Callback, AvPlayer.ErrorCallback {
@Override
public void onSuccess() {
if (avPlayer != null) {
avPlayer.stop();
updateProgressBar(false, true, 0);
}
}
@Override
public void onError() {
if (avPlayer != null) {
avPlayer.stop();
updateProgressBar(false, true, 0);
}
}
}
private class WebViewScrollTriggerListener implements ObservableWebView.OnContentHeightChangedListener {
private int stagedScrollY;
void setStagedScrollY(int stagedScrollY) {
this.stagedScrollY = stagedScrollY;
}
@Override
public void onContentHeightChanged(int contentHeight) {
if (stagedScrollY > 0 && (contentHeight * DimenUtil.getDensityScalar() - webView.getHeight()) > stagedScrollY) {
webView.setScrollY(stagedScrollY);
stagedScrollY = 0;
}
}
}
@Nullable
public Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
@Nullable String getLeadImageEditLang() {
return leadImagesHandler.getCallToActionEditLang();
}
}
|
package org.wikipedia.util;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.google.android.material.snackbar.Snackbar;
import org.wikipedia.R;
import org.wikipedia.analytics.SuggestedEditsFunnel;
import org.wikipedia.main.MainActivity;
import org.wikipedia.page.PageActivity;
import org.wikipedia.random.RandomActivity;
import org.wikipedia.readinglist.ReadingListActivity;
import org.wikipedia.suggestededits.SuggestedEditsCardsActivity;
import java.util.concurrent.TimeUnit;
import static org.wikipedia.util.UriUtil.visitInExternalBrowser;
public final class FeedbackUtil {
public static final int LENGTH_DEFAULT = (int) TimeUnit.SECONDS.toMillis(5);
private static final int SNACKBAR_MAX_LINES = 10;
private static View.OnLongClickListener TOOLBAR_LONG_CLICK_LISTENER = (v) -> {
showToolbarButtonToast(v);
return true;
};
public static void showError(Activity activity, Throwable e) {
ThrowableUtil.AppError error = ThrowableUtil.getAppError(activity, e);
makeSnackbar(activity, error.getError(), LENGTH_DEFAULT).show();
}
public static void showMessageAsPlainText(Activity activity, CharSequence possibleHtml) {
CharSequence richText = StringUtil.fromHtml(possibleHtml.toString());
showMessage(activity, richText.toString());
}
public static void showMessage(Fragment fragment, @StringRes int text) {
makeSnackbar(fragment.requireActivity(), fragment.getString(text), Snackbar.LENGTH_LONG).show();
}
public static void showMessage(Fragment fragment, @NonNull String text) {
makeSnackbar(fragment.requireActivity(), text, Snackbar.LENGTH_LONG).show();
}
public static void showMessage(Activity activity, @StringRes int resId) {
showMessage(activity, activity.getString(resId), Snackbar.LENGTH_LONG);
}
public static void showMessage(Activity activity, CharSequence text) {
showMessage(activity, text, Snackbar.LENGTH_LONG);
}
public static void showMessage(Activity activity, @StringRes int resId, int duration) {
showMessage(activity, activity.getString(resId), duration);
}
public static void showMessage(Activity activity, CharSequence text, int duration) {
makeSnackbar(activity, text, duration).show();
}
public static void showPrivacyPolicy(Context context) {
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.privacy_policy_url)));
}
public static void showOfflineReadingAndData(Context context) {
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.offline_reading_and_data_url)));
}
public static void showAboutWikipedia(Context context) {
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.about_wikipedia_url)));
}
public static void showAndroidAppFAQ(Context context) {
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.android_app_faq_url)));
}
public static void showAndroidAppRequestAnAccount(Context context) {
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.android_app_request_an_account_url)));
}
public static void showAndroidAppEditingFAQ(Context context) {
SuggestedEditsFunnel.get().helpOpened();
visitInExternalBrowser(context, Uri.parse(context.getString(R.string.android_app_edit_help_url)));
}
public static void setToolbarButtonLongPressToast(View... views) {
for (View v : views) {
v.setOnLongClickListener(TOOLBAR_LONG_CLICK_LISTENER);
}
}
public static void showTapTargetView(@NonNull Activity activity, @NonNull View target,
@StringRes int titleId, @StringRes int descriptionId,
@Nullable TapTargetView.Listener listener) {
final float tooltipAlpha = 0.9f;
TapTargetView.showFor(activity,
TapTarget.forView(target, activity.getString(titleId),
activity.getString(descriptionId))
.targetCircleColor(ResourceUtil.getThemedAttributeId(activity, R.attr.colorAccent))
.outerCircleColor(ResourceUtil.getThemedAttributeId(activity, R.attr.colorAccent))
.outerCircleAlpha(tooltipAlpha)
.cancelable(true)
.transparentTarget(true),
listener);
}
public static Snackbar makeSnackbar(Activity activity, CharSequence text, int duration) {
View view = findBestView(activity);
Snackbar snackbar = Snackbar.make(view, StringUtil.fromHtml(text.toString()), duration);
TextView textView = snackbar.getView().findViewById(R.id.snackbar_text);
textView.setMaxLines(SNACKBAR_MAX_LINES);
textView.setMovementMethod(LinkMovementMethod.getInstance());
TextView actionView = snackbar.getView().findViewById(R.id.snackbar_action);
actionView.setTextColor(ContextCompat.getColor(view.getContext(), R.color.green50));
return snackbar;
}
private static void showToolbarButtonToast(View view) {
Toast toast = Toast.makeText(view.getContext(), view.getContentDescription(), Toast.LENGTH_SHORT);
int[] location = new int[2];
view.getLocationOnScreen(location);
toast.setGravity(Gravity.TOP | Gravity.START, location[0], location[1]);
toast.show();
}
private static View findBestView(Activity activity) {
if (activity instanceof MainActivity) {
return activity.findViewById(R.id.fragment_main_coordinator);
} else if (activity instanceof PageActivity) {
return activity.findViewById(R.id.fragment_page_coordinator);
} else if (activity instanceof RandomActivity) {
return activity.findViewById(R.id.random_coordinator_layout);
} else if (activity instanceof ReadingListActivity) {
return activity.findViewById(R.id.fragment_reading_list_coordinator);
} else if (activity instanceof SuggestedEditsCardsActivity) {
return activity.findViewById(R.id.suggestedEditsCardsCoordinator);
} else {
return activity.findViewById(android.R.id.content);
}
}
private FeedbackUtil() {
}
}
|
package org.wikipedia.wikidata;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.wikipedia.dataclient.mwapi.MwResponse;
import org.wikipedia.json.PostProcessingTypeAdapter;
import java.util.Collections;
import java.util.Map;
@SuppressWarnings("unused")
public class Entities extends MwResponse implements PostProcessingTypeAdapter.PostProcessable {
@Nullable private Map<String, Entity> entities;
private int success;
@Nullable public Map<String, Entity> entities() {
return entities;
}
@Nullable public Entity getFirst() {
if (entities == null) {
return null;
}
return entities.values().iterator().next();
}
@Override
public void postProcess() {
if (getFirst() != null && getFirst().isMissing()) {
throw new RuntimeException("The requested entity was not found.");
}
}
public static class Entity {
@Nullable private String type;
@Nullable private String id;
@Nullable private Map<String, Label> labels;
@Nullable private Map<String, Label> descriptions;
@Nullable private Map<String, SiteLink> sitelinks;
@Nullable private String missing;
@NonNull public String id() {
return StringUtils.defaultString(id);
}
@NonNull public Map<String, Label> labels() {
return labels != null ? labels : Collections.emptyMap();
}
@NonNull public Map<String, Label> descriptions() {
return descriptions != null ? descriptions : Collections.emptyMap();
}
@NonNull public Map<String, SiteLink> sitelinks() {
return sitelinks != null ? sitelinks : Collections.emptyMap();
}
boolean isMissing() {
return "-1".equals(id) && missing != null;
}
}
public static class Label {
@Nullable private String language;
@Nullable private String value;
@NonNull public String language() {
return StringUtils.defaultString(language);
}
@NonNull public String value() {
return StringUtils.defaultString(value);
}
}
public static class SiteLink {
@Nullable private String site;
@Nullable private String title;
@NonNull public String getSite() {
return StringUtils.defaultString(site);
}
@NonNull public String getTitle() {
return StringUtils.defaultString(title);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.redhat.ceylon.compiler.typechecker.util;
import java.util.HashSet;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
*
* @author kulikov
*/
public class ReferenceCounter extends Visitor {
private Set<Declaration> referencedDeclarations = new HashSet<Declaration>();
void inc(Declaration d) {
referencedDeclarations.add(d);
}
boolean referenced(Declaration d) {
return referencedDeclarations.contains(d);
}
@Override
public void visit(Tree.MemberOrTypeExpression that) {
super.visit(that);
Declaration d = that.getDeclaration();
if (d!=null) inc(d);
}
@Override
public void visit(Tree.SimpleType that) {
super.visit(that);
TypeDeclaration t = that.getDeclarationModel();
if (t!=null &&
!(t instanceof UnionType) &&
!(t instanceof IntersectionType)) {
inc(t);
}
}
@Override
public void visit(Tree.MemberLiteral that) {
super.visit(that);
Declaration d = that.getDeclaration();
if (d!=null) {
inc(d);
}
}
}
|
package team.crazynetwork.raids;
import org.bukkit.plugin.java.JavaPlugin;
public class SkyBlockRaids extends JavaPlugin {
private static SkyBlockRaids self;
public void onEnable(){ //Runs on startup AND when server is reloaded. DO NOT assume 0 players.
self = this; //A workaround as static vars normally do not allow this.
}
public void onDisable(){ //Save all the file here when the plugin is disabled.
}
public static SkyBlockRaids getPlugin(){ //Give other classes direct access to the plugin's methods.
return self;
}
public Object getSettings(String settingName){
//getConfig conflicts with JavaPlugin.getConfig
//Returns a value from the config file.
//To be implemented. A return of a placeholder for now.
return 1000;
//Code Suggestion:
/*
if(getConfig().get(settingName) != null) {
return getConfig().get(settingName);
} return null;
*/
}
}
|
package com.opensymphony.workflow.designer.views;
import java.awt.geom.Point2D;
import java.util.*;
import org.jgraph.JGraph;
import org.jgraph.graph.*;
public class EdgeRouter implements Edge.Routing
{
public static EdgeRouter sharedInstance = new EdgeRouter();
/**
* The distance between the control point and the middle line. A larger number will lead to a more "bubbly"
* appearance of the bezier edges.
*/
private static final double EDGE_SEPARATION = 25;
public void route(EdgeView edge, List points)
{
if(edge.getSource() == null || edge.getTarget() == null ||
edge.getSource().getParentView() == null ||
edge.getTarget().getParentView() == null)
return;
Object[] edges = getEdgesBetween(edge.getGraph(), edge.getSource().getParentView().getCell(),
edge.getTarget().getParentView().getCell());
// Find the position of the current edge that we are currently routing
int position = 0;
for(int i = 0; i < edges.length; i++)
{
Object e = edges[i];
if(e == edge.getCell())
{
position = i;
}
}
// If there is only 1 edge between the two vertices, we don't need this
// special routing
if(edges.length < 2)
{
if(points.size() > 2)
{
points.remove(1);
}
return;
}
// Find the end point positions
Point2D from = ((PortView)edge.getSource()).getLocation(null);
Point2D to = ((PortView)edge.getTarget()).getLocation(null);
if(from != null && to != null)
{
// double dy = from.getY() - to.getY();
// double dx = from.getX() - to.getX();
// calculate mid-point of the main edge
double midX = Math.min(from.getX(), to.getX()) + Math.abs((from.getX() - to.getX()) / 2);
double midY = Math.min(from.getY(), to.getY()) + Math.abs((from.getY() - to.getY()) / 2);
// compute the normal slope. The normal of a slope is the negative inverse of the original slope.
double m = (from.getY() - to.getY()) / (from.getX() - to.getX());
double theta = Math.atan(-1 / m);
// modify the location of the control point along the axis of the normal using the edge position
double r = EDGE_SEPARATION * (Math.floor(position / 2) + 1);
if(position % 2 == 0)
{
r = -r;
}
// convert polar coordinates to cartesian and translate axis to the mid-point
double ex = r * Math.cos(theta) + midX;
double ey = r * Math.sin(theta) + midY;
Point2D controlPoint = new Point2D.Double(ex, ey);
// add the control point to the points list
if(points.size() == 2)
{
points.add(1, controlPoint);
}
else
{
points.set(1, controlPoint);
}
}
}
/**
* Returns the edges between the specified vertices
*/
public static Object[] getEdgesBetween(JGraph graph, Object vertex1,
Object vertex2)
{
ArrayList result = new ArrayList();
Set edges = DefaultGraphModel.getEdges(graph.getModel(),
new Object[]{vertex1});
Set edges2 = DefaultGraphModel.getEdges(graph.getModel(),
new Object[]{vertex2});
if(edges.size() > edges2.size())
edges = edges2;
Iterator it = edges.iterator();
while(it.hasNext())
{
Object edge = it.next();
Object source = getSourceVertex(graph, edge);
Object target = getTargetVertex(graph, edge);
if(source == vertex1 && target == vertex2
|| source == vertex2 && target == vertex1)
result.add(edge);
}
return result.toArray();
}
public static Object getSourceVertex(JGraph graph, Object edge)
{
Object sourcePort = graph.getModel().getSource(edge);
return graph.getModel().getParent(sourcePort);
}
/**
* @return
*/
public static Object getTargetVertex(JGraph graph, Object edge)
{
Object targetPort = graph.getModel().getTarget(edge);
return graph.getModel().getParent(targetPort);
}
}
|
package com.kcthota.query;
import static com.kcthota.JSONQuery.expressions.Expr.appendTo;
import static com.kcthota.JSONQuery.expressions.Expr.prependTo;
import static com.kcthota.JSONQuery.expressions.Expr.eq;
import static com.kcthota.JSONQuery.expressions.Expr.val;
import static com.kcthota.JSONQuery.expressions.Expr.trim;
import static com.kcthota.JSONQuery.expressions.Expr.upper;
import static com.kcthota.JSONQuery.expressions.Expr.lower;
import static com.kcthota.JSONQuery.expressions.Expr.replace;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kcthota.JSONQuery.Query;
import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/**
* @author Krishna Chaitanya Thota
* Apr 26, 2015 1:40:47 AM
*/
public class ValueTest {
@Test
public void testValue1(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value("city").textValue()).isEqualTo("Santa Clara");
assertThat(q.value("name/firstName").textValue()).isEqualTo("Krishna");
assertThat(q.value(val("name/lastName")).textValue()).isEqualTo("Thota");
assertThat(q.value(val("interests/0")).textValue()).isEqualTo("hiking");
assertThat(q.value("interests/1").textValue()).isEqualTo("biking");
assertThat(q.value(val(val("name"), "firstName")).textValue()).isEqualTo("Krishna");
}
@Test
public void testAppendTo(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(appendTo("name/firstName", "1")).textValue()).isEqualTo("Krishna1");
assertThat(q.value(appendTo("city", ", CA")).textValue()).isEqualTo("Santa Clara, CA");
assertThat(q.value(appendTo(val("name/firstName"), null, " C" )).textValue()).isEqualTo("Krishna C");
assertThat(q.value(appendTo(val("name/firstName"), " C")).textValue()).isEqualTo("Krishna C");
assertThat(q.is(eq(appendTo("name/lastName", "1"), "Thota1"))).isTrue();
assertThat(q.value(appendTo("interests/0", " hills")).textValue()).isEqualTo("hiking hills");
try {
q.value(appendTo("age", "1"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testPrependTo(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(prependTo("name/firstName", "Mr. ")).textValue()).isEqualTo("Mr. Krishna");
assertThat(q.value(prependTo(val("name/firstName"), "Mr. ")).textValue()).isEqualTo("Mr. Krishna");
assertThat(q.is(eq(prependTo("name/lastName", "1"), "1Thota"))).isTrue();
assertThat(q.value(prependTo("interests/0", "hill ")).textValue()).isEqualTo("hill hiking");
try {
q.value(prependTo("age", "1"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testTrim(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", " Krishna ").put("lastName", " Thota ");
node.put("age", 25);
node.put("city", "Santa Clara, ");
node.putArray("interests").add(" hiking ").add(" biking ");
Query q=new Query(node);
assertThat(q.value(trim("name/firstName")).textValue()).isEqualTo("Krishna");
assertThat(q.is(eq(trim("name/lastName"), "Thota"))).isTrue();
assertThat(q.value(appendTo(trim("interests/0"), " hills")).textValue()).isEqualTo("hiking hills");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testUpper(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara,");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(upper("name/firstName")).textValue()).isEqualTo("KRISHNA");
assertThat(q.is(eq(upper("name/lastName"), "THOTA"))).isTrue();
assertThat(q.value(upper(appendTo("interests/0", " hills"))).textValue()).isEqualTo("HIKING HILLS");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testLower(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara,");
node.putArray("interests").add("HIKING").add("biking");
Query q=new Query(node);
assertThat(q.value(lower("name/firstName")).textValue()).isEqualTo("krishna");
assertThat(q.is(eq(lower("name/lastName"), "thota"))).isTrue();
assertThat(q.value(lower(appendTo("interests/0", " hills"))).textValue()).isEqualTo("hiking hills");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testReplace(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(replace("name/firstName", "Krish", "Chris")).textValue()).isEqualTo("Chrisna");
assertThat(q.is(eq(replace("name/lastName", "Thota", "KC"), "KC"))).isTrue();
assertThat(q.is(eq(replace("city", " ", ""), "SantaClara"))).isTrue();
assertThat(q.value(lower(replace("interests/0", "hiking", "hike"))).textValue()).isEqualTo("hike");
assertThat(q.is(eq(replace("city", "something", "somethingelse"), "Santa Clara"))).isTrue();
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
}
|
package dr.evomodel.treedatalikelihood.hmc;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.CompoundSymmetricMatrix;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.math.distributions.WishartSufficientStatistics;
import dr.math.interfaces.ConjugateWishartStatisticsProvider;
import dr.math.matrixAlgebra.SymmetricMatrix;
import dr.math.matrixAlgebra.Vector;
import dr.xml.Reportable;
import static dr.math.matrixAlgebra.SymmetricMatrix.extractUpperTriangular;
/**
* @author Paul Bastide
* @author Marc A. Suchard
*/
public abstract class AbstractPrecisionGradient implements GradientWrtParameterProvider, Reportable {
private final ConjugateWishartStatisticsProvider wishartStatistics;
final Likelihood likelihood;
final CompoundSymmetricMatrix parameter;
private final int dim;
private final Parameterization parameterization;
AbstractPrecisionGradient(ConjugateWishartStatisticsProvider wishartStatistics,
Likelihood likelihood,
CompoundSymmetricMatrix parameter) {
this(wishartStatistics, likelihood, parameter, Parameterization.AS_PRECISION);
}
AbstractPrecisionGradient(ConjugateWishartStatisticsProvider wishartStatistics,
Likelihood likelihood,
CompoundSymmetricMatrix parameter, Parameterization parameterization) {
assert parameter.asCorrelation()
: "PrecisionGradient can only be applied to a CompoundSymmetricMatrix with off-diagonal as correlation.";
this.wishartStatistics = wishartStatistics;
this.likelihood = likelihood;
this.parameter = parameter;
this.dim = parameter.getColumnDimension();
this.parameterization = parameterization;
}
enum Parameterization {
AS_PRECISION {
@Override
double[] chainRule(double[] x) {
return x; // Do nothing
}
},
AS_VARIANCE {
@Override
double[] chainRule(double[] x) {
// TODO Handle matrix-inverse
return x;
}
};
abstract double[] chainRule(double[] x);
}
@Override
public Likelihood getLikelihood() {
return likelihood;
}
@Override
public Parameter getParameter() {
return parameter;
}
@Override
public int getDimension() {
return getParameter().getDimension();
}
int getDimensionCorrelation() {
return dim * (dim - 1) / 2;
}
int getDimensionDiagonal() {
return dim;
}
@Override
public double[] getGradientLogDensity() {
// Statistics
WishartSufficientStatistics statistics = wishartStatistics.getWishartStatistics();
SymmetricMatrix weightedSumOfSquares = new SymmetricMatrix(statistics.getScaleMatrix(), dim);
int numberTips = statistics.getDf();
// TODO For non-matrix-normal models, use sum of gradients w.r.t. branch-specific precisions
// parameters
SymmetricMatrix correlationPrecision = new SymmetricMatrix(parameter.getCorrelationMatrix());
double[] precisionDiagonal = parameter.getDiagonal();
// TODO Chain-rule w.r.t. to parametrization
if (CHECK_GRADIENT) {
System.err.println("Analytic at: \n" + new Vector(parameter.getOffDiagonalParameter().getParameterValues())
+ " " + new Vector(parameter.getDiagonal()));
}
double[] gradient = getGradientParameter(weightedSumOfSquares, numberTips,
correlationPrecision, precisionDiagonal);
if (CHECK_GRADIENT) {
System.err.println(checkNumeric(gradient));
}
return gradient;
}
String getReportString(double[] analytic, double[] numeric) {
return getClass().getCanonicalName() + "\n" +
"analytic: " + new Vector(analytic) +
"\n" +
"numeric : " + new Vector(numeric) +
"\n";
}
abstract String checkNumeric(double[] analytic);
@Override
public String getReport() {
return checkNumeric(getGradientLogDensity());
}
abstract double[] getGradientParameter(SymmetricMatrix weightedSumOfSquares,
int numberTips,
SymmetricMatrix correlationPrecision,
double[] precisionDiagonal);
// Gradient w.r.t. correlation
double[] getGradientCorrelation(SymmetricMatrix weightedSumOfSquares,
int numberTips,
SymmetricMatrix correlationPrecision,
double[] precisionDiagonal) {
// Gradient w.r.t. the correlation matrix (strictly upper diagonal)
double[] gradientCorrelation = extractUpperTriangular((SymmetricMatrix) correlationPrecision.inverse());
int k = 0;
for (int i = 0; i < dim - 1; i++) {
for (int j = i + 1; j < dim; j++) {
gradientCorrelation[k] = numberTips * gradientCorrelation[k]
- weightedSumOfSquares.component(i, j) * Math.sqrt(precisionDiagonal[i] * precisionDiagonal[j]);
k++;
}
}
// TODO Handle chain-rule for parameterization
// If necessary, apply chain rule to get the gradient w.r.t. cholesky of correlation matrix
gradientCorrelation = parameter.updateGradientCorrelation(gradientCorrelation);
return gradientCorrelation;
}
// Gradient w.r.t. diagonal
double[] getGradientDiagonal(SymmetricMatrix weightedSumOfSquares,
int numberTips,
SymmetricMatrix correlationPrecision,
double[] precisionDiagonal) {
// Gradient w.r.t. to the diagonal values of the precision
double[] gradientDiagonal = new double[dim];
for (int i = 0; i < dim; i++) {
// Product
double innerProduct = 0.0;
for (int j = 0; j < dim; j++) {
innerProduct += correlationPrecision.component(i, j) * weightedSumOfSquares.component(i, j)
* Math.sqrt(precisionDiagonal[j] / precisionDiagonal[i]);
}
// diagonal
gradientDiagonal[i] = numberTips * 0.5 / precisionDiagonal[i] - 0.5 * innerProduct;
}
// TODO Handle chain-rule for parameterization
return gradientDiagonal;
}
private static final boolean CHECK_GRADIENT = true;
}
|
package com.rox.emu.env;
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.When;
import com.pholser.junit.quickcheck.generator.InRange;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import com.rox.emu.InvalidDataTypeException;
import org.junit.Test;
import org.junit.runner.RunWith;
import spock.lang.Specification;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.*;
@RunWith(JUnitQuickcheck.class)
public class RoxByteTest extends Specification{
@Test
public void testToTwosCompliment(){
final RoxByte myByte = RoxByte.signedFrom(1);
final RoxByte twosCompliment = myByte.inTwosCompliment();
assertEquals(-1, twosCompliment.getAsInt());
assertEquals(0b11111111, twosCompliment.getRawValue());
}
@Test
public void testToOnesCompliment(){
final RoxByte myByte = RoxByte.signedFrom(1);
final RoxByte onesCompliment = myByte.inOnesCompliment();
assertEquals(-2, onesCompliment.getAsInt());
assertEquals(0b11111110, onesCompliment.getRawValue());
}
@Test
public void testEmptyByteCreation(){
final RoxByte myByte = RoxByte.ZERO;
assertNotNull(myByte);
assertEquals(0, myByte.getAsInt());
}
@Test
public void testSignedFromInteger() throws InvalidDataTypeException {
final RoxByte myByte = RoxByte.signedFrom(1);
assertNotNull(myByte);
assertEquals(RoxByte.ByteFormat.SIGNED_TWOS_COMPLIMENT, myByte.getFormat());
assertEquals(0b00000001, myByte.getRawValue());
}
@Test
public void testLiteralFromInteger() throws InvalidDataTypeException {
final RoxByte myByte = RoxByte.literalFrom(1);
assertNotNull(myByte);
assertEquals(RoxByte.ByteFormat.SIGNED_TWOS_COMPLIMENT, myByte.getFormat());
assertEquals(0b00000001, myByte.getRawValue());
}
@Test
public void testByteFromRaw() throws InvalidDataTypeException {
final RoxByte myByte = RoxByte.literalFrom(0b11111111);
assertNotNull(myByte);
assertEquals(RoxByte.ByteFormat.SIGNED_TWOS_COMPLIMENT, myByte.getFormat());
assertEquals(0b11111111, myByte.getRawValue());
}
@Property(trials = 30)
public void testSignedFromWithInvalid(@When(satisfies = "#_ < -128 || #_ > 127") int byteValue){
try {
RoxByte.signedFrom(byteValue);
fail(byteValue + " was expected to be too low to convert to unsigned byte");
}catch(InvalidDataTypeException e) {
assertNotNull(e);
}
}
@Property(trials = 10)
public void testSignedFromWithTooHigh(@InRange(min = "128", max = "300") int byteValue){
try {
RoxByte.signedFrom(byteValue);
fail(byteValue + " was expected to be too high to convert to unsigned byte");
}catch(InvalidDataTypeException e) {
assertNotNull(e);
}
}
@Test
public void testSetBit(){
final RoxByte myByte = RoxByte.ZERO;
assertEquals(1, myByte.withBit(0).getAsInt());
assertEquals(2, myByte.withBit(1).getAsInt());
assertEquals(4, myByte.withBit(2).getAsInt());
assertEquals(8, myByte.withBit(3).getAsInt());
assertEquals(16, myByte.withBit(4).getAsInt());
assertEquals(32, myByte.withBit(5).getAsInt());
assertEquals(64, myByte.withBit(6).getAsInt());
assertEquals(-128, myByte.withBit(7).getAsInt());
}
@Test
public void testWithoutBit(){
final RoxByte myByte = RoxByte.literalFrom(0b11111111);
assertEquals(0b11111110, myByte.withoutBit(0).getRawValue());
assertEquals(0b11111101, myByte.withoutBit(1).getRawValue());
assertEquals(0b11111011, myByte.withoutBit(2).getRawValue());
assertEquals(0b11110111, myByte.withoutBit(3).getRawValue());
assertEquals(0b11101111, myByte.withoutBit(4).getRawValue());
assertEquals(0b11011111, myByte.withoutBit(5).getRawValue());
assertEquals(0b10111111, myByte.withoutBit(6).getRawValue());
assertEquals(0b01111111, myByte.withoutBit(7).getRawValue());
}
@Property(trials = 5)
public void testWithBitInvalidChoice(@When(satisfies = "#_ < 0 || #_ > 7") int bit){
final RoxByte myByte = RoxByte.ZERO;
try {
myByte.withBit(bit);
fail("There is no bit " + bit + ", this should throw an error");
}catch(ArrayIndexOutOfBoundsException e){
assertNotNull(e);
}
}
@Property(trials = 5)
public void testWithoutBitInvalidChoice(@When(satisfies = "#_ < 0 || #_ > 7") int bit){
final RoxByte myByte = RoxByte.ZERO;
try {
myByte.withoutBit(bit);
fail("There is no bit " + bit + ", this should throw an error");
}catch(ArrayIndexOutOfBoundsException e){
assertNotNull(e);
}
}
@Test
public void testIsBitSet(){
final RoxByte loadedByte = RoxByte.signedFrom(-1);
final RoxByte emptyByte = RoxByte.ZERO;
for (int i=0; i<8; i++){
assertTrue(loadedByte.isBitSet(i));
assertFalse(emptyByte.isBitSet(i));
}
}
@Property(trials = 10)
public void testEquals(@When(satisfies = "#_ < 255 || #_ > 0") int byteValue){
final RoxByte valA = RoxByte.literalFrom(byteValue);
final RoxByte valB = RoxByte.literalFrom(byteValue);
assertTrue(valA.equals(valB));
}
@Property(trials = 10)
public void testEqualsEdgesCases(@When(satisfies = "#_ < 255 || #_ > 0") int byteValue){
final RoxByte valA = RoxByte.literalFrom(byteValue);
final RoxByte valB = RoxByte.literalFrom(byteValue);
assertTrue(valA.equals(valA));
assertTrue(valA.equals(valB));
assertFalse(valA.equals(null));
assertFalse(valA.equals("This does not match"));
}
@Property(trials = 10)
public void testHashcode(@When(satisfies = "#_ < 255 || #_ > 0") int byteValue){
final RoxByte valA = RoxByte.literalFrom(byteValue);
final RoxByte valB = RoxByte.literalFrom(byteValue);
assertTrue(valA.hashCode() == valB.hashCode());
}
@Property(trials = 5)
public void testIsBitSetInvalidChoice(@When(satisfies = "#_ < 0 || #_ > 7") int bit){
final RoxByte myByte = RoxByte.ZERO;
try {
myByte.isBitSet(bit);
fail("There is no bit " + bit + ", this should throw an error");
}catch(ArrayIndexOutOfBoundsException e){
assertNotNull(e);
}
}
}
|
package dr.inference.distribution;
import dr.inference.model.*;
import dr.math.distributions.*;
import dr.xml.*;
import dr.util.Attribute;
import java.util.ArrayList;
/**
* @author Marc Suchard
*/
public class MultivariateDistributionLikelihood extends AbstractDistributionLikelihood {
public static final String MVN_PRIOR = "multivariateNormalPrior";
public static final String MVN_MEAN = "meanParameter";
public static final String MVN_PRECISION = "precisionParameter";
public static final String MVN_CV = "coefficientOfVariation";
public static final String WISHART_PRIOR = "multivariateWishartPrior";
public static final String INV_WISHART_PRIOR = "multivariateInverseWishartPrior";
public static final String DIRICHLET_PRIOR = "dirichletPrior";
public static final String DF = "df";
public static final String SCALE_MATRIX = "scaleMatrix";
public static final String MVGAMMA_PRIOR = "multivariateGammaPrior";
public static final String MVGAMMA_SHAPE = "shapeParameter";
public static final String MVGAMMA_SCALE = "scaleParameter";
public static final String COUNTS = "countsParameter";
public static final String NON_INFORMATIVE = "nonInformative";
public static final String DATA = "data";
private final MultivariateDistribution distribution;
public MultivariateDistributionLikelihood(MultivariateDistribution distribution) {
super(new DefaultModel());
this.distribution = distribution;
}
public double calculateLogLikelihood() {
double logL = 0.0;
for( Attribute<double[]> data : dataList ) {
logL += distribution.logPdf(data.getAttributeValue());
}
return logL;
}
public MultivariateDistribution getDistribution() {
return distribution;
}
public static XMLObjectParser DIRICHLET_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return DIRICHLET_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
XMLObject cxo = xo.getChild(COUNTS);
Parameter counts = (Parameter) cxo.getChild(Parameter.class);
DirichletDistribution dirichlet = new DirichletDistribution(counts.getParameterValues());
MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(
dirichlet);
cxo = xo.getChild(DATA);
for (int j = 0; j < cxo.getChildCount(); j++) {
if (cxo.getChild(j) instanceof Parameter) {
likelihood.addData((Parameter) cxo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element " + cxo.getName());
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new ElementRule(COUNTS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
};
public String getParserDescription() {
return "Calculates the likelihood of some data under an Inverse-Wishart distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
public static XMLObjectParser INV_WISHART_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return INV_WISHART_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
int df = xo.getIntegerAttribute(DF);
XMLObject cxo = xo.getChild(SCALE_MATRIX);
MatrixParameter scaleMatrix = (MatrixParameter) cxo.getChild(MatrixParameter.class);
InverseWishartDistribution invWishart = new InverseWishartDistribution(df, scaleMatrix.getParameterAsMatrix());
MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(
invWishart);
cxo = xo.getChild(DATA);
for (int j = 0; j < cxo.getChildCount(); j++) {
if (cxo.getChild(j) instanceof MatrixParameter) {
likelihood.addData((MatrixParameter) cxo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element " + cxo.getName());
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(DF),
new ElementRule(SCALE_MATRIX,
new XMLSyntaxRule[]{new ElementRule(MatrixParameter.class)}),
};
public String getParserDescription() {
return "Calculates the likelihood of some data under an Inverse-Wishart distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
public static XMLObjectParser WISHART_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return WISHART_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
MultivariateDistributionLikelihood likelihood;
if (xo.hasAttribute(NON_INFORMATIVE) && xo.getBooleanAttribute(NON_INFORMATIVE)) {
// Make non-informative settings
XMLObject cxo = xo.getChild(DATA);
int dim = ((MatrixParameter) cxo.getChild(0)).getColumnDimension();
likelihood = new MultivariateDistributionLikelihood(new WishartDistribution(dim));
} else {
if (!xo.hasAttribute(DF) || !xo.hasChildNamed(SCALE_MATRIX)) {
throw new XMLParseException("Must specify both a df and scaleMatrix");
}
int df = xo.getIntegerAttribute(DF);
XMLObject cxo = xo.getChild(SCALE_MATRIX);
MatrixParameter scaleMatrix = (MatrixParameter) cxo.getChild(MatrixParameter.class);
likelihood = new MultivariateDistributionLikelihood(
new WishartDistribution(df, scaleMatrix.getParameterAsMatrix())
);
}
XMLObject cxo = xo.getChild(DATA);
for (int j = 0; j < cxo.getChildCount(); j++) {
if (cxo.getChild(j) instanceof MatrixParameter) {
likelihood.addData((MatrixParameter) cxo.getChild(j));
System.err.println("added ");
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element " + cxo.getName());
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules;{
rules = new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(NON_INFORMATIVE, true),
AttributeRule.newIntegerRule(DF, true),
new ElementRule(SCALE_MATRIX,
new XMLSyntaxRule[]{new ElementRule(MatrixParameter.class)}, true),
new ElementRule(DATA,
new XMLSyntaxRule[]{new ElementRule(MatrixParameter.class, 1, Integer.MAX_VALUE)}
)
};
}
public String getParserDescription() {
return "Calculates the likelihood of some data under a Wishart distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
public static XMLObjectParser MVN_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MVN_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
XMLObject cxo = xo.getChild(MVN_MEAN);
Parameter mean = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(MVN_PRECISION);
MatrixParameter precision = (MatrixParameter) cxo.getChild(MatrixParameter.class);
if (mean.getDimension() != precision.getRowDimension() ||
mean.getDimension() != precision.getColumnDimension())
throw new XMLParseException("Mean and precision have wrong dimensions in " + xo.getName() + " element");
MultivariateDistributionLikelihood likelihood =
new MultivariateDistributionLikelihood(
new MultivariateNormalDistribution(mean.getParameterValues(),
precision.getParameterAsMatrix())
);
cxo = xo.getChild(DATA);
for (int j = 0; j < cxo.getChildCount(); j++) {
if (cxo.getChild(j) instanceof Parameter) {
Parameter data = (Parameter) cxo.getChild(j);
likelihood.addData(data);
if (data.getDimension() != mean.getDimension())
throw new XMLParseException("dim(" + data.getStatisticName() + ") != dim(" + mean.getStatisticName() + ") in " + xo.getName() + "element");
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new ElementRule(MVN_MEAN,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(MVN_PRECISION,
new XMLSyntaxRule[]{new ElementRule(MatrixParameter.class)}),
new ElementRule(DATA,
new XMLSyntaxRule[]{new ElementRule(Parameter.class, 1, Integer.MAX_VALUE)})
};
public String getParserDescription() {
return "Calculates the likelihood of some data under a given multivariate-normal distribution.";
}
public Class getReturnType() {
return MultivariateDistributionLikelihood.class;
}
};
public static XMLObjectParser MVGAMMA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MVGAMMA_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double[] shape;
double[] scale;
if (xo.hasChildNamed(MVGAMMA_SHAPE)) {
XMLObject cxo = xo.getChild(MVGAMMA_SHAPE);
shape = ((Parameter) cxo.getChild(Parameter.class)).getParameterValues();
cxo = xo.getChild(MVGAMMA_SCALE);
scale = ((Parameter) cxo.getChild(Parameter.class)).getParameterValues();
if (shape.length != scale.length)
throw new XMLParseException("Shape and scale have wrong dimensions in " + xo.getName() + " element");
} else {
XMLObject cxo = xo.getChild(MVN_MEAN);
double[] mean = ((Parameter) cxo.getChild(Parameter.class)).getParameterValues();
cxo = xo.getChild(MVN_CV);
double[] cv = ((Parameter) cxo.getChild(Parameter.class)).getParameterValues();
if (mean.length != cv.length)
throw new XMLParseException("Mean and CV have wrong dimensions in " + xo.getName() + " element");
final int dim = mean.length;
shape = new double[dim];
scale = new double[dim];
for (int i = 0; i < dim; i++) {
double c2 = cv[i] * cv[i];
shape[i] = 1.0 / c2;
scale[i] = c2 * mean[i];
}
}
MultivariateDistributionLikelihood likelihood =
new MultivariateDistributionLikelihood(
new MultivariateGammaDistribution(shape, scale)
);
XMLObject cxo = xo.getChild(DATA);
for (int j = 0; j < cxo.getChildCount(); j++) {
if (cxo.getChild(j) instanceof Parameter) {
Parameter data = (Parameter) cxo.getChild(j);
likelihood.addData(data);
if (data.getDimension() != shape.length)
throw new XMLParseException("dim(" + data.getStatisticName() + ") != " + shape.length + " in " + xo.getName() + "element");
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new XORRule(
new ElementRule(MVGAMMA_SHAPE,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(MVN_MEAN,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)})),
new ElementRule(DATA,
new XMLSyntaxRule[]{new ElementRule(Parameter.class, 1, Integer.MAX_VALUE)})
};
public String getParserDescription() {
return "Calculates the likelihood of some data under a given multivariate-gamma distribution.";
}
public Class getReturnType() {
return MultivariateDistributionLikelihood.class;
}
};
}
|
package com.telesign;
import junit.framework.TestCase;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class RestClientTest extends TestCase {
private MockWebServer mockServer;
private String customerId;
private String apiKey;
private SimpleDateFormat rfc2616 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'");
public void setUp() throws Exception {
super.setUp();
this.customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
this.apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
this.mockServer = new MockWebServer();
this.mockServer.start();
}
public void tearDown() throws Exception {
super.tearDown();
this.mockServer.shutdown();
}
public void testRestClientConstructors() {
RestClient client = new RestClient(this.customerId, this.apiKey);
}
public void testGenerateTelesignHeadersWithPost() throws GeneralSecurityException {
String methodName = "POST";
String dateRfc2616 = "Wed, 14 Dec 2016 18:20:12 GMT";
String nonce = "A1592C6F-E384-4CDB-BC42-C3AB970369E9";
String resource = "/v1/resource";
String bodyParamsUrlEncoded = "test=param";
String expectedAuthorizationHeader = "TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:" +
"2xVlmbrxLjYrrPun3G3WMNG6Jon4yKcTeOoK9DjXJ/Q=";
Map<String, String> actualHeaders = RestClient.generateTelesignHeaders(this.customerId,
this.apiKey,
methodName,
resource,
bodyParamsUrlEncoded,
dateRfc2616,
nonce,
"unitTest");
assertEquals("Authorization header is not as expected", expectedAuthorizationHeader,
actualHeaders.get("Authorization"));
}
public void testGenerateTelesignHeadersUnicodeContent() throws GeneralSecurityException {
String methodName = "POST";
String dateRfc2616 = "Wed, 14 Dec 2016 18:20:12 GMT";
String nonce = "A1592C6F-E384-4CDB-BC42-C3AB970369E9";
String resource = "/v1/resource";
String bodyParamsUrlEncoded = "test=%CF%BF";
String expectedAuthorizationHeader = "TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:" +
"h8d4I0RTxErbxYXuzCOtNqb/f0w3Ck8e5SEkGNj01+8=";
Map<String, String> actualHeaders = RestClient.generateTelesignHeaders(this.customerId,
this.apiKey,
methodName,
resource,
bodyParamsUrlEncoded,
dateRfc2616,
nonce,
"unitTest");
assertEquals("Authorization header is not as expected", expectedAuthorizationHeader,
actualHeaders.get("Authorization"));
}
public void testGenerateTelesignHeadersWithGet() throws GeneralSecurityException {
String methodName = "GET";
String dateRfc2616 = "Wed, 14 Dec 2016 18:20:12 GMT";
String nonce = "A1592C6F-E384-4CDB-BC42-C3AB970369E9";
String resource = "/v1/resource";
String expectedAuthorizationHeader = "TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:" +
"aUm7I+9GKl3ww7PNeeJntCT0iS7b+EmRKEE4LnRzChQ=";
Map<String, String> actualHeaders = RestClient.generateTelesignHeaders(this.customerId,
this.apiKey,
methodName,
resource,
"",
dateRfc2616,
nonce,
"unitTest");
assertEquals("Authorization header is not as expected", expectedAuthorizationHeader,
actualHeaders.get("Authorization"));
}
public void testGenerateTelesignHeadersDefaultValues() throws GeneralSecurityException {
String methodName = "GET";
String resource = "/v1/resource";
String expectedAuthorizationHeader = "TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:" +
"aUm7I+9GKl3ww7PNeeJntCT0iS7b+EmRKEE4LnRzChQ=";
Map<String, String> actualHeaders = RestClient.generateTelesignHeaders(this.customerId,
this.apiKey,
methodName,
resource,
"",
null,
null,
null);
try {
UUID uuid = UUID.fromString(actualHeaders.get("x-ts-nonce"));
} catch (IllegalArgumentException e) {
fail("x-ts-nonce header is not a valid UUID");
}
try {
this.rfc2616.parse(actualHeaders.get("Date"));
} catch (ParseException e) {
fail("Date header is not valid rfc2616 format");
}
}
public void testRestClientPost() throws Exception {
String test_resource = "/test/resource";
Map<String, String> test_params = new HashMap<>();
test_params.put("test", "123_\u03ff_test");
this.mockServer.enqueue(new MockResponse().setBody("{}"));
RestClient client = new RestClient(this.customerId,
this.apiKey,
this.mockServer.url("").toString().replaceAll("/$", ""));
client.post(test_resource, test_params);
RecordedRequest request = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
assertEquals("method is not as expected", "POST", request.getMethod());
assertEquals("path is not as expected", "/test/resource", request.getPath());
assertEquals("body is not as expected", "test=123_%CF%BF_test",
request.getBody().readUtf8());
assertEquals("Content-Type header is not as expected", "application/x-www-form-urlencoded",
request.getHeader("Content-Type"));
assertEquals("x-ts-auth-method header is not as expected", "HMAC-SHA256",
request.getHeader("x-ts-auth-method"));
try {
UUID uuid = UUID.fromString(request.getHeader("x-ts-nonce"));
} catch (IllegalArgumentException e) {
fail("x-ts-nonce header is not a valid UUID");
}
try {
this.rfc2616.parse(request.getHeader("Date"));
} catch (ParseException e) {
fail("Date header is not valid rfc2616 format");
}
assertNotNull(request.getHeader("Authorization"));
}
public void testRestClientGet() throws Exception {
String test_resource = "/test/resource";
Map<String, String> test_params = new HashMap<>();
test_params.put("test", "123_\u03ff_test");
this.mockServer.enqueue(new MockResponse().setBody("{}"));
RestClient client = new RestClient(this.customerId,
this.apiKey,
this.mockServer.url("").toString().replaceAll("/$", ""));
client.get(test_resource, test_params);
RecordedRequest request = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
assertEquals("method is not as expected", "GET", request.getMethod());
assertEquals("path is not as expected","/test/resource?test=123_%CF%BF_test",
request.getPath());
assertEquals("body is not as expected", "", request.getBody().readUtf8());
assertEquals("Content-Type header is not as expected", "",
request.getHeader("Content-Type"));
assertEquals("x-ts-auth-method header is not as expected", "HMAC-SHA256",
request.getHeader("x-ts-auth-method"));
try {
UUID uuid = UUID.fromString(request.getHeader("x-ts-nonce"));
} catch (IllegalArgumentException e) {
fail("x-ts-nonce header is not a valid UUID");
}
try {
this.rfc2616.parse(request.getHeader("Date"));
} catch (ParseException e) {
fail("Date header is not valid rfc2616 format");
}
assertNotNull(request.getHeader("Authorization"));
}
public void testRestClientPut() throws Exception {
String test_resource = "/test/resource";
Map<String, String> test_params = new HashMap<>();
test_params.put("test", "123_\u03ff_test");
this.mockServer.enqueue(new MockResponse().setBody("{}"));
RestClient client = new RestClient(this.customerId,
this.apiKey,
this.mockServer.url("").toString().replaceAll("/$", ""));
client.put(test_resource, test_params);
RecordedRequest request = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
assertEquals("method is not as expected", "PUT", request.getMethod());
assertEquals("path is not as expected","/test/resource", request.getPath());
assertEquals("body is not as expected", "test=123_%CF%BF_test",
request.getBody().readUtf8());
assertEquals("Content-Type header is not as expected","application/x-www-form-urlencoded",
request.getHeader("Content-Type"));
assertEquals("x-ts-auth-method header is not as expected","HMAC-SHA256",
request.getHeader("x-ts-auth-method"));
try {
UUID uuid = UUID.fromString(request.getHeader("x-ts-nonce"));
} catch (IllegalArgumentException e) {
fail("x-ts-nonce header is not a valid UUID");
}
try {
this.rfc2616.parse(request.getHeader("Date"));
} catch (ParseException e) {
fail("Date header is not valid rfc2616 format");
}
assertNotNull(request.getHeader("Authorization"));
}
public void testRestClientDelete() throws Exception {
String test_resource = "/test/resource";
Map<String, String> test_params = new HashMap<>();
test_params.put("test", "123_\u03ff_test");
this.mockServer.enqueue(new MockResponse().setBody("{}"));
RestClient client = new RestClient(this.customerId,
this.apiKey,
this.mockServer.url("").toString().replaceAll("/$", ""));
client.delete(test_resource, test_params);
RecordedRequest request = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
assertEquals("method is not as expected", "DELETE", request.getMethod());
assertEquals("path is not as expected","/test/resource?test=123_%CF%BF_test",
request.getPath());
assertEquals("body is not as expected","", request.getBody().readUtf8());
assertEquals("Content-Type header is not as expected","",
request.getHeader("Content-Type"));
assertEquals("x-ts-auth-method header is not as expected","HMAC-SHA256",
request.getHeader("x-ts-auth-method"));
try {
UUID uuid = UUID.fromString(request.getHeader("x-ts-nonce"));
} catch (IllegalArgumentException e) {
fail("x-ts-nonce header is not a valid UUID");
}
try {
this.rfc2616.parse(request.getHeader("Date"));
} catch (ParseException e) {
fail("Date header is not valid rfc2616 format");
}
assertNotNull(request.getHeader("Authorization"));
}
public void testRestClientProxyAuthentication() throws Exception {
String test_resource = "/test/resource";
Map<String, String> test_params = new HashMap<>();
test_params.put("test", "123_\u03ff_test");
this.mockServer.enqueue(new MockResponse().setBody("{}").setResponseCode(407));
this.mockServer.enqueue(new MockResponse().setBody("{}"));
RestClient client = new RestClient(this.customerId,
this.apiKey,
this.mockServer.url("").toString().replaceAll("/$", ""),
1,
1,
1,
this.mockServer.toProxyAddress(),
"proxyUsername",
"proxyPassword");
client.get(test_resource, test_params);
assertEquals("request count does not match expected",2, this.mockServer.getRequestCount());
RecordedRequest initialRequest = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
RecordedRequest proxyAuthorizationRequest = this.mockServer.takeRequest(1, TimeUnit.SECONDS);
assertNull("Proxy-Authorization header should be absent from initial request",
initialRequest.getHeader("Proxy-Authorization"));
assertNotNull("Proxy-Authorization header should exist in the subsequent request",
proxyAuthorizationRequest.getHeader("Proxy-Authorization"));
}
}
|
package eu.ydp.empiria.player.client.module.dragdrop;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.controller.extensions.Extension;
import eu.ydp.empiria.player.client.controller.extensions.ExtensionType;
import eu.ydp.empiria.player.client.gin.factory.PageScopeFactory;
import eu.ydp.empiria.player.client.module.HasChildren;
import eu.ydp.empiria.player.client.module.IModule;
import eu.ydp.empiria.player.client.module.sourcelist.SourceListModule;
import eu.ydp.empiria.player.client.util.events.bus.EventsBus;
import eu.ydp.empiria.player.client.util.events.dragdrop.DragDropEvent;
import eu.ydp.empiria.player.client.util.events.dragdrop.DragDropEventHandler;
import eu.ydp.empiria.player.client.util.events.dragdrop.DragDropEventTypes;
import eu.ydp.empiria.player.client.util.events.player.PlayerEvent;
import eu.ydp.empiria.player.client.util.events.player.PlayerEventHandler;
import eu.ydp.empiria.player.client.util.events.player.PlayerEventTypes;
public class DragDropManager implements Extension, DragDropEventHandler, PlayerEventHandler {
@Inject
EventsBus eventsBus;
@Inject
PageScopeFactory scopeFactory;
Multimap<IModule, SourceListModule> dropZones = ArrayListMultimap.create();
Map<IModule, String> gapValuesCache = new HashMap<IModule, String>();
Map<IModule, SourceListModule> gapValueSourceCache = new HashMap<IModule, SourceListModule>();
SourceListModule lastDragSource;
List<IModule> waitingForRegister = new ArrayList<IModule>();
DragDropManagerHelper helper;
@Override
public ExtensionType getType() {
return ExtensionType.MULTITYPE;
}
@Override
public void init() {
this.helper = new DragDropManagerHelper(eventsBus, scopeFactory);
eventsBus.addHandler(DragDropEvent.getType(DragDropEventTypes.REGISTER_DROP_ZONE), this);
eventsBus.addHandler(PlayerEvent.getType(PlayerEventTypes.PAGE_LOADED), this);
}
private void handleDragStart(DragDropEvent event) {
lastDragSource = (SourceListModule) event.getIModule();
eventsBus.fireEvent(new DragDropEvent(DragDropEventTypes.ENABLE_ALL_DROP_ZONE, null), scopeFactory.getCurrentPageScope());
for (IModule gap : findInapplicableGaps(lastDragSource)) {
DragDropEvent gapDisableEvent = new DragDropEvent(DragDropEventTypes.DISABLE_DROP_ZONE, gap);
gapDisableEvent.setIModule(gap);
eventsBus.fireEventFromSource(gapDisableEvent, gap, scopeFactory.getCurrentPageScope());
}
}
List<IModule> findInapplicableGaps(SourceListModule dragSource) {
List<IModule> list = new ArrayList<IModule>();
for (IModule gap : dropZones.keySet()) {
if (!dropZones.containsEntry(gap, dragSource)) {
list.add(gap);
}
}
return list;
}
private void handleDragEnd(DragDropEvent event) {
IModule gapModule = (IModule)event.getIModule();
updateDragDataObject(event, gapModule);
String newValue = event.getDragDataObject().getValue();
gapValuesCache.put(gapModule, newValue);
if (lastDragSource != null) {
gapValueSourceCache.put(gapModule, lastDragSource);
helper.fireEventFromSource(lastDragSource, event.getDragDataObject(), DragDropEventTypes.DRAG_END, gapModule);
}
}
private void handleUserChangedDropZone(DragDropEvent event) {
IModule gapChanged = (IModule)event.getIModule();
event.setIModule(gapChanged);
updateDragDataObject(event, gapChanged);
String newValue = event.getDragDataObject().getValue();
gapValuesCache.put(gapChanged, newValue);
Collection<SourceListModule> assignedSourceLists = dropZones.get(gapChanged);
for (SourceListModule sourceList : assignedSourceLists) {
if (sourceList.containsValue(newValue)) {
helper.fireEventFromSource(sourceList, event.getDragDataObject(), DragDropEventTypes.DRAG_END, gapChanged);
break;
}
}
}
private void updateDragDataObject(DragDropEvent event, IModule gapModule) {
String previousValue = gapValuesCache.get(gapModule);
event.getDragDataObject().setPreviousValue(previousValue);
}
@Override
public void onDragEvent(DragDropEvent event) {
switch (event.getType()) {
case DRAG_START:
handleDragStart(event);
break;
case USER_CHANGE_DROP_ZONE:
handleUserChangedDropZone(event);
break;
case DRAG_END:
handleDragEnd(event);
break;
case REGISTER_DROP_ZONE:
registerDropZone(event);
break;
default:
break;
}
}
protected void registerDropZone(DragDropEvent event) {
if (event.getDragDataObject() != null) {
eventsBus.addHandlerToSource(DragDropEvent.getType(DragDropEventTypes.DRAG_END), event.getIModule(), this);
eventsBus.addHandlerToSource(DragDropEvent.getType(DragDropEventTypes.USER_CHANGE_DROP_ZONE), event.getIModule(), this);
waitingForRegister.add(event.getIModule());
}
}
private void buildDropZoneSourceListRelationships(IModule dropZone, HasChildren module) {
if (module != null) {
List<IModule> relatedModules = module.getChildrenModules();
for (IModule relatedModule : relatedModules) {
if (relatedModule instanceof SourceListModule) {
dropZones.put(dropZone, (SourceListModule)relatedModule);
eventsBus.addHandlerToSource(DragDropEvent.getType(DragDropEventTypes.DRAG_START), relatedModule, this);
}
}
buildDropZoneSourceListRelationships(dropZone, module.getParentModule());
}
}
@Override
public void onPlayerEvent(PlayerEvent event) {
for (IModule dropZone : waitingForRegister) {
buildDropZoneSourceListRelationships(dropZone, dropZone.getParentModule());
}
}
}
|
package de.luckydonald;
import de.luckydonald.pipboyserver.MESSAGE_CHANNEL;
import de.luckydonald.pipboyserver.Messages.KeepAlive;
import de.luckydonald.pipboyserver.Messages.ConnectionAccepted;
import de.luckydonald.pipboyserver.Messages.ConnectionRefused;
import de.luckydonald.pipboyserver.Messages.DataUpdate;
import de.luckydonald.pipboyserver.Messages.LocalMapUpdate;
import de.luckydonald.pipboyserver.PipBoyServer.Database;
import de.luckydonald.pipboyserver.PipBoyServer.types.*;
import de.luckydonald.utils.Array;
import de.luckydonald.utils.ObjectWithLogger;
import org.junit.Test;
import java.util.Arrays;
import java.util.function.Function;
import static org.junit.Assert.*;
public class MessagesTest extends ObjectWithLogger {
private byte[] expected_keepAlive = {0x00, 0x00, 0x00, 0x00, 0x00};
private byte[] expected_connectionAccepted = {
0x25, 0x00, 0x00, 0x00, 0x01, 0x7B, 0x22, 0x6C, 0x61, 0x6E, 0x67, 0x22, 0x3A, 0x20, 0x22, 0x64, 0x65, 0x22,
0x2C, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x22, 0x3A, 0x20, 0x22, 0x31, 0x2E, 0x31, 0x2E,
0x33, 0x30, 0x2E, 0x30, 0x22, 0x7D
};
private byte[] expected_connectionRefused = {0x00, 0x00, 0x00, 0x00, 0x02};
private byte[] expectedDataUpdate = {
0x33, 0x00, 0x00, 0x00, 0x03, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x07, 0x0b, 0x00, 0x00,
0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x0c, 0x00, 0x00, 0x00, 0x02, 0x00,
0x05, 0x00, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x00, 0x06, 0x00, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00,
0x00, 0x00
};
private byte[] expectedDataUpdate_delete = {
0x08, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00
};
@Test
public void testEnums() {
assertEquals("KeepAlive", 0x00, MESSAGE_CHANNEL.KeepAlive.toByte());
assertEquals("ConnectionAccepted", 0x01, MESSAGE_CHANNEL.ConnectionAccepted.toByte());
assertEquals("ConnectionRefused", 0x02, MESSAGE_CHANNEL.ConnectionRefused.toByte());
assertEquals("DataUpdate", 0x03, MESSAGE_CHANNEL.DataUpdate.toByte());
assertEquals("LocalMapUpdate", 0x04, MESSAGE_CHANNEL.LocalMapUpdate.toByte());
assertEquals("Command", 0x05, MESSAGE_CHANNEL.Command.toByte());
assertEquals("CommandResult", 0x06, MESSAGE_CHANNEL.CommandResult.toByte());
}
@Test
public void testKeepAlive_Content() throws Exception {
KeepAlive msg = new KeepAlive();
assertArrayEquals("toBytes()", expected_keepAlive, msg.toBytes());
}
@Test
public void testConnectionAccepted_Content() throws Exception {
ConnectionAccepted msg = new ConnectionAccepted();
assertArrayEquals("toBytes()", expected_connectionAccepted, msg.toBytes());
}
@Test
public void testConnectionRefused_Content() throws Exception {
ConnectionRefused msg = new ConnectionRefused();
assertArrayEquals("toBytes()", expected_connectionRefused, msg.toBytes());
}
@Test
public void testDataUpdate_Content() throws Exception {
DBEntry[] updates = new DBEntry[3];
Database db = new Database();
db.add(new DBString("Placeholder with ID 0"));
db.add(new DBString("Placeholder with ID 1"));
db.add(new DBString("Placeholder with ID 2"));
db.add(new DBString("Placeholder with ID 3"));
db.add(new DBString("Placeholder with ID 4"));
db.add(new DBString("Placeholder with ID 5"));
db.add(new DBString("Placeholder with ID 6"));
db.add(new DBString("Placeholder with ID 7"));
db.add(new DBString("Placeholder with ID 8"));
db.add(new DBString("Placeholder with ID 9"));
DBInteger32 package1 = new DBInteger32(42);
db.add(package1);
assertEquals("package1 id", 10, (int) package1.getID());
DBList package2 = new DBList();
db.add(package2);
assertEquals("package2 id", 11, (int) package2.getID());
package2.append(1);
package2.append(2);
DBDict package3 = new DBDict();
db.add(package3);
assertEquals("package3 id", 12, (int) package3.getID());
//package3.add("deleteme_1", db.get(3));
//package3.add("deleteme_2", db.get(4));
package3.add("foo", db.get(5));
package3.add("hello", db.get(6));
//package3.remove(3);
//package3.remove(4);
updates[0] = package1;
updates[1] = package2;
updates[2] = package3;
DataUpdate msg = new DataUpdate(updates);
Function<Object,String> func = this::formatByte;
byte[] message = msg.toBytes(); // content will change after call!
assertEquals("toBytes() (strEquals)", Array.toString(expectedDataUpdate, func), Array.toString(message, func));
assertArrayEquals("toBytes() (arrayEquals)", expectedDataUpdate, message);
}
private String formatByte(Object o) {
if (o instanceof Byte) {
return String.format("%02X", (byte)o);
}
return "";
}
}
|
package fr.adrienbrault.idea.symfony2plugin;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.ResolveResult;
import fr.adrienbrault.idea.symfony2plugin.config.component.parser.ParameterServiceParser;
import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMap;
import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMapParser;
import fr.adrienbrault.idea.symfony2plugin.doctrine.component.EntityNamesServiceParser;
import fr.adrienbrault.idea.symfony2plugin.routing.Route;
import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
public class Symfony2ProjectComponent implements ProjectComponent {
private Project project;
private ServiceMap servicesMap;
private Long servicesMapLastModified;
private Map<String, Route> routes;
private Long routesLastModified;
public Symfony2ProjectComponent(Project project) {
this.project = project;
}
public void initComponent() {
System.out.println("initComponent");
}
public void disposeComponent() {
System.out.println("disposeComponent");
}
@NotNull
public String getComponentName() {
return "Symfony2ProjectComponent";
}
public void projectOpened() {
System.out.println("projectOpened");
this.checkProject();
}
public void projectClosed() {
System.out.println("projectClosed");
}
public void showInfoNotification(String content) {
Notification errorNotification = new Notification("Symfony2 Plugin", "Symfony2 Plugin", content, NotificationType.INFORMATION);
Notifications.Bus.notify(errorNotification, this.project);
}
public boolean isEnabled() {
return Settings.getInstance(project).pluginEnabled;
}
@Nullable
public File getPathToProjectContainer() {
File projectContainer = new File(getPath(project, Settings.getInstance(project).pathToProjectContainer));
if (!projectContainer.exists()) {
return null;
}
return projectContainer;
}
public ServiceMap getServicesMap() {
String defaultServiceMapFilePath = getPath(project, Settings.getInstance(project).pathToProjectContainer);
File xmlFile = new File(defaultServiceMapFilePath);
if (!xmlFile.exists()) {
return new ServiceMap();
}
Long xmlFileLastModified = xmlFile.lastModified();
if (xmlFileLastModified.equals(servicesMapLastModified)) {
return servicesMap;
}
try {
ServiceMapParser serviceMapParser = new ServiceMapParser();
servicesMap = serviceMapParser.parse(xmlFile);
servicesMapLastModified = xmlFileLastModified;
return servicesMap;
} catch (SAXException ignored) {
} catch (IOException ignored) {
} catch (ParserConfigurationException ignored) {
}
return new ServiceMap();
}
public Map<String, Route> getRoutes() {
Map<String, Route> routes = new HashMap<String, Route>();
String urlGeneratorPath = getPath(project, Settings.getInstance(project).pathToUrlGenerator);
File urlGeneratorFile = new File(urlGeneratorPath);
VirtualFile virtualUrlGeneratorFile = VfsUtil.findFileByIoFile(urlGeneratorFile, false);
if (virtualUrlGeneratorFile == null || !urlGeneratorFile.exists()) {
return routes;
}
Long routesLastModified = urlGeneratorFile.lastModified();
if (routesLastModified.equals(this.routesLastModified)) {
return this.routes;
}
Matcher matcher = null;
try {
// Damn, what has he done!
// Right ?
// If you find a better way to parse the file ... submit a PR :P
matcher = Pattern.compile("'((?:[^'\\\\]|\\\\.)*)' => [^\\n]+'_controller' => '((?:[^'\\\\]|\\\\.)*)'[^\\n]+\n").matcher(VfsUtil.loadText(virtualUrlGeneratorFile));
} catch (IOException ignored) {
}
if (null == matcher) {
return routes;
}
while (matcher.find()) {
String routeName = matcher.group(1);
// dont add _assetic_04d92f8, _assetic_04d92f8_0
if(!routeName.matches("_assetic_[0-9a-z]+[_\\d+]*")) {
String controller = matcher.group(2).replace("\\\\", "\\");
Route route = new Route(routeName, controller);
routes.put(route.getName(), route);
}
}
this.routes = routes;
this.routesLastModified = routesLastModified;
return routes;
}
@SuppressWarnings("unchecked")
public Map<String, String> getConfigParameter() {
ServiceXmlParserFactory xmlParser = ServiceXmlParserFactory.getInstance(this.project, ParameterServiceParser.class);
Object domains = xmlParser.parser();
if(domains == null || !(domains instanceof Map)) {
return new HashMap<String, String>();
}
return (Map<String, String>) domains;
}
private String getPath(Project project, String path) {
if (!FileUtil.isAbsolute(path)) { // Project relative path
path = project.getBasePath() + "/" + path;
}
return path;
}
@SuppressWarnings("unchecked")
public Map<String, String> getEntityNamespacesMap() {
ServiceXmlParserFactory xmlParser = ServiceXmlParserFactory.getInstance(this.project, EntityNamesServiceParser.class);
Object domains = xmlParser.parser();
if(domains == null || !(domains instanceof Map)) {
return new HashMap<String, String>();
}
return (Map<String, String>) domains;
}
private void checkProject() {
if(!this.isEnabled()) {
if(VfsUtil.findRelativeFile(this.project.getBaseDir(), "vendor") != null
&& VfsUtil.findRelativeFile(this.project.getBaseDir(), "app", "cache", "dev") != null
&& VfsUtil.findRelativeFile(this.project.getBaseDir(), "app", "cache", "prod") != null
&& VfsUtil.findRelativeFile(this.project.getBaseDir(), "vendor", "symfony", "symfony") != null
) {
showInfoNotification("Looks like this a Symfony2 project. Enable the Symfony2 Plugin in Project Settings");
}
return;
}
if(getPathToProjectContainer() == null) {
showInfoNotification("missing container file");
}
String urlGeneratorPath = getPath(project, Settings.getInstance(project).pathToUrlGenerator);
File urlGeneratorFile = new File(urlGeneratorPath);
if (!urlGeneratorFile.exists()) {
showInfoNotification("missing routing file");
}
}
public static boolean isEnabled(Project project) {
return Settings.getInstance(project).pluginEnabled;
}
public static boolean isEnabled(PsiElement psiElement) {
return psiElement != null && isEnabled(psiElement.getProject());
}
}
|
package integration;
import java.io.File;
import java.util.Locale;
import java.util.logging.Logger;
import com.automation.remarks.junit5.VideoExtension;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.junit5.ScreenShooterExtension;
import com.codeborne.selenide.junit5.TextReportExtension;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import static com.automation.remarks.video.enums.RecordingMode.ANNOTATED;
import static com.codeborne.selenide.Configuration.FileDownloadMode.HTTPGET;
import static com.codeborne.selenide.Configuration.FileDownloadMode.PROXY;
import static com.codeborne.selenide.Configuration.browser;
import static com.codeborne.selenide.Configuration.browserSize;
import static com.codeborne.selenide.Configuration.clickViaJs;
import static com.codeborne.selenide.Configuration.fastSetValue;
import static com.codeborne.selenide.Configuration.timeout;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.closeWebDriver;
import static com.codeborne.selenide.WebDriverRunner.isFirefox;
import static com.codeborne.selenide.WebDriverRunner.isHeadless;
import static com.codeborne.selenide.WebDriverRunner.isIE;
import static com.codeborne.selenide.WebDriverRunner.isLegacyFirefox;
import static com.codeborne.selenide.WebDriverRunner.isPhantomjs;
import static com.codeborne.selenide.WebDriverRunner.isSafari;
import static org.openqa.selenium.net.PortProber.findFreePort;
@ExtendWith({ScreenShooterExtension.class, TextReportExtension.class, VideoExtension.class})
public abstract class IntegrationTest implements WithAssertions {
private static final Logger log = Logger.getLogger(IntegrationTest.class.getName());
// http or https
private static final boolean SSL = false;
protected static LocalHttpServer server;
static long averageSeleniumCommandDuration = 100;
private static String protocol;
private static int port;
private long defaultTimeout;
@BeforeAll
static void setUpAll() throws Exception {
System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tT %4$s %5$s%6$s%n"); // add %2$s for source
Locale.setDefault(Locale.ENGLISH);
runLocalHttpServer();
setUpVideoRecorder();
}
private static void runLocalHttpServer() throws Exception {
if (server == null) {
synchronized (IntegrationTest.class) {
port = findFreePort();
log.info("START " + browser + " TESTS");
server = new LocalHttpServer(port, SSL).start();
if (SSL) {
protocol = "https:
} else {
protocol = "http:
}
Configuration.baseUrl = protocol + "127.0.0.1:" + port;
}
}
}
private static void setUpVideoRecorder() {
File videoFolder = new File("build/reports/tests/" + Configuration.browser);
videoFolder.mkdirs();
System.setProperty("video.folder", videoFolder.getAbsolutePath());
System.setProperty("video.enabled", String.valueOf(!isHeadless()));
System.setProperty("video.mode", String.valueOf(ANNOTATED));
}
@AfterAll
public static void restartUnstableWebdriver() {
if (isIE() || isPhantomjs()) {
closeWebDriver();
}
}
@BeforeEach
void setUpEach() {
resetSettings();
restartReallyUnstableBrowsers();
rememberTimeout();
}
private void resetSettings() {
Configuration.baseUrl = protocol + "127.0.0.1:" + port;
Configuration.reportsFolder = "build/reports/tests/" + Configuration.browser;
fastSetValue = false;
browserSize = "1024x768";
server.uploadedFiles.clear();
// proxy breaks Firefox/Marionette because of this error:
// "InvalidArgumentError: Expected [object Undefined] undefined to be an integer"
Configuration.fileDownload = isFirefox() || isLegacyFirefox() ? HTTPGET : PROXY;
}
private void restartReallyUnstableBrowsers() {
if (isSafari()) {
closeWebDriver();
}
}
private void rememberTimeout() {
defaultTimeout = timeout;
}
protected void openFile(String fileName) {
open("/" + fileName + "?browser=" + Configuration.browser +
"&timeout=" + Configuration.timeout);
}
<T> T openFile(String fileName, Class<T> pageObjectClass) {
return open("/" + fileName + "?browser=" + Configuration.browser +
"&timeout=" + Configuration.timeout, pageObjectClass);
}
@AfterEach
public void restoreDefaultProperties() {
timeout = defaultTimeout;
clickViaJs = false;
}
}
|
package fr.adrienbrault.idea.symfony2plugin;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMap;
import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMapParser;
import fr.adrienbrault.idea.symfony2plugin.routing.Route;
import org.jetbrains.annotations.NotNull;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
public class Symfony2ProjectComponent implements ProjectComponent {
private Project project;
private ServiceMap servicesMap;
private Long servicesMapLastModified;
private Map<String, Route> routes;
private Long routesLastModified;
public Symfony2ProjectComponent(Project project) {
this.project = project;
}
public void initComponent() {
System.out.println("initComponent");
}
public void disposeComponent() {
System.out.println("disposeComponent");
}
@NotNull
public String getComponentName() {
return "Symfony2ProjectComponent";
}
public void projectOpened() {
System.out.println("projectOpened");
}
public void projectClosed() {
System.out.println("projectClosed");
}
public ServiceMap getServicesMap() {
if (null != servicesMap) {
return servicesMap;
}
String defaultServiceMapFilePath = getPath(project, Settings.getInstance(project).pathToProjectContainer);
File xmlFile = new File(defaultServiceMapFilePath);
if (!xmlFile.exists()) {
return new ServiceMap();
}
Long xmlFileLastModified = xmlFile.lastModified();
if (xmlFileLastModified.equals(servicesMapLastModified)) {
return servicesMap;
}
try {
ServiceMapParser serviceMapParser = new ServiceMapParser();
servicesMap = serviceMapParser.parse(xmlFile);
servicesMapLastModified = xmlFileLastModified;
return servicesMap;
} catch (SAXException ignored) {
} catch (IOException ignored) {
} catch (ParserConfigurationException ignored) {
}
return new ServiceMap();
}
public Map<String, Route> getRoutes() {
Map<String, Route> routes = new HashMap<String, Route>();
String urlGeneratorPath = getPath(project, Settings.getInstance(project).pathToUrlGenerator);
File urlGeneratorFile = new File(urlGeneratorPath);
VirtualFile virtualUrlGeneratorFile = VfsUtil.findFileByIoFile(urlGeneratorFile, false);
if (!urlGeneratorFile.exists()) {
return routes;
}
Long routesLastModified = urlGeneratorFile.lastModified();
if (routesLastModified.equals(this.routesLastModified)) {
return this.routes;
}
Matcher matcher = null;
try {
// Damn, what has he done!
// Right ?
// If you find a better way to parse the file ... submit a PR :P
matcher = Pattern.compile("'((?:[^'\\\\]|\\\\.)*)' => [^\\n]+'_controller' => '((?:[^'\\\\]|\\\\.)*)'[^\\n]+\n").matcher(VfsUtil.loadText(virtualUrlGeneratorFile));
} catch (IOException ignored) {
}
if (null == matcher) {
return routes;
}
while (matcher.find()) {
String routeName = matcher.group(1);
String controller = matcher.group(2).replace("\\\\", "\\");
Route route = new Route(routeName, controller);
routes.put(route.getName(), route);
}
this.routes = routes;
this.routesLastModified = routesLastModified;
return routes;
}
private String getPath(Project project, String path) {
if (!FileUtil.isAbsolute(path)) { // Project relative path
path = project.getBasePath() + "/" + path;
}
return path;
}
}
|
package fr.adrienbrault.idea.symfony2plugin.doctrine;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementResolveResult;
import com.intellij.psi.PsiPolyVariantReferenceBase;
import com.intellij.psi.ResolveResult;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.PhpNamespace;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil;
import fr.adrienbrault.idea.symfony2plugin.doctrine.component.EntityNamesServiceParser;
import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineEntityLookupElement;
import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineTypes;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class EntityReference extends PsiPolyVariantReferenceBase<PsiElement> {
private String entityName;
private boolean useClassNameAsLookupString = false;
public EntityReference(@NotNull StringLiteralExpression element, boolean useClassNameAsLookupString) {
this(element);
this.useClassNameAsLookupString = useClassNameAsLookupString;
}
public EntityReference(@NotNull StringLiteralExpression element) {
super(element);
entityName = element.getContents();
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
List<ResolveResult> results = new ArrayList<ResolveResult>();
PhpClass phpClass = EntityHelper.getEntityRepositoryClass(getElement().getProject(), this.entityName);
if(phpClass != null) {
results.add(new PsiElementResolveResult(phpClass));
}
PhpClass entity = EntityHelper.resolveShortcutName(getElement().getProject(), this.entityName);
if(entity != null) {
results.add(new PsiElementResolveResult(entity));
}
return results.toArray(new ResolveResult[results.size()]);
}
@NotNull
@Override
public Object[] getVariants() {
PhpIndex phpIndex = PhpIndex.getInstance(getElement().getProject());
Map<String, String> entityNamespaces = ServiceXmlParserFactory.getInstance(getElement().getProject(), EntityNamesServiceParser.class).getEntityNameMap();
List<LookupElement> results = new ArrayList<LookupElement>();
// find Repository interface to filter RepositoryClasses out
PhpClass repositoryInterface = PhpElementsUtil.getInterface(phpIndex, DoctrineTypes.REPOSITORY_INTERFACE);
if(null == repositoryInterface) {
return results.toArray();
}
for (Map.Entry<String, String> entry : entityNamespaces.entrySet()) {
// search for classes that match the symfony2 namings
Collection<PhpNamespace> entities = phpIndex.getNamespacesByName(entry.getValue());
// @TODO: it looks like PhpIndex cant search for classes like \ns\Path\*\...
// temporary only use flat entities and dont support "MyBundle:Folder\Entity"
for (PhpNamespace entity_files : entities) {
// build our symfony2 shortcut
String filename = entity_files.getContainingFile().getName();
String className = filename.substring(0, filename.lastIndexOf('.'));
String repoName = entry.getKey() + ':' + className;
// dont add Repository classes and abstract entities
PhpClass entityClass = PhpElementsUtil.getClass(phpIndex, entityNamespaces.get(entry.getKey()) + "\\" + className);
if(null != entityClass && isEntity(entityClass, repositoryInterface)) {
results.add(new DoctrineEntityLookupElement(repoName, entityClass, this.useClassNameAsLookupString));
}
}
}
return results.toArray();
}
public static boolean isEntity(PhpClass entityClass, PhpClass repositoryClass) {
if(entityClass.isAbstract()) {
return false;
}
Symfony2InterfacesUtil symfony2Util = new Symfony2InterfacesUtil();
return !symfony2Util.isInstanceOf(entityClass, repositoryClass);
}
}
|
package org.jscep.client;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.jscep.transaction.Transaction;
import org.jscep.transaction.Transaction.State;
import org.jscep.x509.X509Util;
import org.junit.Assume;
import org.junit.Test;
/**
* These tests are coupled to the ScepServletImpl class
*
* @author David Grant
*/
public class ClientTest extends AbstractClientTest {
/**
* The requester MUST use RSA keys for all symmetric key operations.
*
* @throws Exception if any error occurs.
*/
@Test(expected = IllegalArgumentException.class)
public void testRsa() throws Exception {
final KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair();
final X509Certificate identity = X509Util.createEphemeralCertificate(new X500Principal("CN=jscep.org"), keyPair);
final URL url = new URL("http://jscep.org/pkiclient.exe");
new Client(url, identity, keyPair.getPrivate(), new NoSecurityCallbackHandler());
}
@Test
public void testRenewalEnrollAllowed() throws Exception {
// Ignore this test if the CA doesn't support renewal.
Assume.assumeTrue(client.getCaCapabilities().isRenewalSupported());
PKCS10CertificationRequest csr = getCsr(identity.getSubjectX500Principal(), keyPair.getPublic(), keyPair.getPrivate(), password);
Transaction t = client.enrol(csr);
if (t.send() == State.CERT_ISSUED) {
t.getCertStore();
}
}
@Test
public void testEnroll() throws Exception {
PKCS10CertificationRequest csr = getCsr(identity.getSubjectX500Principal(), keyPair.getPublic(), keyPair.getPrivate(), password);
Transaction trans = client.enrol(csr);
State state = trans.send();
if (state == State.CERT_ISSUED) {
CertStore store = trans.getCertStore();
System.out.println(store.getCertificates(null));
}
}
@Test
public void testEnrollThenGet() throws Exception {
Transaction trans = client.enrol(getCsr(identity.getSubjectX500Principal(), keyPair.getPublic(), keyPair.getPrivate(), password));
State state = trans.send();
Assume.assumeTrue(state == State.CERT_ISSUED);
X509Certificate issued = (X509Certificate) trans.getCertStore().getCertificates(null).iterator().next();
Certificate retrieved = client.getCertificate(issued.getSerialNumber()).iterator().next();
assertEquals(issued, retrieved);
}
@Test
public void testEnrollInvalidPassword() throws Exception {
Transaction trans = client.enrol(getCsr(identity.getSubjectX500Principal(), keyPair.getPublic(), keyPair.getPrivate(), new char[0]));
State state = trans.send();
assertThat(state, is(State.CERT_NON_EXISTANT));
}
@Test
public void cgiProgIsIgnoredForIssue24() throws GeneralSecurityException, MalformedURLException {
final KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
final X509Certificate identity = X509Util.createEphemeralCertificate(new X500Principal("CN=jscep.org"), keyPair);
final URL url = new URL("http://someurl/certsrv/mscep/mscep.dll");
Client c = new Client(url, identity, keyPair.getPrivate(), new NoSecurityCallbackHandler());
assertNotNull(c);
}
private PKCS10CertificationRequest getCsr(X500Principal subject, PublicKey pubKey, PrivateKey priKey, char[] password) throws GeneralSecurityException, IOException {
DERPrintableString cpSet = new DERPrintableString(new String(password));
SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded());
JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA1withRSA");
ContentSigner signer;
try {
signer = signerBuilder.build(priKey);
} catch (OperatorCreationException e) {
IOException ioe = new IOException();
ioe.initCause(e);
throw ioe;
}
PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(X500Name.getInstance(subject.getEncoded()), pkInfo);
builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, cpSet);
return builder.build(signer);
}
}
|
package zmq;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
* This test does one setup, and runs a few tests on that setup.
*/
public class TestReqCorrelateRelaxed
{
private static final String PAYLOAD = "Payload";
/**
* Prepares sockets and runs actual tests.
*
* Doing it this way so order is guaranteed.
*
* @throws Exception
*/
@Test
public void overallSetup() throws Exception
{
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
SocketBase dealer = ZMQ.socket(ctx, ZMQ.ZMQ_DEALER);
assertThat(dealer, notNullValue());
boolean brc = ZMQ.bind(dealer, "inproc:
assertThat(brc, is(true));
SocketBase reqClient = ZMQ.socket(ctx, ZMQ.ZMQ_REQ);
assertThat(reqClient, notNullValue());
reqClient.setSocketOpt(ZMQ.ZMQ_REQ_CORRELATE, 1);
reqClient.setSocketOpt(ZMQ.ZMQ_REQ_RELAXED, 1);
reqClient.setSocketOpt(ZMQ.ZMQ_RCVTIMEO, 100);
brc = ZMQ.connect(reqClient, "inproc:
assertThat(brc, is(true));
// Test good path
byte[] origRequestId = testReqSentFrames(dealer, reqClient);
testReqRecvGoodRequestId(dealer, reqClient, origRequestId);
// Test what happens when a bad request ID is sent back.
origRequestId = testReqSentFrames(dealer, reqClient);
testReqRecvBadRequestId(dealer, reqClient, origRequestId);
}
/**
* Tests that the correct frames are sent by the REQ socket.
*
* @param dealer
* @param reqClient
* @throws Exception
* @returns the request ID that was received
*/
public byte[] testReqSentFrames(SocketBase dealer, SocketBase reqClient) throws Exception
{
// Send simple payload over REQ socket
Msg request = new Msg(PAYLOAD.getBytes());
assertThat(ZMQ.sendMsg(reqClient, request, 0), is(PAYLOAD.getBytes().length));
// Verify that the right frames were sent: [request ID, empty frame, payload]
// 1. request ID
Msg receivedReqId = ZMQ.recv(dealer, 0);
assertThat(receivedReqId, notNullValue());
assertThat(receivedReqId.size(), is(Req.REQUEST_ID_LENGTH));
assertThat(receivedReqId.flags() & ZMQ.ZMQ_MORE, not(0));
byte[] buf = new byte[128];
int requestIdLen = receivedReqId.getBytes(0, buf, 0, 128);
assertThat(requestIdLen, is(Req.REQUEST_ID_LENGTH));
byte[] requestId = Arrays.copyOf(buf, Req.REQUEST_ID_LENGTH);
// 2. empty frame
Msg receivedEmpty = ZMQ.recv(dealer, 0);
assertThat(receivedEmpty, notNullValue());
assertThat(receivedEmpty.size(), is(0));
assertThat(receivedEmpty.flags() & ZMQ.ZMQ_MORE, not(0));
// 3. Payload
Msg receivedPayload = ZMQ.recv(dealer, 0);
assertThat(receivedPayload, notNullValue());
assertThat(receivedPayload.size(), is(PAYLOAD.getBytes().length));
assertThat(receivedPayload.flags() & ZMQ.ZMQ_MORE, is(0));
int receivedPayloadLen = receivedPayload.getBytes(0, buf, 0, 128);
assertThat(receivedPayloadLen, is(PAYLOAD.getBytes().length));
for (int i = 0; i < receivedPayloadLen; i++) {
assertThat(PAYLOAD.getBytes()[i], is(PAYLOAD.getBytes()[i]));
}
return requestId;
}
/**
* Test that REQ sockets with CORRELATE/RELAXED receive a response with
* correct request ID correctly.
*
* @param dealer
* @param reqClient
* @param origRequestId the request ID that was sent by the REQ socket
* earlier
* @throws Exception
*/
public void testReqRecvGoodRequestId(SocketBase dealer, SocketBase reqClient, byte[] origRequestId) throws Exception
{
Msg requestId = new Msg(origRequestId);
Msg empty = new Msg();
Msg responsePayload = new Msg(PAYLOAD.getBytes());
// Send response
assertThat(ZMQ.send(dealer, requestId, ZMQ.ZMQ_SNDMORE), is(6));
assertThat(ZMQ.send(dealer, empty, ZMQ.ZMQ_SNDMORE), is(0));
assertThat(ZMQ.send(dealer, responsePayload, 0), is(responsePayload.size()));
// Receive response (payload only)
Msg receivedResponsePayload = ZMQ.recv(reqClient, 0);
assertThat(receivedResponsePayload, notNullValue());
byte[] buf = new byte[128];
int payloadLen = receivedResponsePayload.getBytes(0, buf, 0, 128);
assertThat(payloadLen, is(PAYLOAD.getBytes().length));
}
/**
* Asserts that a response with a non-current request ID is ignored.
*
* @param dealer
* @param reqClient
* @param origRequestId
* @throws Exception
*/
public void testReqRecvBadRequestId(SocketBase dealer, SocketBase reqClient, byte[] origRequestId) throws Exception
{
Msg badRequestId = new Msg("gobbledygook".getBytes());
Msg goodRequestId = new Msg(origRequestId);
Msg empty = new Msg();
Msg badResponsePayload = new Msg("Bad response".getBytes());
Msg goodResponsePayload = new Msg(PAYLOAD.getBytes());
// Send response with bad request ID
assertThat(ZMQ.send(dealer, badRequestId, ZMQ.ZMQ_SNDMORE), is(12));
assertThat(ZMQ.send(dealer, empty, ZMQ.ZMQ_SNDMORE), is(0));
assertThat(ZMQ.send(dealer, badResponsePayload, 0), is(badResponsePayload.size()));
// Send response with good request ID
assertThat(ZMQ.send(dealer, goodRequestId, ZMQ.ZMQ_SNDMORE), is(6));
assertThat(ZMQ.send(dealer, empty, ZMQ.ZMQ_SNDMORE), is(0));
assertThat(ZMQ.send(dealer, goodResponsePayload, 0), is(goodResponsePayload.size()));
// Receive response (payload only)
Msg receivedResponsePayload = ZMQ.recv(reqClient, 0);
assertThat(receivedResponsePayload, notNullValue());
// Expecting PAYLOAD, not "Bad payload"
byte[] buf = new byte[128];
int payloadLen = receivedResponsePayload.getBytes(0, buf, 0, 128);
assertThat(payloadLen, is(PAYLOAD.getBytes().length));
byte[] receivedPayload = Arrays.copyOf(buf, payloadLen);
assertThat(receivedPayload, is(PAYLOAD.getBytes()));
}
}
|
package com.voxelmodpack.hdskins.skins;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import com.mojang.util.UUIDTypeAdapter;
import com.voxelmodpack.hdskins.HDSkinManager;
import com.voxelmodpack.hdskins.upload.ThreadMultipartPostUpload;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Session;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
public class LegacySkinServer implements SkinServer {
private static final String SERVER_ID = "7853dfddc358333843ad55a2c7485c4aa0380a51";
private static final Logger logger = LogManager.getLogger();
private final String address;
private final String gateway;
public LegacySkinServer(String address) {
this(address, null);
}
public LegacySkinServer(String address, @Nullable String gateway) {
this.address = address;
this.gateway = gateway;
}
@Override
public Optional<MinecraftProfileTexture> getPreviewTexture(MinecraftProfileTexture.Type type, GameProfile profile) {
if (Strings.isNullOrEmpty(this.gateway))
return Optional.empty();
return Optional.of(new MinecraftProfileTexture(getPath(this.gateway, type, profile), null));
}
@Override
public Optional<MinecraftTexturesPayload> loadProfileData(GameProfile profile) {
ImmutableMap.Builder<MinecraftProfileTexture.Type, MinecraftProfileTexture> builder = ImmutableMap.builder();
for (MinecraftProfileTexture.Type type : MinecraftProfileTexture.Type.values()) {
String url = getPath(this.address, type, profile);
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
if (urlConnection.getResponseCode() / 100 != 2) {
throw new IOException("Bad response code: " + urlConnection.getResponseCode());
}
builder.put(type, new MinecraftProfileTexture(url, null));
logger.debug("Found skin for {} at {}", profile.getName(), url);
} catch (IOException e) {
logger.trace("Couldn't find texture for {} at {}. Does it exist?", profile.getName(), url, e);
}
}
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = builder.build();
if (map.isEmpty()) {
logger.debug("No textures found for {} at {}", profile, this.address);
return Optional.empty();
}
return Optional.of(new TexturesPayloadBuilder()
.profileId(profile.getId())
.profileName(profile.getName())
.timestamp(System.currentTimeMillis())
.isPublic(true)
.textures(map)
.build());
}
@Override
public ListenableFuture<SkinUploadResponse> uploadSkin(Session session, @Nullable Path image, MinecraftProfileTexture.Type type, boolean thinSkinType) {
if (Strings.isNullOrEmpty(this.gateway))
return Futures.immediateFailedFuture(new NullPointerException("gateway url is blank"));
return HDSkinManager.skinUploadExecutor.submit(() -> {
verifyServerConnection(session, SERVER_ID);
Map<String, ?> data = image == null ? getClearData(session, type) : getUploadData(session, type, (thinSkinType ? "slim" : "default"), image);
ThreadMultipartPostUpload upload = new ThreadMultipartPostUpload(this.gateway, data);
String response = upload.uploadMultipart();
return new SkinUploadResponse(response.equalsIgnoreCase("OK"), response);
});
}
private static Map<String, ?> getData(Session session, MinecraftProfileTexture.Type type, String model, String param, Object val) {
return ImmutableMap.of(
"user", session.getUsername(),
"uuid", session.getPlayerID(),
"type", type.toString().toLowerCase(Locale.US),
"model", model,
param, val);
}
private static Map<String, ?> getClearData(Session session, MinecraftProfileTexture.Type type) {
return getData(session, type, "default", "clear", "1");
}
private static Map<String, ?> getUploadData(Session session, MinecraftProfileTexture.Type type, String model, Path skinFile) {
return getData(session, type, model, type.toString().toLowerCase(Locale.US), skinFile);
}
private static String getPath(String address, MinecraftProfileTexture.Type type, GameProfile profile) {
String uuid = UUIDTypeAdapter.fromUUID(profile.getId());
String path = type.toString().toLowerCase() + "s";
return String.format("%s/%s/%s.png", address, path, uuid);
}
private static void verifyServerConnection(Session session, String serverId) throws AuthenticationException {
MinecraftSessionService service = Minecraft.getMinecraft().getSessionService();
service.joinServer(session.getProfile(), session.getToken(), serverId);
}
static LegacySkinServer from(String parsed) {
Matcher matcher = Pattern.compile("^legacy:(.+?)(?:;(.*))?$").matcher(parsed);
if (matcher.find()) {
String addr = matcher.group(1);
String gate = matcher.group(2);
return new LegacySkinServer(addr, gate);
}
throw new IllegalArgumentException("server format string was not correct");
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("address", address)
.add("gateway", gateway)
.toString();
}
}
|
package org.xins.tests.client;
import com.mycompany.allinone.capi.*;
import com.mycompany.allinone.types.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.client.UnsuccessfulXINSCallException;
import org.xins.client.XINSCallConfig;
import org.xins.common.Utils;
import org.xins.common.collections.BasicPropertyReader;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.service.*;
import org.xins.logdoc.ExceptionUtils;
import org.xins.tests.AllTests;
/**
* Tests the generated <em>allinone</em> CAPI class, other than calling the
* actual functions.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
public class CAPITests extends TestCase {
// Class functions
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(CAPITests.class);
}
// Constructor
/**
* Constructs a new <code>CAPITests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public CAPITests(String name) {
super(name);
}
// Methods
public void testCAPIConstruction_XINS_1_0() throws Exception {
TargetDescriptor td;
CAPI capi;
// Pass null to constructor (should fail)
try {
new CAPI((Descriptor) null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
// Pass URL with unsupported protocol
td = new TargetDescriptor("bla:
try {
new CAPI(td);
fail("Expected UnsupportedProtocolException.");
} catch (UnsupportedProtocolException exception) {
assertEquals(td, exception.getTargetDescriptor());
}
// Pass URL with supported protocol
td = new TargetDescriptor("http:
capi = new CAPI(td);
assertNotNull(capi.getXINSCallConfig());
assertNotNull(capi.getXINSVersion());
}
public void testCAPIConstruction_XINS_1_1() throws Exception {
String url;
BasicPropertyReader properties;
// Pass nulls (should fail)
properties = new BasicPropertyReader();
try {
CAPI.create((PropertyReader) null, (String) null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
try {
CAPI.create((PropertyReader) null, "SomeName");
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
try {
CAPI.create(properties, null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
try {
CAPI.create((PropertyReader) null, (String) null, (XINSCallConfig) null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
try {
CAPI.create(properties, (String) null, (XINSCallConfig) null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
try {
CAPI.create((PropertyReader) null, "SomeName", (XINSCallConfig) null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) { }
// Pass empty property set (missing required property)
try {
CAPI.create(properties, "allinone");
fail("Expected MissingRequiredPropertyException.");
} catch (MissingRequiredPropertyException exception) {
assertEquals("capis.allinone", exception.getPropertyName());
}
try {
CAPI.create(properties, "allinone", (XINSCallConfig) null);
fail("Expected MissingRequiredPropertyException.");
} catch (MissingRequiredPropertyException exception) {
assertEquals("capis.allinone", exception.getPropertyName());
}
// Pass property set with missing property
properties = new BasicPropertyReader();
properties.set("capis.allinone", "group, ordered, one, two");
properties.set("capis.allinone.one", "service, http://xins.org/, 5000");
try {
CAPI.create(properties, "allinone");
fail("Expected MissingRequiredPropertyException.");
} catch (MissingRequiredPropertyException exception) {
assertEquals("capis.allinone.two", exception.getPropertyName());
}
// Pass invalid property value
properties = new BasicPropertyReader();
url = "bla:
properties.set("capis.allinone", url);
try {
CAPI.create(properties, "allinone");
fail("Expected InvalidPropertyValueException.");
} catch (InvalidPropertyValueException exception) {
assertEquals("capis.allinone", exception.getPropertyName());
assertEquals(url, exception.getPropertyValue());
}
// Pass URL with unsupported protocol at root
properties = new BasicPropertyReader();
url = "bla:
properties.set("capis.allinone", "service, " + url + ", 5000");
try {
CAPI.create(properties, "allinone");
} catch (InvalidPropertyValueException exception) {
assertEquals("capis.allinone", exception.getPropertyName());
assertEquals(properties.get("capis.allinone"), exception.getPropertyValue());
Throwable cause = ExceptionUtils.getCause(exception);
assertNotNull("Expected InvalidPropertyValueException to have an UnsupportedProtocolException as the cause.", cause);
assertTrue("Expected cause of InvalidPropertyValueException to be an UnsupportedProtocolException instead of an instance of class " + cause.getClass().getName(), cause instanceof UnsupportedProtocolException);
UnsupportedProtocolException upe = (UnsupportedProtocolException) cause;
assertEquals(url, upe.getTargetDescriptor().getURL());
}
try {
CAPI.create(properties, "allinone", (XINSCallConfig) null);
} catch (InvalidPropertyValueException exception) {
Throwable cause = ExceptionUtils.getCause(exception);
assertNotNull("Expected InvalidPropertyValueException to have an UnsupportedProtocolException as the cause.", cause);
assertTrue("Expected cause of InvalidPropertyValueException to be an UnsupportedProtocolException instead of an instance of class " + cause.getClass().getName(), cause instanceof UnsupportedProtocolException);
UnsupportedProtocolException upe = (UnsupportedProtocolException) cause;
assertEquals(url, upe.getTargetDescriptor().getURL());
}
// Pass URL with unsupported protocol at leaf
properties = new BasicPropertyReader();
url = "bla://xins.org/";
properties.set("capis.allinone", "group, ordered, one, two");
properties.set("capis.allinone.one", "service, http://xins.org/, 5000");
properties.set("capis.allinone.two", "service, " + url + ", 5000");
try {
CAPI.create(properties, "allinone");
} catch (InvalidPropertyValueException exception) {
assertEquals("Expected invalid property value on property \"capis.allinone.two\" instead of on property \"" + exception.getPropertyName() + "\".", "capis.allinone.two", exception.getPropertyName());
assertEquals(properties.get("capis.allinone.two"), exception.getPropertyValue());
Throwable cause = ExceptionUtils.getCause(exception);
assertNotNull("Expected InvalidPropertyValueException to have an UnsupportedProtocolException as the cause.", cause);
assertTrue("Expected cause of InvalidPropertyValueException to be an UnsupportedProtocolException instead of an instance of class " + cause.getClass().getName(), cause instanceof UnsupportedProtocolException);
UnsupportedProtocolException upe = (UnsupportedProtocolException) cause;
assertEquals(url, upe.getTargetDescriptor().getURL());
}
try {
CAPI.create(properties, "allinone", (XINSCallConfig) null);
} catch (InvalidPropertyValueException exception) {
assertEquals("Expected invalid property value on property \"capis.allinone.two\" instead of on property \"" + exception.getPropertyName() + "\".", "capis.allinone.two", exception.getPropertyName());
assertEquals(properties.get("capis.allinone.two"), exception.getPropertyValue());
Throwable cause = ExceptionUtils.getCause(exception);
assertNotNull("Expected InvalidPropertyValueException to have an UnsupportedProtocolException as the cause.", cause);
assertTrue("Expected cause of InvalidPropertyValueException to be an UnsupportedProtocolException instead of an instance of class " + cause.getClass().getName(), cause instanceof UnsupportedProtocolException);
UnsupportedProtocolException upe = (UnsupportedProtocolException) cause;
assertEquals(url, upe.getTargetDescriptor().getURL());
}
}
public void testCompatibility() throws Exception {
// This test does not work on Java 1.3, because XINS 1.1.0 generates
// Java 1.4-specific bytecode.
if (Utils.getJavaVersion() < 1.4) {
// TODO: Log warning
return;
}
// Add the servlet
AllTests.HTTP_SERVER.addServlet("org.xins.tests.client.MyProjectServlet", "/myproject");
try {
TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/myproject");
com.mycompany.myproject.capi.CAPI capi = new com.mycompany.myproject.capi.CAPI(descriptor);
capi.callMyFunction(com.mycompany.myproject.types.Gender.MALE, "Bnd");
fail("callMyFunction succeeded even with a invalid name");
} catch (UnsuccessfulXINSCallException ex) {
assertEquals("NoVowel", ex.getErrorCode());
}
// Remove the servlet
AllTests.HTTP_SERVER.removeServlet("/myproject");
}
}
|
package com.mararok.epicwar.faction.internal;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import com.mararok.epicwar.War;
import com.mararok.epicwar.faction.Faction;
import com.mararok.epicwar.faction.FactionData;
import com.mararok.epicwar.faction.FactionManager;
public class FactionManagerImpl implements FactionManager {
private FactionImpl[] factions;
private FactionMapper mapper;
private War war;
public FactionManagerImpl(FactionMapper mapper, War war) throws Exception {
factions = new FactionImpl[Faction.Color.values().length];
this.mapper = mapper;
Collection<FactionImpl> collection = mapper.findAll();
for (FactionImpl faction : collection) {
factions[faction.getId()] = faction;
}
this.war = war;
}
@Override
public Faction findById(int id) {
return factions[id];
}
@Override
public Faction findByColor(Faction.Color color) {
return factions[color.ordinal()];
}
@Override
public Faction findByName(String name) {
for (Faction faction : factions) {
if (faction.getName().equals(name)) {
return faction;
}
}
return null;
}
@Override
public Faction findByShortcut(String shortcut) {
for (Faction faction : factions) {
if (faction.getShortcut().equals(shortcut)) {
return faction;
}
}
return null;
}
@Override
public Collection<Faction> findAll() {
List<Faction> collection = new LinkedList<Faction>();
for (Faction faction : factions) {
if (faction != null) {
collection.add(faction);
}
}
return collection;
}
@Override
public Faction create(FactionData data) throws Exception {
if (findByColor(data.color) == null) {
FactionImpl faction = mapper.insert(data);
factions[faction.getId()] = faction;
return faction;
}
return null;
}
@Override
public void update(Faction faction) throws Exception {
FactionImpl entity = (FactionImpl) faction;
mapper.update(entity);
entity.clearChanges();
}
@Override
public void delete(Faction faction) throws Exception {
FactionImpl entity = (FactionImpl) faction;
mapper.delete(entity);
factions[faction.getId()] = null;
}
@Override
public War getWar() {
return war;
}
}
|
package br.gov.servicos.editor.config;
import br.gov.servicos.editor.servicos.Orgao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collection;
import static java.util.Arrays.asList;
@Configuration
public class ConteudoDeReferencia {
@Bean
Collection<String> tiposDeCanalDePrestacao() {
return asList(
"Web",
"Presencial",
"Telefone",
"E-mail",
"Caixa postal",
"Aplicativo móvel",
"SMS",
"Fax"
);
}
@Bean
Collection<Orgao> orgaos() {
return asList(
new Orgao("arquivo-nacional-an", "Arquivo Nacional (AN)"),
new Orgao("banco-central-do-brasil-bcb", "Banco Central do Brasil (BCB)"),
new Orgao("comissao-de-anistia-cma", "Comissão de Anistia (CMA)"),
new Orgao("companhia-nacional-de-abastecimento-conab", "Companhia Nacional de Abastecimento (Conab)"),
new Orgao("conselho-administrativo-de-defesa-economica-cade", "Conselho Administrativo de Defesa Econômica (Cade)"),
new Orgao("defensoria-publica-da-uniao-dpu", "Defensoria Pública da União (DPU)"),
new Orgao("departamento-de-policia-federal-dpf", "Departamento de Polícia Federal (DPF)"),
new Orgao("departamento-de-policia-rodoviaria-federal-dprf", "Departamento de Polícia Rodoviária Federal (DPRF)"),
new Orgao("empresa-brasileira-de-infraestrutura-aeroportuaria-infraero", "Empresa Brasileira de Infraestrutura Aeroportuária (Infraero)"),
new Orgao("fundacao-nacional-do-indio-funai", "Fundação Nacional do Índio (Funai)"),
new Orgao("instituto-nacional-de-meteorologia-inmet", "Instituto Nacional de Meteorologia (INMET)"),
new Orgao("instituto-nacional-do-seguro-social-inss", "Instituto Nacional do Seguro Social (INSS)"),
new Orgao("ministerio-da-agricultura-pecuaria-e-abastecimento-mapa", "Ministério da Agricultura, Pecuária e Abastecimento (MAPA)"),
new Orgao("ministerio-da-educacao-mec", "Ministério da Educação (MEC)"),
new Orgao("ministerio-da-fazenda-mf", "Ministério da Fazenda (MF)"),
new Orgao("ministerio-da-justica-mj", "Ministério da Justiça (MJ)"),
new Orgao("ministerio-da-pesca-e-aquicultura-mpa", "Ministério da Pesca e Aquicultura (MPA)"),
new Orgao("ministerio-da-previdencia-social-mps", "Ministério da Previdência Social (MPS)"),
new Orgao("ministerio-da-saude-ms", "Ministério da Saúde"),
new Orgao("ministerio-do-desenvolvimento-agrario-mda", "Ministério do Desenvolvimento Agrário (MDA)"),
new Orgao("ministerio-do-desenvolvimento-social-e-combate-a-fome-mds", "Ministério do Desenvolvimento Social e Combate a Fome (MDS)"),
new Orgao("ministerio-do-planejamento-orcamento-e-gestao-mpog", "Ministério do Planejamento, Orçamento e Gestão (MPOG)"),
new Orgao("ministerio-do-trabalho-e-emprego-mte", "Ministério do Trabalho e Emprego (MTE)"),
new Orgao("ministerio-do-turismo-mtur", "Ministério do Turismo (MTur)"),
new Orgao("secretaria-da-receita-federal-do-brasil-rfb", "Secretaria da Receita Federal do Brasil (RFB)"),
new Orgao("secretaria-de-aviacao-civil-sac", "Secretaria de Aviação Civil (SAC)"),
new Orgao("secretaria-de-planejamento-e-investimentos-estrategicos-spi", "Secretaria de Planejamento e Investimentos Estratégicos (SPI)"),
new Orgao("secretaria-do-patrimonio-da-uniao-spu-mp", "Secretaria do Patrimônio da União (SPU)"),
new Orgao("secretaria-nacional-de-justica-snj", "Secretaria Nacional de Justiça (SNJ)"),
new Orgao("secretaria-nacional-de-politicas-sobre-drogas-senad", "Secretaria Nacional de Políticas Sobre Drogas (Senad)"),
new Orgao("secretaria-nacional-de-seguranca-publica-senasp", "Secretaria Nacional de Segurança Pública (Senasp)")
);
}
@Bean
Collection<String> medidasDeTempo() {
return asList(
"minutos",
"horas",
"dias",
"dias corridos",
"dias úteis",
"meses"
);
}
@Bean
Collection<String> segmentosDaSociedade() {
return asList(
"Cidadãos",
"Empresas",
"Governos",
"Demais segmentos (ONGs, organizações sociais, etc)"
);
}
@Bean
Collection<String> eventosDaLinhaDaVida() {
return asList(
"Apoio financeiro e crédito",
"Aposentadoria",
"Contas e Impostos",
"Cuidados com a saúde",
"Documentos e certidões",
"Empreendedorismo e negócios",
"Estrangeiros no Brasil",
"Estudos",
"Exportação de produtos e serviços",
"Família",
"Importação de produtos e serviços",
"Imóveis",
"Profissão e trabalho",
"Veículos",
"Viagem ao exterior"
);
}
@Bean
Collection<String> areasDeInteresse() {
return asList(
"Administração",
"Agropecuária",
"Comércio e Serviços",
"Comunicações",
"Cultura",
"Defesa Nacional",
"Economia e Finanças",
"Educação",
"Energia",
"Esporte e Lazer",
"Habitação",
"Indústria",
"Meio-ambiente",
"Pesquisa e Desenvolvimento",
"Previdência Social",
"Proteção Social",
"Relações Internacionais",
"Saneamento",
"Saúde",
"Segurança e Ordem Pública",
"Trabalho",
"Transportes",
"Urbanismo");
}
}
|
package ca.corefacility.bioinformatics.irida.model;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.envers.Audited;
import org.hibernate.validator.constraints.URL;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectUserJoin;
import ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProject;
import ca.corefacility.bioinformatics.irida.model.user.Organization;
import ca.corefacility.bioinformatics.irida.validators.annotations.ValidProjectName;
/**
* A project object.
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
* @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca>
*/
@Entity
@Table(name = "project")
@Audited
public class Project implements IridaThing, Comparable<Project> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull(message = "{project.name.notnull}")
@Size(min = 5, message = "{project.name.size}")
@ValidProjectName
private String name;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private final Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
@Lob
private String projectDescription;
@URL(message = "{project.remoteURL.url}")
private String remoteURL;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, mappedBy = "project")
private List<ProjectUserJoin> users;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, mappedBy = "project")
private List<ProjectSampleJoin> samples;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, mappedBy = "subject")
private List<RelatedProject> relatedProjects;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, mappedBy = "relatedProject")
private List<RelatedProject> projectsRelatedTo;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.DETACH)
private Organization organization;
private String organism;
public Project() {
createdDate = new Date();
modifiedDate = createdDate;
}
/**
* Create a new {@link Project} with the given name
*
* @param name
* The name of the project
*/
public Project(String name) {
this();
this.name = name;
}
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public boolean equals(Object other) {
if (other instanceof Project) {
Project p = (Project) other;
return Objects.equals(createdDate, p.createdDate) && Objects.equals(modifiedDate, p.modifiedDate)
&& Objects.equals(name, p.name) && Objects.equals(organization, p.organization);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(createdDate, modifiedDate, name, organization);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Project p) {
return modifiedDate.compareTo(p.modifiedDate);
}
@Override
public String getLabel() {
return name;
}
@Override
public Date getTimestamp() {
return createdDate;
}
@Override
public Date getModifiedDate() {
return modifiedDate;
}
@Override
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getProjectDescription() {
return projectDescription;
}
public void setProjectDescription(String projectDescription) {
this.projectDescription = projectDescription;
}
public String getRemoteURL() {
return remoteURL;
}
public void setRemoteURL(String remoteURL) {
this.remoteURL = remoteURL;
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public String getOrganism() {
return organism;
}
public void setOrganism(String organism) {
this.organism = organism;
}
}
|
package cloud.swiftnode.ksecurity.module.kvaccine;
import cloud.swiftnode.ksecurity.KSecurity;
import cloud.swiftnode.ksecurity.abstraction.StorageCountDownLatch;
import cloud.swiftnode.ksecurity.abstraction.mock.MockPlugin;
import cloud.swiftnode.ksecurity.module.Module;
import cloud.swiftnode.ksecurity.module.kgui.abstraction.gui.KAlert;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.intercepter.KOperatorMap;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.intercepter.KOperatorSet;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.intercepter.KPluginManager;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.intercepter.KProxySelector;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.processor.HighInjectionProcessor;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.processor.LowInjectionProcessor;
import cloud.swiftnode.ksecurity.module.kvaccine.abstraction.processor.VirusScanProcessor;
import cloud.swiftnode.ksecurity.util.Lang;
import cloud.swiftnode.ksecurity.util.Reflections;
import cloud.swiftnode.ksecurity.util.Static;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.net.ProxySelector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class KVaccine extends Module {
public KVaccine(JavaPlugin parent) {
super(parent);
}
@Override
public void onEnable() throws Exception {
// Virus Scan
Static.runTaskAsync(() -> new VirusScanProcessor().process());
// Injection
Static.runTaskAsync(() -> new HighInjectionProcessor().process());
Object playerList = Reflections.getDecFieldObj(Bukkit.getServer(), "playerList");
Class playerListCls = playerList.getClass().getSuperclass();
Field fieldA = playerListCls.getDeclaredField("operators");
fieldA.setAccessible(true);
Field fieldB = Bukkit.getServer().getClass().getDeclaredField("pluginManager");
fieldB.setAccessible(true);
new Thread(() -> {
while (true) {
try {
Thread.sleep(5000);
Object objA = fieldA.get(playerList);
Object objB = fieldB.get(Bukkit.getServer());
Object objC = new Object();
try {
objC = Reflections.getDecFieldObj(objA.getClass().getSuperclass(), objA, "d");
} catch (Exception ex) {
// Ignore
}
if (!(objA instanceof KOperatorSet) && !(objC instanceof KOperatorMap)
|| !(objB instanceof KPluginManager)
|| !(ProxySelector.getDefault() instanceof KProxySelector)
|| KSecurity.inst == null
|| !KSecurity.inst.isEnabled()) {
detect(Lang.DAMAGE_DETECT.builder());
}
} catch (InterruptedException ex) {
shutdown();
} catch (Exception ex) {
detect(Lang.DAMAGE_EXCEPTION_DETECT.builder().addKey(Lang.Key.VALUE).addVal(ex.toString()));
}
}
}).start();
}
private void detect(Lang.MessageBuilder builder) {
try {
StorageCountDownLatch<Optional<ButtonType>> latch = new StorageCountDownLatch<>(1);
Static.log(builder);
new KAlert().setType(Alert.AlertType.ERROR)
.setButton(ButtonType.YES, ButtonType.NO)
.setContextText(builder.flatBuild())
.showAndWait(latch);
latch.await();
Optional<ButtonType> btn = latch.getValue();
if (btn.isPresent() && btn.get() == ButtonType.YES) {
shutdown();
} else {
new HighInjectionProcessor().process();
new LowInjectionProcessor().process();
PluginManager manager = Bukkit.getPluginManager();
Plugin plugin = manager.getPlugin("K-Security");
List<Plugin> plugins = new ArrayList<>(Arrays.asList(Bukkit.getPluginManager().getPlugins()));
if (plugin == null) {
plugin = new MockPlugin();
plugin.onEnable();
}
if (!plugins.contains(plugin)) {
if (manager instanceof KPluginManager) {
((KPluginManager) manager).addPlugin(plugin);
}
}
if (!plugin.isEnabled()) {
Reflections.setDecField(JavaPlugin.class, plugin, "isEnabled", true);
}
KSecurity.inst = plugin;
}
} catch (InterruptedException ex) {
// Ignore
} catch (Exception ex) {
shutdown();
}
}
private void shutdown() {
Bukkit.savePlayers();
for (World world : Bukkit.getWorlds()) {
world.save();
}
Bukkit.shutdown();
}
@Override
public String getSimpleVersion() {
return "1.1";
}
@Override
public void onLoad() {
new LowInjectionProcessor().process();
}
}
|
package com.GB.ChinaMobileMS.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.GB.ChinaMobileMS.entity.Information;
import com.GB.ChinaMobileMS.entity.PropertyServiceEntity;
import com.GB.ChinaMobileMS.entity.User;
import com.GB.ChinaMobileMS.services.interfaces.InfoService;
import com.GB.ChinaMobileMS.services.interfaces.PropertyServices;
import com.GB.ChinaMobileMS.services.interfaces.UserService;
import com.GB.ChinaMobileMS.services.interfaces.PropertyApplicantService;
@Controller
public class FunctionController {
@Autowired
private UserService userService;
@Autowired
private PropertyServices propertyServices;
@Autowired
private PropertyApplicantService propertyApplicantService;
@Autowired
private InfoService infoService;
@Autowired
private PropertyServices propertyService;
@RequestMapping(value = "/system/{id}", method = RequestMethod.GET)
public ModelAndView systemUser(User user, @PathVariable("id") String id, HttpSession session) {
// requestParamid
System.out.println("id=" + id);
if (id.equals("user")) {
return GetUserList();
} else if (id.equals("parameter")) {
return GetInfo();
} else if (id.equals("user-add"))
return new ModelAndView("/function/system-user-add");
else if (id.equals("role-assignment"))
return new ModelAndView("/function/system-role-assignment");
else if (id.equals("role-assignment-add"))
return new ModelAndView("/function/system-role-assignment-add");
else if (id.equals("role-authorization"))
return new ModelAndView("/function/system-role-authorization");
else if (id.equals("role-authorization-add"))
return new ModelAndView("/function/system-role-authorization-add");
else if (id.equals("parameter-update")) {
return new ModelAndView("/function/system-parameter-update");
} else if (id.equals("data"))
return new ModelAndView("/function/system-data");
else
return new ModelAndView("forward:/");
}
@RequestMapping(value = "/property/{id}", method = RequestMethod.GET)
public ModelAndView propertyUser(User user, @PathVariable("id") String id, HttpSession session) {
if (id.equals("server")) {
List<PropertyServiceEntity> listPropertyApplicant = propertyApplicantService.listPropertyApplicant();
Map map = new HashMap();
map.put("listPropertyApplicant", listPropertyApplicant);
return new ModelAndView("/function/property-server", map);
} else if (id.equals("auditing")) {
List<PropertyServiceEntity> propertyList = propertyService.auditParty();
Map map = new HashMap();
map.put("propertyServiceList", propertyList);
return new ModelAndView("/function/property-auditing", map);
} else if (id.equals("applicant"))
return new ModelAndView("/function/property-applicant");
else if (id.equals("management"))
return new ModelAndView("/function/property-management");
else if (id.equals("management-data"))
return new ModelAndView("/function/property-management-data");
else if (id.equals("management-system"))
return new ModelAndView("/function/property-management-system");
else if (id.equals("management-system-add"))
return new ModelAndView("/function/property-management-system-add");
else
return new ModelAndView("forward:/");
}
@RequestMapping(value = "/service/{id}", method = RequestMethod.GET)
public ModelAndView ServiceUser(User user, @PathVariable("id") String id, HttpSession session) {
if (id.equals("management-check"))
return new ModelAndView("/function/service-management-check");
else if (id.equals("management-table-make"))
return new ModelAndView("/function/service-management-table-make");
else if (id.equals("table-info"))
return new ModelAndView("/function/service-table-info");
else if (id.equals("management-send"))
return new ModelAndView("/function/service-management-send");
else if (id.equals("date-statistics"))
return new ModelAndView("/function/service-date-statistics");
else if (id.equals("table-write"))
return new ModelAndView("/function/service-table-write");
else
return new ModelAndView("forward:/");
}
public ModelAndView GetInfo() {
Information info = infoService.findbyInfoID();
ModelAndView mac = new ModelAndView("/function/system-parameter");
mac.addObject("topic", info.getTopic());
mac.addObject("time", info.getTime());
mac.addObject("content", info.getContent());
mac.addObject("recomandRoleId", info.getRecomandRoleId());
return mac;
}
public ModelAndView GetUserList() {
List<User> listUser = userService.listUser();
Map map = new HashMap();
map.put("listUser", listUser);// userlistArraylist
return new ModelAndView("/function/system-user", map);
}
}
|
package com.contrastsecurity.rO0;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
import org.objectweb.asm.commons.Method;
public class ResolveClassMethodVisitor extends AdviceAdapter {
protected ResolveClassMethodVisitor(MethodVisitor mv, int access, String name, String desc) {
super(Opcodes.ASM5, mv, access, name, desc);
}
/**
* Fire off our sensor at the beginning of ObjectInputStream#resolveClass(java.io.ObjectStreamClass).
*/
@Override
protected void onMethodEnter() {
Type type = Type.getType(ResolveClassController.class);
Method method = new Method("onResolveClass", "(Ljava/io/ObjectStreamClass;)V");
loadArg(0);
invokeStatic(type,method);
}
}
|
package com.conveyal.r5.analyst.cluster;
import com.conveyal.r5.analyst.FreeFormPointSet;
import com.conveyal.r5.analyst.Grid;
import com.conveyal.r5.analyst.GridTransformWrapper;
import com.conveyal.r5.analyst.PointSet;
import com.conveyal.r5.analyst.PointSetCache;
import com.conveyal.r5.analyst.WebMercatorExtents;
import com.conveyal.r5.analyst.WebMercatorGridPointSetCache;
import com.conveyal.r5.analyst.WorkerCategory;
import com.conveyal.r5.analyst.decay.DecayFunction;
import com.conveyal.r5.profile.ProfileRequest;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Arrays;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Describes an analysis task to be performed for a single origin, on its own or as part of a multi-origin analysis.
* Instances are serialized and sent from the backend to workers.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
// these match the enum values in AnalysisWorkerTask.Type
// FIXME it does not seem necessary to automatically detect subtypes. Each endpoint accepts only one type.
@JsonSubTypes.Type(name = "TRAVEL_TIME_SURFACE", value = TravelTimeSurfaceTask.class),
@JsonSubTypes.Type(name = "REGIONAL_ANALYSIS", value = RegionalTask.class)
})
public abstract class AnalysisWorkerTask extends ProfileRequest {
/**
* The largest number of cutoffs we'll accept in a regional analysis task. Too many cutoffs can create very large
* output files. This limit does not apply when calculating single-point accessibility on the worker, where there
* will always be 121 cutoffs (from zero to 120 minutes inclusive).
*/
public static final int MAX_REGIONAL_CUTOFFS = 12;
public static final int N_SINGLE_POINT_CUTOFFS = 121;
/** The largest number of percentiles we'll accept in a task. */
public static final int MAX_PERCENTILES = 5;
/**
* A loading cache of gridded pointSets (not opportunity data grids), shared statically among all single point and
* multi-point (regional) requests. TODO make this non-static yet shared.
*/
public static final WebMercatorGridPointSetCache gridPointSetCache = new WebMercatorGridPointSetCache();
// Extents of a web Mercator grid. Unfortunately this grid serves different purposes in different requests.
// In the single-origin TravelTimeSurfaceTasks, the grid points are the destinations.
// In regional multi-origin tasks, the grid points are the origins, with destinations determined by the selected
// opportunity dataset.
// In regional Taui (static site) tasks the grid points serve as both the origins and the destinations.
public int zoom;
public int west;
public int north;
public int width;
public int height;
/** The ID of the graph against which to calculate this task. */
public String graphId;
/** The commit of r5 the worker should be running when it processes this task. */
public String workerVersion;
/**
* The job ID this is associated with.
* TODO it seems like this should be equal to RegionalAnalysis._id, and be called regionalAnalysisId.
* This seems to be only relevant for regional tasks but is on the shared superclass (push it down?)
*/
public String jobId;
/** The id of this particular origin. */
public String originId;
/**
* A unique identifier for this task assigned by the queue/broker system.
* TODO This seems to be only relevant for regional tasks but is on the shared superclass (push it down?)
*/
public int taskId;
/**
* Whether to save results on S3.
* If false, the results will only be sent back to the broker or UI.
* If true, travel time surfaces and paths will be saved to S3
* Currently this only works on regional requests, and causes them to produce travel time surfaces instead of
* accessibility indicator values.
*/
public boolean makeTauiSite = false;
/**
* Whether to include paths and travel time breakdowns in results sent back to broker. Allowed to be true for a
* single-point task or freeform regional task, but not for a regional task with grid origins.
*/
public boolean includePathResults = false;
/** Whether to build a histogram of travel times to each destination, generally used in testing and debugging. */
public boolean recordTravelTimeHistograms = false;
/**
* Which percentiles of travel time to calculate.
* These should probably just be integers, but there are already a lot of them in Mongo as floats.
*/
public int[] percentiles;
/**
* The travel time cutoffs in minutes for regional accessibility analysis.
* A single cutoff was previously determined by superclass field ProfileRequest.maxTripDurationMinutes.
* That field still cuts off the travel search at a certain number of minutes, so it is set to the highest cutoff.
* Note this will only be set for accessibility calculation tasks, not for travel time surfaces.
* TODO move it to the regional task subclass?
*/
public int[] cutoffsMinutes;
/**
* When recording paths as in a static site, how many distinct paths should be saved to each destination?
* Currently this only makes sense in regional tasks, but it could also become relevant for travel time surfaces
* so it's in this superclass.
*/
public int nPathsPerTarget = 3;
/**
* Whether the R5 worker should log an analysis request it receives from the broker. analysis-backend translates
* front-end requests to the format expected by R5. To debug this translation process, set logRequest = true in
* the front-end profile request, then look for the full request received by the worker in its Cloudwatch log.
*/
public boolean logRequest = false;
/**
* The distance decay function applied to make more distant opportunities
* Deserialized into various subtypes from JSON.
*/
public DecayFunction decayFunction;
/**
* The storage keys for the pointsets we will compute access to. The format is regionId/datasetId.fileFormat.
* Ideally we'd just provide the IDs of the grids, but creating the key requires us to know the region
* ID and file format, which are not otherwise easily available on workers that don't have a database connection.
* This field is required for regional analyses, which always compute accessibility to destinations.
* On the other hand, in a single point request this may be null, in which case the worker will report only
* travel times to destinations and not accessibility figures.
*/
public String[] destinationPointSetKeys;
/**
* The pointsets we are calculating accessibility to, including opportunity density data (not bare sets of points).
* Note that these are transient - they are not serialized and sent over the wire, they are loaded by the worker
* from the storage location specified by the destinationPointSetKeys.
*
* For now, if the destinations are grids, there may be more than one but they must have the same WebMercatorExtents;
* if the destinations are freeform points, only a single pointset is allowed.
*/
public transient PointSet[] destinationPointSets;
/**
* Is this a single point or regional request? Needed to encode types in JSON serialization. Can that type field be
* added automatically with a serializer annotation instead of by defining a getter method and two dummy methods?
*/
public abstract Type getType();
/** Ensure that type is perceived as a field by serialization libs, no-op */
public void setType (Type type) {};
public void setTypes (String type) {};
/**
* @return extents for the appropriate destination grid, derived from task's bounds and zoom (for Taui site tasks
* and single-point travel time surface tasks) or destination pointset (for standard regional accessibility
* analysis tasks)
*/
@JsonIgnore
public abstract WebMercatorExtents getWebMercatorExtents();
@JsonIgnore
public WorkerCategory getWorkerCategory () {
return new WorkerCategory(graphId, workerVersion);
}
public enum Type {
/*
TODO we should not need this enum - this should be handled automatically by JSON serializer annotations.
These could also be changed to SINGLE_POINT and MULTI_POINT. The type of results requested (i.e. a grid of
travel times per origin vs. an accessibility value per origin) can be inferred based on whether grids are
specified in the profile request. If travel time results are requested, flags can specify whether components
of travel time (e.g. waiting) and paths should also be returned.
*/
/** Binary grid of travel times from a single origin, for multiple percentiles, returned via broker by default */
TRAVEL_TIME_SURFACE,
/** Cumulative opportunity accessibility values for all cells in a grid, returned to broker for assembly*/
REGIONAL_ANALYSIS
}
public AnalysisWorkerTask clone () {
// no need to catch CloneNotSupportedException, it's caught in ProfileRequest::clone
return (AnalysisWorkerTask) super.clone();
}
/**
* @return the expected number of destination points for this particular kind of task.
*/
public abstract int nTargetsPerOrigin();
/**
* Populate this task's transient array of destination PointSets, loading each destination PointSet key from the
* supplied cache. The PointSets themselves are not serialized and sent over to the worker in the task, so this
* method is called by the worker to materialize them.
*
* This should not be called for Taui sites (which have no destination point sets) so contains logic for only
* non-Taui single point and regional tasks.
*
* If multiple grids are specified, they must be at the same zoom level, but they will all be wrapped to transform
* them all to the same minimum bounding extents.
*/
public void loadAndValidateDestinationPointSets (PointSetCache pointSetCache) {
// First, validate and load the pointsets.
// They need to be loaded so we can see their types and dimensions for the next step.
checkNotNull(destinationPointSetKeys);
int nPointSets = destinationPointSetKeys.length;
checkState(
nPointSets > 0 && nPointSets <= 12,
"You must specify at least 1 destination PointSet, but no more than 12."
);
destinationPointSets = new PointSet[nPointSets];
for (int i = 0; i < nPointSets; i++) {
PointSet pointSet = pointSetCache.get(destinationPointSetKeys[i]);
checkNotNull(pointSet, "Could not load PointSet specified in regional task.");
destinationPointSets[i] = pointSet;
}
// Next, if the destinations are gridded PointSets (as opposed to FreeFormPointSets),
// transform cell numbers where necessary between task-wide grid and each individual grid.
boolean freeForm = Arrays.stream(destinationPointSets).anyMatch(FreeFormPointSet.class::isInstance);
if (freeForm){
checkArgument(nPointSets == 1, "Only one freeform destination PointSet may be specified.");
} else {
// If destinationPointSets does not contain a single freeform pointset, we expect one or more grids.
// Determine the destination grid extents for this task, which are either supplied in request (single point)
// or derived from the opportunity grids (regional). Grids are then transformed to match this single size.
// Determining the minimum bouding extents requires the grids to already be loaded into the array, hence the
// two-stage loading then wrapping. After this wrapping, subsequent calls to getWebMercatorExtents should
// still yield the same extents.
final var taskGridExtents = this.getWebMercatorExtents();
for (int i = 0; i < nPointSets; i++) {
Grid grid = (Grid) destinationPointSets[i];
if (! grid.getWebMercatorExtents().equals(taskGridExtents)) {
destinationPointSets[i] = new GridTransformWrapper(taskGridExtents, grid);
}
}
}
}
public void validatePercentiles () {
checkNotNull(percentiles);
int nPercentiles = percentiles.length;
checkArgument(nPercentiles <= MAX_PERCENTILES, "Maximum number of percentiles allowed is " + MAX_PERCENTILES);
for (int p = 0; p < nPercentiles; p++) {
checkArgument(percentiles[p] > 0 && percentiles[p] < 100, "Percentiles must be in range [1, 99].");
if (p > 0) {
checkState(percentiles[p] >= percentiles[p - 1], "Percentiles must be in ascending order.");
}
}
}
public void validateCutoffsMinutes () {
checkNotNull(cutoffsMinutes);
final int nCutoffs = cutoffsMinutes.length;
checkArgument(nCutoffs >= 1, "At least one cutoff must be supplied.");
// This should probably be handled with method overrides, but we are already using instanceOf everywhere.
// In the longer term we should just merge both subtypes into this AnalysisWorkerTask superclass.
if (this instanceof RegionalTask) {
checkArgument(nCutoffs <= MAX_REGIONAL_CUTOFFS,
"Maximum number of cutoffs allowed in a regional analysis is " + MAX_REGIONAL_CUTOFFS);
} else {
checkArgument(nCutoffs == N_SINGLE_POINT_CUTOFFS,
"Single point accessibility has the wrong number of cutoffs.");
}
for (int c = 0; c < nCutoffs; c++) {
checkArgument(cutoffsMinutes[c] >= 0, "Cutoffs must be non-negative integers.");
checkArgument(cutoffsMinutes[c] <= 120, "Cutoffs must be at most 120 minutes.");
if (c > 0) {
checkArgument(cutoffsMinutes[c] >= cutoffsMinutes[c - 1], "Cutoffs must be in ascending order.");
}
}
}
}
|
package com.demigodsrpg.demigods.classic.model;
import com.demigodsrpg.demigods.classic.DGClassic;
import com.demigodsrpg.demigods.classic.Setting;
import com.demigodsrpg.demigods.classic.battle.Battle;
import com.demigodsrpg.demigods.classic.battle.Participant;
import com.demigodsrpg.demigods.classic.deity.Deity;
import com.demigodsrpg.demigods.classic.deity.IDeity;
import com.demigodsrpg.demigods.classic.registry.AbilityRegistry;
import com.demigodsrpg.demigods.classic.util.ZoneUtil;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PlayerModel extends AbstractPersistentModel<UUID> implements Participant {
private UUID mojangId;
private String lastKnownName;
private Long lastLoginTime;
private Deity majorDeity;
private Set<Deity> contractedDeities = new HashSet<>();
private Map<String, Double> devotion;
private IDeity.Alliance acceptedAlliance;
private BiMap<String, String> binds = HashBiMap.create();
private Double maxHealth;
private Double maxFavor;
private Double favor;
private Integer ascensions;
private Boolean canPvp;
private Integer kills;
private Integer deaths;
private Integer teamKills;
@SuppressWarnings("deprecation")
public PlayerModel(Player player) {
mojangId = player.getUniqueId();
lastKnownName = player.getName();
lastLoginTime = System.currentTimeMillis();
majorDeity = Deity.HUMAN;
devotion = new HashMap<>();
acceptedAlliance = IDeity.Alliance.NEUTRAL;
maxHealth = 20.0;
maxFavor = 0.0;
favor = 0.0;
ascensions = 0;
canPvp = true;
kills = 0;
deaths = 0;
teamKills = 0;
}
public PlayerModel(UUID mojangId, ConfigurationSection conf) {
this.mojangId = mojangId;
lastKnownName = conf.getString("lastKnownName");
lastLoginTime = conf.getLong("lastLoginTime");
majorDeity = Deity.valueOf(conf.getString("majorDeity"));
for (String name : conf.getStringList("contractedDeities")) {
contractedDeities.add(Deity.valueOf(name));
}
acceptedAlliance = IDeity.Alliance.valueOf(conf.getString("alliance"));
binds.putAll((Map) conf.getConfigurationSection("binds").getValues(false));
maxHealth = conf.getDouble("maxHealth");
maxFavor = conf.getDouble("maxFavor");
favor = conf.getDouble("favor");
devotion = Maps.newHashMap(Maps.transformEntries(conf.getConfigurationSection("devotion").getValues(false), new Maps.EntryTransformer<String, Object, Double>() {
@Override
public Double transformEntry(String s, Object o) {
return Double.parseDouble(o.toString());
}
}));
ascensions = conf.getInt("ascensions");
canPvp = conf.getBoolean("canPvp", true);
kills = conf.getInt("kills");
deaths = conf.getInt("deaths");
teamKills = conf.getInt("teamKills");
}
@Override
public Type getType() {
return Type.PERSISTENT;
}
@Override
public UUID getPersistantId() {
return getMojangId();
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = new HashMap<>();
map.put("lastKnownName", lastKnownName);
map.put("lastLoginTime", lastLoginTime);
map.put("majorDeity", majorDeity.name());
List<String> contractedDeities = new ArrayList<>();
for (Deity deity : this.contractedDeities) {
contractedDeities.add(deity.name());
}
map.put("contractedDeities", contractedDeities);
map.put("alliance", acceptedAlliance.name());
map.put("binds", Maps.newHashMap(binds));
map.put("maxHealth", maxHealth);
map.put("maxFavor", maxFavor);
map.put("favor", favor);
map.put("devotion", devotion);
map.put("ascensions", ascensions);
map.put("canPvp", canPvp);
map.put("kills", kills);
map.put("deaths", deaths);
map.put("teamKills", teamKills);
return map;
}
public UUID getMojangId() {
return mojangId;
}
public String getLastKnownName() {
return lastKnownName;
}
public void setLastKnownName(String lastKnownName) {
this.lastKnownName = lastKnownName;
DGClassic.PLAYER_R.register(this);
}
public Long getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Long lastLoginTime) {
this.lastLoginTime = lastLoginTime;
DGClassic.PLAYER_R.register(this);
}
public Deity getMajorDeity() {
return majorDeity;
}
public void setMajorDeity(Deity majorDeity) {
this.majorDeity = majorDeity;
DGClassic.PLAYER_R.register(this);
}
public Set<Deity> getAllDeities() {
Set<Deity> deities = new HashSet<>();
deities.addAll(getContractedDeities());
deities.add(majorDeity);
return deities;
}
public Set<Deity> getContractedDeities() {
return contractedDeities;
}
public void addContractedDeity(Deity deity) {
contractedDeities.add(deity);
DGClassic.PLAYER_R.register(this);
}
public void removeContractedDeity(Deity deity) {
contractedDeities.remove(deity);
DGClassic.PLAYER_R.register(this);
}
@Override
public IDeity.Alliance getAlliance() {
return acceptedAlliance;
}
public void setAlliance(IDeity.Alliance acceptedAlliance) {
this.acceptedAlliance = acceptedAlliance;
DGClassic.PLAYER_R.register(this);
}
public Double getMaxHealth() {
return maxHealth;
}
public void setMaxHealth(Double maxHealth) {
this.maxHealth = maxHealth;
DGClassic.PLAYER_R.register(this);
}
public Double getMaxFavor() {
return maxFavor;
}
public void setMaxFavor(Double maxFavor) {
this.maxFavor = maxFavor;
DGClassic.PLAYER_R.register(this);
}
public Double getFavor() {
return favor;
}
public void setFavor(Double favor) {
this.favor = favor;
DGClassic.PLAYER_R.register(this);
}
public Double getDevotion(Deity deity) {
if (!devotion.containsKey(deity.toString())) {
return 0.0;
}
return devotion.get(deity.name());
}
public Double getTotalDevotion() {
double total = getDevotion(majorDeity);
for (Deity deity : contractedDeities) {
total += getDevotion(deity);
}
return total;
}
public void setDevotion(Deity deity, Double devotion) {
this.devotion.put(deity.name(), devotion);
calculateAscensions();
DGClassic.PLAYER_R.register(this);
}
public Integer getAscensions() {
return ascensions;
}
public void setAscensions(Integer ascensions) {
this.ascensions = ascensions;
DGClassic.PLAYER_R.register(this);
}
public Map<String, String> getBindsMap() {
return binds;
}
public AbilityRegistry.Data getBound(Material material) {
if (binds.inverse().containsKey(material.name())) {
return DGClassic.ABILITY_R.fromCommand(binds.inverse().get(material.name()));
}
return null;
}
public Material getBound(AbilityRegistry.Data ability) {
return getBound(ability.getCommand());
}
public Material getBound(String abilityCommand) {
if (binds.containsKey(abilityCommand)) {
return Material.valueOf(binds.get(abilityCommand));
}
return null;
}
public void bind(AbilityRegistry.Data ability, Material material) {
binds.put(ability.getCommand(), material.name());
DGClassic.PLAYER_R.register(this);
}
public void bind(String abilityCommand, Material material) {
binds.put(abilityCommand, material.name());
DGClassic.PLAYER_R.register(this);
}
public void unbind(AbilityRegistry.Data ability) {
binds.remove(ability.getCommand());
DGClassic.PLAYER_R.register(this);
}
public void unbind(String abilityCommand) {
binds.remove(abilityCommand);
DGClassic.PLAYER_R.register(this);
}
public void unbind(Material material) {
binds.inverse().remove(material.name());
DGClassic.PLAYER_R.register(this);
}
public boolean getCanPvp() {
return canPvp;
}
public void setCanPvp(Boolean canPvp) {
this.canPvp = canPvp;
DGClassic.PLAYER_R.register(this);
}
public Integer getKills() {
return kills;
}
public void addKill() {
kills++;
DGClassic.PLAYER_R.register(this);
}
public Integer getDeaths() {
return deaths;
}
public void addDeath() {
deaths++;
DGClassic.PLAYER_R.register(this);
}
public Integer getTeamKills() {
return teamKills;
}
public void addTeamKill() {
teamKills++;
DGClassic.PLAYER_R.register(this);
}
public void resetTeamKills() {
teamKills = 0;
DGClassic.PLAYER_R.register(this);
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(mojangId);
}
public boolean getOnline() {
return getOfflinePlayer().isOnline();
}
@Override
public EntityType getEntityType() {
return EntityType.PLAYER;
}
@Override
public Location getLocation() {
if (getOnline()) {
return getOfflinePlayer().getPlayer().getLocation();
}
throw new UnsupportedOperationException("We don't support finding locations for players who aren't online.");
}
@SuppressWarnings("RedundantCast")
@Override
public boolean reward(Battle.Data data) {
double devotion = getTotalDevotion();
teamKills += data.getTeamKills();
if (checkTeamKills()) {
double score = data.getHits() + data.getAssists() / 2;
score += data.getDenies();
score += data.getKills() * 2;
score -= data.getDeaths() * 1.5;
score *= (double) Setting.EXP_MULTIPLIER.get();
score /= contractedDeities.size() + 1;
setDevotion(majorDeity, getDevotion(majorDeity) + score);
for (Deity deity : contractedDeities) {
setDevotion(deity, getDevotion(deity) + score);
}
}
DGClassic.PLAYER_R.register(this);
return devotion > getTotalDevotion();
}
public boolean checkTeamKills() {
int maxTeamKills = Setting.MAX_TEAM_KILLS.get();
if (maxTeamKills <= teamKills) {
// Reset them to excommunicated
setAlliance(IDeity.Alliance.EXCOMMUNICATED);
resetTeamKills();
double former = getTotalDevotion();
setDevotion(majorDeity, 0.0);
if (getOnline()) {
Player player = getOfflinePlayer().getPlayer();
player.sendMessage(ChatColor.RED + "Your former alliance has just excommunicated you.");
player.sendMessage(ChatColor.RED + "You will no longer respawn at the alliance spawn.");
player.sendMessage(ChatColor.RED + "You have lost " +
ChatColor.GOLD + DecimalFormat.getCurrencyInstance().format(former - getTotalDevotion()) +
ChatColor.RED + " devotion.");
player.sendMessage(ChatColor.YELLOW + "To join an alliance, "); // TODO
}
return false;
}
return true;
}
public void giveMajorDeity(Deity deity, boolean firstTime) {
setMajorDeity(deity);
if (firstTime) {
setAlliance(deity.getDefaultAlliance());
setMaxHealth(25.0);
setMaxFavor(700.0);
setFavor(getMaxFavor());
setAscensions(1);
}
setDevotion(deity, 20.0);
calculateAscensions();
}
public void giveDeity(Deity deity) {
contractedDeities.add(deity);
setDevotion(deity, 20.0);
}
public void calculateAscensions() {
Player player = getOfflinePlayer().getPlayer();
if (getAscensions() >= (int) Setting.ASCENSION_CAP.get()) return;
while (getTotalDevotion() >= (int) Math.ceil(500 * Math.pow(getAscensions() + 1, 2.02)) && getAscensions() < (int) Setting.ASCENSION_CAP.get()) {
setMaxHealth(getMaxHealth() + 10.0);
player.setMaxHealth(getMaxHealth());
player.setHealthScale(20.0);
player.setHealthScaled(true);
player.setHealth(getMaxHealth());
setAscensions(getAscensions() + 1);
player.sendMessage(ChatColor.AQUA + "Congratulations! Your Ascensions increased to " + getAscensions() + ".");
player.sendMessage(ChatColor.YELLOW + "Your maximum HP has increased to " + getMaxHealth() + ".");
}
DGClassic.PLAYER_R.register(this);
}
public int costForNextDeity() {
switch (contractedDeities.size() + 1) {
case 1:
return 2;
case 2:
return 5;
case 3:
return 9;
case 4:
return 14;
case 5:
return 19;
case 6:
return 25;
case 7:
return 30;
case 8:
return 35;
case 9:
return 40;
case 10:
return 50;
case 11:
return 60;
case 12:
return 70;
case 13:
return 80;
}
return 120;
}
@SuppressWarnings("deprecation")
public void updateCanPvp() {
if (Bukkit.getPlayer(mojangId) == null) return;
// Define variables
final Player player = Bukkit.getPlayer(mojangId);
final boolean inNoPvpZone = ZoneUtil.inNoPvpZone(player.getLocation());
if (DGClassic.BATTLE_R.isInBattle(this)) return;
if (!getCanPvp() && !inNoPvpZone) {
setCanPvp(true);
player.sendMessage(ChatColor.GRAY + "You can now enter in a battle.");
} else if (!inNoPvpZone) {
setCanPvp(true);
DGClassic.SERV_R.remove(player.getName(), "pvp_cooldown");
} else if (getCanPvp() && !DGClassic.SERV_R.exists(player.getName(), "pvp_cooldown")) {
int delay = 10;
DGClassic.SERV_R.put(player.getName(), "pvp_cooldown", true, delay, TimeUnit.SECONDS);
final PlayerModel THIS = this;
Bukkit.getScheduler().scheduleSyncDelayedTask(DGClassic.getInst(), new BukkitRunnable() {
@Override
public void run() {
if (ZoneUtil.inNoPvpZone(player.getLocation())) {
if (DGClassic.BATTLE_R.isInBattle(THIS)) return;
setCanPvp(false);
player.sendMessage(ChatColor.GRAY + "You are now safe from other players.");
}
}
}, (delay * 20));
}
}
public void updateFavor() {
if (getFavor() < getMaxFavor()) {
setFavor(getFavor() + 4);
}
}
}
|
package com.epam.ta.reportportal.database.search;
import com.epam.ta.reportportal.ws.model.ErrorType;
import org.apache.commons.lang3.BooleanUtils;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Pattern;
import static com.epam.ta.reportportal.commons.Predicates.equalTo;
import static com.epam.ta.reportportal.commons.Predicates.or;
import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect;
import static com.epam.ta.reportportal.commons.validation.BusinessRule.fail;
import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier;
import static com.epam.ta.reportportal.database.search.FilterRules.*;
import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_FILTER_PARAMETERS;
import static java.lang.Long.parseLong;
import static java.util.Date.from;
/**
* Types of supported filtering
*
* @author Andrei Varabyeu
*/
public enum Condition {
/**
* EQUALS condition
*/
EQUALS("eq") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
criteria.is(this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(isNegative, equalTo(false)).verify(errorType, "Filter is incorrect. '!' can't be used with 'is' - use 'ne' instead");
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Not equals condition
*/
NOT_EQUALS("ne") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
criteria.ne(this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Contains operation. NON case sensitive
*/
CONTAINS("cnt") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only strings */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
if (!ObjectId.isValid(filter.getValue())) {
criteria.regex("(?i).*" + Pattern.quote(filter.getValue()) + ".*");
} else {
criteria.regex(".*" + filter.getValue() + ".*");
}
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, filterForString()).verify(errorType,
formattedSupplier("Contains condition applyable only for strings. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// values cast is not required here
return values;
}
},
/**
* Size operation
*/
SIZE("size") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
criteria.size(Integer.parseInt(filter.getValue()));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, filterForCollections()).verify(errorType,
formattedSupplier("'Size' condition applyable only for collection data types. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
expect(value, number()).verify(errorType, formattedSupplier("Provided value '{}' is not a number", value));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// values cast is not required here
return values;
}
},
/**
* Exists condition
*/
EXISTS("ex") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
criteria.exists(BooleanUtils.toBoolean(filter.getValue()));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// values cast is not required here
return values;
}
},
/**
* IN condition. Accepts filter value as comma-separated list
*/
IN("in") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
criteria.in((Object[]) this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return castArray(criteriaHolder, value, errorType);
}
},
/**
* HAS condition. Accepts filter value as comma-separated list. Returns
* 'TRUE' of all provided values exist in collection<br>
* <b>Applicable only for collections</b>
*/
HAS("has") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only collections */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
criteria.all((Object[]) this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, filterForCollections()).verify(errorType,
formattedSupplier("'HAS' condition applyable only for collection data types. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return castArray(criteriaHolder, value, errorType);
}
},
/**
* Greater than condition
*/
GREATER_THAN("gt") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
criteria.gt(this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates())).verify(errorType,
formattedSupplier("'Greater than' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Greater than or Equals condition
*/
GREATER_THAN_OR_EQUALS("gte") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
criteria.gte(this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType, formattedSupplier(
"'Greater than or equals' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Lower than condition
*/
LOWER_THAN("lt") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
Object valueToFind = ObjectId.isValid(filter.getValue()) ?
new ObjectId(filter.getValue()) :
this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS);
criteria.lt(valueToFind);
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates())).verify(errorType,
formattedSupplier("'Lower than' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Lower than or Equals condition
*/
LOWER_THAN_OR_EQUALS("lte") {
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
Object valueToFind = ObjectId.isValid(filter.getValue()) ?
new ObjectId(filter.getValue()) :
this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS);
criteria.lte(valueToFind);
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates())).verify(errorType, formattedSupplier(
"'Lower than or equals' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Between condition. Include boundaries
*/
BETWEEN("btw") {
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates())).verify(errorType, formattedSupplier(
"'Between' condition applyable only for positive Numbers, Dates or specific TimeStamp values. "
+ "Type of field is '{}'", criteriaHolder.getDataType().getSimpleName()));
if (value.contains(VALUES_SEPARATOR))
expect(value.split(VALUES_SEPARATOR), countOfValues(2)).verify(errorType,
formattedSupplier("Incorrect between filter format. Expected='value1,value2'. Provided filter is '{}'", value));
else if (value.contains(TIMESTAMP_SEPARATOR)) {
final String[] values = value.split(TIMESTAMP_SEPARATOR);
expect(values, countOfValues(3)).verify(errorType, formattedSupplier(
"Incorrect between filter format. Expected='TIMESTAMP_CONSTANT;TimeZoneOffset'. Provided filter is '{}'", value));
expect(values[2], zoneOffset()).verify(errorType,
formattedSupplier("Incorrect zoneOffset. Expected='+h, +hh, +hh:mm'. Provided value is '{}'", values[2]));
expect(values[0], timeStamp())
.verify(errorType, formattedSupplier("Incorrect timestamp. Expected number. Provided value is '{}'", values[0]));
expect(values[1], timeStamp())
.verify(errorType, formattedSupplier("Incorrect timestamp. Expected number. Provided value is '{}'", values[1]));
} else {
fail().withError(errorType, formattedSupplier(
"Incorrect between filter format. Filter value should be separated by ',' or ';'. Provided filter is '{}'", value));
}
}
@Override
public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder) {
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
Object[] castedValues;
if (filter.getValue().contains(",")) {
castedValues = (Object[]) this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS);
} else {
String[] values = filter.getValue().split(";");
ZoneOffset offset = ZoneOffset.of(values[2]);
ZonedDateTime localDateTime = ZonedDateTime.now(offset).toLocalDate().atStartOfDay(offset);
long start = from(localDateTime.plusMinutes(parseLong(values[0])).toInstant()).getTime();
long end = from(localDateTime.plusMinutes(parseLong(values[1])).toInstant()).getTime();
String newValue = start + "," + end;
castedValues = (Object[]) this.castValue(criteriaHolder, newValue, INCORRECT_FILTER_PARAMETERS);
}
criteria.gte(castedValues[0]).lte(castedValues[1]);
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
/* For linguistic dynamic date range literals */
if (value.contains(";"))
return value;
else
return castArray(criteriaHolder, value, errorType);
}
};
/*
* Workaround. Added to be able to use as constant in annotations
*/
public static final String EQ = "eq.";
public static final String CNT = "cnt.";
public static final String VALUES_SEPARATOR = ",";
public static final String TIMESTAMP_SEPARATOR = ";";
public static final String NEGATIVE_MARKER = "!";
private String marker;
Condition(final String marker) {
this.marker = marker;
}
abstract public void addCondition(Criteria criteria, FilterCondition filter, CriteriaHolder criteriaHolder);
/**
* Validate condition value. This method should be overridden in all
* conditions which contains validations
*
* @param criteriaHolder Criteria description
* @param value Value to be casted
* @param isNegative Whether filter is negative
*/
abstract public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType);
/**
* Cast filter values according condition.
*
* @param criteriaHolder Criteria description
* @param values Value to be casted
* @return Casted value
*/
abstract public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType);
public String getMarker() {
return marker;
}
/**
* Finds condition by marker. If there is no condition with specified marker
* returns NULL
*
* @param marker Marker to be checked
* @return Condition if found or NULL
*/
public static Optional<Condition> findByMarker(String marker) {
// Negative condition excluder
if (isNegative(marker)) {
marker = marker.substring(1);
}
String finalMarker = marker;
return Arrays.stream(values()).filter(it -> it.getMarker().equals(finalMarker)).findAny();
}
/**
* Check whether condition is negative
*
* @param marker Marker to check
* @return TRUE of negative
*/
public static boolean isNegative(String marker) {
return marker.startsWith(NEGATIVE_MARKER);
}
/**
* Makes filter marker negative
*
* @param negative Whether condition is negative
* @param marker Marker to check
* @return TRUE of negative
*/
public static String makeNegative(boolean negative, String marker) {
String result;
if (negative) {
result = marker.startsWith(NEGATIVE_MARKER) ? marker : NEGATIVE_MARKER.concat(marker);
} else {
result = marker.startsWith(NEGATIVE_MARKER) ? marker.substring(1, marker.length()) : marker;
}
return result;
}
/**
* Cast values for filters which have many values(filters with
* conditions:btw, in, etc)
*
* @param criteriaHolder Criteria description
* @param value Value to be casted
* @return Casted value
*/
public Object[] castArray(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
String[] values = value.split(VALUES_SEPARATOR);
Object[] castedValues = new Object[values.length];
if (!String.class.equals(criteriaHolder.getDataType())) {
for (int index = 0; index < values.length; index++) {
castedValues[index] = criteriaHolder.castValue(values[index].trim(), errorType);
}
} else {
castedValues = values;
}
return castedValues;
}
}
|
package com.github.dockerjava.netty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.InvocationBuilder;
import com.github.dockerjava.core.async.ResultCallbackTemplate;
import com.github.dockerjava.netty.handler.FramedResponseStreamHandler;
import com.github.dockerjava.netty.handler.HttpConnectionHijackHandler;
import com.github.dockerjava.netty.handler.HttpRequestProvider;
import com.github.dockerjava.netty.handler.HttpResponseHandler;
import com.github.dockerjava.netty.handler.HttpResponseStreamHandler;
import com.github.dockerjava.netty.handler.JsonResponseCallbackHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.socket.DuplexChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpClientUpgradeHandler;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.stream.ChunkedStream;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* This class is basically a replacement of javax.ws.rs.client.Invocation.Builder to allow simpler migration of JAX-RS code to a netty based
* implementation.
*
* @author Marcus Linke
*/
public class NettyInvocationBuilder implements InvocationBuilder {
public class ResponseCallback<T> extends ResultCallbackTemplate<ResponseCallback<T>, T> {
private T result = null;
public T awaitResult() {
try {
awaitCompletion();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return result;
}
@Override
public void onNext(T object) {
result = object;
}
}
public class SkipResultCallback extends ResultCallbackTemplate<ResponseCallback<Void>, Void> {
@Override
public void onNext(Void object) {
}
}
private ChannelProvider channelProvider;
private String resource;
private Map<String, String> headers = new HashMap<String, String>();
public NettyInvocationBuilder(ChannelProvider channelProvider, String resource) {
this.channelProvider = channelProvider;
this.resource = resource;
}
@Override
public InvocationBuilder accept(com.github.dockerjava.core.MediaType mediaType) {
return header(HttpHeaderNames.ACCEPT.toString(), mediaType.getMediaType());
}
public NettyInvocationBuilder header(String name, String value) {
headers.put(name, value);
return this;
}
public void delete() {
HttpRequestProvider requestProvider = httpDeleteRequestProvider();
ResponseCallback<Void> callback = new ResponseCallback<Void>();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, callback);
Channel channel = getChannel();
channel.pipeline().addLast(responseHandler);
sendRequest(requestProvider, channel);
callback.awaitResult();
}
public void get(ResultCallback<Frame> resultCallback) {
HttpRequestProvider requestProvider = httpGetRequestProvider();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
FramedResponseStreamHandler streamHandler = new FramedResponseStreamHandler(resultCallback);
Channel channel = getChannel();
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(streamHandler);
sendRequest(requestProvider, channel);
}
public <T> T get(TypeReference<T> typeReference) {
ResponseCallback<T> callback = new ResponseCallback<T>();
get(typeReference, callback);
return callback.awaitResult();
}
public <T> void get(TypeReference<T> typeReference, ResultCallback<T> resultCallback) {
HttpRequestProvider requestProvider = httpGetRequestProvider();
Channel channel = getChannel();
JsonResponseCallbackHandler<T> jsonResponseHandler = new JsonResponseCallbackHandler<T>(typeReference,
resultCallback);
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(new JsonObjectDecoder(3 * 1024 * 1024));
channel.pipeline().addLast(jsonResponseHandler);
sendRequest(requestProvider, channel);
return;
}
private DuplexChannel getChannel() {
return channelProvider.getChannel();
}
private HttpRequestProvider httpDeleteRequestProvider() {
return new HttpRequestProvider() {
@Override
public HttpRequest getHttpRequest(String uri) {
return prepareDeleteRequest(uri);
}
};
}
private HttpRequestProvider httpGetRequestProvider() {
return new HttpRequestProvider() {
@Override
public HttpRequest getHttpRequest(String uri) {
return prepareGetRequest(uri);
}
};
}
private HttpRequestProvider httpPostRequestProvider(final Object entity) {
return new HttpRequestProvider() {
@Override
public HttpRequest getHttpRequest(String uri) {
return preparePostRequest(uri, entity);
}
};
}
private HttpRequestProvider httpPutRequestProvider(final Object entity) {
return new HttpRequestProvider() {
@Override
public HttpRequest getHttpRequest(String uri) {
return preparePutRequest(uri, entity);
}
};
}
public InputStream post(final Object entity) {
HttpRequestProvider requestProvider = httpPostRequestProvider(entity);
Channel channel = getChannel();
AsyncResultCallback<InputStream> callback = new AsyncResultCallback<>();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, callback);
HttpResponseStreamHandler streamHandler = new HttpResponseStreamHandler(callback);
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(streamHandler);
sendRequest(requestProvider, channel);
return callback.awaitResult();
}
public void post(final Object entity, final InputStream stdin, final ResultCallback<Frame> resultCallback) {
HttpRequestProvider requestProvider = httpPostRequestProvider(entity);
FramedResponseStreamHandler streamHandler = new FramedResponseStreamHandler(resultCallback);
final DuplexChannel channel = getChannel();
// result callback's close() method must be called when the servers closes the connection
channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
resultCallback.onComplete();
}
});
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
HttpConnectionHijackHandler hijackHandler = new HttpConnectionHijackHandler(responseHandler);
HttpClientCodec httpClientCodec = channel.pipeline().get(HttpClientCodec.class);
channel.pipeline().addLast(
new HttpClientUpgradeHandler(httpClientCodec, hijackHandler, Integer.MAX_VALUE));
channel.pipeline().addLast(streamHandler);
sendRequest(requestProvider, channel);
// wait for successful http upgrade procedure
hijackHandler.awaitUpgrade();
if (stdin != null) {
// now we can start a new thread that reads from stdin and writes to the channel
new Thread(new Runnable() {
private int read(InputStream is, byte[] buf) {
try {
return is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
byte[] buffer = new byte[1024];
int read;
while ((read = read(stdin, buffer)) != -1) {
channel.writeAndFlush(Unpooled.copiedBuffer(buffer, 0, read));
}
// we close the writing side of the socket, but keep the read side open to transfer stdout/stderr
channel.shutdownOutput();
}
}).start();
}
}
public <T> T post(final Object entity, TypeReference<T> typeReference) {
ResponseCallback<T> callback = new ResponseCallback<T>();
post(entity, typeReference, callback);
return callback.awaitResult();
}
public <T> void post(final Object entity, TypeReference<T> typeReference, final ResultCallback<T> resultCallback) {
HttpRequestProvider requestProvider = httpPostRequestProvider(entity);
Channel channel = getChannel();
JsonResponseCallbackHandler<T> jsonResponseHandler = new JsonResponseCallbackHandler<T>(typeReference,
resultCallback);
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(new JsonObjectDecoder(3 * 1024 * 1024));
channel.pipeline().addLast(jsonResponseHandler);
sendRequest(requestProvider, channel);
return;
}
private HttpRequest prepareDeleteRequest(String uri) {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, uri);
setDefaultHeaders(request);
return request;
}
private FullHttpRequest prepareGetRequest(String uri) {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
setDefaultHeaders(request);
return request;
}
private HttpRequest preparePostRequest(String uri, Object entity) {
return prepareEntityRequest(uri, entity, HttpMethod.POST);
}
private HttpRequest preparePutRequest(String uri, Object entity) {
return prepareEntityRequest(uri, entity, HttpMethod.PUT);
}
private HttpRequest prepareEntityRequest(String uri, Object entity, HttpMethod httpMethod) {
HttpRequest request = null;
if (entity != null) {
FullHttpRequest fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri);
byte[] bytes;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
bytes = objectMapper.writeValueAsBytes(entity);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
fullRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
fullRequest.content().clear().writeBytes(Unpooled.copiedBuffer(bytes));
fullRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
request = fullRequest;
} else {
request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri);
request.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
}
setDefaultHeaders(request);
return request;
}
private void sendRequest(HttpRequestProvider requestProvider, Channel channel) {
ChannelFuture channelFuture = channel.writeAndFlush(requestProvider.getHttpRequest(resource));
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
}
});
}
private void setDefaultHeaders(HttpRequest request) {
request.headers().set(HttpHeaderNames.HOST, "");
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.headers().set((CharSequence) entry.getKey(), entry.getValue());
}
}
public <T> T post(TypeReference<T> typeReference, InputStream body) {
ResponseCallback<T> callback = new ResponseCallback<T>();
post(typeReference, callback, body);
return callback.awaitResult();
}
public <T> void post(TypeReference<T> typeReference, ResultCallback<T> resultCallback, InputStream body) {
HttpRequestProvider requestProvider = httpPostRequestProvider(null);
Channel channel = getChannel();
JsonResponseCallbackHandler<T> jsonResponseHandler = new JsonResponseCallbackHandler<T>(typeReference,
resultCallback);
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(new JsonObjectDecoder(3 * 1024 * 1024));
channel.pipeline().addLast(jsonResponseHandler);
postChunkedStreamRequest(requestProvider, channel, body);
}
public void postStream(InputStream body) {
SkipResultCallback resultCallback = new SkipResultCallback();
HttpRequestProvider requestProvider = httpPostRequestProvider(null);
Channel channel = getChannel();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(responseHandler);
postChunkedStreamRequest(requestProvider, channel, body);
try {
resultCallback.awaitCompletion();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void postChunkedStreamRequest(HttpRequestProvider requestProvider, Channel channel, InputStream body) {
HttpRequest request = requestProvider.getHttpRequest(resource);
// don't accept FullHttpRequest here
if (request instanceof FullHttpRequest) {
throw new DockerClientException("fatal: request is instance of FullHttpRequest");
}
request.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
request.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
channel.write(request);
channel.write(new ChunkedStream(new BufferedInputStream(body, 1024 * 1024), 1024 * 1024));
channel.write(LastHttpContent.EMPTY_LAST_CONTENT);
channel.flush();
}
public InputStream get() {
HttpRequestProvider requestProvider = httpGetRequestProvider();
Channel channel = getChannel();
AsyncResultCallback<InputStream> resultCallback = new AsyncResultCallback<>();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
HttpResponseStreamHandler streamHandler = new HttpResponseStreamHandler(resultCallback);
channel.pipeline().addLast(responseHandler);
channel.pipeline().addLast(streamHandler);
sendRequest(requestProvider, channel);
return resultCallback.awaitResult();
}
@Override
public void put(InputStream body, com.github.dockerjava.core.MediaType mediaType) {
HttpRequestProvider requestProvider = httpPutRequestProvider(null);
Channel channel = getChannel();
ResponseCallback<Void> resultCallback = new ResponseCallback<Void>();
HttpResponseHandler responseHandler = new HttpResponseHandler(requestProvider, resultCallback);
channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(responseHandler);
HttpRequest request = requestProvider.getHttpRequest(resource);
// don't accept FullHttpRequest here
if (request instanceof FullHttpRequest) {
throw new DockerClientException("fatal: request is instance of FullHttpRequest");
}
request.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
request.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
request.headers().set(HttpHeaderNames.CONTENT_TYPE, mediaType.getMediaType());
channel.write(request);
channel.write(new ChunkedStream(new BufferedInputStream(body, 1024 * 1024)));
channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
resultCallback.awaitResult();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.