answer
stringlengths 17
10.2M
|
|---|
package org.chromium.distiller;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.BaseElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Window;
public class PagingLinksFinderTest extends DomDistillerJsTestCase {
// EXAMPLE_URL has to have a file extension, or findBaseUrl() would be
// the same as URL, and this would break testFirstPageLinkAsBaseUrl().
private static String EXAMPLE_URL = "http://example.com/path/toward/news.php";
private static void checkResolveLinkHref(AnchorElement anchor, String original_url, String expected, String href) {
anchor.setHref(href);
AnchorElement baseAnchor = PagingLinksFinder.createAnchorWithBase(original_url);
assertEquals(expected, PagingLinksFinder.resolveLinkHref(anchor, baseAnchor));
}
public void testResolveLinkHref() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("", "");
root.appendChild(anchor);
String url = "http://example.com/path/toward/page.html";
checkResolveLinkHref(anchor, url, "http:
checkResolveLinkHref(anchor, url, "https:
checkResolveLinkHref(anchor, url, "http://example.com/next", "/next");
checkResolveLinkHref(anchor, url, "http://example.com/path/toward/next", "next");
checkResolveLinkHref(anchor, url, "http://example.com/path/next", "../next");
checkResolveLinkHref(anchor, url, "http://example.com/1/2/next", "../../1/3/../2/next");
checkResolveLinkHref(anchor, url, "javascript:void(0)", "javascript:void(0)");
checkResolveLinkHref(anchor, url, "mailto:user@example.com", "mailto:user@example.com");
checkResolveLinkHref(anchor, url, "http://example.com/path/toward/page.html?page=2#table_of_content", "?page=2#table_of_content");
}
private static void checkLinks(AnchorElement next, AnchorElement prev, Element root) {
checkLinks(next, prev, root, EXAMPLE_URL);
}
private static void checkLinks(AnchorElement next, AnchorElement prev, Element root, String original_url) {
AnchorElement baseAnchor = PagingLinksFinder.createAnchorWithBase(original_url);
if (next == null) {
assertNull(PagingLinksFinder.findNext(root, original_url));
} else {
String href = PagingLinksFinder.resolveLinkHref(next, baseAnchor);
assertEquals(href, PagingLinksFinder.findNext(root, original_url));
}
if (prev == null) {
assertNull(PagingLinksFinder.findPrevious(root, original_url));
} else {
String href = PagingLinksFinder.resolveLinkHref(prev, baseAnchor);
assertEquals(href, PagingLinksFinder.findPrevious(root, original_url));
}
}
private static String formHrefMockedUrl(String strToAppend) {
String url = StringUtil.findAndReplace(EXAMPLE_URL, "^.*/", "");
if (strToAppend != "") {
url = url + "/" + strToAppend;
}
return url;
}
public void testNoLink() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
checkLinks(null, null, root);
}
public void test1NextLink() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("next", "next page");
root.appendChild(anchor);
checkLinks(null, null, root);
}
public void test1NextLinkWithDifferentDomain() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("http://testing.com/page2", "next page");
root.appendChild(anchor);
checkLinks(null, null, root);
}
public void test1NextLinkWithOriginalDomain() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("http://testing.com/page2", "next page");
root.appendChild(anchor);
checkLinks(anchor, null, root, "http://testing.com");
}
public void testCaseInsensitive() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("HTTP://testing.COM/page2", "next page");
root.appendChild(anchor);
checkLinks(anchor, null, root, "http://testing.com");
}
public void testCaseSensitive() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
// Prepend href with window location path so that base URL is part of final href to increase
// score.
AnchorElement anchor = TestUtil.createAnchor(
formHrefMockedUrl("page2").toUpperCase(), "page 2");
root.appendChild(anchor);
// This would have been checkLinks(anchor, anchor, root), but the URL is converted to upper
// case, and no longer matches base URL.
// See test1PageNumberedLink() for reference.
checkLinks(null, null, root);
}
public void test1PageNumberedLink() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
// Prepend href with window location path so that base URL is part of final href to increase
// score.
AnchorElement anchor = TestUtil.createAnchor(
formHrefMockedUrl("page2"), "page 2");
root.appendChild(anchor);
// The word "page" in the link text increases its score confidently enough to be considered
// as a paging link.
checkLinks(anchor, anchor, root);
}
public void test3NumberedLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
// Prepend href with window location path so that base URL is part of final href to increase
// score.
AnchorElement anchor1 = TestUtil.createAnchor(
formHrefMockedUrl("page1"), "1");
AnchorElement anchor2 = TestUtil.createAnchor(
formHrefMockedUrl("page2"), "2");
AnchorElement anchor3 = TestUtil.createAnchor(
formHrefMockedUrl("page3"), "3");
root.appendChild(anchor1);
root.appendChild(anchor2);
root.appendChild(anchor3);
// Because link text contains only digits with no paging-related words, no link has a score
// high enough to be confidently considered paging link.
checkLinks(null, null, root);
}
public void test2NextLinksWithSameHref() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
// Prepend href with window location path so that base URL is part of final href to increase
// score.
AnchorElement anchor1 = TestUtil.createAnchor(
formHrefMockedUrl("page2"), "dummy link");
AnchorElement anchor2 = TestUtil.createAnchor(
formHrefMockedUrl("page2"), "next page");
root.appendChild(anchor1);
root.appendChild(anchor2);
// anchor1 by itself is not a confident next page link, but anchor2's link text helps bump
// up the score for the shared href, so anchor1 is now a confident next page link.
checkLinks(anchor1, null, root);
}
public void flaky_testPagingParent() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
Element div = TestUtil.createDiv(1);
div.setClassName("page");
root.appendChild(div);
// Prepend href with window location path so that base URL is part of final href to increase
// score.
AnchorElement anchor = TestUtil.createAnchor(
formHrefMockedUrl("page1"), "dummy link");
div.appendChild(anchor);
// While it may seem strange that both previous and next links are the same, this test is
// testing that the anchor's parents will affect its paging score even if it has a
// meaningless link text like "dummy link".
checkLinks(anchor, anchor, root);
}
public void flaky_test1PrevLink() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("prev", "prev page");
root.appendChild(anchor);
checkLinks(null, anchor, root);
}
public void test1PrevAnd1NextLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement prevAnchor = TestUtil.createAnchor("prev", "prev page");
AnchorElement nextAnchor = TestUtil.createAnchor("page2", "next page");
root.appendChild(prevAnchor);
root.appendChild(nextAnchor);
checkLinks(nextAnchor, prevAnchor, root);
}
public void testPopularBadLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement nextAnchor = TestUtil.createAnchor("page2", "next page");
root.appendChild(nextAnchor);
// If the same bad URL can get scores accumulated across links,
// it would wrongly get selected.
AnchorElement bad1 = TestUtil.createAnchor("not-page1", "not page");
root.appendChild(bad1);
AnchorElement bad2 = TestUtil.createAnchor("not-page1", "not page");
root.appendChild(bad2);
AnchorElement bad3 = TestUtil.createAnchor("not-page1", "not page");
root.appendChild(bad3);
checkLinks(nextAnchor, null, root);
}
public void testHeldBackLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement nextAnchor = TestUtil.createAnchor("page2", "next");
root.appendChild(nextAnchor);
// If "page2" gets bad scores from other links, it would be missed.
AnchorElement bad = TestUtil.createAnchor("page2", "prev or next");
root.appendChild(bad);
checkLinks(nextAnchor, null, root);
}
public void testFirstPageLinkAsBaseUrl() {
// Some sites' first page links are the same as the base URL, previous page link needs to
// recognize this.
// For testcases, Window.Location.getPath() returns a ".html" file that will be stripped
// when determining the base URL in PagingLinksFinder.findBaseUrl(), so we need to do the
// same to use a href identical to base URL.
String href = StringUtil.findAndReplace(EXAMPLE_URL, "\\.[^.]*$", "");
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor(href, "PREV");
root.appendChild(anchor);
checkLinks(null, anchor, root);
}
public void testNonHttpOrHttpsLink() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor("javascript:void(0)",
"NEXT");
root.appendChild(anchor);
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
anchor.setHref("file://test.html");
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
}
public void testNextArticleLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor(
TestUtil.formHrefWithWindowLocationPath("page2"), "next article");
root.appendChild(anchor);
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
}
public void testAsOneLinks() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor(
TestUtil.formHrefWithWindowLocationPath("page2"), "view as one page");
root.appendChild(anchor);
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
}
public void testLinksWithLongText() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor(
TestUtil.formHrefWithWindowLocationPath("page2"), "page 2 with long text)");
root.appendChild(anchor);
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
}
public void testNonTailPageInfo() {
Element root = TestUtil.createDiv(0);
mBody.appendChild(root);
AnchorElement anchor = TestUtil.createAnchor(
TestUtil.formHrefWithWindowLocationPath("gap/12/somestuff"), "page down");
root.appendChild(anchor);
assertNull(PagingLinksFinder.findNext(root, EXAMPLE_URL));
}
public void testNoBase() {
Element doc = Document.get().getDocumentElement();
String base = PagingLinksFinder.getBaseUrlForRelative(doc, EXAMPLE_URL);
assertEquals(base, EXAMPLE_URL);
}
public void testBaseUrlForRelative() {
BaseElement base = Document.get().createBaseElement();
mHead.appendChild(base);
BaseElement bogusBase = Document.get().createBaseElement();
bogusBase.setHref("https://itsatrap.com/");
mHead.appendChild(bogusBase);
Element doc = Document.get().getDocumentElement();
String[] baseUrls = {
"http://example.com",
"https://example.com/no/trailing/slash.php",
"http://example.com/trailingslash/",
"/another/path/index.html",
"section/page2.html",
"//testing.com/",
};
String[] expected = {
"http://example.com/", // Note the trailing slash.
"https://example.com/no/trailing/slash.php",
"http://example.com/trailingslash/",
"http://example.com/another/path/index.html",
"http://example.com/path/toward/section/page2.html",
"http://testing.com/",
};
for (int i = 0; i < baseUrls.length; i++) {//String baseUrl: baseUrls) {
String baseUrl = baseUrls[i];
base.setHref(baseUrl);
assertEquals(expected[i], PagingLinksFinder.getBaseUrlForRelative(doc, EXAMPLE_URL));
}
mHead.removeChild(base);
mHead.removeChild(bogusBase);
}
public void testPageDiff() {
assertNull(PagingLinksFinder.pageDiff("", "", null, 0));
assertNull(PagingLinksFinder.pageDiff("asdf", "qwer", null, 0));
assertNull(PagingLinksFinder.pageDiff("commonA", "commonB", null, 0));
assertEquals((Integer) 1, PagingLinksFinder.pageDiff("common1", "common2", null, 0));
assertNull(PagingLinksFinder.pageDiff("common1", "common2", null, 7));
assertNull(PagingLinksFinder.pageDiff("common1", "Common2", null, 0));
assertEquals((Integer) (-8), PagingLinksFinder.pageDiff("common10", "common02", null, 0));
assertNull(PagingLinksFinder.pageDiff("commonA10", "commonB02", null, 0));
assertNull(PagingLinksFinder.pageDiff("common10", "commonB02", null, 0));
assertNull(PagingLinksFinder.pageDiff("commonA10", "common02", null, 0));
assertEquals((Integer) (-7), PagingLinksFinder.pageDiff("common11", "common4", null, 0));
}
}
|
// SECTION-END
package org.jomc.logging;
// SECTION-START[Documentation]
/**
* Logs events for a specific component.
* <p>This specification declares a multiplicity of {@code One}.
* An application assembler is required to provide no more than one implementation of this specification (including none).
* Use of class {@link org.jomc.ObjectManager ObjectManager} is supported for getting that implementation.<pre>
* Logger object = (Logger) ObjectManagerFactory.getObjectManager().getObject( Logger.class );
* </pre>
* </p>
*
* <p>This specification does not apply to any scope. A new object is returned whenever requested.</p>
*
* @author <a href="mailto:cs@jomc.org">Christian Schulte</a> 1.0
* @version $Id$
*/
// SECTION-END
// SECTION-START[Annotations]
@javax.annotation.Generated( value = "org.jomc.tools.JavaSources",
comments = "See http://jomc.sourceforge.net/jomc/1.0-alpha-3/jomc-tools" )
// SECTION-END
public interface Logger
{
/**
* Getter for property {@code debugEnabled}.
*
* @return {@code true} if logging debug messages is enabled; {@code false} if logging debug messages is disabled.
*/
boolean isDebugEnabled();
/**
* Logs a message at log level {@code debug}.
*
* @param message The message to log.
*/
void debug( String message );
/**
* Logs an exception at log level {@code debug}.
*
* @param t The exception to log.
*/
void debug( Throwable t );
/**
* Logs a message and an exception at log level {@code debug}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void debug( String message, Throwable t );
/**
* Getter for property {@code errorEnabled}.
*
* @return {@code true} if logging error messages is enabled; {@code false} if logging error messages is disabled.
*/
boolean isErrorEnabled();
/**
* Logs a message at log level {@code error}.
*
* @param message The message to log.
*/
void error( String message );
/**
* Logs an exception at log level {@code error}.
*
* @param t The exception to log.
*/
void error( Throwable t );
/**
* Logs a message and an exception at log level {@code error}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void error( String message, Throwable t );
/**
* Getter for property {@code fatalEnabled}.
*
* @return {@code true} if logging fatal messages is enabled; {@code false} if logging fatal messages is disabled.
*/
boolean isFatalEnabled();
/**
* Logs a message at log level {@code fatal}.
*
* @param message The message to log.
*/
void fatal( String message );
/**
* Logs an exception at log level {@code fatal}.
*
* @param t The exception to log.
*/
void fatal( Throwable t );
/**
* Logs a message and an exception at log level {@code fatal}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void fatal( String message, Throwable t );
/**
* Getter for property {@code infoEnabled}.
*
* @return {@code true} if logging info messages is enabled; {@code false} if logging info messages is disabled.
*/
boolean isInfoEnabled();
/**
* Logs a message at log level {@code info}.
*
* @param message The message to log.
*/
void info( String message );
/**
* Logs an exception at log level {@code info}.
*
* @param t The exception to log.
*/
void info( Throwable t );
/**
* Logs a message and an exception at log level {@code info}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void info( String message, Throwable t );
/**
* Getter for property {@code traceEnabled}.
*
* @return {@code true} if logging trace messages is enabled; {@code false} if logging trace messages is disabled.
*/
boolean isTraceEnabled();
/**
* Logs a message at log level {@code trace}.
*
* @param message The message to log.
*/
void trace( String message );
/**
* Logs an exception at log level {@code trace}.
*
* @param t The exception to log.
*/
void trace( Throwable t );
/**
* Logs a message and an exception at log level {@code trace}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void trace( String message, Throwable t );
/**
* Getter for property {@code warnEnabled}.
*
* @return {@code true} if logging warning messages is enabled; {@code false} if logging warning messages is
* disabled.
*/
boolean isWarnEnabled();
/**
* Logs a message at log level {@code warn}.
*
* @param message The message to log.
*/
void warn( String message );
/**
* Logs an exception at log level {@code warn}.
*
* @param t The exception to log.
*/
void warn( Throwable t );
/**
* Logs a message and an exception at log level {@code warn}.
*
* @param message The message to log.
* @param t The exception to log.
*/
void warn( String message, Throwable t );
}
|
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.OnActionCompleted;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.FadeTo;
import com.badlogic.gdx.scenes.scene2d.actions.Forever;
import com.badlogic.gdx.scenes.scene2d.actions.Parallel;
import com.badlogic.gdx.scenes.scene2d.actions.RotateBy;
import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo;
import com.badlogic.gdx.scenes.scene2d.actions.Sequence;
import com.badlogic.gdx.scenes.scene2d.actors.Image;
import com.badlogic.gdx.tests.utils.GdxTest;
public class ActionTest extends GdxTest implements OnActionCompleted {
@Override
public boolean needsGL20() {
return false;
}
Stage stage;
@Override
public void create() {
stage = new Stage(480, 320, true);
Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"),
false);
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
final Image img = new Image("actor", texture);
img.width = img.height = 100;
img.originX = 50;
img.originY = 50;
img.x = img.y = 100;
// img.action(Forever.$(Sequence.$(ScaleTo.$(1.1f,
// 1.1f,0.3f),ScaleTo.$(1f, 1f, 0.3f))));
// img.action(Forever.$(Parallel.$(RotateTo.$(1, 1))));
// img.action(Delay.$(RotateBy.$(45, 2),
// 1).setCompletionListener(this));
// Action actionMoveBy = MoveBy.$(30, 0, 0.5f).setCompletionListener(
// new OnActionCompleted() {
// @Override
// public void completed(Action action) {
// System.out.println("move by complete");
// Action actionDelay = Delay.$(actionMoveBy, 1).setCompletionListener(
// new OnActionCompleted() {
// @Override
// public void completed(Action action) {
// System.out.println("delay complete");
// img.action(actionDelay);
// img.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3));
// img.action(Sequence.$(FadeOut.$(1),
// FadeIn.$(1),
// Delay.$(MoveTo.$(100, 100, 1), 2),
// ScaleTo.$(0.5f, 0.5f, 1),
// FadeOut.$(0.5f),
// Delay.$(Parallel.$( RotateTo.$(360, 1),
// FadeIn.$(1),
// ScaleTo.$(1, 1, 1)), 1)));
// OnActionCompleted listener = new OnActionCompleted() {
// @Override public void completed (Action action) {
// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)),
// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(this));
// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)),
// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(listener));
img.action(
Forever.$(
Sequence.$(
Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.4f, 1.4f, 2), FadeTo.$(0.7f, 2)),
Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.0f, 1.0f, 2), FadeTo.$(1.0f, 2))
)
)
);
stage.addActor(img);
}
@Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
}
@Override
public void completed(Action action) {
System.out.println("completed");
}
}
|
package org.jgroups.tests;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.protocols.TP;
import org.jgroups.util.Util;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Bela Ban
* @version $Id: TransportThreadPoolTest.java,v 1.2 2007/11/21 11:27:16 belaban Exp $
*/
public class TransportThreadPoolTest extends ChannelTestBase {
JChannel c1, c2;
protected void setUp() throws Exception {
super.setUp();
c1=createChannel();
c2=createChannel();
}
protected void tearDown() throws Exception {
super.tearDown();
c2.close();
c1.close();
}
public void testThreadPoolReplacement() throws Exception {
Receiver r1=new Receiver(), r2=new Receiver();
c1.setReceiver(r1);
c2.setReceiver(r2);
c1.connect("x");
c2.connect("x");
c1.send(null, null, "hello world");
c2.send(null, null, "bela");
Util.sleep(500); // need to sleep because message sending is asynchronous
assertEquals(2, r1.getMsgs().size());
assertEquals(2, r2.getMsgs().size());
TP transport=(TP)c1.getProtocolStack().getTransport();
ExecutorService thread_pool=Executors.newCachedThreadPool();
transport.setDefaultThreadPool(thread_pool);
transport=(TP)c2.getProtocolStack().getTransport();
thread_pool=Executors.newCachedThreadPool();
transport.setDefaultThreadPool(thread_pool);
c1.send(null, null, "message 3");
c2.send(null, null, "message 4");
Util.sleep(500);
System.out.println("messages c1: " + print(r1.getMsgs()) + "\nmessages c2: " + print(r2.getMsgs()));
assertEquals(4, r1.getMsgs().size());
assertEquals(4, r2.getMsgs().size());
}
private static String print(List<Message> msgs) {
StringBuilder sb=new StringBuilder();
for(Message msg: msgs) {
sb.append("\"" + msg.getObject() + "\"").append(" ");
}
return sb.toString();
}
private static class Receiver extends ReceiverAdapter {
List<Message> msgs=new LinkedList<Message>();
public List<Message> getMsgs() {
return msgs;
}
public void receive(Message msg) {
msgs.add(msg);
}
}
}
|
package com.charlesmadere.hummingbird.models;
import android.os.Build;
import com.charlesmadere.hummingbird.BuildConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.M)
public class SimpleDateTest {
private static final String AM_PM_DATE_0 = "Feb 2, 1998 4:34:20 AM";
private static final String AM_PM_DATE_1 = "Jun 08, 2000 08:10:59 PM";
private static final String AM_PM_DATE_2 = "Dec 28, 2012 12:00:00 AM";
private static final String ARMY_DATE_0 = "Sep 26, 2015 00:00:00";
private static final String ARMY_DATE_1 = "Nov 28, 1989 13:41:26";
private static final String EXTENDED_DATE_0 = "2013-02-20T16:00:15.623Z";
private static final String EXTENDED_DATE_1 = "2015-08-06T18:46:42.723Z";
private static final String SHORT_DATE_0 = "2013-07-18";
private static final String SHORT_DATE_1 = "2016-03-04";
private Constructor<SimpleDate> mConstructor;
private Method mFixTimeZone;
private SimpleDateFormat mAmPmFormat;
private SimpleDateFormat mArmyFormat;
private SimpleDateFormat mExtendedFormat;
private SimpleDateFormat mShortFormat;
@Before
public void setUp() throws Exception {
mConstructor = SimpleDate.class.getDeclaredConstructor(Date.class);
mConstructor.setAccessible(true);
mFixTimeZone = SimpleDate.class.getDeclaredMethod("fixTimeZone", String.class);
mFixTimeZone.setAccessible(true);
final Field field = SimpleDate.class.getDeclaredField("FORMATS");
field.setAccessible(true);
final SimpleDateFormat[] formats = (SimpleDateFormat[]) field.get(null);
mExtendedFormat = formats[0];
mAmPmFormat = formats[1];
mArmyFormat = formats[2];
mShortFormat = formats[3];
}
@Test
public void testAmPmDateConstruction() throws Exception {
SimpleDate sd = mConstructor.newInstance(mAmPmFormat.parse(AM_PM_DATE_0));
assertNotNull(sd);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 1998);
assertEquals(calendar.get(Calendar.MONTH), Calendar.FEBRUARY);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 2);
assertEquals(calendar.get(Calendar.HOUR), 4);
assertEquals(calendar.get(Calendar.MINUTE), 34);
assertEquals(calendar.get(Calendar.SECOND), 20);
assertEquals(calendar.get(Calendar.AM_PM), Calendar.AM);
sd = mConstructor.newInstance(mAmPmFormat.parse(AM_PM_DATE_1));
assertNotNull(sd);
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2000);
assertEquals(calendar.get(Calendar.MONTH), Calendar.JUNE);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 8);
assertEquals(calendar.get(Calendar.HOUR), 8);
assertEquals(calendar.get(Calendar.MINUTE), 10);
assertEquals(calendar.get(Calendar.SECOND), 59);
assertEquals(calendar.get(Calendar.AM_PM), Calendar.PM);
sd = mConstructor.newInstance(mAmPmFormat.parse(AM_PM_DATE_2));
assertNotNull(sd);
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2012);
assertEquals(calendar.get(Calendar.MONTH), Calendar.DECEMBER);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 28);
assertEquals(calendar.get(Calendar.HOUR), 0);
assertEquals(calendar.get(Calendar.MINUTE), 0);
assertEquals(calendar.get(Calendar.SECOND), 0);
assertEquals(calendar.get(Calendar.AM_PM), Calendar.AM);
}
@Test
public void testArmyDateConstruction() throws Exception {
SimpleDate sd = mConstructor.newInstance(mArmyFormat.parse(ARMY_DATE_0));
assertNotNull(sd);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2015);
assertEquals(calendar.get(Calendar.MONTH), Calendar.SEPTEMBER);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 26);
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), 0);
assertEquals(calendar.get(Calendar.MINUTE), 0);
assertEquals(calendar.get(Calendar.SECOND), 0);
sd = mConstructor.newInstance(mArmyFormat.parse(ARMY_DATE_1));
assertNotNull(sd);
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 1989);
assertEquals(calendar.get(Calendar.MONTH), Calendar.NOVEMBER);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 28);
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), 13);
assertEquals(calendar.get(Calendar.MINUTE), 41);
assertEquals(calendar.get(Calendar.SECOND), 26);
}
@Test
public void testExtendedDateConstruction() throws Exception {
String dateString = (String) mFixTimeZone.invoke(null, EXTENDED_DATE_0);
SimpleDate sd = mConstructor.newInstance(mExtendedFormat.parse(dateString));
assertNotNull(sd);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2013);
assertEquals(calendar.get(Calendar.MONTH), Calendar.FEBRUARY);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 20);
dateString = (String) mFixTimeZone.invoke(null, EXTENDED_DATE_1);
sd = mConstructor.newInstance(mExtendedFormat.parse(dateString));
assertNotNull(sd);
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2015);
assertEquals(calendar.get(Calendar.MONTH), Calendar.AUGUST);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 6);
}
@Test
public void testFixTimeZone() throws Exception {
String string = (String) mFixTimeZone.invoke(null, AM_PM_DATE_0);
assertEquals(string, AM_PM_DATE_0);
string = (String) mFixTimeZone.invoke(null, AM_PM_DATE_1);
assertEquals(string, AM_PM_DATE_1);
string = (String) mFixTimeZone.invoke(null, AM_PM_DATE_2);
assertEquals(string, AM_PM_DATE_2);
string = (String) mFixTimeZone.invoke(null, EXTENDED_DATE_0);
assertTrue(string.endsWith("+0000"));
string = (String) mFixTimeZone.invoke(null, EXTENDED_DATE_1);
assertTrue(string.endsWith("+0000"));
string = (String) mFixTimeZone.invoke(null, SHORT_DATE_0);
assertEquals(string, SHORT_DATE_0);
string = (String) mFixTimeZone.invoke(null, SHORT_DATE_1);
assertEquals(string, SHORT_DATE_1);
}
@Test
public void testShortDateConstruction() throws Exception {
SimpleDate sd = mConstructor.newInstance(mShortFormat.parse(SHORT_DATE_0));
assertNotNull(sd);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2013);
assertEquals(calendar.get(Calendar.MONTH), Calendar.JULY);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 18);
sd = mConstructor.newInstance(mShortFormat.parse(SHORT_DATE_1));
assertNotNull(sd);
calendar.setTime(sd.getDate());
assertEquals(calendar.get(Calendar.YEAR), 2016);
assertEquals(calendar.get(Calendar.MONTH), Calendar.MARCH);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 4);
}
}
|
package tlc2.tool.impl;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import tla2sany.parser.SyntaxTreeNode;
import tla2sany.semantic.APSubstInNode;
import tla2sany.semantic.ExprNode;
import tla2sany.semantic.ExprOrOpArgNode;
import tla2sany.semantic.ExternalModuleTable;
import tla2sany.semantic.FormalParamNode;
import tla2sany.semantic.LabelNode;
import tla2sany.semantic.LetInNode;
import tla2sany.semantic.LevelConstants;
import tla2sany.semantic.LevelNode;
import tla2sany.semantic.OpApplNode;
import tla2sany.semantic.OpArgNode;
import tla2sany.semantic.OpDeclNode;
import tla2sany.semantic.OpDefNode;
import tla2sany.semantic.OpDefOrDeclNode;
import tla2sany.semantic.SemanticNode;
import tla2sany.semantic.Subst;
import tla2sany.semantic.SubstInNode;
import tla2sany.semantic.SymbolNode;
import tla2sany.semantic.ThmOrAssumpDefNode;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.Action;
import tlc2.tool.BuiltInOPs;
import tlc2.tool.EvalControl;
import tlc2.tool.EvalException;
import tlc2.tool.IActionItemList;
import tlc2.tool.IContextEnumerator;
import tlc2.tool.INextStateFunctor;
import tlc2.tool.IStateFunctor;
import tlc2.tool.ITool;
import tlc2.tool.StateVec;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateFun;
import tlc2.tool.TLCStateInfo;
import tlc2.tool.TLCStateMut;
import tlc2.tool.TLCStateMutExt;
import tlc2.tool.ToolGlobals;
import tlc2.tool.coverage.CostModel;
import tlc2.util.Context;
import tlc2.util.ExpectInlined;
import tlc2.util.IdThread;
import tlc2.util.RandomGenerator;
import tlc2.util.Vect;
import tlc2.value.IFcnLambdaValue;
import tlc2.value.IMVPerm;
import tlc2.value.IValue;
import tlc2.value.ValueConstants;
import tlc2.value.Values;
import tlc2.value.impl.Applicable;
import tlc2.value.impl.BoolValue;
import tlc2.value.impl.Enumerable;
import tlc2.value.impl.Enumerable.Ordering;
import tlc2.value.impl.EvaluatingValue;
import tlc2.value.impl.FcnLambdaValue;
import tlc2.value.impl.FcnParams;
import tlc2.value.impl.FcnRcdValue;
import tlc2.value.impl.LazySupplierValue;
import tlc2.value.impl.LazyValue;
import tlc2.value.impl.MVPerm;
import tlc2.value.impl.MVPerms;
import tlc2.value.impl.MethodValue;
import tlc2.value.impl.ModelValue;
import tlc2.value.impl.OpLambdaValue;
import tlc2.value.impl.OpValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.Reducible;
import tlc2.value.impl.SetCapValue;
import tlc2.value.impl.SetCupValue;
import tlc2.value.impl.SetDiffValue;
import tlc2.value.impl.SetEnumValue;
import tlc2.value.impl.SetOfFcnsValue;
import tlc2.value.impl.SetOfRcdsValue;
import tlc2.value.impl.SetOfTuplesValue;
import tlc2.value.impl.SetPredValue;
import tlc2.value.impl.StringValue;
import tlc2.value.impl.SubsetValue;
import tlc2.value.impl.TupleValue;
import tlc2.value.impl.UnionValue;
import tlc2.value.impl.Value;
import tlc2.value.impl.ValueEnumeration;
import tlc2.value.impl.ValueExcept;
import tlc2.value.impl.ValueVec;
import util.Assert;
import util.Assert.TLCRuntimeException;
import util.FilenameToStream;
import util.TLAConstants;
import util.UniqueString;
/**
* This class provides useful methods for tools like model checker
* and simulator.
*
* It's instance serves as a spec handle
* This is one of two places in TLC, where not all messages are retrieved from the message printer,
* but constructed just here in the code.
*/
public abstract class Tool
extends Spec
implements ValueConstants, ToolGlobals, ITool
{
public static final String PROBABLISTIC_KEY = Tool.class.getName() + ".probabilistic";
/*
* Prototype, do *not* activate when checking safety or liveness!!!:
* For simulation that is not meant as a substitute of exhaustive checking for too
* large models, it can be useful to generate behaviors as quickly as possible,
* i.e. without checking all successor states along the states of the behavior.
* This flag activates the code path that efficiently generate only a single
* successor state during simulation. It does not let the user parameterize
* the code with a particular distribution, but instead draws from the uniform
* distribution.
*
* In its current form, it only handles non-determinism expressed with opcode
* OPCODE_be (bounded exist), i.e. (which simply happened to be the primary
* expression that we encountered in the SWIM spec during this work):
*
* VARIABLE x
* \E n \in S: x' = n
*
* Activate with: -Dtlc2.tool.impl.Tool.probabilistic=true
*/
private static final boolean PROBABLISTIC = Boolean.getBoolean(PROBABLISTIC_KEY);
public enum Mode {
Simulation, MC, MC_DEBUG, Executor;
}
public static final Value[] EmptyArgs = new Value[0];
protected final Action[] actions; // the list of TLA actions.
private Vect<Action> actionVec = new Vect<>(10);
protected final Mode toolMode;
/**
* Creates a new tool handle
*/
public Tool(String specFile, String configFile) {
this(new File(specFile), specFile, configFile, null);
}
public Tool(String specFile, String configFile, FilenameToStream resolver) {
this(new File(specFile), specFile, configFile, resolver);
}
public Tool(String specFile, String configFile, FilenameToStream resolver, final Map<String, Object> params) {
this(new File(specFile), specFile, configFile, resolver, params);
}
public Tool(String specFile, String configFile, FilenameToStream resolver, Mode mode, final Map<String, Object> params) {
this(new File(specFile), specFile, configFile, resolver, mode, params);
}
private Tool(File specDir, String specFile, String configFile, FilenameToStream resolver)
{
this(specDir.isAbsolute() ? specDir.getParent() : "", specFile, configFile, resolver, new HashMap<>());
}
private Tool(File specDir, String specFile, String configFile, FilenameToStream resolver, final Map<String, Object> params)
{
this(specDir.isAbsolute() ? specDir.getParent() : "", specFile, configFile, resolver, params);
}
private Tool(File specDir, String specFile, String configFile, FilenameToStream resolver, Mode mode, final Map<String, Object> params)
{
this(specDir.isAbsolute() ? specDir.getParent() : "", specFile, configFile, resolver, mode, params);
}
public Tool(String specDir, String specFile, String configFile, FilenameToStream resolver, final Map<String, Object> params)
{
this(specDir, specFile, configFile, resolver, Mode.MC, params);
}
public Tool(String specDir, String specFile, String configFile, FilenameToStream resolver, Mode mode, final Map<String, Object> params)
{
super(specDir, specFile, configFile, resolver, mode, params);
this.toolMode = mode;
// set variables to the static filed in the state
if (mode == Mode.Simulation || mode == Mode.Executor || mode == Mode.MC_DEBUG) {
assert TLCState.Empty instanceof TLCStateMutExt;
TLCStateMutExt.setTool(this);
} else {
// Initialize state.
assert TLCState.Empty instanceof TLCStateMut;
TLCStateMut.setTool(this);
}
Action next = this.getNextStateSpec();
if (next == null) {
this.actions = new Action[0];
} else {
this.getActions(next);
int sz = this.actionVec.size();
this.actions = new Action[sz];
for (int i = 0; i < sz; i++) {
this.actions[i] = (Action) this.actionVec.elementAt(i);
}
}
// Tag the initial predicates and next-state actions.
final Vect<Action> initAndNext = getInitStateSpec().concat(actionVec);
for (int i = 0; i < initAndNext.size(); i++) {
initAndNext.elementAt(i).setId(i);
}
}
Tool(Tool other) {
super(other);
this.actions = other.actions;
this.actionVec = other.actionVec;
this.toolMode = other.toolMode;
}
@Override
public Mode getMode() {
return this.toolMode;
}
/**
* This method returns the set of all possible actions of the
* spec, and sets the actions field of this object. In fact, we
* could simply treat the next predicate as one "giant" action.
* But for efficiency, we preprocess the next state predicate by
* splitting it into a set of actions for the maximum prefix
* of disjunction and existential quantification.
*/
@Override
public final Action[] getActions() {
return this.actions;
}
private final void getActions(final Action next) {
this.getActions(next.pred, next.con, next.getOpDef(), next.cm);
}
private final void getActions(SemanticNode next, Context con, final OpDefNode opDefNode, CostModel cm) {
switch (next.getKind()) {
case OpApplKind:
{
OpApplNode next1 = (OpApplNode)next;
this.getActionsAppl(next1, con, opDefNode, cm);
return;
}
case LetInKind:
{
LetInNode next1 = (LetInNode)next;
this.getActions(next1.getBody(), con, opDefNode, cm);
return;
}
case SubstInKind:
{
SubstInNode next1 = (SubstInNode)next;
Subst[] substs = next1.getSubsts();
if (substs.length == 0) {
this.getActions(next1.getBody(), con, opDefNode, cm);
}
else {
Action action = new Action(next1, con, opDefNode);
this.actionVec.addElement(action);
}
return;
}
// Added by LL on 13 Nov 2009 to handle theorem and assumption names.
case APSubstInKind:
{
APSubstInNode next1 = (APSubstInNode)next;
Subst[] substs = next1.getSubsts();
if (substs.length == 0) {
this.getActions(next1.getBody(), con, opDefNode, cm);
}
else {
Action action = new Action(next1, con, opDefNode);
this.actionVec.addElement(action);
}
return;
}
case LabelKind:
{
LabelNode next1 = (LabelNode)next;
this.getActions(next1.getBody(), con, opDefNode, cm);
return;
}
default:
{
Assert.fail("The next state relation is not a boolean expression.\n" + next, next, con);
}
}
}
private final void getActionsAppl(OpApplNode next, Context con, final OpDefNode actionName, CostModel cm) {
ExprOrOpArgNode[] args = next.getArgs();
SymbolNode opNode = next.getOperator();
int opcode = BuiltInOPs.getOpCode(opNode.getName());
if (opcode == 0) {
Object val = this.lookup(opNode, con, false);
if (val instanceof OpDefNode) {
OpDefNode opDef = (OpDefNode)val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
if (opcode == 0) {
try {
FormalParamNode[] formals = opDef.getParams();
int alen = args.length;
int argLevel = 0;
for (int i = 0; i < alen; i++) {
argLevel = args[i].getLevel();
if (argLevel != 0) break;
}
if (argLevel == 0) {
Context con1 = con;
for (int i = 0; i < alen; i++) {
IValue aval = this.eval(args[i], con, TLCState.Empty, cm);
con1 = con1.cons(formals[i], aval);
}
this.getActions(opDef.getBody(), con1, opDef, cm);
return;
}
}
catch (Throwable e) { /*SKIP*/ }
}
}
if (opcode == 0) {
Action action = new Action(next, con, (OpDefNode) opNode);
this.actionVec.addElement(action);
return;
}
}
switch (opcode) {
case OPCODE_be: // BoundedExists
{
final int cnt = this.actionVec.size();
try {
ContextEnumerator Enum =
this.contexts(next, con, TLCState.Empty, TLCState.Empty, EvalControl.Clear, cm);
if (Enum.isDone()) {
// No exception and no actions created implies Enum was empty:
// \E i \in {} : ...
// \E i \in Nat: FALSE
this.actionVec.addElement(new Action(next, con, actionName));
return;
}
Context econ;
while ((econ = Enum.nextElement()) != null) {
this.getActions(args[0], econ, actionName, cm);
}
assert (cnt < this.actionVec.size())
: "AssertionError when creating Actions. This case should have been handled by Enum.isDone conditional above!";
}
catch (Throwable e) {
Action action = new Action(next, con, actionName);
this.actionVec.removeAll(cnt);
this.actionVec.addElement(action);
}
return;
}
case OPCODE_dl: // DisjList
case OPCODE_lor:
{
for (int i = 0; i < args.length; i++) {
this.getActions(args[i], con, actionName, cm);
}
return;
}
default:
{
// We handle all the other builtin operators here.
Action action = new Action(next, con, actionName);
this.actionVec.addElement(action);
return;
}
}
}
/*
* This method returns the set of possible initial states that
* satisfies the initial state predicate. Initial state predicate
* can be under-specified. Too many possible initial states will
* probably make tools like TLC useless.
*/
@Override
public final StateVec getInitStates() {
final StateVec initStates = new StateVec(0);
getInitStates(initStates);
return initStates;
}
@Override
public final void getInitStates(IStateFunctor functor) {
Vect<Action> init = this.getInitStateSpec();
ActionItemList acts = ActionItemListExt.Empty;
// MAK 09/11/2018: Tail to head iteration order cause the first elem added with
// acts.cons to be acts tail. This fixes the bug/funny behavior that the init
// predicate Init == A /\ B /\ C /\ D was evaluated in the order A, D, C, B (A
// doesn't get added to acts at all).
for (int i = (init.size() - 1); i > 0; i
Action elem = (Action)init.elementAt(i);
acts = (ActionItemList) acts.cons(elem, IActionItemList.PRED);
}
if (init.size() != 0) {
Action elem = (Action)init.elementAt(0);
TLCState ps = TLCState.Empty.createEmpty();
if (acts.isEmpty()) {
acts.setAction(elem);
}
this.getInitStates(elem.pred, acts, elem.con, ps, functor, elem.cm);
}
}
/* Create the state specified by pred. */
@Override
public final TLCState makeState(SemanticNode pred) {
ActionItemList acts = ActionItemList.Empty;
TLCState ps = TLCState.Empty.createEmpty();
StateVec states = new StateVec(0);
this.getInitStates(pred, acts, Context.Empty, ps, states, acts.cm);
if (states.size() != 1) {
Assert.fail("The predicate does not specify a unique state." + pred, pred);
}
TLCState state = states.elementAt(0);
if (!this.isGoodState(state)) {
Assert.fail("The state specified by the predicate is not complete." + pred, pred);
}
return state;
}
protected void getInitStates(SemanticNode init, ActionItemList acts,
Context c, TLCState ps, IStateFunctor states, CostModel cm) {
switch (init.getKind()) {
case OpApplKind:
{
OpApplNode init1 = (OpApplNode)init;
this.getInitStatesAppl(init1, acts, c, ps, states, cm);
return;
}
case LetInKind:
{
LetInNode init1 = (LetInNode)init;
this.getInitStates(init1.getBody(), acts, c, ps, states, cm);
return;
}
case SubstInKind:
{
SubstInNode init1 = (SubstInNode)init;
Subst[] subs = init1.getSubsts();
Context c1 = c;
for (int i = 0; i < subs.length; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId));
}
this.getInitStates(init1.getBody(), acts, c1, ps, states, cm);
return;
}
// Added by LL on 13 Nov 2009 to handle theorem and assumption names.
case APSubstInKind:
{
APSubstInNode init1 = (APSubstInNode)init;
Subst[] subs = init1.getSubsts();
Context c1 = c;
for (int i = 0; i < subs.length; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId));
}
this.getInitStates(init1.getBody(), acts, c1, ps, states, cm);
return;
}
// LabelKind class added by LL on 13 Jun 2007
case LabelKind:
{
LabelNode init1 = (LabelNode)init;
this.getInitStates(init1.getBody(), acts, c, ps, states, cm);
return;
}
default:
{
Assert.fail("The init state relation is not a boolean expression.\n" + init, init, c);
}
}
}
protected void getInitStates(ActionItemList acts, TLCState ps, IStateFunctor states, CostModel cm) {
if (acts.isEmpty()) {
if (coverage) {
cm.incInvocations();
cm.getRoot().incInvocations();
}
states.addElement(ps.copy().setAction(acts.getAction()));
return;
} else if (ps.allAssigned()) {
// MAK 05/25/2018: If all values of the initial state have already been
// assigned, there is no point in further trying to assign values. Instead, all
// remaining statements (ActionItemList) can just be evaluated for their boolean
// value.
// This optimization is especially useful to check inductive invariants which
// require TLC to generate a very large set of initial states.
while (!acts.isEmpty()) {
final Value bval = this.eval(acts.carPred(), acts.carContext(), ps, TLCState.Empty, EvalControl.Init, acts.cm);
if (!(bval instanceof BoolValue)) {
//TODO Choose more fitting error message.
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING,
new String[] { "initial states", "boolean", bval.toString(), acts.pred.toString() }, acts.carPred(), acts.carContext());
}
if (!((BoolValue) bval).val) {
if (coverage) {
// Increase "states found".
cm.getRoot().incSecondary();
}
return;
}
// Move on to the next action in the ActionItemList.
acts = acts.cdr();
}
if (coverage) {
cm.incInvocations();
cm.getRoot().incInvocations();
}
states.addElement(ps.copy().setAction(acts.getAction()));
return;
}
// Assert.check(act.kind > 0 || act.kind == -1);
ActionItemList acts1 = acts.cdr();
this.getInitStates(acts.carPred(), acts1, acts.carContext(), ps, states, acts.cm);
}
protected void getInitStatesAppl(OpApplNode init, ActionItemList acts,
Context c, TLCState ps, IStateFunctor states, CostModel cm) {
if (coverage) {cm = cm.get(init);}
ExprOrOpArgNode[] args = init.getArgs();
int alen = args.length;
SymbolNode opNode = init.getOperator();
int opcode = BuiltInOPs.getOpCode(opNode.getName());
if (opcode == 0) {
// This is a user-defined operator with one exception: it may
// be substed by a builtin operator. This special case occurs
// when the lookup returns an OpDef with opcode
Object val = this.lookup(opNode, c, ps, false);
if (val instanceof OpDefNode) {
OpDefNode opDef = (OpDefNode)val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
if (opcode == 0) {
// Context c1 = this.getOpContext(opDef, args, c, false);
Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId);
this.getInitStates(opDef.getBody(), acts, c1, ps, states, cm);
return;
}
}
// Added 13 Nov 2009 by LL to fix Yuan's fix.
if (val instanceof ThmOrAssumpDefNode) {
ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
Context c1 = this.getOpContext(opDef, args, c, true);
this.getInitStates(opDef.getBody(), acts, c1, ps, states, cm);
return;
}
if (val instanceof LazyValue) {
LazyValue lv = (LazyValue)val;
if (lv.getValue() == null || lv.isUncachable()) {
this.getInitStates(lv.expr, acts, lv.con, ps, states, cm);
return;
}
val = lv.getValue();
}
Object bval = val;
if (alen == 0) {
if (val instanceof MethodValue) {
bval = ((MethodValue)val).apply(EmptyArgs, EvalControl.Init);
} else if (val instanceof EvaluatingValue) {
// Allow EvaluatingValue overwrites to have zero arity.
bval = ((EvaluatingValue) val).eval(this, args, c, ps, TLCState.Empty, EvalControl.Init, cm);
}
}
else {
if (val instanceof OpValue) {
bval = ((OpValue) val).eval(this, args, c, ps, TLCState.Empty, EvalControl.Init, cm);
}
}
if (opcode == 0)
{
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "initial states", "boolean",
bval.toString(), init.toString() }, init, c);
}
if (((BoolValue) bval).val)
{
this.getInitStates(acts, ps, states, cm);
}
return;
}
}
switch (opcode) {
case OPCODE_dl: // DisjList
case OPCODE_lor:
{
for (int i = 0; i < alen; i++) {
this.getInitStates(args[i], acts, c, ps, states, cm);
}
return;
}
case OPCODE_cl: // ConjList
case OPCODE_land:
{
for (int i = alen-1; i > 0; i
acts = (ActionItemList) acts.cons(args[i], c, cm, i);
}
this.getInitStates(args[0], acts, c, ps, states, cm);
return;
}
case OPCODE_be: // BoundedExists
{
SemanticNode body = args[0];
ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init, cm);
Context c1;
while ((c1 = Enum.nextElement()) != null) {
this.getInitStates(body, acts, c1, ps, states, cm);
}
return;
}
case OPCODE_bf: // BoundedForall
{
SemanticNode body = args[0];
ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init, cm);
Context c1 = Enum.nextElement();
if (c1 == null) {
this.getInitStates(acts, ps, states, cm);
}
else {
ActionItemList acts1 = acts;
Context c2;
while ((c2 = Enum.nextElement()) != null) {
acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED);
}
this.getInitStates(body, acts1, c1, ps, states, cm);
}
return;
}
case OPCODE_ite: // IfThenElse
{
Value guard = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!(guard instanceof BoolValue)) {
Assert.fail("In computing initial states, a non-boolean expression (" +
guard.getKindString() + ") was used as the condition " +
"of an IF.\n" + init, init, c);
}
int idx = (((BoolValue)guard).val) ? 1 : 2;
this.getInitStates(args[idx], acts, c, ps, states, cm);
return;
}
case OPCODE_case: // Case
{
SemanticNode other = null;
for (int i = 0; i < alen; i++) {
OpApplNode pair = (OpApplNode)args[i];
ExprOrOpArgNode[] pairArgs = pair.getArgs();
if (pairArgs[0] == null) {
other = pairArgs[1];
}
else {
Value bval = this.eval(pairArgs[0], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("In computing initial states, a non-boolean expression (" +
bval.getKindString() + ") was used as a guard condition" +
" of a CASE.\n" + pairArgs[1], pairArgs[1], c);
}
if (((BoolValue)bval).val) {
this.getInitStates(pairArgs[1], acts, c, ps, states, cm);
return;
}
}
}
if (other == null) {
Assert.fail("In computing initial states, TLC encountered a CASE with no" +
" conditions true.\n" + init, init, c);
}
this.getInitStates(other, acts, c, ps, states, cm);
return;
}
case OPCODE_fa: // FcnApply
{
Value fval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (fval instanceof FcnLambdaValue) {
FcnLambdaValue fcn = (FcnLambdaValue)fval;
if (fcn.fcnRcd == null) {
Context c1 = this.getFcnContext(fcn, args, c, ps, TLCState.Empty, EvalControl.Init, cm);
this.getInitStates(fcn.body, acts, c1, ps, states, cm);
return;
}
fval = fcn.fcnRcd;
}
else if (!(fval instanceof Applicable)) {
Assert.fail("In computing initial states, a non-function (" +
fval.getKindString() + ") was applied as a function.\n" + init, init, c);
}
Applicable fcn = (Applicable) fval;
Value argVal = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm);
Value bval = fcn.apply(argVal, EvalControl.Init);
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "initial states", "boolean",
init.toString() }, args[1], c);
}
if (((BoolValue)bval).val) {
this.getInitStates(acts, ps, states, cm);
}
return;
}
case OPCODE_eq:
{
SymbolNode var = this.getVar(args[0], c, false, toolId);
if (var == null || var.getName().getVarLoc() < 0) {
Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!((BoolValue)bval).val) {
return;
}
}
else {
UniqueString varName = var.getName();
IValue lval = ps.lookup(varName);
Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (lval == null) {
ps = ps.bind(varName, rval);
this.getInitStates(acts, ps, states, cm);
ps.unbind(varName);
return;
}
else {
if (!lval.equals(rval)) {
return;
}
}
}
this.getInitStates(acts, ps, states, cm);
return;
}
case OPCODE_in:
{
SymbolNode var = this.getVar(args[0], c, false, toolId);
if (var == null || var.getName().getVarLoc() < 0) {
Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!((BoolValue)bval).val) {
return;
}
}
else {
UniqueString varName = var.getName();
Value lval = (Value) ps.lookup(varName);
Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (lval == null) {
if (!(rval instanceof Enumerable)) {
Assert.fail("In computing initial states, the right side of \\IN" +
" is not enumerable.\n" + init, init, c);
}
ValueEnumeration Enum = ((Enumerable)rval).elements();
Value elem;
while ((elem = Enum.nextElement()) != null) {
ps.bind(varName, elem);
this.getInitStates(acts, ps, states, cm);
ps.unbind(varName);
}
return;
}
else {
if (!rval.member(lval)) {
return;
}
}
}
this.getInitStates(acts, ps, states, cm);
return;
}
case OPCODE_implies:
{
Value lval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!(lval instanceof BoolValue)) {
Assert.fail("In computing initial states of a predicate of form" +
" P => Q, P was " + lval.getKindString() + "\n." + init, init, c);
}
if (((BoolValue)lval).val) {
this.getInitStates(args[1], acts, c, ps, states, cm);
}
else {
this.getInitStates(acts, ps, states, cm);
}
return;
}
// The following case added by LL on 13 Nov 2009 to handle subexpression names.
case OPCODE_nop:
{
this.getInitStates(args[0], acts, c, ps, states, cm);
return;
}
default:
{
// For all the other builtin operators, simply evaluate:
Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("In computing initial states, TLC expected a boolean expression," +
"\nbut instead found " + bval + ".\n" + init, init, c);
}
if (((BoolValue)bval).val) {
this.getInitStates(acts, ps, states, cm);
}
return;
}
}
}
/**
* This method returns the set of next states when taking the action
* in the given state.
*/
@Override
public final StateVec getNextStates(Action action, TLCState state) {
return getNextStates(action, action.con, state);
}
public final StateVec getNextStates(final Action action, final Context ctx, final TLCState state) {
ActionItemList acts = ActionItemList.Empty;
TLCState s1 = TLCState.Empty.createEmpty();
StateVec nss = new StateVec(0);
this.getNextStates(action, action.pred, acts, ctx, state, s1.setPredecessor(state).setAction(action), nss, action.cm);
if (coverage) { action.cm.incInvocations(nss.size()); }
if (PROBABLISTIC && nss.size() > 1) {System.err.println("Simulator generated more than one next state");}
return nss;
}
@Override
public boolean getNextStates(final INextStateFunctor functor, final TLCState state) {
for (int i = 0; i < actions.length; i++) {
this.getNextStates(functor, state, actions[i]);
}
return false;
}
public boolean getNextStates(final INextStateFunctor functor, final TLCState state, final Action action) {
this.getNextStates(action, action.pred, ActionItemList.Empty, action.con, state,
TLCState.Empty.createEmpty().setPredecessor(state).setAction(action), functor, action.cm);
return false;
}
protected abstract TLCState getNextStates(final Action action, SemanticNode pred, ActionItemList acts, Context c,
TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm);
protected final TLCState getNextStatesImpl(final Action action, SemanticNode pred, ActionItemList acts, Context c,
TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm) {
switch (pred.getKind()) {
case OpApplKind:
{
OpApplNode pred1 = (OpApplNode)pred;
if (coverage) {cm = cm.get(pred);}
return this.getNextStatesAppl(action, pred1, acts, c, s0, s1, nss, cm);
}
case LetInKind:
{
LetInNode pred1 = (LetInNode)pred;
return this.getNextStates(action, pred1.getBody(), acts, c, s0, s1, nss, cm);
}
case SubstInKind:
{
return getNextStatesImplSubstInKind(action, (SubstInNode) pred, acts, c, s0, s1, nss, cm);
}
// Added by LL on 13 Nov 2009 to handle theorem and assumption names.
case APSubstInKind:
{
return getNextStatesImplApSubstInKind(action, (APSubstInNode) pred, acts, c, s0, s1, nss, cm);
}
// LabelKind class added by LL on 13 Jun 2007
case LabelKind:
{
LabelNode pred1 = (LabelNode)pred;
return this.getNextStates(action, pred1.getBody(), acts, c, s0, s1, nss, cm);
}
default:
{
Assert.fail("The next state relation is not a boolean expression.\n" + pred, pred, c);
}
}
return s1;
}
@ExpectInlined
private final TLCState getNextStatesImplSubstInKind(final Action action, SubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm) {
Subst[] subs = pred1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId));
}
return this.getNextStates(action, pred1.getBody(), acts, c1, s0, s1, nss, cm);
}
@ExpectInlined
private final TLCState getNextStatesImplApSubstInKind(final Action action, APSubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm) {
Subst[] subs = pred1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId));
}
return this.getNextStates(action, pred1.getBody(), acts, c1, s0, s1, nss, cm);
}
@ExpectInlined
private final TLCState getNextStates(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1,
final INextStateFunctor nss, CostModel cm) {
final TLCState copy = getNextStates0(action, acts, s0, s1, nss, cm);
if (coverage && copy != s1) {
cm.incInvocations();
}
return copy;
}
@ExpectInlined
private final TLCState getNextStates0(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1,
final INextStateFunctor nss, CostModel cm) {
if (acts.isEmpty()) {
nss.addElement(s0, action, s1);
return s1.copy();
} else if (TLCGlobals.warn && s1.allAssigned()) {
// If all variables have been assigned and warnings are turned off, Tool can
// execute the fast-path that avoids generating known successor states, but
// doesn't trigger a warning in cases like:
// VARIABLES x
// Init == x = 0
// Next == x' = 42 /\ UNCHANGED x \* UNCHANGED and changed!
// => "Warning: The variable x was changed while it is specified as UNCHANGED"
return getNextStatesAllAssigned(action, acts, s0, s1, nss, cm);
}
final int kind = acts.carKind();
SemanticNode pred = acts.carPred();
Context c = acts.carContext();
ActionItemList acts1 = acts.cdr();
cm = acts.cm;
if (kind > 0) {
return this.getNextStates(action, pred, acts1, c, s0, s1, nss, cm);
}
else if (kind == -1) {
return this.getNextStates(action, pred, acts1, c, s0, s1, nss, cm);
}
else if (kind == -2) {
return this.processUnchanged(action, pred, acts1, c, s0, s1, nss, cm);
}
else {
IValue v1 = this.eval(pred, c, s0, cm);
IValue v2 = this.eval(pred, c, s1, cm);
if (!v1.equals(v2)) {
if (coverage) {
return this.getNextStates(action, acts1, s0, s1, nss, cm);
} else {
return this.getNextStates0(action, acts1, s0, s1, nss, cm);
}
}
}
return s1;
}
private final TLCState getNextStatesAllAssigned(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1,
final INextStateFunctor nss, final CostModel cm) {
int kind = acts.carKind();
SemanticNode pred = acts.carPred();
Context c = acts.carContext();
CostModel cm2 = acts.cm;
while (!acts.isEmpty()) {
if (kind > 0 || kind == -1) {
final Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm2);
if (!(bval instanceof BoolValue)) {
// TODO Choose more fitting error message.
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING,
new String[] { "next states", "boolean", bval.toString(), acts.pred.toString() }, pred, c);
}
if (!((BoolValue) bval).val) {
return s1;
}
} else if (kind == -2) {
// Identical to default handling below (line 876). Ignored during this optimization.
return this.processUnchanged(action, pred, acts.cdr(), c, s0, s1, nss, cm2);
} else {
final IValue v1 = this.eval(pred, c, s0, cm2);
final IValue v2 = this.eval(pred, c, s1, cm2);
if (v1.equals(v2)) {
return s1;
}
}
// Move on to the next action in the ActionItemList.
acts = acts.cdr();
pred = acts.carPred();
c = acts.carContext();
kind = acts.carKind();
cm2 = acts.cm;
}
nss.addElement(s0, action, s1);
return s1.copy();
}
/* getNextStatesAppl */
@ExpectInlined
protected abstract TLCState getNextStatesAppl(final Action action, OpApplNode pred, ActionItemList acts, Context c,
TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm);
protected final TLCState getNextStatesApplImpl(final Action action, final OpApplNode pred, final ActionItemList acts, final Context c,
final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm) {
final ExprOrOpArgNode[] args = pred.getArgs();
final int alen = args.length;
final SymbolNode opNode = pred.getOperator();
int opcode = BuiltInOPs.getOpCode(opNode.getName());
if (opcode == 0) {
// This is a user-defined operator with one exception: it may
// be substed by a builtin operator. This special case occurs
// when the lookup returns an OpDef with opcode
Object val = this.lookup(opNode, c, s0, false);
if (val instanceof OpDefNode) {
final OpDefNode opDef = (OpDefNode) val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
if (opcode == 0) {
return this.getNextStates(action, opDef.getBody(), acts, this.getOpContext(opDef, args, c, true, cm, toolId), s0, s1, nss, cm);
}
}
// Added by LL 13 Nov 2009 to fix Yuan's fix
if (val instanceof ThmOrAssumpDefNode) {
final ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val;
return this.getNextStates(action, opDef.getBody(), acts, this.getOpContext(opDef, args, c, true), s0, s1, nss, cm);
}
if (val instanceof LazyValue) {
final LazyValue lv = (LazyValue)val;
if (lv.getValue() == null || lv.isUncachable()) {
return this.getNextStates(action, lv.expr, acts, lv.con, s0, s1, nss, lv.cm);
}
val = lv.getValue();
}
//TODO If all eval/apply in getNextStatesApplEvalAppl would be side-effect free (ie. not mutate args, c, s0,...),
// this call could be moved into the if(opcode==0) branch below. However, opcode!=0 will only be the case if
// OpDefNode above has been substed with a built-in operator. In other words, a user defines an operator Op1,
// and re-defines Op1 with a TLA+ built-in one in a TLC model (not assumed to be common). => No point in trying
// to move this call into if(opcode==0) because this will be the case most of the time anyway.
final Object bval = getNextStatesApplEvalAppl(alen, args, c, s0, s1, cm, val);
// opcode == 0 is a user-defined operator.
if (opcode == 0)
{
return getNextStatesApplUsrDefOp(action, pred, acts, s0, s1, nss, cm, bval);
}
}
return getNextStatesApplSwitch(action, pred, acts, c, s0, s1, nss, cm, args, alen, opcode);
}
private final Object getNextStatesApplEvalAppl(final int alen, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final CostModel cm, final Object val) {
if (alen == 0) {
if (val instanceof MethodValue) {
return ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear);
} else if (val instanceof EvaluatingValue) {
return ((EvaluatingValue)val).eval(this, args, c, s0, s1, EvalControl.Clear, cm);
}
}
else {
if (val instanceof OpValue) { // EvaluatingValue sub-class of OpValue!
return ((OpValue) val).eval(this, args, c, s0, s1, EvalControl.Clear, cm);
}
}
return val;
}
private final TLCState getNextStatesApplUsrDefOp(final Action action, final OpApplNode pred, final ActionItemList acts, final TLCState s0,
final TLCState s1, final INextStateFunctor nss, final CostModel cm, final Object bval) {
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean",
bval.toString(), pred.toString() }, pred);
}
if (((BoolValue) bval).val)
{
if (coverage) {
return this.getNextStates(action, acts, s0, s1, nss, cm);
} else {
return this.getNextStates0(action, acts, s0, s1, nss, cm);
}
}
return s1;
}
private final TLCState getNextStatesApplSwitch(final Action action, final OpApplNode pred, final ActionItemList acts, final Context c, final TLCState s0,
final TLCState s1, final INextStateFunctor nss, final CostModel cm, final ExprOrOpArgNode[] args, final int alen, final int opcode) {
TLCState resState = s1;
switch (opcode) {
case OPCODE_cl: // ConjList
case OPCODE_land:
{
ActionItemList acts1 = acts;
for (int i = alen - 1; i > 0; i
acts1 = (ActionItemList) acts1.cons(args[i], c, cm, i);
}
return this.getNextStates(action, args[0], acts1, c, s0, s1, nss, cm);
}
case OPCODE_dl: // DisjList
case OPCODE_lor:
{
if (PROBABLISTIC) {
// probabilistic (return after a state has been generated, ordered is randomized)
final RandomGenerator rng = TLCGlobals.simulator.getRNG();
int index = (int) Math.floor(rng.nextDouble() * alen);
final int p = rng.nextPrime();
for (int i = 0; i < alen; i++) {
resState = this.getNextStates(action, args[index], acts, c, s0, resState, nss, cm);
if (nss.hasStates()) {
return resState;
}
index = (index + p) % alen;
}
} else {
for (int i = 0; i < alen; i++) {
resState = this.getNextStates(action, args[i], acts, c, s0, resState, nss, cm);
}
}
return resState;
}
case OPCODE_be: // BoundedExists
{
SemanticNode body = args[0];
if (PROBABLISTIC) {
// probabilistic (return after a state has been generated, ordered is randomized)
final ContextEnumerator Enum = this.contexts(Ordering.RANDOMIZED, pred, c, s0, s1, EvalControl.Clear, cm);
Context c1;
while ((c1 = Enum.nextElement()) != null) {
resState = this.getNextStates(action, body, acts, c1, s0, resState, nss, cm);
if (nss.hasStates()) {
return resState;
}
}
} else {
// non-deterministically generate successor states (potentially many)
ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear, cm);
Context c1;
while ((c1 = Enum.nextElement()) != null) {
resState = this.getNextStates(action, body, acts, c1, s0, resState, nss, cm);
}
}
return resState;
}
case OPCODE_bf: // BoundedForall
{
SemanticNode body = args[0];
ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear, cm);
Context c1 = Enum.nextElement();
if (c1 == null) {
resState = this.getNextStates(action, acts, s0, s1, nss, cm);
}
else {
ActionItemList acts1 = acts;
Context c2;
while ((c2 = Enum.nextElement()) != null) {
acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED);
}
resState = this.getNextStates(action, body, acts1, c1, s0, s1, nss, cm);
}
return resState;
}
case OPCODE_fa: // FcnApply
{
Value fval = this.eval(args[0], c, s0, s1, EvalControl.KeepLazy, cm);
if (fval instanceof FcnLambdaValue) {
FcnLambdaValue fcn = (FcnLambdaValue)fval;
if (fcn.fcnRcd == null) {
Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Clear, cm);
return this.getNextStates(action, fcn.body, acts, c1, s0, s1, nss, fcn.cm);
}
fval = fcn.fcnRcd;
}
if (!(fval instanceof Applicable)) {
Assert.fail("In computing next states, a non-function (" +
fval.getKindString() + ") was applied as a function.\n" + pred, pred, c);
}
Applicable fcn = (Applicable)fval;
Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm);
Value bval = fcn.apply(argVal, EvalControl.Clear);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "next states", "boolean",
pred.toString() }, args[1], c);
}
if (((BoolValue)bval).val) {
return this.getNextStates(action, acts, s0, s1, nss, cm);
}
return resState;
}
case OPCODE_aa: // AngleAct <A>_e
{
ActionItemList acts1 = (ActionItemList) acts.cons(args[1], c, cm, IActionItemList.CHANGED);
return this.getNextStates(action, args[0], acts1, c, s0, s1, nss, cm);
}
case OPCODE_sa:
{
/* The following two lines of code did not work, and were changed by
* YuanYu to mimic the way \/ works. Change made
* 11 Mar 2009, with LL sitting next to him.
*/
// this.getNextStates(action, args[0], acts, c, s0, s1, nss);
// return this.processUnchanged(args[1], acts, c, s0, s1, nss);
resState = this.getNextStates(action, args[0], acts, c, s0, resState, nss, cm);
return this.processUnchanged(action, args[1], acts, c, s0, resState, nss, cm);
}
case OPCODE_ite: // IfThenElse
{
Value guard = this.eval(args[0], c, s0, s1, EvalControl.Clear, cm);
if (!(guard instanceof BoolValue)) {
Assert.fail("In computing next states, a non-boolean expression (" +
guard.getKindString() + ") was used as the condition of" +
" an IF." + pred, pred, c);
}
if (((BoolValue)guard).val) {
return this.getNextStates(action, args[1], acts, c, s0, s1, nss, cm);
}
else {
return this.getNextStates(action, args[2], acts, c, s0, s1, nss, cm);
}
}
case OPCODE_case: // Case
{
SemanticNode other = null;
if (PROBABLISTIC) {
// See Bounded exists above!
throw new UnsupportedOperationException(
"Probabilistic evaluation of next-state relation not implemented for CASE yet.");
}
for (int i = 0; i < alen; i++) {
OpApplNode pair = (OpApplNode)args[i];
ExprOrOpArgNode[] pairArgs = pair.getArgs();
if (pairArgs[0] == null) {
other = pairArgs[1];
}
else {
Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Clear, coverage ? cm.get(args[i]) : cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("In computing next states, a non-boolean expression (" +
bval.getKindString() + ") was used as a guard condition" +
" of a CASE.\n" + pairArgs[1], pairArgs[1], c);
}
if (((BoolValue)bval).val) {
return this.getNextStates(action, pairArgs[1], acts, c, s0, s1, nss, coverage ? cm.get(args[i]) : cm);
}
}
}
if (other == null) {
Assert.fail("In computing next states, TLC encountered a CASE with no" +
" conditions true.\n" + pred, pred, c);
}
return this.getNextStates(action, other, acts, c, s0, s1, nss, coverage ? cm.get(args[alen - 1]) : cm);
}
case OPCODE_eq:
{
SymbolNode var = this.getPrimedVar(args[0], c, false);
// Assert.check(var.getName().getVarLoc() >= 0);
if (var == null) {
Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm);
if (!((BoolValue)bval).val) {
return resState;
}
}
else {
UniqueString varName = var.getName();
IValue lval = s1.lookup(varName);
Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm);
if (lval == null) {
resState.bind(varName, rval);
resState = this.getNextStates(action, acts, s0, resState, nss, cm);
resState.unbind(varName);
return resState;
}
else if (!lval.equals(rval)) {
return resState;
}
}
return this.getNextStates(action, acts, s0, s1, nss, cm);
}
case OPCODE_in:
{
SymbolNode var = this.getPrimedVar(args[0], c, false);
// Assert.check(var.getName().getVarLoc() >= 0);
if (var == null) {
Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm);
if (!((BoolValue)bval).val) {
return resState;
}
}
else {
UniqueString varName = var.getName();
Value lval = (Value) s1.lookup(varName);
Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm);
if (lval == null) {
if (!(rval instanceof Enumerable)) {
Assert.fail("In computing next states, the right side of \\IN" +
" is not enumerable.\n" + pred, pred, c);
}
if (PROBABLISTIC) {
final ValueEnumeration Enum = ((Enumerable)rval).elements(Ordering.RANDOMIZED);
Value elem;
while ((elem = Enum.nextElement()) != null) {
resState.bind(varName, elem);
resState = this.getNextStates(action, acts, s0, resState, nss, cm);
resState.unbind(varName);
if (nss.hasStates()) {
return resState;
}
}
}
ValueEnumeration Enum = ((Enumerable)rval).elements();
Value elem;
while ((elem = Enum.nextElement()) != null) {
resState.bind(varName, elem);
resState = this.getNextStates(action, acts, s0, resState, nss, cm);
resState.unbind(varName);
}
return resState;
}
else if (!rval.member(lval)) {
return resState;
}
}
return this.getNextStates(action, acts, s0, s1, nss, cm);
}
case OPCODE_implies:
{
Value bval = this.eval(args[0], c, s0, s1, EvalControl.Clear, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("In computing next states of a predicate of the form" +
" P => Q, P was\n" + bval.getKindString() + ".\n" + pred, pred, c);
}
if (((BoolValue)bval).val) {
return this.getNextStates(action, args[1], acts, c, s0, s1, nss, cm);
}
else {
return this.getNextStates(action, acts, s0, s1, nss, cm);
}
}
case OPCODE_unchanged:
{
return this.processUnchanged(action, args[0], acts, c, s0, s1, nss, cm);
}
case OPCODE_cdot:
{
Assert.fail("The current version of TLC does not support action composition.", pred, c);
return s1;
}
// The following case added by LL on 13 Nov 2009 to handle subexpression names.
case OPCODE_nop:
{
return this.getNextStates(action, args[0], acts, c, s0, s1, nss, cm);
}
default:
{
// We handle all the other builtin operators here.
Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean",
bval.toString(), pred.toString() }, pred, c);
}
if (((BoolValue)bval).val) {
resState = this.getNextStates(action, acts, s0, s1, nss, cm);
}
return resState;
}
}
}
/* processUnchanged */
@ExpectInlined
protected abstract TLCState processUnchanged(final Action action, SemanticNode expr, ActionItemList acts, Context c,
TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm);
protected final TLCState processUnchangedImpl(final Action action, SemanticNode expr, ActionItemList acts, Context c,
TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm) {
if (coverage){cm = cm.get(expr);}
SymbolNode var = this.getVar(expr, c, false, toolId);
TLCState resState = s1;
if (var != null) {
return processUnchangedImplVar(action, expr, acts, s0, s1, nss, var, cm);
}
if (expr instanceof OpApplNode) {
OpApplNode expr1 = (OpApplNode)expr;
ExprOrOpArgNode[] args = expr1.getArgs();
int alen = args.length;
SymbolNode opNode = expr1.getOperator();
UniqueString opName = opNode.getName();
int opcode = BuiltInOPs.getOpCode(opName);
if (opcode == OPCODE_tup) {
return processUnchangedImplTuple(action, acts, c, s0, s1, nss, args, alen, cm, coverage ? cm.get(expr1) : cm);
}
if (opcode == 0 && alen == 0) {
// a 0-arity operator:
return processUnchangedImpl0Arity(action, expr, acts, c, s0, s1, nss, cm, opNode, opName);
}
}
return verifyUnchanged(action, expr, acts, c, s0, s1, nss, cm);
}
@ExpectInlined
private final TLCState processUnchangedImpl0Arity(final Action action, final SemanticNode expr, final ActionItemList acts,
final Context c, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm,
final SymbolNode opNode, final UniqueString opName) {
final Object val = this.lookup(opNode, c, false);
if (val instanceof OpDefNode) {
return this.processUnchanged(action, ((OpDefNode)val).getBody(), acts, c, s0, s1, nss, cm);
}
else if (val instanceof LazyValue) {
final LazyValue lv = (LazyValue)val;
return this.processUnchanged(action, lv.expr, acts, lv.con, s0, s1, nss, cm);
}
return verifyUnchanged(action, expr, acts, c, s0, s1, nss, cm);
}
/**
* Check that <code>expr</code> is unchanged without attempting to synthesize values for variables in the
* successor state.
*/
private TLCState verifyUnchanged(final Action action, final SemanticNode expr, final ActionItemList acts,
final Context c, final TLCState s0, final TLCState s1, final INextStateFunctor nss,
final CostModel cm) {
TLCState resState = s1;
IValue v0 = this.eval(expr, c, s0, cm);
IValue v1 = this.eval(expr, c, s1, TLCState.Null, EvalControl.Clear, cm);
if (v0.equals(v1)) {
resState = this.getNextStates(action, acts, s0, s1, nss, cm);
}
return resState;
}
@Override
public IValue eval(SemanticNode expr, Context c, TLCState s0) {
return this.eval(expr, c, s0, TLCState.Empty, EvalControl.Clear, CostModel.DO_NOT_RECORD);
}
@Override
public IValue eval(SemanticNode expr, Context c) {
return this.eval(expr, c, TLCState.Empty);
}
@Override
public IValue eval(SemanticNode expr) {
return this.eval(expr, Context.Empty);
}
@ExpectInlined
private final TLCState processUnchangedImplTuple(final Action action, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss,
ExprOrOpArgNode[] args, int alen, CostModel cm, CostModel cmNested) {
// a tuple:
if (alen != 0) {
ActionItemList acts1 = acts;
for (int i = alen-1; i > 0; i
acts1 = (ActionItemList) acts1.cons(args[i], c, cmNested, IActionItemList.UNCHANGED);
}
return this.processUnchanged(action, args[0], acts1, c, s0, s1, nss, cmNested);
}
return this.getNextStates(action, acts, s0, s1, nss, cm);
}
@ExpectInlined
private final TLCState processUnchangedImplVar(final Action action, SemanticNode expr, ActionItemList acts, TLCState s0, TLCState s1, INextStateFunctor nss,
SymbolNode var, final CostModel cm) {
TLCState resState = s1;
// expr is a state variable:
final UniqueString varName = var.getName();
final IValue val0 = s0.lookup(varName);
final IValue val1 = s1.lookup(varName);
if (val1 == null) {
resState.bind(varName, val0);
if (coverage) {
resState = this.getNextStates(action, acts, s0, resState, nss, cm);
} else {
resState = this.getNextStates0(action, acts, s0, resState, nss, cm);
}
resState.unbind(varName);
}
else if (val0.equals(val1)) {
if (coverage) {
resState = this.getNextStates(action, acts, s0, s1, nss, cm);
} else {
resState = this.getNextStates0(action, acts, s0, s1, nss, cm);
}
}
else {
MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString(), expr.toString()});
}
return resState;
}
/* eval */
public TLCState evalAlias(TLCState current, TLCState successor) {
if ("".equals(this.config.getAlias())) {
return current;
}
// see getState(..)
IdThread.setCurrentState(current);
// See asserts in tlc2.debug.TLCActionStackFrame.TLCActionStackFrame(TLCStackFrame, SemanticNode, Context, Tool, TLCState, Action, TLCState, RuntimeException)
if (successor.getLevel() != current.getLevel()) {
// Calling setPrecessor when the levels are equal would increase the level of
// successor.
successor.setPredecessor(current);
}
try {
final TLCState alias = eval(getAliasSpec(), Context.Empty, current, successor, EvalControl.Clear).toState();
if (alias != null) {
return alias;
}
} catch (EvalException | TLCRuntimeException e) {
// Fall back to original state if eval fails.
return current;
}
return current;
}
@Override
public TLCStateInfo evalAlias(TLCStateInfo current, TLCState successor) {
if (!hasAlias()) {
return current;
}
return evalAlias(current, successor, Context.Empty);
}
@Override
public TLCStateInfo evalAlias(TLCStateInfo current, TLCState successor, Supplier<List<TLCStateInfo>> prefix) {
if (!hasAlias()) {
return current;
}
final ExternalModuleTable emt = getSpecProcessor().getSpecObj().getExternalModuleTable();
final tla2sany.semantic.Context tlcExt = emt.getContext(UniqueString.of("TLCExt"));
if (tlcExt == null) {
// tlcExt is null if the TLCExt module is not extended or instantiated. Thus,
// Trace cannot appear in the spec.
return evalAlias(current, successor, Context.Empty);
}
final SymbolNode tlcExtTrace = tlcExt.getSymbol(UniqueString.of("Trace"));
return evalAlias(current, successor,
Context.Empty.cons(tlcExtTrace, new LazySupplierValue(tlcExtTrace, (Supplier<Value>) () -> {
return new TupleValue(
prefix.get().stream().map(si -> new RecordValue(si.state)).toArray(Value[]::new));
})));
}
private TLCStateInfo evalAlias(TLCStateInfo current, TLCState successor, Context ctxt) {
// see getState(..)
IdThread.setCurrentState(current.state);
// See asserts in
// tlc2.debug.TLCActionStackFrame.TLCActionStackFrame(TLCStackFrame,
// SemanticNode, Context, Tool, TLCState, Action, TLCState, RuntimeException)
if (successor.getLevel() != current.state.getLevel()) {
// Calling setPrecessor when the levels are equal would increase the level of
// successor.
successor.setPredecessor(current);
}
try {
final TLCState alias = eval(getAliasSpec(), ctxt, current.state, successor, EvalControl.Clear).toState();
if (alias != null) {
return new AliasTLCStateInfo(alias, current);
}
} catch (EvalException | TLCRuntimeException e) {
// Fall back to original state if eval fails.
return current;
// TODO We have to somehow communicate this exception back to the user.
// Unfortunately, the alias cannot be validated by SpecProcess (unless pure
// constant expression who are too simple to be used in trace expressions).
// Throwing the exception would be possible, but pretty annoying if TLC fails
// to print an error trace because of a bogus alias after hours of model
// checking (this is the very reason why the code falls back to return the
// original/current state). Printing the exception to stdout/stderr here
// would mess with the Toolbox's parsing that reads stdout back in. It would
// also look bad because we would print the error on every evaluation of the
// alias and it's conceivable that -in most cases- evaluation would fail for
// all evaluations. This suggests that we have to defer reporting of evaluation
// and runtime exception until after the error-trace has been printed. If
// evaluation only failed for some invocations of evalAlias, the user will
// be able to figure out the ones that failed by looking at the trace. This
// state should not be kept in Tool, because it doesn't know how to group
// sequences of evalAlias invocations.
// We could avoid keeping state entirely, if the exception was attached as an
// "auxiliary" variable to the TLCStateInfo and printed as part of the error
// trace. The error trace would look strange, but it appears to be the best
// compromise, especially if only some of the evaluations fail.
}
return current;
}
/* Special version of eval for state expressions. */
@Override
public IValue eval(SemanticNode expr, Context c, TLCState s0, CostModel cm) {
return this.eval(expr, c, s0, TLCState.Empty, EvalControl.Clear, cm);
}
@Override
public final IValue eval(SemanticNode expr, Context c, TLCState s0,
TLCState s1, final int control) {
return eval(expr, c, s0, s1, control, CostModel.DO_NOT_RECORD);
}
public Value evalPure(final OpDefNode opDef, final ExprOrOpArgNode[] args, final Context c, final TLCState s0,
final TLCState s1, final int control, final CostModel cm) {
final Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId);
return this.eval(opDef.getBody(), c1, s0, s1, control, cm);
}
/*
* This method evaluates the expression expr in the given context,
* current state, and partial next state.
*/
public abstract Value eval(SemanticNode expr, Context c, TLCState s0,
TLCState s1, final int control, final CostModel cm);
@ExpectInlined
protected Value evalImpl(final SemanticNode expr, final Context c, final TLCState s0,
final TLCState s1, final int control, CostModel cm) {
switch (expr.getKind()) {
case LabelKind:
{
LabelNode expr1 = (LabelNode) expr;
return this.eval(expr1.getBody(), c, s0, s1, control, cm);
}
case OpApplKind:
{
OpApplNode expr1 = (OpApplNode)expr;
if (coverage) {cm = cm.get(expr);}
return this.evalAppl(expr1, c, s0, s1, control, cm);
}
case LetInKind:
{
return evalImplLetInKind((LetInNode) expr, c, s0, s1, control, cm);
}
case SubstInKind:
{
return evalImplSubstInKind((SubstInNode) expr, c, s0, s1, control, cm);
}
// Added by LL on 13 Nov 2009 to handle theorem and assumption names.
case APSubstInKind:
{
return evalImplApSubstInKind((APSubstInNode) expr, c, s0, s1, control, cm);
}
case NumeralKind:
case DecimalKind:
case StringKind:
{
return (Value) WorkerValue.mux(expr.getToolObject(toolId));
}
case AtNodeKind:
{
return (Value)c.lookup(EXCEPT_AT);
}
case OpArgKind:
{
return evalImplOpArgKind((OpArgNode) expr, c, s0, s1, cm);
}
default:
{
Assert.fail("Attempted to evaluate an expression that cannot be evaluated.\n" +
expr, expr, c);
return null; // make compiler happy
}
}
}
@ExpectInlined
private final Value evalImplLetInKind(LetInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) {
OpDefNode[] letDefs = expr1.getLets();
int letLen = letDefs.length;
Context c1 = c;
for (int i = 0; i < letLen; i++) {
OpDefNode opDef = letDefs[i];
if (opDef.getArity() == 0) {
Value rhs = new LazyValue(opDef.getBody(), c1, cm);
c1 = c1.cons(opDef, rhs);
}
}
return this.eval(expr1.getBody(), c1, s0, s1, control, cm);
}
@ExpectInlined
private final Value evalImplSubstInKind(SubstInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) {
Subst[] subs = expr1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true, coverage ? sub.getCM() : cm, toolId));
}
return this.eval(expr1.getBody(), c1, s0, s1, control, cm);
}
@ExpectInlined
private final Value evalImplApSubstInKind(APSubstInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) {
Subst[] subs = expr1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true, cm, toolId));
}
return this.eval(expr1.getBody(), c1, s0, s1, control, cm);
}
@ExpectInlined
private final Value evalImplOpArgKind(OpArgNode expr1, Context c, TLCState s0, TLCState s1, final CostModel cm) {
SymbolNode opNode = expr1.getOp();
Object val = this.lookup(opNode, c, false);
if (val instanceof OpDefNode) {
return setSource(expr1, new OpLambdaValue((OpDefNode)val, this, c, s0, s1, cm));
}
return (Value)val;
}
/* evalAppl */
@ExpectInlined
protected abstract Value evalAppl(final OpApplNode expr, Context c, TLCState s0,
TLCState s1, final int control, final CostModel cm);
protected final Value evalApplImpl(final OpApplNode expr, Context c, TLCState s0,
TLCState s1, final int control, CostModel cm) {
if (coverage){
cm = cm.getAndIncrement(expr);
}
ExprOrOpArgNode[] args = expr.getArgs();
SymbolNode opNode = expr.getOperator();
int opcode = BuiltInOPs.getOpCode(opNode.getName());
if (opcode == 0) {
// This is a user-defined operator with one exception: it may
// be substed by a builtin operator. This special case occurs
// when the lookup returns an OpDef with opcode
Object val = this.lookup(opNode, c, s0, EvalControl.isPrimed(control));
// if (val instanceof Supplier) {
// val = ((Supplier) val).get();
// First, unlazy if it is a lazy value. We cannot use the cached
// value when s1 == null or isEnabled(control).
if (val instanceof LazyValue) {
final LazyValue lv = (LazyValue) val;
if (s1 == null) {
val = this.eval(lv.expr, lv.con, s0, TLCState.Null, control, lv.getCostModel());
} else if (lv.isUncachable() || EvalControl.isEnabled(control)) {
// Never use cached LazyValues in an ENABLED expression. This is why all
// this.enabled* methods pass EvalControl.Enabled (the only exception being the
// call on line line 2799 which passes EvalControl.Primed). This is why we can
// be sure that ENALBED expressions are not affected by the caching bug tracked
// in Github issue 113 (see below).
val = this.eval(lv.expr, lv.con, s0, s1, control, lv.getCostModel());
} else {
val = lv.getValue();
if (val == null) {
final Value res = this.eval(lv.expr, lv.con, s0, s1, control, lv.getCostModel());
// This check has been suggested by Yuan Yu on 01/15/2018:
// If init-states are being generated, level has to be <= ConstantLevel for
// caching/LazyValue to be allowed. If next-states are being generated, level
// has to be <= VariableLevel. The level indicates if the expression to be
// evaluated contains only constants, constants & variables, constants &
// variables and primed variables (thus action) or is a temporal formula.
// This restriction is in place to fix Github issue 113
// TLC can generate invalid sets of init or next-states caused by broken
// LazyValue evaluation. The related tests are AssignmentInit* and
// AssignmentNext*. Without this fix TLC essentially reuses a stale lv.val when
// it needs to re-evaluate res because the actual operands to eval changed.
// Below is Leslie's formal description of the bug:
// The possible initial values of some variable var are specified by a subformula
// F(..., var, ...)
// in the initial predicate, for some operator F such that expanding the
// definition of F results in a formula containing more than one occurrence of
// var , not all occurring in separate disjuncts of that formula.
// The possible next values of some variable var are specified by a subformula
// F(..., var', ...)
// in the next-state relation, for some operator F such that expanding the
// definition of F results in a formula containing more than one occurrence of
// var' , not all occurring in separate disjuncts of that formula.
// An example of the first case is an initial predicate Init defined as follows:
// VARIABLES x, ...
// F(var) == \/ var \in 0..99 /\ var % 2 = 0
// \/ var = -1
// Init == /\ F(x)
// The error would not appear if F were defined by:
// F(var) == \/ var \in {i \in 0..99 : i % 2 = 0}
// \/ var = -1
// or if the definition of F(x) were expanded in Init :
// Init == /\ \/ x \in 0..99 /\ x % 2 = 0
// \/ x = -1
// A similar example holds for case 2 with the same operator F and the
// next-state formula
// Next == /\ F(x')
// The workaround is to rewrite the initial predicate or next-state relation so
// it is not in the form that can cause the bug. The simplest way to do that is
// to expand (in-line) the definition of F in the definition of the initial
// predicate or next-state relation.
// Note that EvalControl.Init is only set in the scope of this.getInitStates*,
// but not in the scope of methods such as this.isInModel, this.isGoodState...
// which are invoked by DFIDChecker and ModelChecker#doInit and doNext. These
// invocation however don't pose a problem with regards to issue 113 because
// they don't generate the set of initial or next states but get passed fully
// generated/final states.
// !EvalControl.isInit(control) means Tool is either processing the spec in
// this.process* as part of initialization or that next-states are being
// generated. The latter case has to restrict usage of cached LazyValue as
// discussed above.
final int level = ((LevelNode) lv.expr).getLevel(); // cast to LevelNode is safe because LV only subclass of SN.
if ((EvalControl.isInit(control) && level <= LevelConstants.ConstantLevel)
|| (!EvalControl.isInit(control) && level <= LevelConstants.VariableLevel)) {
// The performance benefits of caching values is generally debatable. The time
// it takes TLC to check a reasonable sized model of the PaxosCommit [1] spec is
// ~2h with, with limited caching due to the fix for issue 113 or without
// caching. There is no measurable performance difference even though the change
// for issue 113 reduces the cache hits from ~13 billion to ~4 billion. This was
// measured with an instrumented version of TLC.
// [1] general/performance/PaxosCommit/
lv.setValue(res);
}
val = res;
}
}
}
Value res = null;
if (val instanceof OpDefNode) {
OpDefNode opDef = (OpDefNode)val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
if (opcode == 0) {
Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId);
res = this.eval(opDef.getBody(), c1, s0, s1, control, cm);
}
}
else if (val instanceof Value) {
res = (Value)val;
int alen = args.length;
if (alen == 0) {
if (val instanceof MethodValue) {
res = ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear);
} else if (val instanceof EvaluatingValue) {
// Allow EvaluatingValue overwrites to have zero arity.
res = ((EvaluatingValue) val).eval(this, args, c, s0, s1, control, cm);
}
}
else {
if (val instanceof OpValue) {
res = ((OpValue) val).eval(this, args, c, s0, s1, control, cm);
}
}
}
else if (val instanceof ThmOrAssumpDefNode) {
// Assert.fail("Trying to evaluate the theorem or assumption name `"
// + opNode.getName() + "'. \nUse `" + opNode.getName()
// + "!:' instead.\n" +expr);
ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val ;
Context c1 = this.getOpContext(opDef, args, c, true);
return this.eval(opDef.getBody(), c1, s0, s1, control, cm);
}
else {
if (!EvalControl.isEnabled(control) && EvalControl.isPrimed(control) && opNode instanceof OpDeclNode) {
// We end up here if fairness is declared on a sub-action that doesn't define
// the value of all variables given in the subscript vars (state pred) part of
// the (weak or strong) fairness operator:
// VARIABLES a,b \* opNode is b up here.
// vars == <<a,b>>
// A == a' = 42
// Next == A /\ b = b' \* Do something with b.
// Spec == ... /\ WF_vars(A)
// Variants:
// /\ WF_b(TRUE)
// /\ WF_vars(TRUE)
// This variant is debatable. It triggers the "generic" exception below:
// /\ WF_vars(a' = b')
// For larger specs, this is obviously difficult to debug. Especially,
// because opNode usually points to b on the vars == <<...>> line.
// The following issues confirm that even seasoned users run into this:
Assert.fail(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_LIVE,
new String[] { opNode.getName().toString(), expr.toString() }, expr, c);
// Assert#fail throws exception, thus, no need for an else.
}
// EV#Enabled /\ EV#Prime /\ OpDeclNode is the case when A is an action (a boolean
// valued transition function (see page 312 in Specifying Systems) appearing in an
// invariant that TLC cannot evaluate. E.g.:
// Spec == Init /\ [][a' = a + 1]_a
// Inv == ENABLED a' > a
// EV#Clear /\ OpDeclNode is the case when A is an action that TLC
// cannot evaluate. E.g.:
// Spec == Init /\ [][a' > a]_a
Assert.fail(EC.TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR,
new String[] { opNode.getName().toString(), expr.toString() }, expr, c);
}
if (opcode == 0) {
return res;
}
}
switch (opcode) {
case OPCODE_bc: // BoundedChoose
{
SemanticNode pred = args[0];
SemanticNode inExpr = expr.getBdedQuantBounds()[0];
Value inVal = this.eval(inExpr, c, s0, s1, control, cm);
if (!(inVal instanceof Enumerable)) {
Assert.fail("Attempted to compute the value of an expression of\n" +
"form CHOOSE x \\in S: P, but S was not enumerable.\n" + expr, expr, c);
}
// To fix Bugzilla Bug 279 : TLC bug caused by TLC's not preserving the semantics of CHOOSE
// (@see tlc2.tool.BugzillaBug279Test),
// the statement
// inVal.normalize();
// was replaced by the following by LL on 7 Mar 2012. This fix has not yet received
// the blessing of Yuan Yu, so it should be considered to be provisional.
// Value convertedVal = inVal.ToSetEnum();
// if (convertedVal != null) {
// inVal = convertedVal;
// } else {
// inVal.normalize();
// end of fix.
// MAK 09/22/2018:
// The old fix above has the undesired side effect of enumerating inVal. In
// other words, e.g. a SUBSET 1..8 would be enumerated and normalized into a
// SetEnumValue. This is expensive and especially overkill, if the CHOOSE
// predicate holds for most if not all elements of inVal. In this case, we
// don't want to fully enumerate inVal but instead return the first element
// obtained from Enumerable#elements for which the predicate holds. Thus,
// Enumerable#elements(Ordering) has been added by which we make the requirement
// for elements to be normalized explicit. Implementor of Enumerable, such as
// SubsetValue are then free to implement elements that returns elements in
// normalized order without converting SubsetValue into SetEnumValue first.
inVal.normalize();
ValueEnumeration enumSet = ((Enumerable)inVal).elements(Enumerable.Ordering.NORMALIZED);
FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0];
boolean isTuple = expr.isBdedQuantATuple()[0];
if (isTuple) {
// Identifier tuple case:
int cnt = bvars.length;
Value val;
while ((val = enumSet.nextElement()) != null) {
TupleValue tv = (TupleValue) val.toTuple();
if (tv == null || tv.size() != cnt) {
Assert.fail("Attempted to compute the value of an expression of form\n" +
"CHOOSE <<x1, ... , xN>> \\in S: P, but S was not a set\n" +
"of N-tuples.\n" + expr, expr, c);
}
Context c1 = c;
for (int i = 0; i < cnt; i++) {
c1 = c1.cons(bvars[i], tv.elems[i]);
}
Value bval = this.eval(pred, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, pred, c1);
}
if (((BoolValue)bval).val) {
return (Value) val;
}
}
}
else {
// Simple identifier case:
SymbolNode name = bvars[0];
Value val;
while ((val = enumSet.nextElement()) != null) {
Context c1 = c.cons(name, val);
Value bval = this.eval(pred, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, pred, c1);
}
if (((BoolValue)bval).val) {
return (Value) val;
}
}
}
Assert.fail("Attempted to compute the value of an expression of form\n" +
"CHOOSE x \\in S: P, but no element of S satisfied P.\n" + expr, expr, c);
return null; // make compiler happy
}
case OPCODE_be: // BoundedExists
{
ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm);
SemanticNode body = args[0];
Context c1;
while ((c1 = Enum.nextElement()) != null) {
Value bval = this.eval(body, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, body, c1);
}
if (((BoolValue)bval).val) {
return BoolValue.ValTrue;
}
}
return BoolValue.ValFalse;
}
case OPCODE_bf: // BoundedForall
{
ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm);
SemanticNode body = args[0];
Context c1;
while ((c1 = Enum.nextElement()) != null) {
Value bval = this.eval(body, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, body, c1);
}
if (!((BoolValue)bval).val) {
return BoolValue.ValFalse;
}
}
return BoolValue.ValTrue;
}
case OPCODE_case: // Case
{
int alen = args.length;
SemanticNode other = null;
for (int i = 0; i < alen; i++) {
OpApplNode pairNode = (OpApplNode)args[i];
ExprOrOpArgNode[] pairArgs = pairNode.getArgs();
if (pairArgs[0] == null) {
other = pairArgs[1];
if (coverage) { cm = cm.get(pairNode); }
}
else {
Value bval = this.eval(pairArgs[0], c, s0, s1, control, coverage ? cm.get(pairNode) : cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("A non-boolean expression (" + bval.getKindString() +
") was used as a condition of a CASE. " + pairArgs[0], pairArgs[0], c);
}
if (((BoolValue)bval).val) {
return this.eval(pairArgs[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm);
}
}
}
if (other == null) {
Assert.fail("Attempted to evaluate a CASE with no conditions true.\n" + expr, expr, c);
}
return this.eval(other, c, s0, s1, control, cm);
}
case OPCODE_cp: // CartesianProd
{
int alen = args.length;
Value[] sets = new Value[alen];
for (int i = 0; i < alen; i++) {
sets[i] = this.eval(args[i], c, s0, s1, control, cm);
}
return setSource(expr, new SetOfTuplesValue(sets, cm));
}
case OPCODE_cl: // ConjList
{
int alen = args.length;
for (int i = 0; i < alen; i++) {
Value bval = this.eval(args[i], c, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("A non-boolean expression (" + bval.getKindString() +
") was used as a formula in a conjunction.\n" + args[i], args[i], c);
}
if (!((BoolValue)bval).val) {
return BoolValue.ValFalse;
}
}
return BoolValue.ValTrue;
}
case OPCODE_dl: // DisjList
{
int alen = args.length;
for (int i = 0; i < alen; i++) {
Value bval = this.eval(args[i], c, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("A non-boolean expression (" + bval.getKindString() +
") was used as a formula in a disjunction.\n" + args[i], args[i], c);
}
if (((BoolValue)bval).val) {
return BoolValue.ValTrue;
}
}
return BoolValue.ValFalse;
}
case OPCODE_exc: // Except
{
int alen = args.length;
Value result = this.eval(args[0], c, s0, s1, control, cm);
// SZ: variable not used ValueExcept[] expts = new ValueExcept[alen-1];
for (int i = 1; i < alen; i++) {
OpApplNode pairNode = (OpApplNode)args[i];
ExprOrOpArgNode[] pairArgs = pairNode.getArgs();
SemanticNode[] cmpts = ((OpApplNode)pairArgs[0]).getArgs();
Value[] lhs = new Value[cmpts.length];
for (int j = 0; j < lhs.length; j++) {
lhs[j] = this.eval(cmpts[j], c, s0, s1, control, coverage ? cm.get(pairNode).get(pairArgs[0]) : cm);
}
Value atVal = result.select(lhs);
if (atVal == null) {
// Do nothing but warn:
MP.printWarning(EC.TLC_EXCEPT_APPLIED_TO_UNKNOWN_FIELD, new String[]{args[0].toString()});
}
else {
Context c1 = c.cons(EXCEPT_AT, atVal);
Value rhs = this.eval(pairArgs[1], c1, s0, s1, control, coverage ? cm.get(pairNode) : cm);
ValueExcept vex = new ValueExcept(lhs, rhs);
result = (Value) result.takeExcept(vex);
}
}
return result;
}
case OPCODE_fa: // FcnApply
{
Value result = null;
Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(control), cm);
if ((fval instanceof FcnRcdValue) ||
(fval instanceof FcnLambdaValue)) {
Applicable fcn = (Applicable)fval;
Value argVal = this.eval(args[1], c, s0, s1, control, cm);
result = fcn.apply(argVal, control);
}
else if ((fval instanceof TupleValue) ||
(fval instanceof RecordValue)) {
Applicable fcn = (Applicable)fval;
if (args.length != 2) {
Assert.fail("Attempted to evaluate an expression of form f[e1, ... , eN]" +
"\nwith f a tuple or record and N > 1.\n" + expr, expr, c);
}
Value aval = this.eval(args[1], c, s0, s1, control, cm);
result = fcn.apply(aval, control);
}
else {
Assert.fail("A non-function (" + fval.getKindString() + ") was applied" +
" as a function.\n" + expr, expr, c);
}
return result;
}
case OPCODE_fc: // FcnConstructor
case OPCODE_nrfs: // NonRecursiveFcnSpec
case OPCODE_rfs: // RecursiveFcnSpec
{
FormalParamNode[][] formals = expr.getBdedQuantSymbolLists();
boolean[] isTuples = expr.isBdedQuantATuple();
ExprNode[] domains = expr.getBdedQuantBounds();
Value[] dvals = new Value[domains.length];
boolean isFcnRcd = true;
for (int i = 0; i < dvals.length; i++) {
dvals[i] = this.eval(domains[i], c, s0, s1, control, cm);
isFcnRcd = isFcnRcd && (dvals[i] instanceof Reducible);
}
FcnParams params = new FcnParams(formals, isTuples, dvals);
SemanticNode fbody = args[0];
FcnLambdaValue fval = (FcnLambdaValue) setSource(expr, new FcnLambdaValue(params, fbody, this, c, s0, s1, control, cm));
if (opcode == OPCODE_rfs) {
SymbolNode fname = expr.getUnbdedQuantSymbols()[0];
fval.makeRecursive(fname);
isFcnRcd = false;
}
if (isFcnRcd && !EvalControl.isKeepLazy(control)) {
return (Value) fval.toFcnRcd();
}
return fval;
}
case OPCODE_ite: // IfThenElse
{
Value bval = this.eval(args[0], c, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("A non-boolean expression (" + bval.getKindString() +
") was used as the condition of an IF.\n" + expr, expr, c);
}
if (((BoolValue)bval).val) {
return this.eval(args[1], c, s0, s1, control, cm);
}
return this.eval(args[2], c, s0, s1, control, cm);
}
case OPCODE_rc: // RcdConstructor
{
int alen = args.length;
UniqueString[] names = new UniqueString[alen];
Value[] vals = new Value[alen];
for (int i = 0; i < alen; i++) {
OpApplNode pairNode = (OpApplNode)args[i];
ExprOrOpArgNode[] pair = pairNode.getArgs();
names[i] = ((StringValue)pair[0].getToolObject(toolId)).getVal();
vals[i] = this.eval(pair[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm);
}
return setSource(expr, new RecordValue(names, vals, false, cm));
}
case OPCODE_rs: // RcdSelect
{
Value rval = this.eval(args[0], c, s0, s1, control, cm);
Value sval = (Value) WorkerValue.mux(args[1].getToolObject(toolId));
if (rval instanceof RecordValue) {
Value result = (Value) ((RecordValue)rval).select(sval);
if (result == null) {
Assert.fail("Attempted to select nonexistent field " + sval + " from the" +
" record\n" + Values.ppr(rval.toString()) + "\n" + expr, expr, c);
}
return result;
}
else {
FcnRcdValue fcn = (FcnRcdValue) rval.toFcnRcd();
if (fcn == null) {
Assert.fail("Attempted to select field " + sval + " from a non-record" +
" value " + Values.ppr(rval.toString()) + "\n" + expr, expr, c);
}
return fcn.apply(sval, control);
}
}
case OPCODE_se: // SetEnumerate
{
int alen = args.length;
ValueVec vals = new ValueVec(alen);
for (int i = 0; i < alen; i++) {
vals.addElement(this.eval(args[i], c, s0, s1, control, cm));
}
return setSource(expr, new SetEnumValue(vals, false, cm));
}
case OPCODE_soa: // SetOfAll: {e(x) : x \in S}
{
ValueVec vals = new ValueVec();
ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm);
SemanticNode body = args[0];
Context c1;
while ((c1 = Enum.nextElement()) != null) {
Value val = this.eval(body, c1, s0, s1, control, cm);
vals.addElement(val);
// vals.addElement1(val);
}
return setSource(expr, new SetEnumValue(vals, false, cm));
}
case OPCODE_sor: // SetOfRcds
{
int alen = args.length;
UniqueString names[] = new UniqueString[alen];
Value vals[] = new Value[alen];
for (int i = 0; i < alen; i++) {
OpApplNode pairNode = (OpApplNode)args[i];
ExprOrOpArgNode[] pair = pairNode.getArgs();
names[i] = ((StringValue)pair[0].getToolObject(toolId)).getVal();
vals[i] = this.eval(pair[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm);
}
return setSource(expr, new SetOfRcdsValue(names, vals, false, cm));
}
case OPCODE_sof: // SetOfFcns
{
Value lhs = this.eval(args[0], c, s0, s1, control, cm);
Value rhs = this.eval(args[1], c, s0, s1, control, cm);
return setSource(expr, new SetOfFcnsValue(lhs, rhs, cm));
}
case OPCODE_sso: // SubsetOf
{
SemanticNode pred = args[0];
SemanticNode inExpr = expr.getBdedQuantBounds()[0];
Value inVal = this.eval(inExpr, c, s0, s1, control, cm);
boolean isTuple = expr.isBdedQuantATuple()[0];
FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0];
if (inVal instanceof Reducible) {
ValueVec vals = new ValueVec();
ValueEnumeration enumSet = ((Enumerable)inVal).elements();
Value elem;
if (isTuple) {
while ((elem = enumSet.nextElement()) != null) {
Context c1 = c;
Value[] tuple = ((TupleValue)elem).elems;
for (int i = 0; i < bvars.length; i++) {
c1 = c1.cons(bvars[i], tuple[i]);
}
Value bval = this.eval(pred, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" +
" when P was " + bval.getKindString() + ".\n" + pred, pred, c1);
}
if (((BoolValue)bval).val) {
vals.addElement(elem);
}
}
}
else {
SymbolNode idName = bvars[0];
while ((elem = enumSet.nextElement()) != null) {
Context c1 = c.cons(idName, elem);
Value bval = this.eval(pred, c1, s0, s1, control, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" +
" when P was " + bval.getKindString() + ".\n" + pred, pred, c1);
}
if (((BoolValue)bval).val) {
vals.addElement(elem);
}
}
}
return setSource(expr, new SetEnumValue(vals, inVal.isNormalized(), cm));
}
else if (isTuple) {
return setSource(expr, new SetPredValue(bvars, inVal, pred, this, c, s0, s1, control, cm));
}
else {
return setSource(expr, new SetPredValue(bvars[0], inVal, pred, this, c, s0, s1, control, cm));
}
}
case OPCODE_tup: // Tuple
{
int alen = args.length;
Value[] vals = new Value[alen];
for (int i = 0; i < alen; i++) {
vals[i] = this.eval(args[i], c, s0, s1, control, cm);
}
return setSource(expr, new TupleValue(vals, cm));
}
case OPCODE_uc: // UnboundedChoose
{
Assert.fail("TLC attempted to evaluate an unbounded CHOOSE.\n" +
"Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" +
expr, expr, c);
return null; // make compiler happy
}
case OPCODE_ue: // UnboundedExists
{
Assert.fail("TLC attempted to evaluate an unbounded \\E.\n" +
"Make sure that the expression is of form \\E x \\in S: P(x).\n" +
expr, expr, c);
return null; // make compiler happy
}
case OPCODE_uf: // UnboundedForall
{
Assert.fail("TLC attempted to evaluate an unbounded \\A.\n" +
"Make sure that the expression is of form \\A x \\in S: P(x).\n" +
expr, expr, c);
return null; // make compiler happy
}
case OPCODE_lnot:
{
Value arg = this.eval(args[0], c, s0, s1, control, cm);
if (!(arg instanceof BoolValue)) {
Assert.fail("Attempted to apply the operator ~ to a non-boolean\n(" +
arg.getKindString() + ")\n" + expr, args[0], c);
}
return (((BoolValue)arg).val) ? BoolValue.ValFalse : BoolValue.ValTrue;
}
case OPCODE_subset:
{
Value arg = this.eval(args[0], c, s0, s1, control, cm);
return setSource(expr, new SubsetValue(arg, cm));
}
case OPCODE_union:
{
Value arg = this.eval(args[0], c, s0, s1, control, cm);
return setSource(expr, UnionValue.union(arg));
}
case OPCODE_domain:
{
Value arg = this.eval(args[0], c, s0, s1, control, cm);
if (!(arg instanceof Applicable)) {
Assert.fail("Attempted to apply the operator DOMAIN to a non-function\n(" +
arg.getKindString() + ")\n" + expr, expr, c);
}
return setSource(expr, ((Applicable)arg).getDomain());
}
case OPCODE_enabled:
{
TLCState sfun = TLCStateFun.Empty;
Context c1 = Context.branch(c);
sfun = this.enabled(args[0], ActionItemList.Empty, c1, s0, sfun, cm);
return (sfun != null) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_eq:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
return (arg1.equals(arg2)) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_land:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
if (!(arg1 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P /\\ Q" +
" when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c);
}
if (((BoolValue)arg1).val) {
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (!(arg2 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P /\\ Q" +
" when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c);
}
return arg2;
}
return BoolValue.ValFalse;
}
case OPCODE_lor:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
if (!(arg1 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P \\/ Q" +
" when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c);
}
if (((BoolValue)arg1).val) {
return BoolValue.ValTrue;
}
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (!(arg2 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P \\/ Q" +
" when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c);
}
return arg2;
}
case OPCODE_implies:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
if (!(arg1 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P => Q" +
" when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c);
}
if (((BoolValue)arg1).val) {
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (!(arg2 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P => Q" +
" when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c);
}
return arg2;
}
return BoolValue.ValTrue;
}
case OPCODE_equiv:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (!(arg1 instanceof BoolValue) || !(arg2 instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form P <=> Q" +
" when P or Q was not a boolean.\n" + expr, expr, c);
}
BoolValue bval1 = (BoolValue)arg1;
BoolValue bval2 = (BoolValue)arg2;
return (bval1.val == bval2.val) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_noteq:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
return arg1.equals(arg2) ? BoolValue.ValFalse : BoolValue.ValTrue;
}
case OPCODE_subseteq:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (!(arg1 instanceof Enumerable)) {
Assert.fail("Attempted to evaluate an expression of form S \\subseteq T," +
" but S was not enumerable.\n" + expr, expr, c);
}
return ((Enumerable) arg1).isSubsetEq(arg2);
}
case OPCODE_in:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
return (arg2.member(arg1)) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_notin:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
return (arg2.member(arg1)) ? BoolValue.ValFalse : BoolValue.ValTrue;
}
case OPCODE_setdiff:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (arg1 instanceof Reducible) {
return setSource(expr, ((Reducible)arg1).diff(arg2));
}
return setSource(expr, new SetDiffValue(arg1, arg2));
}
case OPCODE_cap:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (arg1 instanceof Reducible) {
return setSource(expr, ((Reducible)arg1).cap(arg2));
}
else if (arg2 instanceof Reducible) {
return setSource(expr, ((Reducible)arg2).cap(arg1));
}
return setSource(expr, new SetCapValue(arg1, arg2));
}
case OPCODE_nop:
// Added by LL on 2 Aug 2007
{
return eval(args[0], c, s0, s1, control, cm);
}
case OPCODE_cup:
{
Value arg1 = this.eval(args[0], c, s0, s1, control, cm);
Value arg2 = this.eval(args[1], c, s0, s1, control, cm);
if (arg1 instanceof Reducible) {
return setSource(expr, ((Reducible)arg1).cup(arg2));
}
else if (arg2 instanceof Reducible) {
return setSource(expr, ((Reducible)arg2).cup(arg1));
}
return setSource(expr, new SetCupValue(arg1, arg2, cm));
}
case OPCODE_prime:
{
// MAK 03/2019: Cannot reproduce this but without this check the nested evaluation
// fails with a NullPointerException which subsequently is swallowed. This makes it
// impossible for a user to diagnose what is going on. Since I cannot reproduce the
// actual expression, I leave this commented for. I recall an expression along the
// lines of:
// TLCSet(23, CHOOSE p \in pc: pc[p] # pc[p]')
// The fail statement below is obviously too generic to be useful and needs to be
// clarified if the actual cause has been identified.
// if (s1 == null) {
// Assert.fail("Attempted to evaluate the following expression," +
// " but expression failed to evaluate.\n" + expr);
return this.eval(args[0], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm);
}
case OPCODE_unchanged:
{
Value v0 = this.eval(args[0], c, s0, TLCState.Empty, control, cm);
Value v1 = this.eval(args[0], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm);
return (v0.equals(v1)) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_aa:
{
Value res = this.eval(args[0], c, s0, s1, control, cm);
if (!(res instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form <A>_e," +
" but A was not a boolean.\n" + expr, expr, c);
}
if (!((BoolValue)res).val) {
return BoolValue.ValFalse;
}
Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control, cm);
Value v1 = this.eval(args[1], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm);
return v0.equals(v1) ? BoolValue.ValFalse : BoolValue.ValTrue;
}
case OPCODE_sa:
{
Value res = this.eval(args[0], c, s0, s1, control, cm);
if (!(res instanceof BoolValue)) {
Assert.fail("Attempted to evaluate an expression of form [A]_e," +
" but A was not a boolean.\n" + expr, expr, c);
}
if (((BoolValue)res).val) {
return BoolValue.ValTrue;
}
Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control, cm);
Value v1 = this.eval(args[1], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm);
return (v0.equals(v1)) ? BoolValue.ValTrue : BoolValue.ValFalse;
}
case OPCODE_cdot:
{
Assert.fail("The current version of TLC does not support action composition.", expr, c);
return null; // make compiler happy
}
case OPCODE_sf:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"SF", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_wf:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"WF", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_te: // TemporalExists
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\EE", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_tf: // TemporalForAll
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\AA", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_leadto:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a ~> b", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_arrow:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a -+-> formula", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_box:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"[]A", expr.toString()}, expr, c);
return null; // make compiler happy
}
case OPCODE_diamond:
{
Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"<>A", expr.toString()}, expr, c);
return null; // make compiler happy
}
default:
{
Assert.fail("TLC BUG: could not evaluate this expression.\n" + expr, expr, c);
return null;
}
}
}
protected abstract Value setSource(final SemanticNode expr, final Value value);
@Override
public final boolean isGoodState(TLCState state) {
return state.allAssigned();
}
/* This method determines if a state satisfies the model constraints. */
@Override
public final boolean isInModel(TLCState state) throws EvalException {
ExprNode[] constrs = this.getModelConstraints();
for (int i = 0; i < constrs.length; i++) {
final CostModel cm = coverage ? ((Action) constrs[i].getToolObject(toolId)).cm : CostModel.DO_NOT_RECORD;
IValue bval = this.eval(constrs[i], Context.Empty, state, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}, constrs[i]);
}
if (!((BoolValue)bval).val) {
if (coverage) {
cm.incInvocations();
}
return false;
} else {
if (coverage) {
cm.incSecondary();
}
}
}
return true;
}
/* This method determines if a pair of states satisfy the action constraints. */
@Override
public final boolean isInActions(TLCState s1, TLCState s2) throws EvalException {
ExprNode[] constrs = this.getActionConstraints();
for (int i = 0; i < constrs.length; i++) {
final CostModel cm = coverage ? ((Action) constrs[i].getToolObject(toolId)).cm : CostModel.DO_NOT_RECORD;
Value bval = this.eval(constrs[i], Context.Empty, s1, s2, EvalControl.Clear, cm);
if (!(bval instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}, constrs[i]);
}
if (!((BoolValue)bval).val) {
if (coverage) {
cm.incInvocations();
}
return false;
} else {
if (coverage) {
cm.incSecondary();
}
}
}
return true;
}
@Override
public final boolean hasStateOrActionConstraints() {
return this.getModelConstraints().length > 0 || this.getActionConstraints().length > 0;
}
@Override
public final TLCState enabled(SemanticNode pred, Context c, TLCState s0, TLCState s1) {
return enabled(pred, ActionItemList.Empty, c, s0, s1, CostModel.DO_NOT_RECORD);
}
@Override
public final TLCState enabled(SemanticNode pred, Context c, TLCState s0, TLCState s1, ExprNode subscript, final int ail) {
ActionItemList acts = (ActionItemList) ActionItemList.Empty.cons(subscript, c, CostModel.DO_NOT_RECORD, ail);
return enabled(pred, acts, c, s0, s1, CostModel.DO_NOT_RECORD);
}
@Override
public final TLCState enabled(SemanticNode pred, IActionItemList acts, Context c, TLCState s0, TLCState s1) {
return enabled(pred, acts, c, s0, s1, CostModel.DO_NOT_RECORD);
}
/**
* This method determines if an action is enabled in the given state.
* More precisely, it determines if (act.pred /\ (sub' # sub)) is
* enabled in the state s and context act.con.
*/
@Override
public abstract TLCState enabled(SemanticNode pred, IActionItemList acts,
Context c, TLCState s0, TLCState s1, CostModel cm);
protected final TLCState enabledImpl(SemanticNode pred, ActionItemList acts,
Context c, TLCState s0, TLCState s1, CostModel cm) {
switch (pred.getKind()) {
case OpApplKind:
{
OpApplNode pred1 = (OpApplNode)pred;
return this.enabledAppl(pred1, acts, c, s0, s1, cm);
}
case LetInKind:
{
LetInNode pred1 = (LetInNode)pred;
OpDefNode[] letDefs = pred1.getLets();
Context c1 = c;
for (int i = 0; i < letDefs.length; i++) {
OpDefNode opDef = letDefs[i];
if (opDef.getArity() == 0) {
Value rhs = new LazyValue(opDef.getBody(), c1, cm);
c1 = c1.cons(opDef, rhs);
}
}
return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm);
}
case SubstInKind:
{
SubstInNode pred1 = (SubstInNode)pred;
Subst[] subs = pred1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId));
}
return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm);
}
// Added by LL on 13 Nov 2009 to handle theorem and assumption names.
case APSubstInKind:
{
APSubstInNode pred1 = (APSubstInNode)pred;
Subst[] subs = pred1.getSubsts();
int slen = subs.length;
Context c1 = c;
for (int i = 0; i < slen; i++) {
Subst sub = subs[i];
c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId));
}
return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm);
}
// LabelKind class added by LL on 13 Jun 2007
case LabelKind:
{
LabelNode pred1 = (LabelNode)pred;
return this.enabled(pred1.getBody(), acts, c, s0, s1, cm);
}
default:
{
// We should not compute enabled on anything else.
Assert.fail("Attempted to compute ENABLED on a non-boolean expression.\n" + pred, pred, c);
return null; // make compiler happy
}
}
}
private final TLCState enabled(ActionItemList acts, TLCState s0, TLCState s1, CostModel cm) {
if (acts.isEmpty()) return s1;
final int kind = acts.carKind();
SemanticNode pred = acts.carPred();
Context c = acts.carContext();
cm = acts.cm;
ActionItemList acts1 = acts.cdr();
if (kind > IActionItemList.CONJUNCT) {
TLCState res = this.enabled(pred, acts1, c, s0, s1, cm);
return res;
}
else if (kind == IActionItemList.PRED) {
TLCState res = this.enabled(pred, acts1, c, s0, s1, cm);
return res;
}
if (kind == IActionItemList.UNCHANGED) {
TLCState res = this.enabledUnchanged(pred, acts1, c, s0, s1, cm);
return res;
}
Value v1 = this.eval(pred, c, s0, TLCState.Empty, EvalControl.Enabled, cm);
// We are now in ENABLED and primed state. Second TLCState parameter being null
// effectively disables LazyValue in evalAppl (same effect as
// EvalControl.setPrimed(EvalControl.Enabled)).
Value v2 = this.eval(pred, c, s1, TLCState.Null, EvalControl.Primed, cm);
if (v1.equals(v2)) return null;
TLCState res = this.enabled(acts1, s0, s1, cm);
return res;
}
protected abstract TLCState enabledAppl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm);
protected final TLCState enabledApplImpl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm)
{
if (coverage) {cm = cm.get(pred);}
ExprOrOpArgNode[] args = pred.getArgs();
int alen = args.length;
SymbolNode opNode = pred.getOperator();
int opcode = BuiltInOPs.getOpCode(opNode.getName());
if (opcode == 0)
{
// This is a user-defined operator with one exception: it may
// be substed by a builtin operator. This special case occurs
// when the lookup returns an OpDef with opcode
Object val = this.lookup(opNode, c, s0, false);
if (val instanceof OpDefNode)
{
OpDefNode opDef = (OpDefNode) val;
opcode = BuiltInOPs.getOpCode(opDef.getName());
if (opcode == 0)
{
// Context c1 = this.getOpContext(opDef, args, c, false);
Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId);
return this.enabled(opDef.getBody(), acts, c1, s0, s1, cm);
}
}
// Added 13 Nov 2009 by LL to handle theorem or assumption names
if (val instanceof ThmOrAssumpDefNode)
{
ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val;
Context c1 = this.getOpContext(opDef, args, c, true);
return this.enabled(opDef.getBody(), acts, c1, s0, s1, cm);
}
if (val instanceof LazyValue)
{
LazyValue lv = (LazyValue) val;
return this.enabled(lv.expr, acts, lv.con, s0, s1, lv.cm);
}
Object bval = val;
if (alen == 0)
{
if (val instanceof MethodValue)
{
bval = ((MethodValue) val).apply(EmptyArgs, EvalControl.Clear); // EvalControl.Clear is ignored by MethodValuea#apply
} else if (val instanceof EvaluatingValue) {
bval = ((EvaluatingValue) val).eval(this, args, c, s0, s1, EvalControl.Enabled, cm);
}
} else
{
if (val instanceof OpValue)
{
bval = ((OpValue) val).eval(this, args, c, s0, s1, EvalControl.Enabled, cm);
}
}
if (opcode == 0)
{
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean",
bval.toString(), pred.toString() }, pred, c);
}
if (((BoolValue) bval).val)
{
return this.enabled(acts, s0, s1, cm);
}
return null;
}
}
switch (opcode) {
case OPCODE_aa: // AngleAct <A>_e
{
ActionItemList acts1 = (ActionItemList) acts.cons(args[1], c, cm, IActionItemList.CHANGED);
return this.enabled(args[0], acts1, c, s0, s1, cm);
}
case OPCODE_be: // BoundedExists
{
SemanticNode body = args[0];
ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled, cm);
Context c1;
while ((c1 = Enum.nextElement()) != null)
{
TLCState s2 = this.enabled(body, acts, c1, s0, s1, cm);
if (s2 != null) {
return s2;
}
}
return null;
}
case OPCODE_bf: // BoundedForall
{
SemanticNode body = args[0];
ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled, cm);
Context c1 = Enum.nextElement();
if (c1 == null)
{
return this.enabled(acts, s0, s1, cm);
}
ActionItemList acts1 = acts;
Context c2;
while ((c2 = Enum.nextElement()) != null)
{
acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED);
}
return this.enabled(body, acts1, c1, s0, s1, cm);
}
case OPCODE_case: // Case
{
SemanticNode other = null;
for (int i = 0; i < alen; i++)
{
OpApplNode pair = (OpApplNode) args[i];
ExprOrOpArgNode[] pairArgs = pair.getArgs();
if (pairArgs[0] == null)
{
other = pairArgs[1];
} else
{
Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Enabled, cm);
if (!(bval instanceof BoolValue))
{
Assert.fail("In computing ENABLED, a non-boolean expression(" + bval.getKindString()
+ ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1], pairArgs[1], c);
}
if (((BoolValue) bval).val)
{
return this.enabled(pairArgs[1], acts, c, s0, s1, cm);
}
}
}
if (other == null)
{
Assert.fail("In computing ENABLED, TLC encountered a CASE with no" + " conditions true.\n" + pred, pred, c);
}
return this.enabled(other, acts, c, s0, s1, cm);
}
case OPCODE_cl: // ConjList
case OPCODE_land:
{
ActionItemList acts1 = acts;
for (int i = alen - 1; i > 0; i
{
acts1 = (ActionItemList) acts1.cons(args[i], c, cm, i);
}
return this.enabled(args[0], acts1, c, s0, s1, cm);
}
case OPCODE_dl: // DisjList
case OPCODE_lor:
{
for (int i = 0; i < alen; i++)
{
TLCState s2 = this.enabled(args[i], acts, c, s0, s1, cm);
if (s2 != null) {
return s2;
}
}
return null;
}
case OPCODE_fa: // FcnApply
{
Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(EvalControl.Enabled), cm); // KeepLazy does not interfere with EvalControl.Enabled in this.evalAppl
if (fval instanceof FcnLambdaValue)
{
FcnLambdaValue fcn = (FcnLambdaValue) fval;
if (fcn.fcnRcd == null)
{
Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Enabled, cm); // EvalControl.Enabled passed on to nested this.evalAppl
return this.enabled(fcn.body, acts, c1, s0, s1, cm);
}
fval = fcn.fcnRcd;
}
if (fval instanceof Applicable)
{
Applicable fcn = (Applicable) fval;
Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm);
Value bval = fcn.apply(argVal, EvalControl.Enabled); // EvalControl.Enabled not taken into account by any subclass of Applicable
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "ENABLED", "boolean",
pred.toString() }, args[1], c);
}
if (!((BoolValue) bval).val) {
return null;
}
} else
{
Assert.fail("In computing ENABLED, a non-function (" + fval.getKindString()
+ ") was applied as a function.\n" + pred, pred, c);
}
return this.enabled(acts, s0, s1, cm);
}
case OPCODE_ite: // IfThenElse
{
Value guard = this.eval(args[0], c, s0, s1, EvalControl.Enabled, cm);
if (!(guard instanceof BoolValue))
{
Assert.fail("In computing ENABLED, a non-boolean expression(" + guard.getKindString()
+ ") was used as the guard condition" + " of an IF.\n" + pred, pred, c);
}
int idx = (((BoolValue) guard).val) ? 1 : 2;
return this.enabled(args[idx], acts, c, s0, s1, cm);
}
case OPCODE_sa: // SquareAct [A]_e
{
TLCState s2 = this.enabled(args[0], acts, c, s0, s1, cm);
if (s2 != null) {
return s2;
}
return this.enabledUnchanged(args[1], acts, c, s0, s1, cm);
}
case OPCODE_te: // TemporalExists
case OPCODE_tf: // TemporalForAll
{
Assert.fail("In computing ENABLED, TLC encountered temporal quantifier.\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_uc: // UnboundedChoose
{
Assert.fail("In computing ENABLED, TLC encountered unbounded CHOOSE. "
+ "Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_ue: // UnboundedExists
{
Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. "
+ "Make sure that the expression is of form \\E x \\in S: P(x).\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_uf: // UnboundedForall
{
Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. "
+ "Make sure that the expression is of form \\A x \\in S: P(x).\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_sf:
{
Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[]{ "SF", pred.toString()}, pred, c);
return null; // make compiler happy
}
case OPCODE_wf:
{
Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "WF", pred.toString() }, pred, c);
return null; // make compiler happy
}
case OPCODE_box:
{
Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "[]", pred.toString() }, pred, c);
return null; // make compiler happy
}
case OPCODE_diamond:
{
Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "<>", pred.toString() }, pred, c);
return null; // make compiler happy
}
case OPCODE_unchanged:
{
return this.enabledUnchanged(args[0], acts, c, s0, s1, cm);
}
case OPCODE_eq:
{
SymbolNode var = this.getPrimedVar(args[0], c, true);
if (var == null)
{
Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm);
if (!((BoolValue) bval).val) {
return null;
}
} else
{
UniqueString varName = var.getName();
IValue lval = s1.lookup(varName);
Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm);
if (lval == null)
{
TLCState s2 = s1.bind(var, rval);
return this.enabled(acts, s0, s2, cm);
} else
{
if (!lval.equals(rval)) {
return null;
}
}
}
return this.enabled(acts, s0, s1, cm);
}
case OPCODE_implies:
{
Value bval = this.eval(args[0], c, s0, s1, EvalControl.Enabled, cm);
if (!(bval instanceof BoolValue))
{
Assert.fail("While computing ENABLED of an expression of the form" + " P => Q, P was "
+ bval.getKindString() + ".\n" + pred, pred, c);
}
if (((BoolValue) bval).val)
{
return this.enabled(args[1], acts, c, s0, s1, cm);
}
return this.enabled(acts, s0, s1, cm);
}
case OPCODE_cdot:
{
Assert.fail("The current version of TLC does not support action composition.", pred, c);
return null; // make compiler happy
}
case OPCODE_leadto:
{
Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a ~> b).\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_arrow:
{
Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a -+-> formula).\n" + pred, pred, c);
return null; // make compiler happy
}
case OPCODE_in:
{
SymbolNode var = this.getPrimedVar(args[0], c, true);
if (var == null)
{
Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm);
if (!((BoolValue) bval).val) {
return null;
}
} else
{
UniqueString varName = var.getName();
Value lval = (Value) s1.lookup(varName);
Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm);
if (lval == null)
{
if (!(rval instanceof Enumerable))
{
Assert.fail("The right side of \\IN is not enumerable.\n" + pred, pred, c);
}
ValueEnumeration Enum = ((Enumerable) rval).elements();
Value val;
while ((val = Enum.nextElement()) != null)
{
TLCState s2 = s1.bind(var, val);
s2 = this.enabled(acts, s0, s2, cm);
if (s2 != null) {
return s2;
}
}
return null;
} else
{
if (!rval.member(lval)) {
return null;
}
}
}
return this.enabled(acts, s0, s1, cm);
}
// The following case added by LL on 13 Nov 2009 to handle subexpression names.
case OPCODE_nop:
{
return this.enabled(args[0], acts, c, s0, s1, cm);
}
default:
{
// We handle all the other builtin operators here.
Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm);
if (!(bval instanceof BoolValue))
{
Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean",
bval.toString(), pred.toString() }, pred, c);
}
if (((BoolValue) bval).val)
{
return this.enabled(acts, s0, s1, cm);
}
return null;
}
}
}
protected abstract TLCState enabledUnchanged(SemanticNode expr, ActionItemList acts,
Context c, TLCState s0, TLCState s1, CostModel cm);
protected final TLCState enabledUnchangedImpl(SemanticNode expr, ActionItemList acts,
Context c, TLCState s0, TLCState s1, CostModel cm) {
if (coverage) {cm = cm.get(expr);}
SymbolNode var = this.getVar(expr, c, true, toolId);
if (var != null) {
// a state variable, e.g. UNCHANGED var1
UniqueString varName = var.getName();
Value v0 = this.eval(expr, c, s0, s1, EvalControl.Enabled, cm);
IValue v1 = s1.lookup(varName);
if (v1 == null) {
s1 = s1.bind(var, v0);
return this.enabled(acts, s0, s1, cm);
}
if (v1.equals(v0)) {
return this.enabled(acts, s0, s1, cm);
}
MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString() , expr.toString()});
return null;
}
if (expr instanceof OpApplNode) {
OpApplNode expr1 = (OpApplNode)expr;
ExprOrOpArgNode[] args = expr1.getArgs();
int alen = args.length;
SymbolNode opNode = expr1.getOperator();
UniqueString opName = opNode.getName();
int opcode = BuiltInOPs.getOpCode(opName);
if (opcode == OPCODE_tup) {
// a tuple, e.g. UNCHANGED <<var1, var2>>
if (alen != 0) {
ActionItemList acts1 = acts;
for (int i = 1; i < alen; i++) {
acts1 = (ActionItemList) acts1.cons(args[i], c, cm, IActionItemList.UNCHANGED);
}
return this.enabledUnchanged(args[0], acts1, c, s0, s1, cm);
}
return this.enabled(acts, s0, s1, cm);
}
if (opcode == 0 && alen == 0) {
// a 0-arity operator:
Object val = this.lookup(opNode, c, false);
if (val instanceof LazyValue) {
LazyValue lv = (LazyValue)val;
return this.enabledUnchanged(lv.expr, acts, lv.con, s0, s1, cm);
}
else if (val instanceof OpDefNode) {
return this.enabledUnchanged(((OpDefNode)val).getBody(), acts, c, s0, s1, cm);
}
else if (val == null) {
Assert.fail("In computing ENABLED, TLC found the undefined identifier\n" +
opName + " in an UNCHANGED expression at\n" + expr, expr ,c);
}
return this.enabled(acts, s0, s1, cm);
}
}
final Value v0 = this.eval(expr, c, s0, TLCState.Empty, EvalControl.Enabled, cm);
// We are in ENABLED and primed but why pass only primed? This appears to
// be the only place where we call eval from the ENABLED scope without
// additionally passing EvalControl.Enabled. Not passing Enabled allows a
// cached LazyValue could be used (see comments above on line 1384).
// The current scope is a nested UNCHANGED in an ENABLED and evaluation is set
// to primed. However, UNCHANGED e equals e' = e , so anything primed in e
// which is rejected by SANY's level checking. A perfectly valid spec - where
// e is not primed - but that also causes this code path to be taken is 23 below:
// VARIABLE t
// op(var) == var
// Next == /\ (ENABLED (UNCHANGED op(t)))
// /\ (t'= t)
// Spec == (t = 0) /\ [][Next]_t
// However, spec 23 causes the call to this.eval(...) below to throw an
// EvalException either with EvalControl.Primed. The exception's message is
// "In evaluation, the identifier t is either undefined or not an operator."
// indicating that this code path is buggy.
// If this bug is ever fixed to make TLC accept spec 23, EvalControl.Primed
// should likely be rewritten to EvalControl.setPrimed(EvalControl.Enabled)
// to disable reusage of LazyValues on line ~1384 above.
final Value v1 = this.eval(expr, c, s1, TLCState.Empty, EvalControl.Primed, cm);
if (!v0.equals(v1)) {
return null;
}
return this.enabled(acts, s0, s1, cm);
}
/* This method determines if the action predicate is valid in (s0, s1). */
@Override
public final boolean isValid(Action act, TLCState s0, TLCState s1) {
Value val = this.eval(act.pred, act.con, s0, s1, EvalControl.Clear, act.cm);
if (!(val instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", act.pred.toString()}, act.pred, act.con);
}
return ((BoolValue)val).val;
}
/* Returns true iff the predicate is valid in the state. */
@Override
public boolean isValid(Action act, TLCState state) {
return this.isValid(act, state, TLCState.Empty);
}
/* Returns true iff the predicate is valid in the state. */
@Override
public final boolean isValid(Action act) {
return this.isValid(act, TLCState.Empty, TLCState.Empty);
}
@Override
public boolean isValid(ExprNode expr, Context ctxt) {
IValue val = this.eval(expr, ctxt, TLCState.Empty, TLCState.Empty,
EvalControl.Const, CostModel.DO_NOT_RECORD);
if (!(val instanceof BoolValue)) {
Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, expr);
}
return ((BoolValue)val).val;
}
@Override
public final boolean isValid(ExprNode expr) {
return isValid(expr, Context.Empty);
}
public boolean isValidAssumption(ExprNode assumption) {
return isValid(assumption);
}
@Override
public final int checkAssumptions() {
final ExprNode[] assumps = getAssumptions();
final boolean[] isAxiom = getAssumptionIsAxiom();
for (int i = 0; i < assumps.length; i++)
{
try
{
if ((!isAxiom[i]) && !isValidAssumption(assumps[i]))
{
return MP.printError(EC.TLC_ASSUMPTION_FALSE, assumps[i].toString());
}
} catch (final Exception e)
{
// Assert.printStack(e);
return MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR,
new String[] { assumps[i].toString(), e.getMessage() });
}
}
return EC.NO_ERROR;
}
@Override
public final int checkPostCondition() {
return checkPostConditionWithContext(Context.Empty);
}
@Override
public final int checkPostConditionWithCounterExample(final IValue value) {
final SymbolNode def = getCounterExampleDef();
if (def == null) {
// TLCExt!CounterExample does not appear anywhere in the spec.
return checkPostCondition();
}
final Context ctxt = Context.Empty.cons(def, value);
return checkPostConditionWithContext(ctxt);
}
private final int checkPostConditionWithContext(final Context ctxt) {
final ExprNode[] postConditions = getPostConditionSpecs();
for (int i = 0; i < postConditions.length; i++) {
final ExprNode en = postConditions[i];
try {
if (!isValid(en, ctxt)) {
// It's not an assumption because the expression doesn't appear inside
// an ASSUME, but good enough for this prototype.
return MP.printError(EC.TLC_ASSUMPTION_FALSE, en.toString());
}
} catch (Exception e) {
// tool.isValid(sn) failed to evaluate...
return MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR,
new String[] { en.toString(), e.getMessage() });
}
}
// The PostCheckAssumption/PostCondition cannot be stated as an ordinary
// invariant
// with the help of TLCSet/Get because the invariant will only be evaluated for
// distinct states, but we want it to be evaluated after state-space exploration
// finished. Hacking away with TLCGet("queue") = 0 doesn't work because the
// queue
// can be empty during the evaluation of the next-state relation when a worker
// dequeues
// the last state S, that has more successor states.
return EC.NO_ERROR;
}
/* Reconstruct the initial state whose fingerprint is fp. */
@Override
public final TLCStateInfo getState(final long fp) {
class InitStateSelectorFunctor implements IStateFunctor {
private final long fp;
public TLCState state;
public InitStateSelectorFunctor(long fp) {
this.fp = fp;
}
@Override
public Object addElement(TLCState state) {
if (state == null) {
return null;
} else if (this.state != null) {
// Always return the first match found. Do not let later matches override
// this.state. This is in line with the original implementation that called
// getInitStates().
return null;
} else if (fp == state.fingerPrint()) {
this.state = state;
// TODO Stop generation of initial states preemptively. E.g. make the caller of
// addElement check for a special return value such as this (the functor).
}
return null;
}
}
// Registry a selector that extract out of the (possibly) large set of initial
// states the one identified by fp. The functor pattern has the advantage
// compared to this.getInitStates(), that it kind of streams the initial states
// to the functor whereas getInitStates() stores _all_ init states in a set
// which is traversed afterwards. This is also consistent with
// ModelChecker#DoInitFunctor. Using the functor pattern for the processing of
// init states in ModelChecker#doInit but calling getInitStates() here results
// in a bug during error trace generation when the set of initial states is too
// large for getInitStates(). Earlier TLC would have refused to run the model
// during ModelChecker#doInit.
final InitStateSelectorFunctor functor = new InitStateSelectorFunctor(fp);
this.getInitStates(functor);
final TLCState state = functor.state;
if (state != null) {
assert state.isInitial();
final TLCStateInfo info = new TLCStateInfo(state);
info.fp = fp;
return info;
}
return null;
}
/**
* Reconstruct the next state of state s whose fingerprint is fp.
*
* @return Returns the TLCState wrapped in TLCStateInfo. TLCStateInfo stores
* the stateNumber (relative to the given sinfo) and a pointer to
* the predecessor.
*/
@Override
public final TLCStateInfo getState(long fp, TLCStateInfo sinfo) {
final TLCStateInfo tlcStateInfo = getState(fp, sinfo.state);
if (tlcStateInfo == null) {
throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT);
}
tlcStateInfo.stateNumber = sinfo.stateNumber + 1;
tlcStateInfo.predecessorState = sinfo;
tlcStateInfo.fp = fp;
return tlcStateInfo;
}
/* Reconstruct the next state of state s whose fingerprint is fp. */
@Override
public final TLCStateInfo getState(long fp, TLCState s) {
IdThread.setCurrentState(s);
for (int i = 0; i < this.actions.length; i++) {
Action curAction = this.actions[i];
StateVec nextStates = this.getNextStates(curAction, s);
for (int j = 0; j < nextStates.size(); j++) {
TLCState state = nextStates.elementAt(j);
long nfp = state.fingerPrint();
if (fp == nfp) {
state.setPredecessor(s);
assert !state.isInitial();
return new TLCStateInfo(state, curAction);
}
}
}
return null;
}
/* Reconstruct the info for s1. */
@Override
public final TLCStateInfo getState(TLCState s1, TLCState s) {
IdThread.setCurrentState(s);
for (int i = 0; i < this.actions.length; i++) {
Action curAction = this.actions[i];
StateVec nextStates = this.getNextStates(curAction, s);
for (int j = 0; j < nextStates.size(); j++) {
TLCState state = nextStates.elementAt(j);
try {
if (s1.equals(state)) {
state.setPredecessor(s);
assert !state.isInitial();
return new TLCStateInfo(state, curAction);
}
} catch (TLCRuntimeException e) {
// s might have two or more successors, whose values are incomparable to the
// to equal <<"foo", 3>> and its two successor states t1 to equal <<"foo", 4>>
// and t2 to equal <<TRUE, 5>>. t1 and s1 equal to <<TRUE, 5>> are incomparable.
// and t2 to equal <<TRUE, 5>>. t1 and s1 equal to <<TRUE, 5>> are incomparable.
// Next ==
// \/ /\ x' = "foo"
// /\ y' = y + 1
// \/ /\ x' = TRUE
// /\ y' = y + 2
continue;
}
}
}
return null;
}
/* Return the set of all permutations under the symmetry assumption. */
@Override
public final IMVPerm[] getSymmetryPerms() {
final String name = this.config.getSymmetry();
if (name.length() == 0) { return null; }
final Object symm = this.unprocessedDefns.get(name);
if (symm == null) {
Assert.fail(EC.TLC_CONFIG_SPECIFIED_NOT_DEFINED, new String[] { "symmetry function", name});
}
if (!(symm instanceof OpDefNode)) {
Assert.fail("The symmetry function " + name + " must specify a set of permutations.");
}
final OpDefNode opDef = (OpDefNode)symm;
// This calls tlc2.module.TLC.Permutations(Value) and returns a Value of |fcns|
// = n! where n is the capacity of the symmetry set.
final IValue fcns = this.eval(opDef.getBody(), Context.Empty, TLCState.Empty, CostModel.DO_NOT_RECORD);
if (!(fcns instanceof Enumerable) || !(fcns instanceof SetEnumValue)) {
Assert.fail("The symmetry operator must specify a set of functions.", opDef.getBody());
}
final List<Value> values = ((SetEnumValue)fcns).elements().all();
for (final Value v : values) {
if (!(v instanceof FcnRcdValue)) {
Assert.fail("The symmetry values must be function records.", opDef.getBody());
}
}
final ExprOrOpArgNode[] argNodes = ((OpApplNode)opDef.getBody()).getArgs();
// In the case where the config defines more than one set which is symmetric, they will pass through the
// enumerable size() check even if they are single element sets
final StringBuilder cardinalityOneSetList = new StringBuilder();
int offenderCount = 0;
if (argNodes.length >= values.size()) {
// If equal, we have as many values as we have permuted sets => we have all 1-element sets;
// if greater than, then we have a heterogenous cardinality of sets, including 0 element sets.
for (final ExprOrOpArgNode node : argNodes) {
addToSubTwoSizedSymmetrySetList(node, cardinalityOneSetList);
offenderCount++;
}
}
final IMVPerm[] subgroup;
if (offenderCount == 0) {
subgroup = MVPerms.permutationSubgroup((Enumerable)fcns);
final HashSet<ModelValue> subgroupMembers = new HashSet<>();
for (final IMVPerm imvp : subgroup) {
if (imvp instanceof MVPerm) { // should always be the case
subgroupMembers.addAll(((MVPerm)imvp).getAllModelValues());
}
}
for (final ExprOrOpArgNode node : argNodes) {
final SetEnumValue enumValue = getSetEnumValueFromArgumentNode(node);
if (enumValue != null) {
final ValueEnumeration ve = enumValue.elements();
boolean found = false;
Value v;
while ((v = ve.nextElement()) != null) {
if ((v instanceof ModelValue) && subgroupMembers.contains(v)) {
found = true;
break;
}
}
if (!found) {
addToSubTwoSizedSymmetrySetList(node, cardinalityOneSetList);
offenderCount++;
}
}
}
} else {
subgroup = null;
}
if (offenderCount > 0) {
final String plurality = (offenderCount > 1) ? "s" : "";
final String antiPlurality = (offenderCount > 1) ? "" : "s";
final String toHaveConjugation = (offenderCount > 1) ? "have" : "has";
MP.printWarning(EC.TLC_SYMMETRY_SET_TOO_SMALL,
new String[] { plurality, cardinalityOneSetList.toString(), toHaveConjugation, antiPlurality });
}
return subgroup;
}
/**
* Teases the original spec name for the set out of node and appends it to the {@code StringBuilder} instance.
*/
private void addToSubTwoSizedSymmetrySetList(final ExprOrOpArgNode node, final StringBuilder cardinalityOneSetList) {
final SyntaxTreeNode tn = (SyntaxTreeNode)node.getTreeNode();
final String image = tn.getHumanReadableImage();
final String alias;
if (image.startsWith(TLAConstants.BuiltInOperators.PERMUTATIONS)) {
final int imageLength = image.length();
alias = image.substring((TLAConstants.BuiltInOperators.PERMUTATIONS.length() + 1),
(imageLength - 1));
} else {
alias = image;
}
final String specDefinitionName = this.config.getOverridenSpecNameForConfigName(alias);
final String displayDefinition = (specDefinitionName != null) ? specDefinitionName : alias;
if (cardinalityOneSetList.length() > 0) {
cardinalityOneSetList.append(", and ");
}
cardinalityOneSetList.append(displayDefinition);
}
/**
* @param node
* @return if the node represents a permutation, this will return the {@link SetEnumValue} instance contains its
* model values
*/
private SetEnumValue getSetEnumValueFromArgumentNode(final ExprOrOpArgNode node) {
if (node instanceof OpApplNode) {
final OpApplNode permutationNode = (OpApplNode)node;
if (permutationNode.getOperator() instanceof OpDefNode) {
final OpDefNode operator = (OpDefNode)permutationNode.getOperator();
if (TLAConstants.BuiltInOperators.PERMUTATIONS.equals(operator.getName().toString())) {
final ExprOrOpArgNode[] operands = permutationNode.getArgs();
if ((operands.length == 1)
&& (operands[0] instanceof OpApplNode)
&& (((OpApplNode)operands[0]).getOperator() instanceof OpDefOrDeclNode)) {
final Object o = ((OpDefOrDeclNode)((OpApplNode)operands[0]).getOperator()).getToolObject(toolId);
if (o instanceof SetEnumValue) {
return (SetEnumValue)o;
} else if (o instanceof WorkerValue) {
// If TLC was started with a -workers N specification, N > 1, o will be a WorkerValue instance
final WorkerValue wv = (WorkerValue)o;
final Object unwrapped = WorkerValue.mux(wv);
if (unwrapped instanceof SetEnumValue) {
return (SetEnumValue)unwrapped;
}
}
}
}
}
}
return null;
}
@Override
public final boolean hasSymmetry() {
if (this.config == null) {
return false;
}
final String name = this.config.getSymmetry();
return name.length() > 0;
}
@Override
public final Context getFcnContext(IFcnLambdaValue fcn, ExprOrOpArgNode[] args,
Context c, TLCState s0, TLCState s1,
final int control) {
return getFcnContext(fcn, args, c, s0, s1, control, CostModel.DO_NOT_RECORD);
}
@Override
public final Context getFcnContext(IFcnLambdaValue fcn, ExprOrOpArgNode[] args,
Context c, TLCState s0, TLCState s1,
final int control, CostModel cm) {
Context fcon = fcn.getCon();
int plen = fcn.getParams().length();
FormalParamNode[][] formals = fcn.getParams().getFormals();
Value[] domains = (Value[]) fcn.getParams().getDomains();
boolean[] isTuples = fcn.getParams().isTuples();
Value argVal = this.eval(args[1], c, s0, s1, control, cm);
if (plen == 1) {
if (!domains[0].member(argVal)) {
Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) +
",\nthe first argument is:\n" + Values.ppr(argVal.toString()) +
"which is not in its domain.\n" + args[0], args[0], c);
}
if (isTuples[0]) {
FormalParamNode[] ids = formals[0];
TupleValue tv = (TupleValue) argVal.toTuple();
if (tv == null || argVal.size() != ids.length) {
Assert.fail("In applying the function\n" + Values.ppr(this.toString()) +
",\nthe argument is:\n" + Values.ppr(argVal.toString()) +
"which does not match its formal parameter.\n" + args[0], args[0], c);
}
Value[] elems = tv.elems;
for (int i = 0; i < ids.length; i++) {
fcon = fcon.cons(ids[i], elems[i]);
}
}
else {
fcon = fcon.cons(formals[0][0], argVal);
}
}
else {
TupleValue tv = (TupleValue) argVal.toTuple();
if (tv == null) {
Assert.fail("Attempted to apply a function to an argument not in its" +
" domain.\n" + args[0], args[0], c);
}
int argn = 0;
Value[] elems = tv.elems;
for (int i = 0; i < formals.length; i++) {
FormalParamNode[] ids = formals[i];
Value domain = domains[i];
if (isTuples[i]) {
if (!domain.member(elems[argn])) {
Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) +
",\nthe argument number " + (argn+1) + " is:\n" +
Values.ppr(elems[argn].toString()) +
"\nwhich is not in its domain.\n" + args[0], args[0], c);
}
TupleValue tv1 = (TupleValue) elems[argn++].toTuple();
if (tv1 == null || tv1.size() != ids.length) {
Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) +
",\nthe argument number " + argn + " is:\n" +
Values.ppr(elems[argn-1].toString()) +
"which does not match its formal parameter.\n" + args[0], args[0], c);
}
Value[] avals = tv1.elems;
for (int j = 0; j < ids.length; j++) {
fcon = fcon.cons(ids[j], avals[j]);
}
}
else {
for (int j = 0; j < ids.length; j++) {
if (!domain.member(elems[argn])) {
Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) +
",\nthe argument number " + (argn+1) + " is:\n" +
Values.ppr(elems[argn].toString()) +
"which is not in its domain.\n" + args[0], args[0], c);
}
fcon = fcon.cons(ids[j], elems[argn++]);
}
}
}
}
return fcon;
}
@Override
public final IContextEnumerator contexts(OpApplNode appl, Context c, TLCState s0,
TLCState s1, final int control) {
return contexts(appl, c, s0, s1, control, CostModel.DO_NOT_RECORD);
}
/* A context enumerator for an operator application. */
public final ContextEnumerator contexts(OpApplNode appl, Context c, TLCState s0,
TLCState s1, final int control, CostModel cm) {
return contexts(Ordering.NORMALIZED, appl, c, s0, s1, control, cm);
}
private final ContextEnumerator contexts(Ordering ordering, OpApplNode appl, Context c, TLCState s0, TLCState s1, final int control,
CostModel cm) {
FormalParamNode[][] formals = appl.getBdedQuantSymbolLists();
boolean[] isTuples = appl.isBdedQuantATuple();
ExprNode[] domains = appl.getBdedQuantBounds();
int flen = formals.length;
int alen = 0;
for (int i = 0; i < flen; i++) {
alen += (isTuples[i]) ? 1 : formals[i].length;
}
Object[] vars = new Object[alen];
ValueEnumeration[] enums = new ValueEnumeration[alen];
int idx = 0;
for (int i = 0; i < flen; i++) {
Value boundSet = this.eval(domains[i], c, s0, s1, control, cm);
if (!(boundSet instanceof Enumerable)) {
Assert.fail("TLC encountered a non-enumerable quantifier bound\n" +
Values.ppr(boundSet.toString()) + ".\n" + domains[i], domains[i], c);
}
FormalParamNode[] farg = formals[i];
if (isTuples[i]) {
vars[idx] = farg;
enums[idx++] = ((Enumerable)boundSet).elements(ordering);
}
else {
for (int j = 0; j < farg.length; j++) {
vars[idx] = farg[j];
enums[idx++] = ((Enumerable)boundSet).elements(ordering);
}
}
}
return new ContextEnumerator(vars, enums, c);
}
// These three are expected by implementing the {@link ITool} interface; they used
// to mirror exactly methods that our parent class ({@link Spec}) implemented
// however those methods have changed signature with refactoring done for
// Issue #393
@Override
public Context getOpContext(OpDefNode odn, ExprOrOpArgNode[] args, Context ctx, boolean b) {
return getOpContext(odn, args, ctx, b, toolId);
}
@Override
public Object lookup(SymbolNode opNode, Context con, boolean b) {
return lookup(opNode, con, b, toolId);
}
@Override
public Object getVal(ExprOrOpArgNode expr, Context con, boolean b) {
return getVal(expr, con, b, toolId);
}
public static boolean isProbabilistic() {
return PROBABLISTIC;
}
}
|
package natlab.toolkits.analysis;
import ast.*;
import java.util.*;
/**
* Very General interface for analysis. Note: implementations should
* supply a standard constructor that takes in ASTNode as argument.
*/
public interface Analysis extends NodeCaseHandler
{
/**
* Executes the analysis.
*/
public void analyze();
/**
* Get the AST on which the analysis is being performed.
*
* @return ASTNode on which the analysis is performed.
*/
public ASTNode getTree();
/**
* Returns a boolean signifying whether or not the analysis has
* been performed on the given AST. This does not necessarily
* take into account changes to the AST.
*
* @return Whether or not the analysis has been performed.
*/
public boolean isAnalyzed();
/**
* Process the condition of a while loop or if stmt or any other
* statement that includes a condition.
*
* @param condExpr The condition expression to be handled.
*/
public void caseCondition( Expr condExpr );
/**
* Process the condition of a while loop.
*
* @param condExpr The condition expression to be handled.
*/
public void caseWhileCondition( Expr condExpr );
/**
* Process the condition of an if statement.
*
* @param condExpr The condition expression to be handled.
*/
public void caseIfCondition( Expr condExpr );
/**
* Process the loop variable assignment statement from a for
* loop.
*
* @param loopVar The loop variable assignment statement to be
* handled.
*/
public void caseLoopVar( AssignStmt loopVar );
/**
* Process the main expression of a case statement. This is the
* expression that you get as part of the switch header e.g.
*<pre>
* switch switchExpr
* case caseExpr
* ....
* end
*</pre>
*
*
* @param switchExpr The switch expression to process.
*/
public void caseSwitchExpr( Expr switchExpr );
/**
* sets the NodeCaseHandler that gets called first by the node's analyze
* method. The given NodeCaseHandler is responsible for calling back to
* the corresponding node case of this analysis.
*
* This should only be used internally.
*/
public void setCallback(NodeCaseHandler handler);
}
|
package pl.grzeslowski.jsupla.protocol.decoders;
import pl.grzeslowski.jsupla.protocol.calltypes.CallType;
import pl.grzeslowski.jsupla.protocol.structs.ds.DeviceServer;
public interface DecoderFactory {
<T extends DeviceServer> Decoder<T> getDecoderForCallType(CallType callType);
}
|
package org.bouncycastle.jcajce.provider.keystore.bc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyStoreException;
import java.security.KeyStoreSpi;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoServicesRegistrar;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator;
import org.bouncycastle.crypto.io.DigestInputStream;
import org.bouncycastle.crypto.io.DigestOutputStream;
import org.bouncycastle.crypto.io.MacInputStream;
import org.bouncycastle.crypto.io.MacOutputStream;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.jcajce.io.CipherInputStream;
import org.bouncycastle.jcajce.io.CipherOutputStream;
import org.bouncycastle.jcajce.util.BCJcaJceHelper;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.jce.interfaces.BCKeyStore;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Properties;
import org.bouncycastle.util.io.Streams;
import org.bouncycastle.util.io.TeeOutputStream;
public class BcKeyStoreSpi
extends KeyStoreSpi
implements BCKeyStore
{
private static final int STORE_VERSION = 2;
private static final int STORE_SALT_SIZE = 20;
private static final String STORE_CIPHER = "PBEWithSHAAndTwofish-CBC";
private static final int KEY_SALT_SIZE = 20;
private static final int MIN_ITERATIONS = 1024;
private static final String KEY_CIPHER = "PBEWithSHAAnd3-KeyTripleDES-CBC";
// generic object types
static final int NULL = 0;
static final int CERTIFICATE = 1;
static final int KEY = 2;
static final int SECRET = 3;
static final int SEALED = 4;
// key types
static final int KEY_PRIVATE = 0;
static final int KEY_PUBLIC = 1;
static final int KEY_SECRET = 2;
protected Hashtable table = new Hashtable();
protected SecureRandom random = CryptoServicesRegistrar.getSecureRandom();
protected int version;
private final JcaJceHelper helper = new BCJcaJceHelper();
public BcKeyStoreSpi(int version)
{
this.version = version;
}
private class StoreEntry
{
int type;
String alias;
Object obj;
Certificate[] certChain;
Date date = new Date();
StoreEntry(
String alias,
Certificate obj)
{
this.type = CERTIFICATE;
this.alias = alias;
this.obj = obj;
this.certChain = null;
}
StoreEntry(
String alias,
byte[] obj,
Certificate[] certChain)
{
this.type = SECRET;
this.alias = alias;
this.obj = obj;
this.certChain = certChain;
}
StoreEntry(
String alias,
Key key,
char[] password,
Certificate[] certChain)
throws Exception
{
this.type = SEALED;
this.alias = alias;
this.certChain = certChain;
byte[] salt = new byte[KEY_SALT_SIZE];
random.nextBytes(salt);
int iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
dOut.writeInt(salt.length);
dOut.write(salt);
dOut.writeInt(iterationCount);
Cipher cipher = makePBECipher(KEY_CIPHER, Cipher.ENCRYPT_MODE, password, salt, iterationCount);
CipherOutputStream cOut = new CipherOutputStream(dOut, cipher);
dOut = new DataOutputStream(cOut);
encodeKey(key, dOut);
dOut.close();
obj = bOut.toByteArray();
}
StoreEntry(
String alias,
Date date,
int type,
Object obj)
{
this.alias = alias;
this.date = date;
this.type = type;
this.obj = obj;
}
StoreEntry(
String alias,
Date date,
int type,
Object obj,
Certificate[] certChain)
{
this.alias = alias;
this.date = date;
this.type = type;
this.obj = obj;
this.certChain = certChain;
}
int getType()
{
return type;
}
String getAlias()
{
return alias;
}
Object getObject()
{
return obj;
}
Object getObject(
char[] password)
throws NoSuchAlgorithmException, UnrecoverableKeyException
{
if (password == null || password.length == 0)
{
if (obj instanceof Key)
{
return obj;
}
}
if (type == SEALED)
{
ByteArrayInputStream bIn = new ByteArrayInputStream((byte[])obj);
DataInputStream dIn = new DataInputStream(bIn);
try
{
byte[] salt = new byte[dIn.readInt()];
dIn.readFully(salt);
int iterationCount = dIn.readInt();
Cipher cipher = makePBECipher(KEY_CIPHER, Cipher.DECRYPT_MODE, password, salt, iterationCount);
CipherInputStream cIn = new CipherInputStream(dIn, cipher);
try
{
return decodeKey(new DataInputStream(cIn));
}
catch (Exception x)
{
bIn = new ByteArrayInputStream((byte[])obj);
dIn = new DataInputStream(bIn);
salt = new byte[dIn.readInt()];
dIn.readFully(salt);
iterationCount = dIn.readInt();
cipher = makePBECipher("Broken" + KEY_CIPHER, Cipher.DECRYPT_MODE, password, salt, iterationCount);
cIn = new CipherInputStream(dIn, cipher);
Key k = null;
try
{
k = decodeKey(new DataInputStream(cIn));
}
catch (Exception y)
{
bIn = new ByteArrayInputStream((byte[])obj);
dIn = new DataInputStream(bIn);
salt = new byte[dIn.readInt()];
dIn.readFully(salt);
iterationCount = dIn.readInt();
cipher = makePBECipher("Old" + KEY_CIPHER, Cipher.DECRYPT_MODE, password, salt, iterationCount);
cIn = new CipherInputStream(dIn, cipher);
k = decodeKey(new DataInputStream(cIn));
}
// reencrypt key with correct cipher.
if (k != null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
dOut.writeInt(salt.length);
dOut.write(salt);
dOut.writeInt(iterationCount);
Cipher out = makePBECipher(KEY_CIPHER, Cipher.ENCRYPT_MODE, password, salt, iterationCount);
CipherOutputStream cOut = new CipherOutputStream(dOut, out);
dOut = new DataOutputStream(cOut);
encodeKey(k, dOut);
dOut.close();
obj = bOut.toByteArray();
return k;
}
else
{
throw new UnrecoverableKeyException("no match");
}
}
}
catch (Exception e)
{
throw new UnrecoverableKeyException("no match");
}
}
else
{
throw new RuntimeException("forget something!");
// TODO
// if we get to here key was saved as byte data, which
// according to the docs means it must be a private key
// in EncryptedPrivateKeyInfo (PKCS8 format), later...
}
}
Certificate[] getCertificateChain()
{
return certChain;
}
Date getDate()
{
return date;
}
}
private void encodeCertificate(
Certificate cert,
DataOutputStream dOut)
throws IOException
{
try
{
byte[] cEnc = cert.getEncoded();
dOut.writeUTF(cert.getType());
dOut.writeInt(cEnc.length);
dOut.write(cEnc);
}
catch (CertificateEncodingException ex)
{
throw new IOException(ex.toString());
}
}
private Certificate decodeCertificate(
DataInputStream dIn)
throws IOException
{
String type = dIn.readUTF();
byte[] cEnc = new byte[dIn.readInt()];
dIn.readFully(cEnc);
try
{
CertificateFactory cFact = helper.createCertificateFactory(type);
ByteArrayInputStream bIn = new ByteArrayInputStream(cEnc);
return cFact.generateCertificate(bIn);
}
catch (NoSuchProviderException ex)
{
throw new IOException(ex.toString());
}
catch (CertificateException ex)
{
throw new IOException(ex.toString());
}
}
private void encodeKey(
Key key,
DataOutputStream dOut)
throws IOException
{
byte[] enc = key.getEncoded();
if (key instanceof PrivateKey)
{
dOut.write(KEY_PRIVATE);
}
else if (key instanceof PublicKey)
{
dOut.write(KEY_PUBLIC);
}
else
{
dOut.write(KEY_SECRET);
}
dOut.writeUTF(key.getFormat());
dOut.writeUTF(key.getAlgorithm());
dOut.writeInt(enc.length);
dOut.write(enc);
}
private Key decodeKey(
DataInputStream dIn)
throws IOException
{
int keyType = dIn.read();
String format = dIn.readUTF();
String algorithm = dIn.readUTF();
byte[] enc = new byte[dIn.readInt()];
KeySpec spec;
dIn.readFully(enc);
if (format.equals("PKCS#8") || format.equals("PKCS8"))
{
spec = new PKCS8EncodedKeySpec(enc);
}
else if (format.equals("X.509") || format.equals("X509"))
{
spec = new X509EncodedKeySpec(enc);
}
else if (format.equals("RAW"))
{
return new SecretKeySpec(enc, algorithm);
}
else
{
throw new IOException("Key format " + format + " not recognised!");
}
try
{
switch (keyType)
{
case KEY_PRIVATE:
return BouncyCastleProvider.getPrivateKey(PrivateKeyInfo.getInstance(enc));
case KEY_PUBLIC:
return BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(enc));
case KEY_SECRET:
return helper.createSecretKeyFactory(algorithm).generateSecret(spec);
default:
throw new IOException("Key type " + keyType + " not recognised!");
}
}
catch (Exception e)
{
throw new IOException("Exception creating key: " + e.toString());
}
}
protected Cipher makePBECipher(
String algorithm,
int mode,
char[] password,
byte[] salt,
int iterationCount)
throws IOException
{
try
{
PBEKeySpec pbeSpec = new PBEKeySpec(password);
SecretKeyFactory keyFact = helper.createSecretKeyFactory(algorithm);
PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount);
Cipher cipher = helper.createCipher(algorithm);
cipher.init(mode, keyFact.generateSecret(pbeSpec), defParams);
return cipher;
}
catch (Exception e)
{
throw new IOException("Error initialising store of key store: " + e);
}
}
public void setRandom(
SecureRandom rand)
{
this.random = rand;
}
public Enumeration engineAliases()
{
return table.keys();
}
public boolean engineContainsAlias(
String alias)
{
return (table.get(alias) != null);
}
public void engineDeleteEntry(
String alias)
throws KeyStoreException
{
Object entry = table.get(alias);
if (entry == null)
{
return;
}
table.remove(alias);
}
public Certificate engineGetCertificate(
String alias)
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null)
{
if (entry.getType() == CERTIFICATE)
{
return (Certificate)entry.getObject();
}
else
{
Certificate[] chain = entry.getCertificateChain();
if (chain != null)
{
return chain[0];
}
}
}
return null;
}
public String engineGetCertificateAlias(
Certificate cert)
{
Enumeration e = table.elements();
while (e.hasMoreElements())
{
StoreEntry entry = (StoreEntry)e.nextElement();
if (entry.getObject() instanceof Certificate)
{
Certificate c = (Certificate)entry.getObject();
if (c.equals(cert))
{
return entry.getAlias();
}
}
else
{
Certificate[] chain = entry.getCertificateChain();
if (chain != null && chain[0].equals(cert))
{
return entry.getAlias();
}
}
}
return null;
}
public Certificate[] engineGetCertificateChain(
String alias)
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null)
{
return entry.getCertificateChain();
}
return null;
}
public Date engineGetCreationDate(String alias)
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null)
{
return entry.getDate();
}
return null;
}
public Key engineGetKey(
String alias,
char[] password)
throws NoSuchAlgorithmException, UnrecoverableKeyException
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry == null || entry.getType() == CERTIFICATE)
{
return null;
}
return (Key)entry.getObject(password);
}
public boolean engineIsCertificateEntry(
String alias)
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null && entry.getType() == CERTIFICATE)
{
return true;
}
return false;
}
public boolean engineIsKeyEntry(
String alias)
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null && entry.getType() != CERTIFICATE)
{
return true;
}
return false;
}
public void engineSetCertificateEntry(
String alias,
Certificate cert)
throws KeyStoreException
{
StoreEntry entry = (StoreEntry)table.get(alias);
if (entry != null && entry.getType() != CERTIFICATE)
{
throw new KeyStoreException("key store already has a key entry with alias " + alias);
}
table.put(alias, new StoreEntry(alias, cert));
}
public void engineSetKeyEntry(
String alias,
byte[] key,
Certificate[] chain)
throws KeyStoreException
{
table.put(alias, new StoreEntry(alias, key, chain));
}
public void engineSetKeyEntry(
String alias,
Key key,
char[] password,
Certificate[] chain)
throws KeyStoreException
{
if ((key instanceof PrivateKey))
{
if (chain == null)
{
throw new KeyStoreException("no certificate chain for private key");
}
if (key.getEncoded() == null)
{
throw new KeyStoreException("cannot store protected private key");
}
}
try
{
table.put(alias, new StoreEntry(alias, key, password, chain));
}
catch (Exception e)
{
throw new BCKeyStoreException(e.toString(), e);
}
}
public int engineSize()
{
return table.size();
}
protected void loadStore(
InputStream in)
throws IOException
{
DataInputStream dIn = new DataInputStream(in);
int type = dIn.read();
while (type > NULL)
{
String alias = dIn.readUTF();
Date date = new Date(dIn.readLong());
int chainLength = dIn.readInt();
Certificate[] chain = null;
if (chainLength != 0)
{
chain = new Certificate[chainLength];
for (int i = 0; i != chainLength; i++)
{
chain[i] = decodeCertificate(dIn);
}
}
switch (type)
{
case CERTIFICATE:
Certificate cert = decodeCertificate(dIn);
table.put(alias, new StoreEntry(alias, date, CERTIFICATE, cert));
break;
case KEY:
Key key = decodeKey(dIn);
table.put(alias, new StoreEntry(alias, date, KEY, key, chain));
break;
case SECRET:
case SEALED:
byte[] b = new byte[dIn.readInt()];
dIn.readFully(b);
table.put(alias, new StoreEntry(alias, date, type, b, chain));
break;
default:
throw new IOException("Unknown object type in store.");
}
type = dIn.read();
}
}
protected void saveStore(
OutputStream out)
throws IOException
{
Enumeration e = table.elements();
DataOutputStream dOut = new DataOutputStream(out);
while (e.hasMoreElements())
{
StoreEntry entry = (StoreEntry)e.nextElement();
dOut.write(entry.getType());
dOut.writeUTF(entry.getAlias());
dOut.writeLong(entry.getDate().getTime());
Certificate[] chain = entry.getCertificateChain();
if (chain == null)
{
dOut.writeInt(0);
}
else
{
dOut.writeInt(chain.length);
for (int i = 0; i != chain.length; i++)
{
encodeCertificate(chain[i], dOut);
}
}
switch (entry.getType())
{
case CERTIFICATE:
encodeCertificate((Certificate)entry.getObject(), dOut);
break;
case KEY:
encodeKey((Key)entry.getObject(), dOut);
break;
case SEALED:
case SECRET:
byte[] b = (byte[])entry.getObject();
dOut.writeInt(b.length);
dOut.write(b);
break;
default:
throw new IOException("Unknown object type in store.");
}
}
dOut.write(NULL);
}
public void engineLoad(
InputStream stream,
char[] password)
throws IOException
{
table.clear();
if (stream == null) // just initialising
{
return;
}
DataInputStream dIn = new DataInputStream(stream);
int version = dIn.readInt();
if (version != STORE_VERSION)
{
if (version != 0 && version != 1)
{
throw new IOException("Wrong version of key store.");
}
}
int saltLength = dIn.readInt();
if (saltLength <= 0)
{
throw new IOException("Invalid salt detected");
}
byte[] salt = new byte[saltLength];
dIn.readFully(salt);
int iterationCount = dIn.readInt();
// we only do an integrity check if the password is provided.
HMac hMac = new HMac(new SHA1Digest());
if (password != null && password.length != 0)
{
byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
pbeGen.init(passKey, salt, iterationCount);
CipherParameters macParams;
if (version != 2)
{
macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize());
}
else
{
macParams = pbeGen.generateDerivedMacParameters(hMac.getMacSize() * 8);
}
Arrays.fill(passKey, (byte)0);
hMac.init(macParams);
MacInputStream mIn = new MacInputStream(dIn, hMac);
loadStore(mIn);
// Finalise our mac calculation
byte[] mac = new byte[hMac.getMacSize()];
hMac.doFinal(mac, 0);
// TODO Should this actually be reading the remainder of the stream?
// Read the original mac from the stream
byte[] oldMac = new byte[hMac.getMacSize()];
dIn.readFully(oldMac);
if (!Arrays.constantTimeAreEqual(mac, oldMac))
{
table.clear();
throw new IOException("KeyStore integrity check failed.");
}
}
else
{
loadStore(dIn);
// TODO Should this actually be reading the remainder of the stream?
// Parse the original mac from the stream too
byte[] oldMac = new byte[hMac.getMacSize()];
dIn.readFully(oldMac);
}
}
public void engineStore(OutputStream stream, char[] password)
throws IOException
{
DataOutputStream dOut = new DataOutputStream(stream);
byte[] salt = new byte[STORE_SALT_SIZE];
int iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
random.nextBytes(salt);
dOut.writeInt(version);
dOut.writeInt(salt.length);
dOut.write(salt);
dOut.writeInt(iterationCount);
HMac hMac = new HMac(new SHA1Digest());
MacOutputStream mOut = new MacOutputStream(hMac);
PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
pbeGen.init(passKey, salt, iterationCount);
if (version < 2)
{
hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize()));
}
else
{
hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize() * 8));
}
for (int i = 0; i != passKey.length; i++)
{
passKey[i] = 0;
}
saveStore(new TeeOutputStream(dOut, mOut));
byte[] mac = new byte[hMac.getMacSize()];
hMac.doFinal(mac, 0);
dOut.write(mac);
dOut.close();
}
/**
* the BouncyCastle store. This wont work with the key tool as the
* store is stored encrypted on disk, so the password is mandatory,
* however if you hard drive is in a bad part of town and you absolutely,
* positively, don't want nobody peeking at your things, this is the
* one to use, no problem! After all in a Bouncy Castle nothing can
* touch you.
*
* Also referred to by the alias UBER.
*/
public static class BouncyCastleStore
extends BcKeyStoreSpi
{
public BouncyCastleStore()
{
super(1);
}
public void engineLoad(
InputStream stream,
char[] password)
throws IOException
{
table.clear();
if (stream == null) // just initialising
{
return;
}
DataInputStream dIn = new DataInputStream(stream);
int version = dIn.readInt();
if (version != STORE_VERSION)
{
if (version != 0 && version != 1)
{
throw new IOException("Wrong version of key store.");
}
}
byte[] salt = new byte[dIn.readInt()];
if (salt.length != STORE_SALT_SIZE)
{
throw new IOException("Key store corrupted.");
}
dIn.readFully(salt);
int iterationCount = dIn.readInt();
if ((iterationCount < 0) || (iterationCount > (MIN_ITERATIONS << 6)))
{
throw new IOException("Key store corrupted.");
}
String cipherAlg;
if (version == 0)
{
cipherAlg = "Old" + STORE_CIPHER;
}
else
{
cipherAlg = STORE_CIPHER;
}
Cipher cipher = this.makePBECipher(cipherAlg, Cipher.DECRYPT_MODE, password, salt, iterationCount);
CipherInputStream cIn = new CipherInputStream(dIn, cipher);
Digest dig = new SHA1Digest();
DigestInputStream dgIn = new DigestInputStream(cIn, dig);
this.loadStore(dgIn);
// Finalise our digest calculation
byte[] hash = new byte[dig.getDigestSize()];
dig.doFinal(hash, 0);
// TODO Should this actually be reading the remainder of the stream?
// Read the original digest from the stream
byte[] oldHash = new byte[dig.getDigestSize()];
Streams.readFully(cIn, oldHash);
if (!Arrays.constantTimeAreEqual(hash, oldHash))
{
table.clear();
throw new IOException("KeyStore integrity check failed.");
}
}
public void engineStore(OutputStream stream, char[] password)
throws IOException
{
Cipher cipher;
DataOutputStream dOut = new DataOutputStream(stream);
byte[] salt = new byte[STORE_SALT_SIZE];
int iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
random.nextBytes(salt);
dOut.writeInt(version);
dOut.writeInt(salt.length);
dOut.write(salt);
dOut.writeInt(iterationCount);
cipher = this.makePBECipher(STORE_CIPHER, Cipher.ENCRYPT_MODE, password, salt, iterationCount);
CipherOutputStream cOut = new CipherOutputStream(dOut, cipher);
DigestOutputStream dgOut = new DigestOutputStream(new SHA1Digest());
this.saveStore(new TeeOutputStream(cOut, dgOut));
byte[] dig = dgOut.getDigest();
cOut.write(dig);
cOut.close();
}
}
public static class Std
extends BcKeyStoreSpi
{
public Std()
{
super(STORE_VERSION);
}
}
public static class Version1
extends BcKeyStoreSpi
{
public Version1()
{
super(1);
if (!Properties.isOverrideSet("org.bouncycastle.bks.enable_v1"))
{
throw new IllegalStateException("BKS-V1 not enabled");
}
}
}
private static class BCKeyStoreException
extends KeyStoreException
{
private final Exception cause;
public BCKeyStoreException(String msg, Exception cause)
{
super(msg);
this.cause = cause;
}
public Throwable getCause()
{
return cause;
}
}
}
|
package io.quantumdb.core.planner;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import com.google.common.collect.Sets;
import io.quantumdb.core.backends.PostgresqlDatabase;
import io.quantumdb.core.schema.definitions.Catalog;
import io.quantumdb.core.schema.definitions.Column;
import io.quantumdb.core.schema.definitions.Column.Hint;
import io.quantumdb.core.schema.definitions.PostgresTypes;
import io.quantumdb.core.schema.definitions.Table;
import io.quantumdb.core.versioning.RefLog;
import io.quantumdb.core.versioning.RefLog.ColumnRef;
import io.quantumdb.core.versioning.RefLog.TableRef;
import io.quantumdb.core.versioning.Version;
import org.junit.Rule;
import org.junit.Test;
public class SyncFunctionTest {
@Rule
public final PostgresqlDatabase database = new PostgresqlDatabase();
@Test
public void createSimpleSyncFunction() {
RefLog refLog = new RefLog();
Version v1 = new Version("v1", null);
Version v2 = new Version("v2", v1);
TableRef t1 = refLog.addTable("users", "table_a", v1,
new ColumnRef("id"),
new ColumnRef("name"));
TableRef t2 = refLog.addTable("users", "table_b", v2,
new ColumnRef("id", t1.getColumn("id")),
new ColumnRef("name", t1.getColumn("name")));
Catalog catalog = new Catalog(database.getCatalogName());
catalog.addTable(new Table("table_a")
.addColumn(new Column("id", PostgresTypes.bigint(), Hint.PRIMARY_KEY, Hint.AUTO_INCREMENT))
.addColumn(new Column("name", PostgresTypes.bigint(), Hint.NOT_NULL)));
catalog.addTable(new Table("table_b")
.addColumn(new Column("id", PostgresTypes.bigint(), Hint.PRIMARY_KEY, Hint.AUTO_INCREMENT))
.addColumn(new Column("name", PostgresTypes.bigint(), Hint.NOT_NULL)));
NullRecords nullRecords = new NullRecords(database.getConfig());
Map<ColumnRef, ColumnRef> columnMapping = refLog.getColumnMapping(t1, t2);
SyncFunction function = new SyncFunction(refLog, t1, t2, columnMapping, catalog, nullRecords,
"migrate_data", "migration_trigger");
function.setColumnsToMigrate(Sets.newHashSet("id", "name"));
String createFunctionStatement = function.createFunctionStatement().toString();
String createTriggerStatement = function.createTriggerStatement().toString();
assertEquals("CREATE OR REPLACE FUNCTION \"migrate_data\"() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'INSERT' THEN INSERT INTO \"table_b\" (\"name\", \"id\") VALUES (NEW.\"name\", NEW.\"id\"); ELSIF TG_OP = 'UPDATE' THEN LOOP UPDATE \"table_b\" SET \"id\" = NEW.\"id\", \"name\" = NEW.\"name\" WHERE \"id\" = OLD.\"id\"; IF found THEN EXIT; END IF; BEGIN INSERT INTO \"table_b\" (\"name\", \"id\") VALUES (NEW.\"name\", NEW.\"id\"); EXIT; EXCEPTION WHEN unique_violation THEN END; END LOOP; ELSIF TG_OP = 'DELETE' THEN DELETE FROM \"table_b\" WHERE \"id\" = OLD.\"id\"; END IF; RETURN NEW; END; $$ LANGUAGE 'plpgsql';", createFunctionStatement);
assertEquals("CREATE TRIGGER \"migration_trigger\" AFTER INSERT OR UPDATE OR DELETE ON \"table_a\" FOR EACH ROW WHEN (pg_trigger_depth() = 0) EXECUTE PROCEDURE \"migrate_data\"();", createTriggerStatement);
}
}
|
package com.rho.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import javolution.io.UTF8StreamReader;
import com.rho.RhoClassFactory;
//import com.rho.RhoConf;
import com.rho.RhoConf;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.SimpleFile;
import com.rho.IRAFile;
import com.rho.Tokenizer;
import java.util.Enumeration;
import java.util.Hashtable;
public class NetRequest
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Net");
static final int MAX_NETREQUEST_RETRY = 1;
boolean m_bCancel = false;
public static interface IRhoSession
{
public abstract void logout()throws Exception;
public abstract String getSession();
}
private IHttpConnection m_connection = null;
//private char[] m_charBuffer = new char[1024];
public byte[] m_byteBuffer = new byte[4096];
private boolean m_bIgnoreSuffixOnSim = true;
private Hashtable m_OutHeaders;
public boolean isCancelled(){ return m_bCancel;}
public NetResponse pullData(String strUrl, IRhoSession oSession ) throws Exception
{
return doRequestTry(strUrl, "", oSession);
}
private NetResponse doRequestTry(String strUrl, String strBody, IRhoSession oSession ) throws Exception
{
NetResponse resp = null;
int nTry = 0;
m_bCancel = false;
do
{
try{
resp = doRequest(strBody != null && strBody.length() > 0 ? "POST" : "GET", strUrl, strBody, oSession, null);
break;
}catch(IOException exc)
{
if ( m_bCancel )
break;
if ( nTry+1 >= MAX_NETREQUEST_RETRY )
throw exc;
}
nTry++;
}while( true );
return resp;
}
private void writeHeaders(Hashtable headers) throws Exception
{
if (headers != null && headers.size() > 0)
{
Enumeration valsHeaders = headers.elements();
Enumeration keysHeaders = headers.keys();
while (valsHeaders.hasMoreElements())
{
String strName = (String)keysHeaders.nextElement();
String strValue = (String)valsHeaders.nextElement();
m_connection.setRequestProperty(strName,strValue);
}
}
}
private void readHeaders(Hashtable headers) throws Exception
{
if ( headers != null )
{
m_OutHeaders = new Hashtable();
for (int i = 0;; i++) {
String strField = m_connection.getHeaderFieldKey(i);
if (strField == null && i > 0)
break;
if (strField != null )
{
String header_field = m_connection.getHeaderField(i);
m_OutHeaders.put(strField, header_field);
}
}
}
}
public static void copyHashtable(Hashtable from, Hashtable to)
{
if ( from == null || to == null )
return;
Enumeration valsHeaders = from.elements();
Enumeration keysHeaders = from.keys();
while (valsHeaders.hasMoreElements())
{
Object key = (String)keysHeaders.nextElement();
Object value = (String)valsHeaders.nextElement();
to.put(key, value);
}
}
public NetResponse doRequest(String strMethod, String strUrl, String strBody, IRhoSession oSession, Hashtable headers ) throws Exception
{
String strRespBody = null;
InputStream is = null;
OutputStream os = null;
int code = -1;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, m_bIgnoreSuffixOnSim);
if ( oSession != null )
{
String strSession = oSession.getSession();
LOG.INFO("Cookie : " + (strSession != null ? strSession : "") );
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
m_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
m_connection.setRequestProperty("Connection", "keep-alive");
//m_connection.setRequestProperty("Accept", "application/x-www-form-urlencoded,application/json,text/html");
writeHeaders(headers);
if ( strBody != null && strBody.length() > 0 )
{
m_connection.setRequestMethod(strMethod);
os = m_connection.openOutputStream();
os.write(strBody.getBytes(), 0, strBody.length());
}else
m_connection.setRequestMethod(strMethod);
is = m_connection.openInputStream();
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
if (code != IHttpConnection.HTTP_OK)
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED)
oSession.logout();
//if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
{
strRespBody = readFully(is);
if ( code == IHttpConnection.HTTP_MOVED_TEMPORARILY ||
code == IHttpConnection.HTTP_MOVED_PERMANENTLY )
LOG.INFO("Response body: " + strRespBody );
else
LOG.TRACE("Response body: " + strRespBody );
}
}else
{
long len = m_connection.getLength();
LOG.INFO("fetchRemoteData data size:" + len );
strRespBody = readFully(is);
LOG.INFO("fetchRemoteData data readFully.");
}
readHeaders(headers);
copyHashtable(m_OutHeaders, headers);
}finally
{
if ( is != null )
try{ is.close(); }catch(IOException exc){}
if ( os != null )
try{ os.close(); }catch(IOException exc){}
closeConnection();
m_bIgnoreSuffixOnSim = true;
}
return new NetResponse(strRespBody != null ? strRespBody : "", code );
}
public NetResponse pushData(String strUrl, String strBody, IRhoSession oSession)throws Exception
{
return doRequest("POST", strUrl, strBody, oSession, null);
}
static class ParsedCookie {
String strAuth = "";
String strSession = "";
};
public NetResponse pullCookies(String strUrl, String strBody, IRhoSession oSession)throws Exception
{
Hashtable headers = new Hashtable();
m_bIgnoreSuffixOnSim = false;
NetResponse resp = doRequest/*Try*/("POST", strUrl, strBody, oSession, headers);
if ( resp.isOK() )
{
ParsedCookie cookie = makeCookie(headers);
//if ( cookie.strAuth.length() > 0 || cookie.strSession.length() >0 )
resp.setCharData(cookie.strAuth + ";" + cookie.strSession + ";");
//else
// resp.setCharData("");
LOG.INFO("pullCookies: " + resp.getCharData() );
}
return resp;
}
static String szMultipartPrefix =
"
"Content-Disposition: form-data; name=\"blob\"; filename=\"doesnotmatter.png\"\r\n"+
"Content-Type: application/octet-stream\r\n\r\n";
static String szMultipartPostfix =
"\r\n
static String szMultipartContType =
"multipart/form-data; boundary=
public NetResponse pushFile( String strUrl, String strFileName, IRhoSession oSession, Hashtable headers)throws Exception
{
SimpleFile file = null;
NetResponse resp = null;
try{
file = RhoClassFactory.createFile();
file.open(strFileName, true, true);
if ( !file.isOpened() ){
LOG.ERROR("File not found: " + strFileName);
throw new RuntimeException("File not found:" + strFileName);
}
int nTry = 0;
do{
try{
resp = pushFile1(strUrl, file, oSession, headers );
break;
}catch(IOException e)
{
if ( nTry+1 >= MAX_NETREQUEST_RETRY )
throw e;
}
nTry++;
}while( true );
}finally{
if ( file != null )
try{ file.close(); }catch(IOException e){}
}
copyHashtable(m_OutHeaders, headers);
return resp;
}
private NetResponse pushFile1( String strUrl, SimpleFile file, IRhoSession oSession, Hashtable headers)throws Exception
{
String strRespBody = null;
InputStream is = null;
OutputStream os = null;
InputStream fis = null;
int code = -1;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, false);
if ( oSession != null )
{
String strSession = oSession.getSession();
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
m_connection.setRequestProperty("content-type", szMultipartContType);
writeHeaders(headers);
m_connection.setRequestMethod(IHttpConnection.POST);
//PUSH specific
os = m_connection.openOutputStream();
os.write(szMultipartPrefix.getBytes(), 0, szMultipartPrefix.length());
fis = file.getInputStream();
synchronized (m_byteBuffer) {
int nRead = 0;
do{
nRead = fis.read(m_byteBuffer);
if ( nRead > 0 )
os.write(m_byteBuffer, 0, nRead);
}while( nRead > 0 );
}
os.write(szMultipartPostfix.getBytes(), 0, szMultipartPostfix.length());
os.flush();
//PUSH specific
is = m_connection.openInputStream();
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
if (code != IHttpConnection.HTTP_OK)
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED)
oSession.logout();
if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
strRespBody = readFully(is);
}else
{
long len = m_connection.getLength();
LOG.INFO("fetchRemoteData data size:" + len );
strRespBody = readFully(is);
LOG.INFO("fetchRemoteData data readFully.");
}
readHeaders(headers);
}finally{
try{
if (fis != null)
fis.close();
if ( is != null )
is.close();
if (os != null)
os.close();
closeConnection();
}catch(IOException exc2){}
}
return new NetResponse(strRespBody != null ? strRespBody : "", code );
}
long m_nMaxPacketSize = 0;
int m_nCurDownloadSize = 0;
boolean m_bFlushFileAfterWrite = false;
public NetResponse pullFile( String strUrl, String strFileName, IRhoSession oSession, Hashtable headers )throws Exception
{
IRAFile file = null;
NetResponse resp = null;
m_nMaxPacketSize = RhoClassFactory.getNetworkAccess().getMaxPacketSize();
m_bFlushFileAfterWrite = RhoConf.getInstance().getBool("use_persistent_storage");
try{
if (!strFileName.startsWith("file:")) {
try{
//TODO: implement FilePath.join
String url = RhoClassFactory.createFile().getDirPath("");
if ( strFileName.charAt(0) == '/' || strFileName.charAt(0) == '\\' )
url += strFileName.substring(1);
else
url += strFileName;
strFileName = url;
} catch (IOException x) {
LOG.ERROR("getDirPath failed.", x);
throw x;
}
}
file = RhoClassFactory.createRAFile();
file.open(strFileName, "rw");
file.seek(file.size());
int nFailTry = 0;
do{
try{
resp = pullFile1( strUrl, file, file.size(), oSession, headers );
}catch(IOException e)
{
if ( m_bCancel || nFailTry+1 >= MAX_NETREQUEST_RETRY )
throw e;
nFailTry++;
m_nCurDownloadSize = 1;
}
}while( !m_bCancel && (resp == null || resp.isOK()) && m_nCurDownloadSize > 0 && m_nMaxPacketSize > 0 );
}finally{
if ( file != null )
{
file.close();
file = null;
}
}
copyHashtable(m_OutHeaders, headers);
return resp != null && !m_bCancel ? resp : new NetResponse("", IHttpConnection.HTTP_INTERNAL_ERROR );
}
static byte[] m_byteDownloadBuffer = new byte[1024*20];
NetResponse pullFile1( String strUrl, IRAFile file, long nStartPos, IRhoSession oSession, Hashtable headers )throws Exception
{
String strRespBody = null;
InputStream is = null;
int code = -1;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, true);
if (oSession!= null)
{
String strSession = oSession.getSession();
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
m_connection.setRequestProperty("Connection", "keep-alive");
if ( nStartPos > 0 || m_nMaxPacketSize > 0 )
{
if ( m_nMaxPacketSize > 0 )
m_connection.setRequestProperty("Range", "bytes="+nStartPos+"-" + (nStartPos + m_nMaxPacketSize-1));
else
m_connection.setRequestProperty("Range", "bytes="+nStartPos+"-");
}
writeHeaders(headers);
m_connection.setRequestMethod(IHttpConnection.GET);
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
m_nCurDownloadSize = 0;
if ( code == IHttpConnection.HTTP_RANGENOTSATISFY )
code = IHttpConnection.HTTP_PARTIAL_CONTENT;
else
{
if (code != IHttpConnection.HTTP_OK && code != IHttpConnection.HTTP_PARTIAL_CONTENT )
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED)
oSession.logout();
if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
{
is = m_connection.openInputStream();
strRespBody = readFully(is);
}
}else
{
int nRead = 0;
is = m_connection.openInputStream();
do{
nRead = /*bufferedReadByByte(m_byteBuffer, is);*/is.read(m_byteDownloadBuffer);
if ( nRead > 0 )
{
file.write(m_byteDownloadBuffer, 0, nRead);
if (m_bFlushFileAfterWrite)
file.sync();
m_nCurDownloadSize += nRead;
}
}while( !m_bCancel && nRead >= 0 );
if ( code == IHttpConnection.HTTP_PARTIAL_CONTENT && isFinishDownload() )
m_nCurDownloadSize = 0;
}
}
readHeaders(headers);
}finally
{
if ( is != null )
try{ is.close(); }catch(IOException exc){}
closeConnection();
}
return new NetResponse(strRespBody != null ? strRespBody : "", code );
}
private boolean isFinishDownload()throws IOException
{
String strContRange = m_connection.getHeaderField("Content-Range");
if ( strContRange != null )
{
int nMinus = strContRange.indexOf('-');
if ( nMinus > 0 )
{
int nSep = strContRange.indexOf('/', nMinus);
if ( nSep > 0 )
{
String strHigh = strContRange.substring(nMinus+1,nSep);
String strTotal = strContRange.substring(nSep+1);
if ( Integer.parseInt(strHigh) + 1 >= Integer.parseInt(strTotal) )
return true;
}
}
}
return false;
}
public String resolveUrl(String url) throws Exception
{
if ( url == null || url.length() == 0 )
return "";
String _httpRoot = RhoClassFactory.getNetworkAccess().getHomeUrl();
if(!_httpRoot.endsWith("/"))
_httpRoot = _httpRoot + "/";
url.replace('\\', '/');
if ( !url.startsWith(_httpRoot) ){
if ( url.charAt(0) == '/' )
url = _httpRoot.substring(0, _httpRoot.length()-1) + url;
else
url = _httpRoot + url;
}
return url;
}
public void cancel()
{
m_bCancel = true;
closeConnection();
}
private static void parseCookie(String value, ParsedCookie cookie) {
boolean bAuth = false;
boolean bSession = false;
Tokenizer stringtokenizer = new Tokenizer(value, ";");
while (stringtokenizer.hasMoreTokens()) {
String tok = stringtokenizer.nextToken();
tok = tok.trim();
if (tok.length() == 0) {
continue;
}
int i = 0;
if ( (i=tok.indexOf("auth_token=")) >= 0 )
{
String val = tok.substring(i+11);
val.trim();
if ( val.length() > 0 )
{
cookie.strAuth = "auth_token=" + val;
bAuth = true;
}
}else if ( (i=tok.indexOf("path=")) >= 0 )
{
String val = tok.substring(i+6);
val.trim();
if ( val.length() > 0 )
{
if (bAuth)
cookie.strAuth += ";path=" + val;
else if (bSession)
cookie.strSession += ";path=" + val;
}
}else if ( (i=tok.indexOf("rhosync_session=")) >= 0 )
{
String val = tok.substring(i+16);
val.trim();
if ( val.length() > 0 )
{
cookie.strSession = "rhosync_session=" + val;
bSession = true;
}
}
}
}
private static String extractToc(String toc_name, String data) {
int start = data.indexOf(toc_name);
if (start != -1) {
int end = data.indexOf(';', start);
if (end != -1) {
return data.substring(start, end);
}
}
return null;
}
/*public static void TEST()
{
ParsedCookie cookie = new ParsedCookie();
//parseCookie("auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT, auth_token=887b2ffd30a7b97be9a0986d7746a934421eec7d; path=/; expires=Sat, 24 Oct 2009 20:56:55 GMT, rhosync_session=BAh7BzoMdXNlcl9pZGkIIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--f9b67d99397fc534107fb3b7483ccdae23b4a761; path=/; expires=Sun, 10 Oct 2010 19:10:58 GMT; HttpOnly", cookie);
parseCookie("auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT", cookie);
parseCookie("rhosync_session=BAh7CToNcGFzc3dvcmQiFTiMYru1W11zuoAlN%2FPtgjc6CmxvZ2luIhU4jGK7tVtdc7qAJTfz7YI3Ogx1c2VyX2lkaQYiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA%3D--a7829a70171203d72cd4e83d07b18e8fcf5e2f78; path=/; expires=Thu, 02 Sep 2010 23:51:31 GMT; HttpOnly", cookie);
}*/
private static ParsedCookie makeCookie(Hashtable headers)
throws IOException
{
ParsedCookie cookie = new ParsedCookie();
Enumeration valsHeaders = headers.elements();
Enumeration keysHeaders = headers.keys();
while (valsHeaders.hasMoreElements())
{
String strName = (String)keysHeaders.nextElement();
String strValue = (String)valsHeaders.nextElement();
if (strName.equalsIgnoreCase("Set-Cookie"))
{
LOG.INFO("Set-Cookie: " + strValue);
parseCookie(strValue, cookie);
// Hack to make it work on 4.6 device which doesn't parse
// cookies correctly
// if (cookie.strAuth==null) {
// String auth = extractToc("auth_token", header_field);
// cookie.strAuth = auth;
// System.out.println("Extracted auth_token: " + auth);
if (cookie.strSession == null) {
String rhosync_session = extractToc("rhosync_session", strValue);
cookie.strSession = rhosync_session;
LOG.INFO("Extracted rhosync_session: " + rhosync_session);
}
}
}
return cookie;
}
/*
private final StringBuffer readFully(InputStream in) throws Exception
{
boolean bReadByBytes = false;
if ( RhoConf.getInstance().getInt("bb_netreadbybytes") > 0 )
bReadByBytes = RhoClassFactory.createRhoRubyHelper().isSimulator();
StringBuffer buffer = new StringBuffer();
UTF8StreamReader reader = new UTF8StreamReader(4096,bReadByBytes);
reader.setInput(in);
while (true) {
synchronized (m_charBuffer) {
int len = reader.read(m_charBuffer);
if (len < 0) {
break;
}
buffer.append(m_charBuffer, 0, len);
}
}
return buffer;
}*/
private final String readFully(InputStream in) throws Exception
{
String strRes = "";
synchronized (m_byteBuffer) {
int nRead = 0;
do{
nRead = in.read(m_byteBuffer);
if (nRead>0)
{
String strTemp = new String(m_byteBuffer,0,nRead);
strRes += strTemp;
}
}while( nRead > 0 );
}
return strRes;
}
/*
private final int bufferedRead(byte[] a, InputStream in) throws Exception {
int bytesRead = 0;
while (bytesRead < (a.length)) {
int read = in.read(a);//, bytesRead, (a.length - bytesRead));
if (read < 0) {
break;
}
bytesRead += read;
}
return bytesRead;
}
private final int bufferedReadByByte(byte[] a, InputStream in) throws IOException {
int bytesRead = 0;
while (bytesRead < (a.length)) {
int read = in.read();// a, 0, a.length );
if (read < 0) {
return bytesRead > 0 ? bytesRead : -1;
}
a[bytesRead] = (byte)read;
bytesRead ++;
}
return bytesRead;
}*/
public void closeConnection(){
if ( m_connection != null ){
try{
m_connection.close();
}catch(IOException exc){
LOG.ERROR("There was an error close connection", exc);
}
}
m_connection = null;
}
}
|
package net.sandius.rembulan.gen;
import net.sandius.rembulan.core.CallInfo;
import net.sandius.rembulan.core.ControlThrowable;
import net.sandius.rembulan.core.Coroutine;
import net.sandius.rembulan.core.Function;
import net.sandius.rembulan.core.LuaState;
import net.sandius.rembulan.core.ObjectStack;
import net.sandius.rembulan.core.OpCode;
import net.sandius.rembulan.core.Operators;
import net.sandius.rembulan.core.Preempted;
import net.sandius.rembulan.util.Check;
import net.sandius.rembulan.util.ReadOnlyArray;
import net.sandius.rembulan.util.asm.ASMUtils;
import org.objectweb.asm.*;
import static org.objectweb.asm.Opcodes.*;
public class LuaBytecodeMethodVisitor extends MethodVisitor implements InstructionEmitter {
private static Type REGISTERS_TYPE = ASMUtils.arrayTypeFor(Object.class);
private static final int REGISTER_OFFSET = 5;
private static final int LVAR_THIS = 0;
private static final int LVAR_COROUTINE = 1;
private static final int LVAR_BASE = 2;
private static final int LVAR_RETURN_BASE = 3;
private static final int LVAR_PC = 4;
private final Type thisType;
private final ReadOnlyArray<Object> constants;
private final int numRegs;
private Label l_first;
private Label l_last;
private Label l_default;
private Label l_save_and_yield;
private final int numInstrs;
private Label[] l_pc_begin;
private Label[] l_pc_end;
private Label[] l_pc_preempt_handler;
protected InstructionEmitter ie;
public static void emitConstructor(ClassVisitor cv, Type thisType) {
Type ctorType = Type.getMethodType(
Type.VOID_TYPE
);
MethodVisitor mv = cv.visitMethod(ACC_PUBLIC, "<init>", ctorType.getDescriptor(), null, null);
mv.visitCode();
Label l_begin = new Label();
mv.visitLabel(l_begin);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Function.class), "<init>", ctorType.getDescriptor(), false);
mv.visitInsn(RETURN);
Label l_end = new Label();
mv.visitLabel(l_end);
mv.visitLocalVariable("this", thisType.getDescriptor(), null, l_begin, l_end, 0);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
public LuaBytecodeMethodVisitor(ClassVisitor cv, Type thisType, ReadOnlyArray<Object> constants, int numInstrs, int numRegs) {
super(ASM5);
Check.notNull(cv);
Check.notNull(thisType);
this.thisType = thisType;
this.constants = constants;
this.numRegs = numRegs;
this.numInstrs = numInstrs;
ie = this;
Type resumeType = Type.getMethodType(
Type.VOID_TYPE,
Type.getType(Coroutine.class),
Type.INT_TYPE,
Type.INT_TYPE,
Type.INT_TYPE
);
l_first = new Label();
l_last = new Label();
l_save_and_yield = new Label();
l_default = new Label();
// luapc-to-jvmpc mapping
l_pc_begin = new Label[numInstrs];
l_pc_end = new Label[numInstrs];
l_pc_preempt_handler = new Label[numInstrs];
for (int i = 0; i < l_pc_begin.length; i++) {
l_pc_begin[i] = new Label();
l_pc_end[i] = new Label();
l_pc_preempt_handler[i] = new Label();
}
mv = cv.visitMethod(ACC_PUBLIC, "resume", resumeType.getDescriptor(),
null,
new String[] { Type.getInternalName(ControlThrowable.class) });
}
public void begin() {
visitParameter("coroutine", 0);
visitParameter("base", 0);
visitParameter("returnBase", 0);
visitParameter("pc", 0);
visitCode();
luaCodeBegin();
}
public void end() {
luaCodeEnd();
mv.visitLabel(l_last);
visitLocalVariable("this", thisType.getDescriptor(), null, l_first, l_last, LVAR_THIS);
visitLocalVariable("coroutine", Type.getDescriptor(Coroutine.class), null, l_first, l_last, LVAR_COROUTINE);
visitLocalVariable("base", Type.INT_TYPE.getDescriptor(), null, l_first, l_last, LVAR_BASE);
visitLocalVariable("returnBase", Type.INT_TYPE.getDescriptor(), null, l_first, l_last, LVAR_RETURN_BASE);
visitLocalVariable("pc", Type.INT_TYPE.getDescriptor(), null, l_first, l_last, LVAR_PC);
// registers
for (int i = 0; i < numRegs; i++) {
visitLocalVariable("r_" + (i + 1), Type.getDescriptor(Object.class), null, l_first, l_last, REGISTER_OFFSET + i);
}
visitMaxs(numRegs + 5, REGISTER_OFFSET + numRegs);
visitEnd();
System.err.println("Begin: " + l_first.getOffset());
System.err.println("Save-and-yield: " + l_save_and_yield.getOffset());
System.err.println("Error branch: " + l_default.getOffset());
System.err.println("End: " + l_last.getOffset());
for (int i = 0; i < numInstrs; i++) {
System.err.println("Handler for pc=" + i + ": [" + l_pc_begin[i].getOffset() + ", " + l_pc_end[i].getOffset() + ") -> " + l_pc_preempt_handler[i].getOffset());
}
}
public void luaCodeBegin() {
preamble();
}
public void luaCodeEnd() {
visitLabel(l_pc_end[numInstrs - 1]);
// visitInsn(NOP);
emitPreemptHandlers();
emitSaveRegistersAndThrowBranch();
emitErrorBranch();
}
// save registers and yield
// pc must be saved by now
// control throwable is on the stack top
public void emitSaveRegistersAndThrowBranch() {
visitLabel(l_save_and_yield);
visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{Type.getInternalName(ControlThrowable.class)});
saveRegisters();
pushCallInfoAndThrow();
}
private void constructCallInfo() {
visitTypeInsn(NEW, Type.getInternalName(CallInfo.class));
visitInsn(DUP);
visitVarInsn(ALOAD, LVAR_THIS);
visitVarInsn(ILOAD, LVAR_BASE);
visitVarInsn(ILOAD, LVAR_RETURN_BASE);
loadPc();
visitMethodInsn(INVOKESPECIAL, Type.getInternalName(CallInfo.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Function.class), Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE), false);
}
private void pushCallInfoAndThrow() {
// control throwable is on the stack top
visitInsn(DUP);
constructCallInfo();
visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(ControlThrowable.class), "push", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(CallInfo.class)), false);
visitInsn(ATHROW);
}
// error branch
public void emitErrorBranch() {
visitLabel(l_default);
visitLineNumber(2, l_default);
visitFrame(Opcodes.F_SAME, 0, null, 0, null);
visitTypeInsn(NEW, Type.getInternalName(IllegalStateException.class)); // TODO: use a more precise exception
visitInsn(DUP);
visitMethodInsn(INVOKESPECIAL, Type.getInternalName(IllegalStateException.class), "<init>", "()V", false);
visitInsn(ATHROW);
}
public void preemptHandler(int pc) {
visitLabel(l_pc_preempt_handler[pc]);
visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { Type.getInternalName(ControlThrowable.class) });
savePc(pc);
visitJumpInsn(GOTO, l_save_and_yield);
}
public void declarePreemptHandler(int pc) {
visitTryCatchBlock(l_pc_begin[pc], l_pc_end[pc], l_pc_preempt_handler[pc], Type.getInternalName(ControlThrowable.class));
}
public void declarePreemptHandlers() {
for (int i = 0; i < numInstrs; i++) {
declarePreemptHandler(i);
}
}
public void emitPreemptHandlers() {
for (int i = 0; i < numInstrs; i++) {
preemptHandler(i);
}
}
public void preamble() {
declarePreemptHandlers();
visitLabel(l_first);
visitLineNumber(2, l_first);
loadRegisters();
Object[] regTypes = new Object[numRegs];
for (int i = 0; i < regTypes.length; i++) {
regTypes[i] = Type.getInternalName(Object.class);
}
visitFrame(Opcodes.F_APPEND, numRegs, regTypes, 0, null);
// branch according to the program counter
preambleSwitch();
}
private void preambleSwitch() {
loadPc();
mv.visitTableSwitchInsn(0, numInstrs - 1, l_default, l_pc_begin);
}
private void pushThis() {
visitVarInsn(ALOAD, LVAR_THIS);
}
private void pushCoroutine() {
visitVarInsn(ALOAD, LVAR_COROUTINE);
}
private void pushRegister(int idx) {
visitVarInsn(ALOAD, REGISTER_OFFSET + idx);
}
private void pushIntoRegister(int idx) {
visitVarInsn(ASTORE, REGISTER_OFFSET + idx);
}
private void pushInt(int i) {
if (i >= -1 && i <= 5) mv.visitInsn(ICONST_0 + i);
else mv.visitLdcInsn(i);
}
private void pushLong(long l) {
if (l >= 0 && l <= 1) mv.visitInsn(LCONST_0 + (int) l);
else mv.visitLdcInsn(l);
}
private void pushFloat(float f) {
if (f == 0.0f) mv.visitInsn(FCONST_0);
else if (f == 1.0f) mv.visitInsn(FCONST_1);
else if (f == 2.0f) mv.visitInsn(FCONST_2);
else mv.visitLdcInsn(f);
}
public void pushDouble(double d) {
if (d == 0.0) mv.visitInsn(DCONST_0);
else if (d == 1.0) mv.visitInsn(DCONST_1);
else mv.visitLdcInsn(d);
}
public void pushString(String s) {
Check.notNull(s);
mv.visitLdcInsn(s);
}
private void pushBasePlus(int offset) {
// pushThis();
visitVarInsn(ILOAD, LVAR_BASE);
if (offset > 0) {
pushInt(offset);
mv.visitInsn(IADD);
}
}
private void pushObjectStack() {
pushCoroutine();
visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Coroutine.class), "getObjectStack", Type.getMethodDescriptor(Type.getType(ObjectStack.class)), false);
}
private void loadRegister(int idx) {
Check.nonNegative(idx);
pushObjectStack();
pushBasePlus(idx);
visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(ObjectStack.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), false);
visitVarInsn(ASTORE, REGISTER_OFFSET + idx);
}
private void saveRegister(int idx) {
Check.nonNegative(idx);
pushObjectStack();
pushBasePlus(idx);
pushRegister(idx);
visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(ObjectStack.class), "set", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(Object.class)), false);
}
public void loadRegisters() {
// load registers into local variables
for (int i = 0; i < numRegs; i++) {
loadRegister(i);
}
}
public void saveRegisters() {
for (int i = 0; i < numRegs; i++) {
saveRegister(i);
}
}
public void loadPc() {
visitVarInsn(ILOAD, LVAR_PC);
}
public void savePc(int pc) {
pushInt(pc);
visitVarInsn(ISTORE, LVAR_PC);
}
public void setTop(int to) {
pushObjectStack();
pushBasePlus(to);
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(ObjectStack.class), "setTop", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false);
}
private void checkPreemptFromHere(int pc) {
pushCoroutine();
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Coroutine.class), "getOwnerState", Type.getMethodDescriptor(Type.getType(LuaState.class)), false);
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(LuaState.class), "shouldPreemptNow", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), false);
mv.visitJumpInsn(IFEQ, l_pc_begin[pc]); // continue with pc + 1
pushPreemptThrowable();
visitJumpInsn(GOTO, l_pc_preempt_handler[pc]);
}
public void atPc(int pc, int lineNumber) {
if (pc > 0) {
mv.visitLabel(l_pc_end[pc - 1]);
checkPreemptFromHere(pc);
}
// declarePreemptHandler(pc);
mv.visitLabel(l_pc_begin[pc]);
if (lineNumber > 0) mv.visitLineNumber(lineNumber, l_pc_begin[pc]);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
public void pushPreemptThrowable() {
visitMethodInsn(INVOKESTATIC, Type.getInternalName(Preempted.class), "newInstance", Type.getMethodDescriptor(Type.getType(Preempted.class)), false);
}
// public void rethrow() {
// mv.visitInsn(ATHROW);
// public void preempted() {
// pushPreemptThrowable();
// rethrow();
public void pushConstant(int idx) {
Object c = constants.get(idx);
if (c instanceof Integer) {
pushInt((Integer) c);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
}
else if (c instanceof Long) {
pushLong((Long) c);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
}
else if (c instanceof Float) {
pushFloat((Float) c);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
}
else if (c instanceof Double) {
pushDouble((Double) c);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
}
else if (c instanceof String) {
pushString((String) c);
}
else {
throw new IllegalArgumentException("Unsupported constant type: " + c.getClass());
}
}
public void instruction(int i) {
int oc = OpCode.opCode(i);
int a = OpCode.arg_A(i);
int b = OpCode.arg_B(i);
int c = OpCode.arg_C(i);
int ax = OpCode.arg_Ax(i);
int bx = OpCode.arg_Bx(i);
int sbx = OpCode.arg_sBx(i);
switch (oc) {
case OpCode.MOVE: ie.l_MOVE(a, b); break;
case OpCode.LOADK: ie.l_LOADK(a, bx); break;
//case OpCode.LOADKX: ie.l_LOADKX(extra); break;
case OpCode.LOADBOOL: ie.l_LOADBOOL(a, b, c); break;
case OpCode.LOADNIL: ie.l_LOADNIL(a, b); break;
case OpCode.GETUPVAL: ie.l_GETUPVAL(a, b); break;
case OpCode.GETTABUP: ie.l_GETTABUP(a, b, c); break;
case OpCode.GETTABLE: ie.l_GETTABLE(a, b, c); break;
case OpCode.SETTABUP: ie.l_SETTABUP(a, b, c); break;
case OpCode.SETUPVAL: ie.l_SETUPVAL(a, b); break;
case OpCode.SETTABLE: ie.l_SETTABLE(a, b, c); break;
case OpCode.NEWTABLE: ie.l_NEWTABLE(a, b, c); break;
case OpCode.SELF: ie.l_SELF(a, b, c); break;
case OpCode.ADD: ie.l_ADD(a, b, c); break;
case OpCode.SUB: ie.l_SUB(a, b, c); break;
case OpCode.MUL: ie.l_MUL(a, b, c); break;
case OpCode.MOD: ie.l_MOD(a, b, c); break;
case OpCode.POW: ie.l_POW(a, b, c); break;
case OpCode.DIV: ie.l_DIV(a, b, c); break;
case OpCode.IDIV: ie.l_IDIV(a, b, c); break;
case OpCode.BAND: ie.l_BAND(a, b, c); break;
case OpCode.BOR: ie.l_BOR(a, b, c); break;
case OpCode.BXOR: ie.l_BXOR(a, b, c); break;
case OpCode.SHL: ie.l_SHL(a, b, c); break;
case OpCode.SHR: ie.l_SHR(a, b, c); break;
case OpCode.UNM: ie.l_UNM(a, b); break;
case OpCode.BNOT: ie.l_BNOT(a, b); break;
case OpCode.NOT: ie.l_NOT(a, b); break;
case OpCode.LEN: ie.l_LEN(a, b); break;
case OpCode.CONCAT: ie.l_CONCAT(a, b, c); break;
case OpCode.JMP: ie.l_JMP(sbx); break;
case OpCode.EQ: ie.l_EQ(a, b, c); break;
case OpCode.LT: ie.l_LT(a, b, c); break;
case OpCode.LE: ie.l_LE(a, b, c); break;
case OpCode.TEST: ie.l_TEST(a, c); break;
case OpCode.TESTSET: ie.l_TESTSET(a, b, c); break;
case OpCode.CALL: ie.l_CALL(a, b, c); break;
case OpCode.TAILCALL: ie.l_TAILCALL(a, b, c); break;
case OpCode.RETURN: ie.l_RETURN(a, b); break;
case OpCode.FORLOOP: ie.l_FORLOOP(a, sbx); break;
case OpCode.FORPREP: ie.l_FORPREP(a, sbx); break;
case OpCode.TFORCALL: ie.l_TFORCALL(a, c); break;
case OpCode.TFORLOOP: ie.l_TFORLOOP(a, sbx); break;
case OpCode.SETLIST: ie.l_SETLIST(a, b, c); break;
case OpCode.CLOSURE: ie.l_CLOSURE(a, bx); break;
case OpCode.VARARG: ie.l_VARARG(a, b); break;
case OpCode.EXTRAARG: ie.l_EXTRAARG(ax); break;
default: throw new UnsupportedOperationException("Unsupported opcode: " + oc);
}
}
@Override
public void l_MOVE(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_LOADK(int dest, int idx) {
System.err.println("LOADK " + dest + " " + idx);
pushConstant(OpCode.indexK(idx));
pushIntoRegister(dest);
}
@Override
public void l_LOADBOOL(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_LOADNIL(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_GETUPVAL(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_GETTABUP(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_GETTABLE(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_SETTABUP(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_SETUPVAL(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_SETTABLE(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_NEWTABLE(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_SELF(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
private void l_binOp(String method, int dest, int left, int right) {
System.err.println("BINOP(" + method + ") " + dest + " " + left + " " + right);
// TODO: swap these?
if (OpCode.isK(left)) pushConstant(OpCode.indexK(left)); else pushRegister(left);
if (OpCode.isK(right)) pushConstant(OpCode.indexK((byte) right)); else pushRegister(right);
visitMethodInsn(INVOKESTATIC, Type.getInternalName(Operators.class), method, "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false);
pushIntoRegister(dest);
}
@Override
public void l_ADD(int a, int b, int c) {
l_binOp("add", a, b, c);
}
@Override
public void l_SUB(int a, int b, int c) {
l_binOp("sub", a, b, c);
}
@Override
public void l_MUL(int a, int b, int c) {
l_binOp("mul", a, b, c);
}
@Override
public void l_MOD(int a, int b, int c) {
l_binOp("mod", a, b, c);
}
@Override
public void l_POW(int a, int b, int c) {
l_binOp("pow", a, b, c);
}
@Override
public void l_DIV(int a, int b, int c) {
l_binOp("div", a, b, c);
}
@Override
public void l_IDIV(int a, int b, int c) {
l_binOp("idiv", a, b, c);
}
@Override
public void l_BAND(int a, int b, int c) {
l_binOp("band", a, b, c);
}
@Override
public void l_BOR(int a, int b, int c) {
l_binOp("bor", a, b, c);
}
@Override
public void l_BXOR(int a, int b, int c) {
l_binOp("bxor", a, b, c);
}
@Override
public void l_SHL(int a, int b, int c) {
l_binOp("shl", a, b, c);
}
@Override
public void l_SHR(int a, int b, int c) {
l_binOp("shr", a, b, c);
}
@Override
public void l_UNM(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_BNOT(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_NOT(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_LEN(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_CONCAT(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_JMP(int sbx) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_EQ(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_LT(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_LE(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_TEST(int a, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_TESTSET(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_CALL(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_TAILCALL(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_RETURN(int a, int b) {
saveRegisters();
// FIXME: adjusting stack top
setTop(1);
mv.visitInsn(RETURN); // end; TODO: signal a return!
}
@Override
public void l_FORLOOP(int a, int sbx) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_FORPREP(int a, int sbx) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_TFORCALL(int a, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_TFORLOOP(int a, int sbx) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_SETLIST(int a, int b, int c) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_CLOSURE(int a, int bx) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_VARARG(int a, int b) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void l_EXTRAARG(int ax) {
throw new UnsupportedOperationException("not implemented");
}
}
|
package com.rho.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import javolution.io.UTF8StreamReader;
import com.rho.RhoClassFactory;
//import com.rho.RhoConf;
import com.rho.FilePath;
import com.rho.IRhoRubyHelper;
import com.rho.RhoConf;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.RhodesApp;
import com.rho.file.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class NetRequest
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Net");
boolean m_bCancel = false;
boolean m_sslVerifyPeer = true;
public static interface IRhoSession
{
public abstract void logout()throws Exception;
public abstract String getSession();
public abstract String getContentType();
}
public static class MultipartItem
{
//mutually exclusive
public String m_strFilePath = "";
public String m_strBody = "";
public String m_strName = "", m_strFileName = "", m_strContentType = "";
public String m_strDataPrefix = "";
};
private IHttpConnection m_connection = null;
private boolean m_bIgnoreSuffixOnSim = true;
private Hashtable m_OutHeaders;
public boolean isCancelled(){ return m_bCancel;}
//TODO: use sslVerifyPeer
boolean sslVerifyPeer() {return m_sslVerifyPeer;}
void sslVerifyPeer(boolean mode) {m_sslVerifyPeer = mode;}
public NetResponse pullData(String strUrl, IRhoSession oSession ) throws Exception
{
return doRequest("GET", strUrl, "", oSession, null);
}
public void setIgnoreSuffixOnSim(boolean bset)
{
m_bIgnoreSuffixOnSim = bset;
}
private void writeHeaders(Hashtable headers) throws Exception
{
if (headers != null && headers.size() > 0)
{
Enumeration valsHeaders = headers.elements();
Enumeration keysHeaders = headers.keys();
while (valsHeaders.hasMoreElements())
{
String strName = (String)keysHeaders.nextElement();
String strValue = (String)valsHeaders.nextElement();
m_connection.setRequestProperty(strName,strValue);
}
}
}
private void readHeaders(Hashtable headers) throws Exception
{
if ( headers != null )
{
m_OutHeaders = new Hashtable();
for (int i = 0;; i++) {
String strField = m_connection.getHeaderFieldKey(i);
if (strField == null && i > 0)
break;
if (strField != null )
{
String header_field = m_connection.getHeaderField(i);
m_OutHeaders.put(strField.toLowerCase(), header_field);
}
}
}
}
public static void copyHashtable(Hashtable from, Hashtable to)
{
if ( from == null || to == null )
return;
Enumeration valsHeaders = from.elements();
Enumeration keysHeaders = from.keys();
while (valsHeaders.hasMoreElements())
{
Object key = (String)keysHeaders.nextElement();
Object value = (String)valsHeaders.nextElement();
to.put(key, value);
}
}
private String getResponseEncoding() throws Exception
{
if ( m_OutHeaders != null )
return (String)m_OutHeaders.get("content-type");
return "";
}
public NetResponse doRequest(String strMethod, String strUrl, String strBody, IRhoSession oSession, Hashtable headers ) throws Exception
{
String strRespBody = null;
InputStream is = null;
OutputStream os = null;
int code = -1;
m_bCancel = false;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, m_bIgnoreSuffixOnSim);
LOG.INFO("connection done");
if ( oSession != null )
{
String strSession = oSession.getSession();
LOG.INFO("Cookie : " + (strSession != null ? strSession : "") );
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
//m_connection.setRequestProperty("Connection", "keep-alive");
//m_connection.setRequestProperty("Accept", "application/x-www-form-urlencoded,application/json,text/html");
if ( strBody != null && strBody.length() > 0 )
{
if ( oSession != null )
m_connection.setRequestProperty("Content-Type", oSession.getContentType());
else
m_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
writeHeaders(headers);
LOG.INFO("writeHeaders done");
m_connection.setRequestMethod(IHttpConnection.POST);
os = m_connection.openOutputStream();
os.write(strBody.getBytes(), 0, strBody.length());
LOG.INFO("write body done");
}else
{
writeHeaders(headers);
m_connection.setRequestMethod(strMethod);
}
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
is = m_connection.openInputStream();
LOG.INFO("openInputStream done");
readHeaders(headers);
copyHashtable(m_OutHeaders, headers);
if ( code >= 400 )
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED && oSession != null)
{
LOG.ERROR("Unauthorize error.Client will be logged out");
oSession.logout();
}
//if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
{
strRespBody = readFully(is, getResponseEncoding());
LOG.TRACE("Response body: " + strRespBody );
}
}else
{
long len = m_connection.getLength();
LOG.INFO("fetchRemoteData data size:" + len );
strRespBody = readFully(is, getResponseEncoding());
LOG.INFO("fetchRemoteData data readFully.");
}
}finally
{
if ( is != null )
try{ is.close(); }catch(IOException exc){}
if ( os != null )
try{ os.close(); }catch(IOException exc){}
closeConnection();
m_bIgnoreSuffixOnSim = true;
}
return makeResponse(strRespBody, code );
}
private NetResponse makeResponse(String strRespBody, int nErrorCode)throws Exception
{
NetResponse pResp = new NetResponse(strRespBody != null ? strRespBody : "", nErrorCode );
if (pResp.isOK())
pResp.setCookies(makeClientCookie(m_OutHeaders));
return pResp;
}
public NetResponse pushData(String strUrl, String strBody, IRhoSession oSession)throws Exception
{
m_bCancel = false;
if ( RhodesApp.getInstance().isRhodesAppUrl(strUrl) )
{
IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
return helper.postUrl(strUrl,strBody);
}
return doRequest("POST", strUrl, strBody, oSession, null);
}
public NetResponse pushMultipartData(String strUrl, MultipartItem oItem, IRhoSession oSession, Hashtable/*<String,String>**/ pHeaders)throws Exception
{
Vector arItems = new Vector();
arItems.addElement(oItem);
return pushMultipartData(strUrl, arItems, oSession, pHeaders);
}
public NetResponse pullCookies(String strUrl, String strBody, IRhoSession oSession)throws Exception
{
Hashtable headers = new Hashtable();
m_bIgnoreSuffixOnSim = false;
m_bCancel = false;
NetResponse resp = doRequest/*Try*/("POST", strUrl, strBody, oSession, headers);
if ( resp.isOK() )
{
resp.setCharData(resp.getCookies());
LOG.INFO("pullCookies: " + resp.getCharData() );
}
return resp;
}
static String szMultipartPostfix =
"\r\n
static String szMultipartContType =
"multipart/form-data; boundary=
void processMultipartItems( Vector/*Ptr<CMultipartItem*>&*/ arItems )throws Exception
{
for( int i = 0; i < (int)arItems.size(); i++ )
{
MultipartItem oItem = (MultipartItem)arItems.elementAt(i);
if ( oItem.m_strName.length() == 0 )
oItem.m_strName = "blob";
if ( oItem.m_strFileName.length() == 0 )
{
if ( oItem.m_strFilePath.length() > 0 )
{
FilePath oPath = new FilePath(oItem.m_strFilePath);
oItem.m_strFileName = oPath.getBaseName();
}
//else
// oItem.m_strFileName = "doesnotmatter.txt";
}
oItem.m_strDataPrefix = i > 0 ? "\r\n" : "";
oItem.m_strDataPrefix +=
"
"Content-Disposition: form-data; name=\"";
oItem.m_strDataPrefix += oItem.m_strName + "\"";
if (oItem.m_strFileName.length()>0)
oItem.m_strDataPrefix += "; filename=\"" + oItem.m_strFileName + "\"";
oItem.m_strDataPrefix += "\r\n";
if ( oItem.m_strContentType != null && oItem.m_strContentType.length() > 0 )
oItem.m_strDataPrefix += "Content-Type: " + oItem.m_strContentType + "\r\n";
long nContentSize = 0;
if ( oItem.m_strFilePath.length() > 0 )
{
SimpleFile file = null;
try{
file = RhoClassFactory.createFile();
file.open(oItem.m_strFilePath, true, true);
nContentSize = file.length();
if ( !file.isOpened() ){
LOG.ERROR("File not found: " + oItem.m_strFilePath);
throw new RuntimeException("File not found:" + oItem.m_strFilePath);
}
}finally{
if ( file != null )
try{ file.close(); }catch(IOException e){}
}
}
else
nContentSize = oItem.m_strBody.length();
if ( oItem.m_strContentType != null && oItem.m_strContentType.length() > 0 )
oItem.m_strDataPrefix += "Content-Length: " + nContentSize + "\r\n";
oItem.m_strDataPrefix += "\r\n";
}
}
public NetResponse pushMultipartData(String strUrl, Vector/*Ptr<CMultipartItem*>&*/ arItems, IRhoSession oSession, Hashtable/*<String,String>**/ headers)throws Exception
{
String strRespBody = null;
InputStream is = null;
OutputStream os = null;
int code = -1;
m_bCancel = false;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, false);
if ( oSession != null )
{
String strSession = oSession.getSession();
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
m_connection.setRequestProperty("Connection", "keep-alive");
m_connection.setRequestProperty("content-type", szMultipartContType);
writeHeaders(headers);
m_connection.setRequestMethod(IHttpConnection.POST);
//PUSH specific
processMultipartItems( arItems );
os = m_connection.openOutputStream();
//write all items
for( int i = 0; i < (int)arItems.size(); i++ )
{
MultipartItem oItem = (MultipartItem)arItems.elementAt(i);
os.write(oItem.m_strDataPrefix.getBytes(), 0, oItem.m_strDataPrefix.length());
if ( oItem.m_strFilePath.length() > 0 )
{
SimpleFile file = null;
InputStream fis = null;
try{
file = RhoClassFactory.createFile();
file.open(oItem.m_strFilePath, true, true);
if ( !file.isOpened() ){
LOG.ERROR("File not found: " + oItem.m_strFilePath);
throw new RuntimeException("File not found:" + oItem.m_strFilePath);
}
fis = file.getInputStream();
byte[] byteBuffer = new byte[1024*4];
int nRead = 0;
do{
nRead = fis.read(byteBuffer);
if ( nRead > 0 )
os.write(byteBuffer, 0, nRead);
}while( nRead > 0 );
}finally{
if (fis != null)
try{ fis.close(); }catch(IOException e){}
if ( file != null )
try{ file.close(); }catch(IOException e){}
}
}else
{
os.write(oItem.m_strBody.getBytes(), 0, oItem.m_strBody.length());
}
}
os.write(szMultipartPostfix.getBytes(), 0, szMultipartPostfix.length());
//os.flush();
//PUSH specific
is = m_connection.openInputStream();
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
readHeaders(headers);
copyHashtable(m_OutHeaders, headers);
if (code >= 400 )
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED)
{
LOG.ERROR("Unauthorize error.Client will be logged out");
oSession.logout();
}
//if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
strRespBody = readFully(is, getResponseEncoding());
LOG.TRACE("Response body: " + strRespBody );
}else
{
long len = m_connection.getLength();
LOG.INFO("fetchRemoteData data size:" + len );
strRespBody = readFully(is, getResponseEncoding());
LOG.INFO("fetchRemoteData data readFully.");
}
}finally{
try{
if ( is != null )
is.close();
if (os != null)
os.close();
closeConnection();
}catch(IOException exc2){}
}
return makeResponse(strRespBody, code );
}
long m_nMaxPacketSize = 0;
int m_nCurDownloadSize = 0;
boolean m_bFlushFileAfterWrite = false;
public NetResponse pullFile( String strUrl, String strFileName, IRhoSession oSession, Hashtable headers )throws Exception
{
IRAFile file = null;
NetResponse resp = null;
m_nMaxPacketSize = RhoClassFactory.getNetworkAccess().getMaxPacketSize();
m_bFlushFileAfterWrite = RhoConf.getInstance().getBool("use_persistent_storage");
m_bCancel = false;
try{
if (!strFileName.startsWith("file:")) {
try{
strFileName = FilePath.join(RhoClassFactory.createFile().getDirPath(""), strFileName);
} catch (IOException x) {
LOG.ERROR("getDirPath failed.", x);
throw x;
}
}
file = RhoClassFactory.createFSRAFile();
file.open(strFileName, "rw");
file.seek(file.size());
do{
resp = pullFile1( strUrl, file, file.size(), oSession, headers );
}while( !m_bCancel && (resp == null || resp.isOK()) && m_nCurDownloadSize > 0 && m_nMaxPacketSize > 0 );
}finally{
if ( file != null )
{
file.close();
file = null;
}
}
copyHashtable(m_OutHeaders, headers);
return resp != null && !m_bCancel ? resp : makeResponse("", IHttpConnection.HTTP_INTERNAL_ERROR );
}
NetResponse pullFile1( String strUrl, IRAFile file, long nStartPos, IRhoSession oSession, Hashtable headers )throws Exception
{
String strRespBody = null;
InputStream is = null;
int code = -1;
try{
closeConnection();
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, true);
if (oSession!= null)
{
String strSession = oSession.getSession();
if ( strSession != null && strSession.length() > 0 )
m_connection.setRequestProperty("Cookie", strSession );
}
m_connection.setRequestProperty("Connection", "keep-alive");
if ( nStartPos > 0 || m_nMaxPacketSize > 0 )
{
if ( m_nMaxPacketSize > 0 )
m_connection.setRequestProperty("Range", "bytes="+nStartPos+"-" + (nStartPos + m_nMaxPacketSize-1));
else
m_connection.setRequestProperty("Range", "bytes="+nStartPos+"-");
}
writeHeaders(headers);
m_connection.setRequestMethod(IHttpConnection.GET);
code = m_connection.getResponseCode();
LOG.INFO("getResponseCode : " + code);
m_nCurDownloadSize = 0;
readHeaders(headers);
if ( code == IHttpConnection.HTTP_RANGENOTSATISFY )
code = IHttpConnection.HTTP_PARTIAL_CONTENT;
else
{
if (code >= 400 && code != IHttpConnection.HTTP_PARTIAL_CONTENT )
{
LOG.ERROR("Error retrieving data: " + code);
if (code == IHttpConnection.HTTP_UNAUTHORIZED)
{
LOG.ERROR("Unauthorize error.Client will be logged out");
oSession.logout();
}
//if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
{
is = m_connection.openInputStream();
strRespBody = readFully(is, getResponseEncoding());
}
}else
{
int nRead = 0;
is = m_connection.openInputStream();
byte[] byteBuffer = new byte[1024*20];
do{
nRead = /*bufferedReadByByte(m_byteBuffer, is);*/is.read(byteBuffer);
if ( nRead > 0 )
{
file.write(byteBuffer, 0, nRead);
if (m_bFlushFileAfterWrite)
file.sync();
m_nCurDownloadSize += nRead;
}
}while( !m_bCancel && nRead >= 0 );
if ( code == IHttpConnection.HTTP_OK || (code == IHttpConnection.HTTP_PARTIAL_CONTENT && isFinishDownload()) )
m_nCurDownloadSize = 0;
}
}
}finally
{
if ( is != null )
try{ is.close(); }catch(IOException exc){}
closeConnection();
}
return makeResponse(strRespBody != null ? strRespBody : "", code );
}
private boolean isFinishDownload()throws IOException
{
String strContRange = m_connection.getHeaderField("Content-Range");
if ( strContRange != null )
{
int nMinus = strContRange.indexOf('-');
if ( nMinus > 0 )
{
int nSep = strContRange.indexOf('/', nMinus);
if ( nSep > 0 )
{
String strHigh = strContRange.substring(nMinus+1,nSep);
String strTotal = strContRange.substring(nSep+1);
if ( Integer.parseInt(strHigh) + 1 >= Integer.parseInt(strTotal) )
return true;
}
}
}
return false;
}
public String resolveUrl(String strUrl) throws Exception
{
return RhodesApp.getInstance().canonicalizeRhoUrl(strUrl);
}
public void cancel()
{
m_bCancel = true;
closeConnection();
}
/*static{
TEST();
}
public static void TEST()
{
//ParsedCookie cookie = new ParsedCookie();
String strClientCookie = "";
strClientCookie = URI.parseCookie("auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT, auth_token=887b2ffd30a7b97be9a0986d7746a934421eec7d; path=/; expires=Sat, 24 Oct 2009 20:56:55 GMT, rhosync_session=BAh7BzoMdXNlcl9pZGkIIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--f9b67d99397fc534107fb3b7483ccdae23b4a761; path=/; expires=Sun, 10 Oct 2010 19:10:58 GMT; HttpOnly");
strClientCookie = URI.parseCookie("auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT");
strClientCookie = URI.parseCookie("rhosync_session=BAh7CToNcGFzc3dvcmQiFTiMYru1W11zuoAlN%2FPtgjc6CmxvZ2luIhU4jGK7tVtdc7qAJTfz7YI3Ogx1c2VyX2lkaQYiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA%3D--a7829a70171203d72cd4e83d07b18e8fcf5e2f78; path=/; expires=Thu, 02 Sep 2010 23:51:31 GMT; HttpOnly");
}*/
private static String makeClientCookie(Hashtable headers)
throws IOException
{
if ( headers == null )
return "";
//ParsedCookie cookie = new ParsedCookie();
String strRes = "";
Enumeration valsHeaders = headers.elements();
Enumeration keysHeaders = headers.keys();
while (valsHeaders.hasMoreElements())
{
String strName = (String)keysHeaders.nextElement();
String strValue = (String)valsHeaders.nextElement();
if (strName.equalsIgnoreCase("Set-Cookie"))
{
LOG.INFO("Set-Cookie: " + strValue);
strRes += URI.parseCookie(strValue);
}
}
return strRes;
}
public static final String readFully(InputStream in, String strContType) throws Exception
{
String strRes = "";
byte[] byteBuffer = new byte[1024*4];
boolean bUTF8 = false;
if ( strContType != null )
{
int nCharsetPos = strContType.lastIndexOf('=');
if ( nCharsetPos > 0 )
{
String strEnc = strContType.substring(nCharsetPos+1);
bUTF8 = strEnc.equalsIgnoreCase("UTF-8");
}
}
int nRead = 0;
do{
nRead = in.read(byteBuffer);
if (nRead>0)
{
String strTemp;
if (bUTF8)
strTemp = new String(byteBuffer,0,nRead, "UTF-8");
else
strTemp = new String(byteBuffer,0,nRead);
strRes += strTemp;
}
}while( nRead > 0 );
return strRes;
}
public void closeConnection(){
if ( m_connection != null ){
try{
m_connection.close();
}catch(IOException exc){
LOG.ERROR("There was an error close connection", exc);
}
}
m_connection = null;
}
}
|
package net.somethingdreadful.MAL;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MALDateTools {
private static final String ISO8601DATESTRING = "yyyy-MM-dd'T'HH:mm:ssZ";
private static final String MALTIMEZONE = "America/Los_Angeles";
/*
* this parses all the different date formats MAL returns into one normalized to store in the db
*/
public static Date parseMALDate(String maldate) {
// easiest possibility
if (maldate.toLowerCase(Locale.US).equals("now")) {
Date result = new Date();
return result;
}
/* simply using SimpleDateformat and parse different strings is not working, because
* SDF can't distinguish between the format "yyyy-MM-dd, h:m a" and "MM-dd-yy, h:m a" (which
* are both used by MAL) and it also can't parse relative dates like "<Weekday>, h:m a" or
* "x hours ago", so determine the date format by using regex
*/
String[] date_regex = {
"\\d{4}-\\d{2}-\\d{2}, \\d{1,2}:\\d{2} (AM|PM)", // yyyy-MM-dd, h:m a
"\\d{2}-\\d{2}-\\d{2}, \\d{1,2}:\\d{2} (AM|PM)", // MM-dd-yy, h:m a
"\\d{4}-\\d{2}-\\d{2}", // yyyy-MM-dd
"(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{1,2}):(\\d{2}) (AM|PM)", // EEEE, h:m a
"(January|February|March|April|May|June|July|August|September|October|November|December) +\\d{1,2}, \\d{4}", // MMMM dd, yyyy
"Yesterday, (\\d{1,2}):(\\d{2}) (AM|PM)", // Yesterday, h:m a
"(\\d*) (hours?|minutes?) ago" // x hours/minutes ago
};
for (int i = 0; i < date_regex.length; i++) {
Pattern pattern = Pattern.compile(date_regex[i]);
Matcher matcher = pattern.matcher(maldate);
SimpleDateFormat sdf;
Calendar cal;
if (matcher.find()) {
switch (i) {
case 0: // yyyy-MM-dd, h:m a
sdf = new SimpleDateFormat("yyyy-MM-dd, h:m a", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone(MALTIMEZONE));
try {
Date result = sdf.parse(maldate);
return result;
} catch (ParseException e) {
Crashlytics.log(Log.ERROR, "MALX", "MALDateTools.parseMALDate(): case 0: " + e.getMessage());
Crashlytics.logException(e);
}
break;
case 1: // MM-dd-yy, h:m a
sdf = new SimpleDateFormat("MM-dd-yy, h:m a", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone(MALTIMEZONE));
try {
Date result = sdf.parse(maldate);
return result;
} catch (ParseException e) {
Crashlytics.log(Log.ERROR, "MALX", "MALDateTools.parseMALDate(): case 1: " + e.getMessage());
Crashlytics.logException(e);
}
break;
case 2: // yyyy-MM-dd
sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone(MALTIMEZONE));
try {
Date result = sdf.parse(maldate);
return result;
} catch (ParseException e) {
Crashlytics.log(Log.ERROR, "MALX", "MALDateTools.parseMALDate(): case 2: " + e.getMessage());
Crashlytics.logException(e);
}
break;
case 3: // EEEE, h:m a
String[] week_days = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
cal = Calendar.getInstance(TimeZone.getTimeZone(MALTIMEZONE));
int currentdayofweek = cal.get(Calendar.DAY_OF_WEEK);
int dayofweek = Arrays.asList(week_days).indexOf(matcher.group(1)) + 1;
int difference = currentdayofweek - dayofweek;
if (difference <= 0) // if difference is < 0, then it was in the last week
difference += 7;
cal.add(Calendar.DATE, difference > 0 ? difference * -1 : difference);
cal.set(Calendar.HOUR, Integer.parseInt(matcher.group(2)));
cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(3)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.AM_PM, matcher.group(4).equals("AM") ? Calendar.AM : Calendar.PM);
return cal.getTime();
case 4: //MMMM dd, yyyy
sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone(MALTIMEZONE));
try {
Date result = sdf.parse(maldate);
return result;
} catch (ParseException e) {
Crashlytics.log(Log.ERROR, "MALX", "MALDateTools.parseMALDate(): case 4: " + e.getMessage());
Crashlytics.logException(e);
}
break;
case 5: // Yesterday, h:m a
cal = Calendar.getInstance(TimeZone.getTimeZone(MALTIMEZONE));
cal.add(Calendar.DATE, -1);
cal.set(Calendar.HOUR, Integer.parseInt(matcher.group(1)));
cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(2)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.AM_PM, matcher.group(3).equals("AM") ? Calendar.AM : Calendar.PM);
return cal.getTime();
case 6:
Date result = new Date();
int count = Integer.parseInt(matcher.group(1));
String unit = matcher.group(2);
if (unit.matches("minute[s?]"))
result.setTime(result.getTime() - (count * 60000));
else if (unit.matches("hour[s?]"))
result.setTime(result.getTime() - (count * 3600000));
return result;
}
}
}
return null;
}
public static String parseMALDateToISO8601String(String maldate) {
SimpleDateFormat formatSdf = new SimpleDateFormat(ISO8601DATESTRING);
Date date = parseMALDate(maldate);
if (date != null)
return formatSdf.format(date);
// return empty string if parsing failed
return "";
}
public static String formatDate(Date date, Context context, boolean withtime) {
if (date == null)
return "";
SimpleDateFormat formatSdf;
Resources res = context.getResources();
if (withtime) { // only do "nice" formatting if time
long diffHoursToNow = new Date().getTime() - date.getTime();
final int MINUTE = 60000;
final int HOUR = MINUTE * 60;
final int DAY = HOUR * 24;
if (diffHoursToNow > 0) {
if (diffHoursToNow < HOUR) {
int minutes = (int) diffHoursToNow / MINUTE;
return res.getQuantityString(R.plurals.minutes_ago, minutes, minutes);
}
if (diffHoursToNow < DAY) {
int hours = (int) diffHoursToNow / HOUR;
return res.getQuantityString(R.plurals.hours_ago, hours, hours);
}
if (diffHoursToNow < DAY * 2) {
String dateformat_yesterday = res.getString(R.string.datetimeformat_yesterday);
formatSdf = new SimpleDateFormat(dateformat_yesterday);
return formatSdf.format(date);
}
if (diffHoursToNow < DAY * 5) {
String dateformat_dayname = res.getString(R.string.datetimeformat_dayname);
formatSdf = new SimpleDateFormat(dateformat_dayname);
return formatSdf.format(date);
}
} else {
diffHoursToNow = date.getTime() - new Date().getTime();
if (diffHoursToNow < HOUR) {
int minutes = (int) diffHoursToNow / MINUTE;
return res.getQuantityString(R.plurals.minutes_left, minutes, minutes);
}
if (diffHoursToNow < DAY) {
int hours = (int) diffHoursToNow / HOUR;
return res.getQuantityString(R.plurals.hours_left, hours, hours);
}
if (diffHoursToNow < DAY * 2) {
String dateformat_yesterday = res.getString(R.string.datetimeformat_tomorrow);
formatSdf = new SimpleDateFormat(dateformat_yesterday);
return formatSdf.format(date);
}
if (diffHoursToNow < DAY * 5) {
String dateformat_dayname = res.getString(R.string.datetimeformat_dayname);
formatSdf = new SimpleDateFormat(dateformat_dayname);
return formatSdf.format(date);
}
}
String dateformat = res.getString(R.string.datetimeformat);
formatSdf = new SimpleDateFormat(dateformat);
return formatSdf.format(date);
} else {
String dateformat = res.getString(R.string.dateformat);
formatSdf = new SimpleDateFormat(dateformat);
return formatSdf.format(date);
}
}
private static Date parseISODate(String date) {
Date result = null;
String[] isoFormats = {
ISO8601DATESTRING,
"yyyy-MM-dd'T'HH:mmZ",
"yyyy-MM-dd'T'HHZ"
};
int i = 0;
while (i < isoFormats.length && result == null) {
SimpleDateFormat sdf = new SimpleDateFormat(isoFormats[i], Locale.US);
i++;
try {
result = sdf.parse(date);
} catch (ParseException e) {
// really nothing to do here
}
}
return result;
}
public static String formatDateString(String date, Context context, boolean withtime) {
Date result = parseISODate(date);
if (result == null) {
result = parseMALDate(date);
}
if (result != null) {
return formatDate(result, context, withtime);
}
// return empty string if parsing failed
return "";
}
}
|
package git4idea.history;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import git4idea.GitFormatException;
import git4idea.GitUtil;
import git4idea.config.GitVersionSpecialty;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>Parses the 'git log' output basing on the given number of options.
* Doesn't execute of prepare the command itself, performs only parsing.</p>
* <p>
* Usage:<ol>
* <li> Pass options you want to have in the output to the constructor using the {@link GitLogOption} enum constants.
* <li> Get the custom format pattern for 'git log' by calling {@link #getPretty()}
* <li> Call the command and retrieve the output.
* <li> Parse the output via {@link #parseLine(CharSequence)}(prefered), {@link #parse(CharSequence)} or {@link #parseOneRecord(CharSequence)}.
* Note that {@link #parseLine(CharSequence)} expects lines without line separators</ol></p>
* <p>Note that you may pass one set of options to the GitLogParser constructor and then execute git log with other set of options.
* In that case {@link #parse(CharSequence)} will likely fail with {@link GitFormatException}.
* Moreover you really <b>must</b> use {@link #getPretty()} to pass "--pretty=format" pattern to 'git log' -- otherwise the parser won't be able
* to parse output of 'git log' (because special separator characters are used for that).</p>
* <p>Commit records have the following format:
* <pre>
* RECORD_START (commit information, separated by ITEMS_SEPARATOR) RECORD_END \n (changed paths with statuses)?</pre>
* Example:
* <pre>
* 2c815939f45fbcfda9583f84b14fe9d393ada790<ITEMS_SEPARATOR>sample commit<RECORD_END>
* D a.txt</pre></p>
*
* @see GitLogRecord
*/
public class GitLogParser<R extends GitLogRecord> {
private static final Logger LOG = Logger.getInstance(GitLogParser.class);
// Single records begin with %x01%x01, end with %03%03. Items of commit information (hash, committer, subject, etc.) are separated by %x02%x02.
static final String RECORD_START = "\u0001\u0001";
static final String ITEMS_SEPARATOR = "\u0002\u0002";
static final String RECORD_END = "\u0003\u0003";
private static final int MAX_SEPARATOR_LENGTH = 10;
private static final char[] CONTROL_CHARS = new char[]{'\u0001', '\u0002', '\u0003'};
private static final int INPUT_ERROR_MESSAGE_HEAD_LIMIT = 1000000; // limit the string by ~2mb
private static final int INPUT_ERROR_MESSAGE_TAIL_LIMIT = 100;
private static final AtomicInteger ERROR_COUNT = new AtomicInteger();
private final boolean mySupportsRawBody;
@NotNull private final String myPretty;
@NotNull private final OptionsParser myOptionsParser;
@NotNull private final PathsParser myPathsParser;
@NotNull private final GitLogRecordBuilder<R> myRecordBuilder;
private final String myRecordStart;
private final String myRecordEnd;
private final String myItemsSeparator;
private boolean myIsInBody = true;
private GitLogParser(@NotNull GitLogRecordBuilder<R> recordBuilder,
boolean supportsRawBody,
@NotNull NameStatus nameStatusOption,
@NotNull GitLogOption... options) {
mySupportsRawBody = supportsRawBody;
myRecordBuilder = recordBuilder;
myRecordStart = RECORD_START + generateRandomSequence();
myRecordEnd = RECORD_END + generateRandomSequence();
myItemsSeparator = ITEMS_SEPARATOR + generateRandomSequence();
myPretty = "--pretty=format:" + makeFormatFromOptions(options);
myOptionsParser = new OptionsParser(options);
myPathsParser = new MyPathsParser(nameStatusOption);
}
public GitLogParser(@NotNull Project project,
@NotNull GitLogRecordBuilder<R> recordBuilder,
@NotNull NameStatus nameStatus,
@NotNull GitLogOption... options) {
this(recordBuilder, GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project), nameStatus, options);
}
@NotNull
public static GitLogParser<GitLogFullRecord> createDefaultParser(@NotNull Project project,
@NotNull NameStatus nameStatus,
@NotNull GitLogOption... options) {
return new GitLogParser<>(project, new DefaultGitLogFullRecordBuilder(), nameStatus, options);
}
@NotNull
public static GitLogParser<GitLogRecord> createDefaultParser(@NotNull Project project,
@NotNull GitLogOption... options) {
return new GitLogParser<>(project, new DefaultGitLogRecordBuilder(), NameStatus.NONE, options);
}
@NotNull
public List<R> parse(@NotNull CharSequence output) {
List<R> result = new ArrayList<>();
List<CharSequence> lines = StringUtil.split(output, "\n", true, false);
for (CharSequence line : lines) {
try {
R record = parseLine(line);
if (record != null) {
result.add(record);
}
}
catch (GitFormatException e) {
clear();
LOG.error(e);
}
}
R record = finish();
if (record != null) result.add(record);
return result;
}
@Nullable
public R parseOneRecord(@NotNull CharSequence output) {
List<R> records = parse(output);
clear();
if (records.isEmpty()) return null;
return ContainerUtil.getFirstItem(records);
}
/**
* Expects a line without separator.
*/
@Nullable
public R parseLine(@NotNull CharSequence line) {
if (myPathsParser.expectsPaths()) {
return parseLineWithPaths(line);
}
return parseLineWithoutPaths(line);
}
@Nullable
private R parseLineWithPaths(@NotNull CharSequence line) {
if (myIsInBody) {
myIsInBody = !myOptionsParser.parseLine(line);
}
else {
if (CharArrayUtil.regionMatches(line, 0, myRecordStart)) {
R record = createRecord();
myIsInBody = !myOptionsParser.parseLine(line);
return record;
}
myPathsParser.parseLine(line);
}
return null;
}
@Nullable
private R parseLineWithoutPaths(@NotNull CharSequence line) {
if (myOptionsParser.parseLine(line)) {
return createRecord();
}
return null;
}
@Nullable
public R finish() {
if (myOptionsParser.isEmpty()) return null;
return createRecord();
}
@Nullable
private R createRecord() {
if (myPathsParser.getErrorText() != null) {
LOG.debug("Creating record was skipped: " + myPathsParser.getErrorText());
myOptionsParser.clear();
myRecordBuilder.clear();
myPathsParser.clear();
return null;
}
Map<GitLogOption, String> options = myOptionsParser.getResult();
myOptionsParser.clear();
R record = myRecordBuilder.build(options, mySupportsRawBody);
myRecordBuilder.clear();
myPathsParser.clear();
myIsInBody = true;
return record;
}
public void clear() {
myOptionsParser.clear();
myRecordBuilder.clear();
myIsInBody = true;
}
@NotNull
public String getPretty() {
return myPretty;
}
@NotNull
private String makeFormatFromOptions(@NotNull GitLogOption[] options) {
Function<GitLogOption, String> function = option -> "%" + option.getPlaceholder();
return encodeForGit(myRecordStart) + StringUtil.join(options, function, encodeForGit(myItemsSeparator)) + encodeForGit(myRecordEnd);
}
@NotNull
private static String encodeForGit(@NotNull String line) {
StringBuilder encoded = new StringBuilder();
line.chars().forEachOrdered(c -> encoded.append("%x").append(String.format("%02x", c)));
return encoded.toString();
}
@NotNull
private static String generateRandomSequence() {
int length = ERROR_COUNT.get() % (MAX_SEPARATOR_LENGTH - RECORD_START.length());
StringBuilder tail = new StringBuilder();
for (int i = 0; i < length; i++) {
int randomIndex = ThreadLocalRandom.current().nextInt(0, CONTROL_CHARS.length);
tail.append(CONTROL_CHARS[randomIndex]);
}
return tail.toString();
}
private static void throwGFE(@NotNull String message, @NotNull CharSequence line) {
ERROR_COUNT.incrementAndGet();
throw new GitFormatException(message + " [" + getTruncatedEscapedOutput(line) + "]");
}
@NotNull
private static String getTruncatedEscapedOutput(@NotNull CharSequence line) {
String lineString;
String formatString = "%s...(%d more characters)...%s";
if (line.length() > INPUT_ERROR_MESSAGE_HEAD_LIMIT + INPUT_ERROR_MESSAGE_TAIL_LIMIT + formatString.length()) {
lineString = String.format(formatString, line.subSequence(0, INPUT_ERROR_MESSAGE_HEAD_LIMIT),
(line.length() - INPUT_ERROR_MESSAGE_HEAD_LIMIT - INPUT_ERROR_MESSAGE_TAIL_LIMIT),
line.subSequence(line.length() - INPUT_ERROR_MESSAGE_TAIL_LIMIT, line.length()));
}
else {
lineString = line.toString();
}
return StringUtil.escapeStringCharacters(lineString);
}
// --name-status or no flag
enum NameStatus {
/**
* No flag.
*/
NONE,
/**
* --name-status
*/
STATUS
}
/**
* Options which may be passed to 'git log --pretty=format:' as placeholders and then parsed from the result.
* These are the pieces of information about a commit which we want to get from 'git log'.
*/
enum GitLogOption {
HASH("H"), TREE("T"), COMMIT_TIME("ct"), AUTHOR_NAME("an"), AUTHOR_TIME("at"), AUTHOR_EMAIL("ae"), COMMITTER_NAME("cn"),
COMMITTER_EMAIL("ce"), SUBJECT("s"), BODY("b"), PARENTS("P"), REF_NAMES("d"), SHORT_REF_LOG_SELECTOR("gd"),
RAW_BODY("B");
private final String myPlaceholder;
GitLogOption(String placeholder) {
myPlaceholder = placeholder;
}
private String getPlaceholder() {
return myPlaceholder;
}
}
private class OptionsParser {
@NotNull private final GitLogOption[] myOptions;
@NotNull private final PartialResult myResult = new PartialResult();
OptionsParser(@NotNull GitLogOption[] options) {
myOptions = options;
}
public boolean parseLine(@NotNull CharSequence line) {
int offset = 0;
if (myResult.isEmpty()) {
if (!CharArrayUtil.regionMatches(line, offset, myRecordStart)) {
return false;
}
offset += myRecordStart.length();
}
while (offset < line.length()) {
if (atRecordEnd(line, offset)) {
myResult.finishItem();
if (myResult.getResult().size() != myOptions.length) {
throwGFE("Parsed incorrect options " + myResult.getResult() + " for " +
Arrays.toString(myOptions), line);
}
return true;
}
if (CharArrayUtil.regionMatches(line, offset, myItemsSeparator)) {
myResult.finishItem();
offset += myItemsSeparator.length();
}
else {
char c = line.charAt(offset);
myResult.append(c);
offset++;
}
}
myResult.append('\n');
return false;
}
private boolean atRecordEnd(@NotNull CharSequence line, int offset) {
return (offset == line.length() - myRecordEnd.length() && CharArrayUtil.regionMatches(line, offset, myRecordEnd));
}
@NotNull
public Map<GitLogOption, String> getResult() {
return createOptions(myResult.getResult());
}
@NotNull
private Map<GitLogOption, String> createOptions(@NotNull List<String> options) {
Map<GitLogOption, String> optionsMap = new HashMap<>(options.size());
for (int index = 0; index < options.size(); index++) {
optionsMap.put(myOptions[index], options.get(index));
}
return optionsMap;
}
public void clear() {
myResult.clear();
}
public boolean isEmpty() {
return myResult.isEmpty();
}
}
public static class PathsParser<R extends GitLogRecord> {
@NotNull private final NameStatus myNameStatusOption;
@NotNull private final GitLogRecordBuilder<R> myRecordBuilder;
@Nullable private String myErrorText = null;
PathsParser(@NotNull NameStatus nameStatusOption, @NotNull GitLogRecordBuilder<R> recordBuilder) {
myNameStatusOption = nameStatusOption;
myRecordBuilder = recordBuilder;
}
public void parseLine(@NotNull CharSequence line) {
if (line.length() == 0) return;
List<String> match = parsePathsLine(line);
if (match.isEmpty()) {
// ignore
}
else {
if (myNameStatusOption != NameStatus.STATUS) throwGFE("Status list not expected", line);
if (match.size() < 2) {
myErrorText = getErrorText(line);
}
else {
if (match.size() == 2) {
addPath(match.get(0), match.get(1), null);
}
else {
addPath(match.get(0), match.get(1), match.get(2));
}
}
}
}
@NotNull
protected String getErrorText(@NotNull CharSequence line) {
return "Could not parse status line [" + line + "]";
}
private void addPath(@NotNull String type, @NotNull String firstPath, @Nullable String secondPath) {
myRecordBuilder.addPath(GitChangesParser.getChangeType(GitChangeType.fromString(type)), tryUnescapePath(firstPath),
tryUnescapePath(secondPath));
}
@Nullable
@Contract("!null -> !null")
private static String tryUnescapePath(@Nullable String path) {
if (path == null) return null;
try {
return GitUtil.unescapePath(path);
}
catch (VcsException e) {
LOG.error(e);
return path;
}
}
@NotNull
private static List<String> parsePathsLine(@NotNull CharSequence line) {
int offset = 0;
PartialResult result = new PartialResult();
while (offset < line.length()) {
if (atLineEnd(line, offset)) {
break;
}
char charAt = line.charAt(offset);
if (charAt == '\t') {
result.finishItem();
}
else {
result.append(charAt);
}
offset++;
}
result.finishItem();
return result.getResult();
}
private static boolean atLineEnd(@NotNull CharSequence line, int offset) {
while (offset < line.length() && (line.charAt(offset) == '\t')) offset++;
if (offset == line.length() || (line.charAt(offset) == '\n' || line.charAt(offset) == '\r')) return true;
return false;
}
public boolean expectsPaths() {
return myNameStatusOption == NameStatus.STATUS;
}
public void clear() {
myErrorText = null;
}
@Nullable
public String getErrorText() {
return myErrorText;
}
}
private class MyPathsParser extends PathsParser<R> {
MyPathsParser(@NotNull NameStatus nameStatusOption) {
super(nameStatusOption, myRecordBuilder);
}
@NotNull
@Override
protected String getErrorText(@NotNull CharSequence line) {
return super.getErrorText(line) + " for record " + myOptionsParser.myResult.getResult();
}
}
private static class PartialResult {
@NotNull private List<String> myResult = new ArrayList<>();
@NotNull private final StringBuilder myCurrentItem = new StringBuilder();
public void append(char c) {
myCurrentItem.append(c);
}
public void finishItem() {
myResult.add(myCurrentItem.toString());
myCurrentItem.setLength(0);
}
@NotNull
public List<String> getResult() {
return myResult;
}
public void clear() {
myCurrentItem.setLength(0);
myResult = new ArrayList<>();
}
public boolean isEmpty() {
return myResult.isEmpty() && myCurrentItem.length() == 0;
}
}
}
|
package io.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The Class IOConnection.
*/
class IOConnection implements IOCallback {
/** Debug logger */
static final Logger logger = Logger.getLogger("io.socket");
public static final String FRAME_DELIMITER = "\ufffd";
/** The Constant STATE_INIT. */
private static final int STATE_INIT = 0;
/** The Constant STATE_HANDSHAKE. */
private static final int STATE_HANDSHAKE = 1;
/** The Constant STATE_CONNECTING. */
private static final int STATE_CONNECTING = 2;
/** The Constant STATE_READY. */
private static final int STATE_READY = 3;
/** The Constant STATE_INTERRUPTED. */
private static final int STATE_INTERRUPTED = 4;
/** The Constant STATE_INVALID. */
private static final int STATE_INVALID = 6;
/** The state. */
private int state = STATE_INIT;
/** Socket.io path. */
public static final String SOCKET_IO_1 = "/socket.io/1/";
/** The SSL socket factory for HTTPS connections */
private static SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
/** All available connections. */
private static HashMap<String, List<IOConnection>> connections = new HashMap<String, List<IOConnection>>();
/** The url for this connection. */
private URL url;
/** The transport for this connection. */
private IOTransport transport;
/** The connection timeout. */
private int connectTimeout = 10000;
/** The session id of this connection. */
private String sessionId;
/** The heartbeat timeout. Set by the server */
private long heartbeatTimeout;
/** The closing timeout. Set By the server */
private long closingTimeout;
/** The protocols supported by the server. */
private List<String> protocols;
/** The output buffer used to cache messages while (re-)connecting. */
private ConcurrentLinkedQueue<String> outputBuffer = new ConcurrentLinkedQueue<String>();
/** The sockets of this connection. */
private HashMap<String, SocketIO> sockets = new HashMap<String, SocketIO>();
/** Custom Request headers used while handshaking */
private Properties headers;
/**
* The first socket to be connected. the socket.io server does not send a
* connected response to this one.
*/
private SocketIO firstSocket = null;
/** The reconnect timer. IOConnect waits a second before trying to reconnect */
final private Timer backgroundTimer = new Timer("backgroundTimer");
/** A String representation of {@link #url}. */
private String urlStr;
/**
* The last occurred exception, which will be given to the user if
* IOConnection gives up.
*/
private Exception lastException;
/** The next ID to use. */
private int nextId = 1;
/** Acknowledges. */
HashMap<Integer, IOAcknowledge> acknowledge = new HashMap<Integer, IOAcknowledge>();
/** true if there's already a keepalive in {@link #outputBuffer}. */
private boolean keepAliveInQueue;
/**
* The heartbeat timeout task. Only null before connection has been
* initialised.
*/
private HearbeatTimeoutTask heartbeatTimeoutTask;
/**
* The Class HearbeatTimeoutTask. Handles dropping this IOConnection if no
* heartbeat is received within life time.
*/
private class HearbeatTimeoutTask extends TimerTask {
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
setState(STATE_INVALID);
error(new SocketIOException(
"Timeout Error. No heartbeat from server within life time of the socket. closing.",
lastException));
}
}
/** The reconnect task. Null if no reconnection is in progress. */
private ReconnectTask reconnectTask = null;
/**
* The Class ReconnectTask. Handles reconnect attempts
*/
private class ReconnectTask extends TimerTask {
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
connectTransport();
if (!keepAliveInQueue) {
sendPlain("2::");
keepAliveInQueue = true;
}
}
}
/**
* The Class ConnectThread. Handles connecting to the server with an
* {@link IOTransport}
*/
private class ConnectThread extends Thread {
/**
* Instantiates a new thread for handshaking/connecting.
*/
public ConnectThread() {
super("ConnectThread");
}
/**
* Tries handshaking if necessary and connects with corresponding
* transport afterwards.
*/
@Override
public void run() {
if (IOConnection.this.getState() == STATE_INIT)
handshake();
connectTransport();
}
};
/**
* Set the socket factory used for SSL connections.
*
* @param socketFactory
*/
public static void setDefaultSSLSocketFactory(SSLSocketFactory socketFactory) {
sslSocketFactory = socketFactory;
}
/**
* Creates a new connection or returns the corresponding one.
*
* @param origin
* the origin
* @param socket
* the socket
* @return a IOConnection object
*/
static public IOConnection register(String origin, SocketIO socket) {
List<IOConnection> list = connections.get(origin);
if (list == null) {
list = new LinkedList<IOConnection>();
connections.put(origin, list);
} else {
for (IOConnection connection : list) {
if (connection.register(socket))
return connection;
}
}
IOConnection connection = new IOConnection(origin, socket);
list.add(connection);
return connection;
}
/**
* Connects a socket to the IOConnection.
*
* @param socket
* the socket to be connected
* @return true, if successfully registered on this transport, otherwise
* false.
*/
public boolean register(SocketIO socket) {
String namespace = socket.getNamespace();
if (sockets.containsKey(namespace))
return false;
sockets.put(namespace, socket);
socket.setHeaders(headers);
IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT,
socket.getNamespace(), "");
sendPlain(connect.toString());
return true;
}
/**
* Disconnect a socket from the IOConnection. Shuts down this IOConnection
* if no further connections are available for this IOConnection.
*
* @param socket
* the socket to be shut down
*/
public void unregister(SocketIO socket) {
sendPlain("0::" + socket.getNamespace());
sockets.remove(socket.getNamespace());
socket.getCallback().onDisconnect();
if (sockets.size() == 0) {
cleanup();
}
}
/**
* Handshake.
*
*/
private void handshake() {
URL url;
String response;
URLConnection connection;
try {
setState(STATE_HANDSHAKE);
url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1);
connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection)
.setSSLSocketFactory(sslSocketFactory);
}
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(connectTimeout);
/* Setting the request headers */
for (Entry<Object, Object> entry : headers.entrySet()) {
connection.setRequestProperty((String) entry.getKey(),
(String) entry.getValue());
}
InputStream stream = connection.getInputStream();
Scanner in = new Scanner(stream);
response = in.nextLine();
String[] data = response.split(":");
sessionId = data[0];
heartbeatTimeout = Long.parseLong(data[1]) * 1000;
closingTimeout = Long.parseLong(data[2]) * 1000;
protocols = Arrays.asList(data[3].split(","));
} catch (Exception e) {
error(new SocketIOException("Error while handshaking", e));
}
}
/**
* Connect transport.
*/
private void connectTransport() {
if (getState() == STATE_INVALID)
return;
setState(STATE_CONNECTING);
if (protocols.contains(WebsocketTransport.TRANSPORT_NAME))
transport = WebsocketTransport.create(url, this);
else if (protocols.contains(XhrTransport.TRANSPORT_NAME))
transport = XhrTransport.create(url, this);
else {
error(new SocketIOException(
"Server supports no available transports. You should reconfigure the server to support a available transport"));
return;
}
transport.connect();
}
/**
* Creates a new {@link IOAcknowledge} instance which sends its arguments
* back to the server.
*
* @param message
* the message
* @return an {@link IOAcknowledge} instance, may be <code>null</code> if
* server doesn't request one.
*/
private IOAcknowledge remoteAcknowledge(IOMessage message) {
String _id = message.getId();
if (_id.equals(""))
return null;
else if (_id.endsWith("+") == false)
_id = _id + "+";
final String id = _id;
final String endPoint = message.getEndpoint();
return new IOAcknowledge() {
@Override
public void ack(Object... args) {
JSONArray array = new JSONArray();
for (Object o : args) {
try {
array.put(o == null ? JSONObject.NULL : o);
} catch (Exception e) {
error(new SocketIOException(
"You can only put values in IOAcknowledge.ack() which can be handled by JSONArray.put()",
e));
}
}
IOMessage ackMsg = new IOMessage(IOMessage.TYPE_ACK, endPoint,
id + array.toString());
sendPlain(ackMsg.toString());
}
};
}
/**
* adds an {@link IOAcknowledge} to an {@link IOMessage}.
*
* @param message
* the {@link IOMessage}
* @param ack
* the {@link IOAcknowledge}
*/
private void synthesizeAck(IOMessage message, IOAcknowledge ack) {
if (ack != null) {
int id = nextId++;
acknowledge.put(id, ack);
message.setId(id + "+");
}
}
/**
* Instantiates a new IOConnection.
*
* @param url
* the URL
* @param socket
* the socket
*/
private IOConnection(String url, SocketIO socket) {
try {
this.url = new URL(url);
this.urlStr = url;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
firstSocket = socket;
headers = socket.getHeaders();
sockets.put(socket.getNamespace(), socket);
new ConnectThread().start();
}
/**
* Cleanup. IOConnection is not usable after this calling this.
*/
private void cleanup() {
setState(STATE_INVALID);
if (transport != null)
transport.disconnect();
sockets.clear();
synchronized (connections) {
List<IOConnection> con = connections.get(urlStr);
if (con != null && con.size() > 1)
con.remove(this);
else
connections.remove(urlStr);
}
logger.info("Cleanup");
backgroundTimer.cancel();
}
/**
* Populates an error to the connected {@link IOCallback}s and shuts down.
*
* @param e
* an exception
*/
private void error(SocketIOException e) {
for (SocketIO socket : sockets.values()) {
socket.getCallback().onError(e);
}
cleanup();
}
/**
* Sends a plain message to the {@link IOTransport}.
*
* @param text
* the Text to be send.
*/
private void sendPlain(String text) {
synchronized (outputBuffer) {
if (getState() == STATE_READY)
try {
logger.info("> " + text);
transport.send(text);
} catch (Exception e) {
logger.info("IOEx: saving");
outputBuffer.add(text);
}
else {
outputBuffer.add(text);
}
}
}
/**
* Invalidates an {@link IOTransport}, used for forced reconnecting.
*/
private void invalidateTransport() {
if (transport != null)
transport.invalidate();
transport = null;
}
/**
* Reset timeout.
*/
private void resetTimeout() {
if (heartbeatTimeoutTask != null) {
heartbeatTimeoutTask.cancel();
}
heartbeatTimeoutTask = new HearbeatTimeoutTask();
backgroundTimer.schedule(heartbeatTimeoutTask, closingTimeout
+ heartbeatTimeout);
}
/**
* finds the corresponding callback object to an incoming message. Returns a
* dummy callback if no corresponding callback can be found
*
* @param message
* the message
* @return the iO callback
* @throws SocketIOException
*/
private IOCallback findCallback(IOMessage message) throws SocketIOException {
if ("".equals(message.getEndpoint()))
return this;
SocketIO socket = sockets.get(message.getEndpoint());
if (socket == null) {
throw new SocketIOException("Cannot find socket for '"
+ message.getEndpoint() + "'");
}
return socket.getCallback();
}
/**
* Transport connected.
*
* {@link IOTransport} calls this when a connection is established.
*/
public void transportConnected() {
setState(STATE_READY);
if (reconnectTask != null) {
reconnectTask.cancel();
reconnectTask = null;
}
resetTimeout();
synchronized (outputBuffer) {
if (transport.canSendBulk()) {
ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
this.outputBuffer = new ConcurrentLinkedQueue<String>();
try {
// DEBUG
String[] texts = outputBuffer
.toArray(new String[outputBuffer.size()]);
logger.info("Bulk start:");
for (String text : texts) {
logger.info("> " + text);
}
logger.info("Bulk end");
// DEBUG END
transport.sendBulk(texts);
} catch (IOException e) {
this.outputBuffer = outputBuffer;
}
} else {
String text;
while ((text = outputBuffer.poll()) != null)
sendPlain(text);
}
this.keepAliveInQueue = false;
}
}
/**
* Transport disconnected.
*
* {@link IOTransport} calls this when a connection has been shut down.
*/
public void transportDisconnected() {
this.lastException = null;
setState(STATE_INTERRUPTED);
reconnect();
}
/**
* Transport error.
*
* @param error
* the error {@link IOTransport} calls this, when an exception
* has occurred and the transport is not usable anymore.
*/
public void transportError(Exception error) {
this.lastException = error;
setState(STATE_INTERRUPTED);
reconnect();
}
/**
* {@link IOTransport} should call this function if it does not support
* framing. If it does, transportMessage should be used
*
* @param text
* the text
*/
public void transportData(String text) {
if (!text.startsWith(FRAME_DELIMITER)) {
transportMessage(text);
return;
}
Iterator<String> fragments = Arrays.asList(text.split(FRAME_DELIMITER))
.listIterator(1);
while (fragments.hasNext()) {
int length = Integer.parseInt(fragments.next());
String string = (String) fragments.next();
// Potential BUG: it is not defined if length is in bytes or
// characters. Assuming characters.
if (length != string.length()) {
error(new SocketIOException("Garbage from server: " + text));
return;
}
transportMessage(string);
}
}
/**
* Transport message. {@link IOTransport} calls this, when a message has
* been received.
*
* @param text
* the text
*/
public void transportMessage(String text) {
logger.info("< " + text);
IOMessage message;
try {
message = new IOMessage(text);
} catch (Exception e) {
error(new SocketIOException("Garbage from server: " + text, e));
return;
}
resetTimeout();
switch (message.getType()) {
case IOMessage.TYPE_DISCONNECT:
try {
findCallback(message).onDisconnect();
} catch (Exception e) {
error(new SocketIOException(
"Exception was thrown in onDisconnect()", e));
}
break;
case IOMessage.TYPE_CONNECT:
try {
if (firstSocket != null && "".equals(message.getEndpoint())) {
if (firstSocket.getNamespace().equals("")) {
firstSocket.getCallback().onConnect();
} else {
IOMessage connect = new IOMessage(
IOMessage.TYPE_CONNECT,
firstSocket.getNamespace(), "");
sendPlain(connect.toString());
}
} else {
findCallback(message).onConnect();
}
firstSocket = null;
} catch (Exception e) {
error(new SocketIOException(
"Exception was thrown in onConnect()", e));
}
break;
case IOMessage.TYPE_HEARTBEAT:
sendPlain("2::");
break;
case IOMessage.TYPE_MESSAGE:
try {
findCallback(message).onMessage(message.getData(),
remoteAcknowledge(message));
} catch (Exception e) {
error(new SocketIOException(
"Exception was thrown in onMessage(String).\n"
+ "Message was: " + message.toString(), e));
}
break;
case IOMessage.TYPE_JSON_MESSAGE:
try {
JSONObject obj = null;
String data = message.getData();
if (data.trim().equals("null") == false)
obj = new JSONObject(data);
try {
findCallback(message).onMessage(obj,
remoteAcknowledge(message));
} catch (Exception e) {
error(new SocketIOException(
"Exception was thrown in onMessage(JSONObject).\n"
+ "Message was: " + message.toString(), e));
}
} catch (JSONException e) {
logger.warning("Malformated JSON received");
}
break;
case IOMessage.TYPE_EVENT:
try {
JSONObject event = new JSONObject(message.getData());
Object[] argsArray;
if (event.has("args")) {
JSONArray args = event.getJSONArray("args");
argsArray = new Object[args.length()];
for (int i = 0; i < args.length(); i++) {
if (args.isNull(i) == false)
argsArray[i] = args.get(i);
}
} else
argsArray = new Object[0];
String eventName = event.getString("name");
try {
findCallback(message).on(eventName,
remoteAcknowledge(message), argsArray);
} catch (Exception e) {
error(new SocketIOException(
"Exception was thrown in on(String, JSONObject[]).\n"
+ "Message was: " + message.toString(), e));
}
} catch (JSONException e) {
logger.warning("Malformated JSON received");
}
break;
case IOMessage.TYPE_ACK:
String[] data = message.getData().split("\\+", 2);
if (data.length == 2) {
try {
int id = Integer.parseInt(data[0]);
IOAcknowledge ack = acknowledge.get(id);
if (ack == null)
logger.warning("Received unknown ack packet");
else {
JSONArray array = new JSONArray(data[1]);
Object[] args = new Object[array.length()];
for (int i = 0; i < args.length; i++) {
args[i] = array.get(i);
}
ack.ack(args);
}
} catch (NumberFormatException e) {
logger.warning("Received malformated Acknowledge! This is potentially filling up the acknowledges!");
} catch (JSONException e) {
logger.warning("Received malformated Acknowledge data!");
}
} else if (data.length == 1) {
sendPlain("6:::" + data[0]);
}
break;
case IOMessage.TYPE_ERROR:
try {
findCallback(message).onError(
new SocketIOException(message.getData()));
} catch (SocketIOException e) {
error(e);
}
if (message.getData().endsWith("+0")) {
// We are advised to disconnect
cleanup();
}
break;
case IOMessage.TYPE_NOOP:
break;
default:
logger.warning("Unkown type received" + message.getType());
break;
}
}
/**
* forces a reconnect. This had become useful on some android devices which
* do not shut down TCP-connections when switching from HSDPA to Wifi
*/
public void reconnect() {
synchronized (this) {
if (getState() != STATE_INVALID) {
invalidateTransport();
setState(STATE_INTERRUPTED);
if (reconnectTask != null) {
reconnectTask.cancel();
}
reconnectTask = new ReconnectTask();
backgroundTimer.schedule(reconnectTask, 1000);
}
}
}
/**
* Returns the session id. This should be called from a {@link IOTransport}
*
* @return the session id to connect to the right Session.
*/
public String getSessionId() {
return sessionId;
}
/**
* sends a String message from {@link SocketIO} to the {@link IOTransport}.
*
* @param socket
* the socket
* @param ack
* acknowledge package which can be called from the server
* @param text
* the text
*/
public void send(SocketIO socket, IOAcknowledge ack, String text) {
IOMessage message = new IOMessage(IOMessage.TYPE_MESSAGE,
socket.getNamespace(), text);
synthesizeAck(message, ack);
sendPlain(message.toString());
}
/**
* sends a JSON message from {@link SocketIO} to the {@link IOTransport}.
*
* @param socket
* the socket
* @param ack
* acknowledge package which can be called from the server
* @param json
* the json
*/
public void send(SocketIO socket, IOAcknowledge ack, JSONObject json) {
IOMessage message = new IOMessage(IOMessage.TYPE_JSON_MESSAGE,
socket.getNamespace(), json.toString());
synthesizeAck(message, ack);
sendPlain(message.toString());
}
/**
* emits an event from {@link SocketIO} to the {@link IOTransport}.
*
* @param socket
* the socket
* @param event
* the event
* @param ack
* acknowledge package which can be called from the server
* @param args
* the arguments to be send
*/
public void emit(SocketIO socket, String event, IOAcknowledge ack,
Object... args) {
try {
JSONObject json = new JSONObject().put("name", event).put("args",
new JSONArray(Arrays.asList(args)));
IOMessage message = new IOMessage(IOMessage.TYPE_EVENT,
socket.getNamespace(), json.toString());
synthesizeAck(message, ack);
sendPlain(message.toString());
} catch (JSONException e) {
error(new SocketIOException(
"Error while emitting an event. Make sure you only try to send arguments, which can be serialized into JSON."));
}
}
/**
* Checks if IOConnection is currently connected.
*
* @return true, if is connected
*/
public boolean isConnected() {
return getState() == STATE_READY;
}
/**
* Gets the current state of this IOConnection.
*
* @return current state
*/
private synchronized int getState() {
return state;
}
/**
* Sets the current state of this IOConnection.
*
* @param state
* the new state
*/
private synchronized void setState(int state) {
this.state = state;
}
/**
* gets the currently used transport.
*
* @return currently used transport
*/
public IOTransport getTransport() {
return transport;
}
@Override
public void onDisconnect() {
SocketIO socket = sockets.get("");
if (socket != null)
socket.getCallback().onConnect();
}
@Override
public void onConnect() {
SocketIO socket = sockets.get("");
if (socket != null)
socket.getCallback().onConnect();
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
for (SocketIO socket : sockets.values())
socket.getCallback().onMessage(data, ack);
}
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
for (SocketIO socket : sockets.values())
socket.getCallback().onMessage(json, ack);
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
for (SocketIO socket : sockets.values())
socket.getCallback().on(event, ack, args);
}
@Override
public void onError(SocketIOException socketIOException) {
for (SocketIO socket : sockets.values())
socket.getCallback().onError(socketIOException);
}
}
|
package jfmi.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jfmi.app.FileTag;
import jfmi.app.TaggedFile;
import static jfmi.app.TaggedFileSorters.SQLPrimaryKeySorter;
import jfmi.app.FileTagging;
import jfmi.repo.SQLiteRepository;
import jfmi.util.StringUtil;
/** A TaggedFileDAO provides data access for storing TaggedFile objects
in an underlying database.
*/
public class TaggedFileDAO extends AbstractDAO<TaggedFile, Integer> {
// PUBLIC CLASS Fields
public static final String TABLE_NAME = "main.TaggedFile";
// PRIVATE CLASS Fields
private static final String CREATE_PSQL;
private static final String READ_BY_ID_PSQL;
private static final String READ_BY_TAGS_SQL;
private static final String READ_ALL_SQL;
private static final String UPDATE_PSQL;
private static final String DELETE_PSQL;
private static final String DELETE_ALL_SQL;
static {
CREATE_PSQL = "INSERT INTO " + TABLE_NAME + "(path) VALUES(?)";
READ_BY_ID_PSQL = "SELECT * FROM " + TABLE_NAME + " WHERE fileId = ? ";
READ_BY_TAGS_SQL = "SELECT * FROM " + TABLE_NAME + " file, "
+ FileTaggingDAO.TABLE_NAME + " t "
+ " WHERE file.fileId = t.fileId ";
READ_ALL_SQL = "SELECT * FROM " + TABLE_NAME;
UPDATE_PSQL = "UPDATE " + TABLE_NAME
+ " SET fileId = ?, path = ? WHERE fileId = ? ";
DELETE_PSQL = "DELETE FROM " + TABLE_NAME + " WHERE fileId = ? ";
DELETE_ALL_SQL = "DELETE FROM " + TABLE_NAME;
}
/** Creates a new TaggedFile record in the underlying database.
@param createMe a TaggedFile instance containing the necessary information
to replicate it in the database
@return true if the record was created successfully
@throws SQLException if a problem occurs working with the database
*/
public boolean create(TaggedFile createMe) throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
PreparedStatement ps = conn.prepareStatement(CREATE_PSQL);
try {
ps.setString(1, createMe.getFilePath());
return ps.executeUpdate() == 1; // 1 row should be created
} finally {
SQLiteRepository.closeQuietly(ps);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Reads all TaggedFile records from the database.
@return a set of retrieved TaggedFile records
@throws SQLException if a problem occurs working with the database
*/
public SortedSet<TaggedFile> readAll() throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(READ_ALL_SQL);
try {
FileTaggingDAO tDAO = new FileTaggingDAO();
SortedSet<TaggedFile> set;
set = new TreeSet<TaggedFile>(new SQLPrimaryKeySorter());
TaggedFile next = null;
while (rs.next()) {
next = new TaggedFile();
next.setFileId(rs.getInt("fileId"));
next.setFilePath(rs.getString("path"));
SortedSet<FileTagging> tSet;
tSet = tDAO.readByFileId(next.getFileId());
next.setFileTaggings(tSet);
set.add(next);
}
return set;
} finally {
SQLiteRepository.closeQuietly(rs);
}
} finally {
SQLiteRepository.closeQuietly(stmt);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Retrieves the information necessary to create a TaggedFile object
from the relevant database tables.
@param id the file id of the record to search for
@return a new TaggedFile if the read was successful, null otherwise
@throws SQLException if a problem occurs working with the database
*/
public TaggedFile readById(Integer id) throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
PreparedStatement ps = conn.prepareStatement(READ_BY_ID_PSQL);
try {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
try {
TaggedFile result = null;
if (rs.next()) {
result = new TaggedFile();
result.setFileId(id);
result.setFilePath(rs.getString("path"));
FileTaggingDAO taggingDAO = new FileTaggingDAO();
result.setFileTaggings(taggingDAO.readByFileId(id));
}
return result;
} finally {
SQLiteRepository.closeQuietly(rs);
}
} finally {
SQLiteRepository.closeQuietly(ps);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Returns a sorted set of TaggedFile objects which have been tagged with
any of the specified tags.
@param tags the tag values by which to select TaggedFile records
@return a sorted set of results
@throws SQLException if a problem occurs working with the database
*/
public SortedSet<TaggedFile> readByTags(Set<FileTag> tags)
throws SQLException
{
String query = getReadByTagsQuery(tags);
Connection conn = SQLiteRepository.instance().getConnection();
try {
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
try {
return readFromResultSet(rs);
} finally {
SQLiteRepository.closeQuietly(rs);
}
} finally {
SQLiteRepository.closeQuietly(stmt);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Reads table fields from a ResultSet, creating a new TaggedFile for
each row, and returning a sorted set of all created TaggedFiles. This
method assumes that the ResultSet cursor is set one position before
the row to start reading from. The method attempts to read all fields
from the ResultSet. If a field is not present, the corresponding object's
field is left at the default value. If no fields are present in a row,
no object is created for the row.
@param rs the ResultSet to read records from
@return a sorted set of TaggedFiles
@throws SQLException if a problem occurs working with the database
*/
public SortedSet<TaggedFile> readFromResultSet(ResultSet rs)
throws SQLException
{
FileTaggingDAO taggingDAO = new FileTaggingDAO();
SortedSet<FileTagging> taggings = null;
SortedSet<TaggedFile> files = new TreeSet<TaggedFile>();
TaggedFile file = null;
boolean aFieldIsSet = false;
while (rs.next()) {
if (file == null) {
file = new TaggedFile();
}
try {
file.setFileId(rs.getInt("fileId"));
aFieldIsSet = true;
taggings = taggingDAO.readByFileId(rs.getInt("fileId"));
file.setFileTaggings(taggings);
} catch (SQLException e) {
}
try {
file.setFilePath(rs.getString("path"));
aFieldIsSet = true;
} catch (SQLException e) {
}
if (aFieldIsSet) {
files.add(file);
file = null;
}
}
return files;
}
/** Updates the specified TaggedFile's corresponding record in the database,
if it exists.
@param updateMe the TaggedFile whose information will update the record
@param id the id used to choose which record is updated
@return true if the record existed and was updated successfully
@throws SQLException if a problem occurs working with the database
*/
public boolean update(TaggedFile updateMe, Integer id) throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
PreparedStatement ps = conn.prepareStatement(UPDATE_PSQL);
try {
ps.setInt(1, updateMe.getFileId());
ps.setString(2, updateMe.getFilePath());
ps.setInt(3, id);
return ps.executeUpdate() == 1; // 1 row should be updated
} finally {
SQLiteRepository.closeQuietly(ps);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Deletes the specified TaggedFile's corresponding record from the
database if it exists.
@param deleteMe the TaggedFile whose record should be deleted
@return true if the record was deleted, or did not exist
@throws SQLException if a problem occurs working with the database
*/
public boolean delete(TaggedFile deleteMe) throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
PreparedStatement ps = conn.prepareStatement(DELETE_PSQL);
try {
ps.setInt(1, deleteMe.getFileId());
int rowCount = ps.executeUpdate();
return rowCount == 0 || rowCount == 1;
} finally {
SQLiteRepository.closeQuietly(ps);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Deletes all TaggedFile records from the database.
@throws SQLException if a problem occurs working with the database
*/
public void deleteAll() throws SQLException
{
Connection conn = SQLiteRepository.instance().getConnection();
try {
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate(DELETE_ALL_SQL);
} finally {
SQLiteRepository.closeQuietly(stmt);
}
} finally {
SQLiteRepository.closeQuietly(conn);
}
}
/** Creates an SQL query used by the readByTags() method.
@param tags a set of FileTags to be used in the query
@return the created SQL query string, or null if tags is null
*/
private String getReadByTagsQuery(Set<FileTag> tags)
{
Iterator<FileTag> it = tags.iterator();
String tag;
StringBuilder sql = new StringBuilder(READ_BY_TAGS_SQL);
if (it.hasNext()) {
tag = StringUtil.doubleQuote(it.next().getTag());
sql.append(" AND ( t.tag = " + tag);
} else {
return null;
}
while (it.hasNext()) {
tag = StringUtil.doubleQuote(it.next().getTag());
sql.append(", OR t.tag = " + tag);
}
sql.append(" )");
return sql.toString();
}
}
|
package com.yahoo.security.tls;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateUtils;
import com.yahoo.security.tls.authz.PeerAuthorizerTrustManager;
import com.yahoo.security.tls.policy.AuthorizedPeers;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.ref.WeakReference;
import java.nio.file.Path;
import java.security.KeyStore;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@link TlsContext} that uses the tls configuration specified in the transport security options file.
* The credentials are regularly reloaded to support short-lived certificates.
*
* @author bjorncs
*/
public class ConfigFileBasedTlsContext implements TlsContext {
private static final Duration UPDATE_PERIOD = Duration.ofHours(1);
private static final Logger log = Logger.getLogger(ConfigFileBasedTlsContext.class.getName());
private final TlsContext tlsContext;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ReloaderThreadFactory());
public ConfigFileBasedTlsContext(Path tlsOptionsConfigFile, AuthorizationMode mode) {
this(tlsOptionsConfigFile, mode, PeerAuthentication.NEED);
}
/**
* Allows the caller to override the default peer authentication mode. This is only intended to be used in situations where
* the TLS peer authentication is enforced at a higher protocol or application layer (e.g with {@link PeerAuthentication#WANT}).
*/
public ConfigFileBasedTlsContext(Path tlsOptionsConfigFile, AuthorizationMode mode, PeerAuthentication peerAuthentication) {
TransportSecurityOptions options = TransportSecurityOptions.fromJsonFile(tlsOptionsConfigFile);
MutableX509TrustManager trustManager = new MutableX509TrustManager();
MutableX509KeyManager keyManager = new MutableX509KeyManager();
reloadTrustManager(options, trustManager);
reloadKeyManager(options, keyManager);
this.tlsContext = createDefaultTlsContext(options, mode, trustManager, keyManager, peerAuthentication);
this.scheduler.scheduleAtFixedRate(new CryptoMaterialReloader(tlsOptionsConfigFile, scheduler, trustManager, keyManager),
UPDATE_PERIOD.getSeconds()/*initial delay*/,
UPDATE_PERIOD.getSeconds(),
TimeUnit.SECONDS);
}
private static void reloadTrustManager(TransportSecurityOptions options, MutableX509TrustManager trustManager) {
if (options.getCaCertificatesFile().isPresent()) {
trustManager.updateTruststore(loadTruststore(options.getCaCertificatesFile().get()));
} else {
trustManager.useDefaultTruststore();
}
}
private static void reloadKeyManager(TransportSecurityOptions options, MutableX509KeyManager keyManager) {
if (options.getPrivateKeyFile().isPresent() && options.getCertificatesFile().isPresent()) {
keyManager.updateKeystore(loadKeystore(options.getPrivateKeyFile().get(), options.getCertificatesFile().get()), new char[0]);
} else {
keyManager.useDefaultKeystore();
}
}
private static KeyStore loadTruststore(Path caCertificateFile) {
try {
return KeyStoreBuilder.withType(KeyStoreType.PKCS12)
.withCertificateEntries("cert", X509CertificateUtils.certificateListFromPem(com.yahoo.vespa.jdk8compat.Files.readString(caCertificateFile)))
.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static KeyStore loadKeystore(Path privateKeyFile, Path certificatesFile) {
try {
return KeyStoreBuilder.withType(KeyStoreType.PKCS12)
.withKeyEntry(
"default",
KeyUtils.fromPemEncodedPrivateKey(com.yahoo.vespa.jdk8compat.Files.readString(privateKeyFile)),
X509CertificateUtils.certificateListFromPem(com.yahoo.vespa.jdk8compat.Files.readString(certificatesFile)))
.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static DefaultTlsContext createDefaultTlsContext(TransportSecurityOptions options,
AuthorizationMode mode,
MutableX509TrustManager mutableTrustManager,
MutableX509KeyManager mutableKeyManager,
PeerAuthentication peerAuthentication) {
PeerAuthorizerTrustManager authorizerTrustManager = options.getAuthorizedPeers()
.map(authorizedPeers -> new PeerAuthorizerTrustManager(authorizedPeers, mode, mutableTrustManager))
.orElseGet(() -> new PeerAuthorizerTrustManager(new AuthorizedPeers(com.yahoo.vespa.jdk8compat.Set.of()), AuthorizationMode.DISABLE, mutableTrustManager)));
SSLContext sslContext = new SslContextBuilder()
.withKeyManager(mutableKeyManager)
.withTrustManager(authorizerTrustManager)
.build();
List<String> acceptedCiphers = options.getAcceptedCiphers();
Set<String> ciphers = acceptedCiphers.isEmpty() ? TlsContext.ALLOWED_CIPHER_SUITES : new HashSet<>(acceptedCiphers);
return new DefaultTlsContext(sslContext, ciphers, peerAuthentication);
}
// Wrapped methods from TlsContext
@Override public SSLContext context() { return tlsContext.context(); }
@Override public SSLParameters parameters() { return tlsContext.parameters(); }
@Override public SSLEngine createSslEngine() { return tlsContext.createSslEngine(); }
@Override public SSLEngine createSslEngine(String peerHost, int peerPort) { return tlsContext.createSslEngine(peerHost, peerPort); }
@Override
public void close() {
try {
scheduler.shutdownNow();
if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
throw new RuntimeException("Unable to shutdown executor before timeout");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// Note: no reference to outer class (directly or indirectly) to ensure trust/key managers are eventually GCed once
// there are no more use of the outer class and the underlying SSLContext
private static class CryptoMaterialReloader implements Runnable {
final Path tlsOptionsConfigFile;
final ScheduledExecutorService scheduler;
final WeakReference<MutableX509TrustManager> trustManager;
final WeakReference<MutableX509KeyManager> keyManager;
CryptoMaterialReloader(Path tlsOptionsConfigFile,
ScheduledExecutorService scheduler,
MutableX509TrustManager trustManager,
MutableX509KeyManager keyManager) {
this.tlsOptionsConfigFile = tlsOptionsConfigFile;
this.scheduler = scheduler;
this.trustManager = new WeakReference<>(trustManager);
this.keyManager = new WeakReference<>(keyManager);
}
@Override
public void run() {
try {
MutableX509TrustManager trustManager = this.trustManager.get();
MutableX509KeyManager keyManager = this.keyManager.get();
if (trustManager == null && keyManager == null) {
scheduler.shutdown();
return;
}
TransportSecurityOptions options = TransportSecurityOptions.fromJsonFile(tlsOptionsConfigFile);
if (trustManager != null) {
reloadTrustManager(options, trustManager);
}
if (keyManager != null) {
reloadKeyManager(options, keyManager);
}
} catch (Throwable t) {
log.log(Level.SEVERE, String.format("Failed to reload crypto material (path='%s'): %s", tlsOptionsConfigFile, t.getMessage()), t);
}
}
}
// Static class to ensure no reference to outer class is contained
private static class ReloaderThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "tls-context-reloader");
thread.setDaemon(true);
return thread;
}
}
}
|
package org.zanata.security;
import static org.jboss.seam.ScopeType.SESSION;
import java.util.List;
import javax.faces.context.ExternalContext;
import javax.servlet.http.HttpServletRequest;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesManager;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.international.StatusMessage;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.openid.OpenIdPrincipal;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.FetchRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zanata.ApplicationConfiguration;
import org.zanata.dao.AccountDAO;
import org.zanata.model.HAccount;
import org.zanata.security.openid.FedoraOpenIdProvider;
import org.zanata.security.openid.GenericOpenIdProvider;
import org.zanata.security.openid.GoogleOpenIdProvider;
import org.zanata.security.openid.MyOpenIdProvider;
import org.zanata.security.openid.OpenIdAuthCallback;
import org.zanata.security.openid.OpenIdAuthenticationResult;
import org.zanata.security.openid.OpenIdProvider;
import org.zanata.security.openid.OpenIdProviderType;
import org.zanata.security.openid.YahooOpenIdProvider;
@Name("org.jboss.seam.security.zanataOpenId")
@Scope(SESSION)
@AutoCreate
/*
* based on org.jboss.seam.security.openid.OpenId class
*/
public class ZanataOpenId implements OpenIdAuthCallback
{
private static final Logger LOGGER = LoggerFactory.getLogger(ZanataOpenId.class);
private ZanataIdentity identity;
private ApplicationConfiguration applicationConfiguration;
@In
private Credentials credentials;
@In
private UserRedirectBean userRedirect;
@In
private AccountDAO accountDAO;
private String id;
private OpenIdAuthenticationResult authResult;
private OpenIdAuthCallback callback;
private OpenIdProvider openIdProvider;
private ConsumerManager manager;
private DiscoveryInformation discovered;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public OpenIdAuthenticationResult getAuthResult()
{
return authResult;
}
public void setCallback(OpenIdAuthCallback callback)
{
this.callback = callback;
}
@SuppressWarnings("rawtypes")
protected String authRequest(String userSuppliedString, String returnToUrl)
{
try
{
// perform discovery on the user-supplied identifier
List discoveries = manager.discover(userSuppliedString);
// attempt to associate with the OpenID providerType
// and retrieve one service endpoint for authentication
discovered = manager.associate(discoveries);
// // store the discovery information in the user's session
// httpReq.getSession().setAttribute("openid-disc", discovered);
// obtain a AuthRequest message to be sent to the OpenID providerType
AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
// Attribute Exchange example: fetching the 'email' attribute
FetchRequest fetch = FetchRequest.createFetchRequest();
openIdProvider.prepareRequest(fetch);
// attach the extension to the authentication request
authReq.addExtension(fetch);
return authReq.getDestinationUrl(true);
}
catch (OpenIDException e)
{
LOGGER.warn("exception", e);
}
return null;
}
public void verify()
{
ExternalContext context = javax.faces.context.FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest) context.getRequest();
authResult.setAuthenticatedId( verifyResponse(request) );
}
public boolean loginImmediately()
{
if (authResult.isAuthenticated())
{
Identity.instance().acceptExternallyAuthenticatedPrincipal((new OpenIdPrincipal(authResult.getAuthenticatedId())));
return true;
}
return false;
}
public String verifyResponse(HttpServletRequest httpReq)
{
try
{
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID providerType)
ParameterList response = new ParameterList(httpReq.getParameterMap());
StringBuilder receivingURL = new StringBuilder(returnToUrl());
String queryString = httpReq.getQueryString();
if (queryString != null && queryString.length() > 0)
{
receivingURL.append("?").append(httpReq.getQueryString());
}
// verify the response; ConsumerManager needs to be the same
// (static) instance used to place the authentication request
VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);
// The OpenId provider cancelled the authentication
if( "cancel".equals( response.getParameterValue("openid.mode") ) )
{
// TODO This should be done at a higher level. i.e. instead of returning a string, return an
// object that holds more information for the UI to render
FacesMessages.instance().add(StatusMessage.Severity.INFO, "Authentication Request Cancelled");
}
// examine the verification result and extract the verified identifier
Identifier verified = verification.getVerifiedId();
if (verified != null)
{
authResult = new OpenIdAuthenticationResult();
authResult.setAuthenticatedId( verified.getIdentifier() );
authResult.setEmail( openIdProvider.getEmail(response) ); // Get the email address
}
// invoke the callbacks
if( callback != null )
{
callback.afterOpenIdAuth(authResult);
if( callback.getRedirectToUrl() != null )
{
userRedirect.setLocalUrl(callback.getRedirectToUrl());
}
}
if( verified != null )
{
return verified.getIdentifier();
}
}
catch (OpenIDException e)
{
LOGGER.warn("exception", e);
}
return null;
}
public void logout()
{
init();
}
@Create
public void init()
{
try
{
manager = new ConsumerManager();
discovered = null;
id = null;
authResult = new OpenIdAuthenticationResult();
}
catch (ConsumerException e)
{
throw new RuntimeException(e);
}
identity = (ZanataIdentity) Component.getInstance(ZanataIdentity.class, ScopeType.SESSION);
applicationConfiguration = (ApplicationConfiguration) Component.getInstance(ApplicationConfiguration.class, ScopeType.APPLICATION);
}
private void loginImmediate()
{
if (loginImmediately() && Events.exists())
{
Events.instance().raiseEvent(Identity.EVENT_POST_AUTHENTICATE, identity);
// Events.instance().raiseEvent(Identity.EVENT_LOGIN_SUCCESSFUL,
// AuthenticationType.OPENID);
Events.instance().raiseEvent(AuthenticationManager.EVENT_LOGIN_COMPLETED, AuthenticationType.OPENID);
}
}
private void login(String username, OpenIdProviderType openIdProviderType, OpenIdAuthCallback callback)
{
try
{
this.setProvider(openIdProviderType);
String var = openIdProvider.getOpenId(username);
setId(var);
setCallback(callback);
LOGGER.info("openid: {}", getId());
login();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void login(ZanataCredentials credentials)
{
this.login(credentials, this);
}
public void login(ZanataCredentials credentials, OpenIdAuthCallback callback)
{
this.login(credentials.getUsername(), credentials.getOpenIdProviderType(), callback);
}
private void login()
{
authResult = new OpenIdAuthenticationResult();
String returnToUrl = returnToUrl();
String url = authRequest(id, returnToUrl);
if (url != null)
{
Redirect redirect = Redirect.instance();
redirect.captureCurrentView();
FacesManager.instance().redirectToExternalURL(url);
}
}
public String returnToUrl()
{
return applicationConfiguration.getServerPath() + "/openid.seam";
}
/**
* Default implementation for an authentication callback. This implementations simply authenticates
* the user locally.
*/
@Override
public void afterOpenIdAuth(OpenIdAuthenticationResult result)
{
if( result.isAuthenticated() )
{
HAccount authenticatedAccount = accountDAO.getByCredentialsId( result.getAuthenticatedId() );
identity.setPreAuthenticated(true);
// If the user hasn't been registered, there is no authenticated account
if( authenticatedAccount != null && authenticatedAccount.isEnabled() )
{
credentials.setUsername(authenticatedAccount.getUsername());
Identity.instance().acceptExternallyAuthenticatedPrincipal((new OpenIdPrincipal(result.getAuthenticatedId())));
this.loginImmediate();
}
}
}
/**
* Default implementation for an authentication callback. This implementation does not provide a redirect url.
*/
@Override
public String getRedirectToUrl()
{
return null;
}
public void setProvider( OpenIdProviderType providerType )
{
if( providerType != null )
{
switch (providerType)
{
case Fedora:
this.openIdProvider = new FedoraOpenIdProvider();
break;
case Google:
this.openIdProvider = new GoogleOpenIdProvider();
break;
case MyOpenId:
this.openIdProvider = new MyOpenIdProvider();
break;
case Yahoo:
this.openIdProvider = new YahooOpenIdProvider();
break;
case Generic:
this.openIdProvider = new GenericOpenIdProvider();
break;
default:
this.openIdProvider = new GenericOpenIdProvider();
break;
}
}
}
public boolean isFederatedProvider()
{
return this.openIdProvider instanceof GoogleOpenIdProvider;
}
}
|
package gameEngine.model;
import gameEngine.factory.gridFactory.GridFactory;
import gameEngine.factory.towerfactory.TowerFactory;
import gameEngine.model.purchase.PurchaseInfo;
import gameEngine.model.tile.Tile;
import gameEngine.model.tower.Tower;
import gameEngine.model.warehouse.EnemyWarehouse;
import gameEngine.model.warehouse.TowerWarehouse;
import gameEngine.parser.Parser;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import jgame.impl.JGEngineInterface;
public class Model {
/**
* @author Yuhua
*
* warehouse - store different kinds of tower, enemy warehouse
*
*/
private Scanner scanner;
private Parser parser;
private GameInfo gameInfo;
private TowerWarehouse towerWarehouse;
private EnemyWarehouse enemyWarehouse;
private GridFactory gridFactory;
private LinkedList<Tile> path;
private JGEngineInterface myEng;
private Rule rule; // how each waves created, ruleStart, ruleStop
private ArrayList<ArrayList<Tile>> grid;
private ArrayList<Tile> barriers;
public Model () {
rule = new Rule();
}
public void newGame (File jsonFile) throws Exception {
// For test convenience
// jsonFile = new File(System.getProperty("user.dir") + "/src/gameEngine/test/testTowerEnemyBullet/mygame.json");
scanner = new Scanner(jsonFile);
parser = new Parser(scanner);
gridFactory = new GridFactory(parser);
gridFactory.initialize();
path = gridFactory.getPathList();
grid = gridFactory.getGridList();
barriers = gridFactory.getBarrierList();
towerWarehouse = new TowerWarehouse(parser);
enemyWarehouse = new EnemyWarehouse(parser, this);
gameInfo = new GameInfo(parser);
}
public void startGame () {
Wave w = new Wave("1", 10, 500, 1000, enemyWarehouse);
rule.addWave(w);
rule.ruleStart();
}
//Yuhua change it
// public List<Tile> getPathList () {
public LinkedList<Tile> getPathList () {
return path;
}
public ArrayList<Tile> getBarrierList () {
return barriers;
}
/**
* @author Yuhua
* Tower Related Method
*/
/**
* return all kinds of TowerFactory
*/
//edit by Jiaran to hold encapsulation by passing TowerInfo.
public List<PurchaseInfo> getAllTowerInfo () {
List<PurchaseInfo> result= new ArrayList<PurchaseInfo>();
List<TowerFactory> factoryList=towerWarehouse.getTowerFactory();
for(int i=0; i< factoryList.size();i++){
result.add((PurchaseInfo)(factoryList.get(i)));
}
return result;
}
//Refractor method to check whether Tower exist at (x, y)
public Tower checkTowerAtXY(int x, int y){
int detectRange = 10;
Detector<Tower> d= new Detector<Tower>(myEng,Tower.class);
return d.getOneTargetInRange(x, y, detectRange);
}
//Jiaran: Im thinking maybe this should return a TowerInfo instead of Tower
// Tower can implemetns Towerinfo which has getDescription,getDamage....
// now it is not functional because no myEng, we need discussion on this.
public PurchaseInfo getTowerInfo (int x, int y) {
return (PurchaseInfo)checkTowerAtXY(x, y);
}
// Jiaran: purchase, get tower info. If something is wrong plz contact
public boolean purchaseTower (int x, int y, String name) {
Tile currentTile = getTile(x, y);
if (currentTile.isEmpty() && !currentTile.hasPath()) { return towerWarehouse
.create((int) currentTile.getX(), (int) currentTile.getY(), name, gameInfo); }
return false;
}
public boolean sellTower(int x, int y){
Tower tower = checkTowerAtXY(x, y);
if(tower != null){
return true;
}
return false;
}
public boolean upgradeTower(int x, int y){
Tower tower = checkTowerAtXY(x, y);
if(tower != null){
return true;
}
return false;
}
public boolean setTowerAttackMode(int x, int y, int attackMode){
Tower tower = checkTowerAtXY(x, y);
if(tower != null){
return true;
}
return false;
}
public Tile getTile(int x, int y) {
for(int k=0; k<grid.size(); k++) {
ArrayList<Tile> tempArray = grid.get(k);
for(int m=0; m<tempArray.size(); m++) {
Tile tile = tempArray.get(m);
if(tile.getX() <= x && tile.getEndX() >= x && tile.getY() <= y && tile.getEndY() >= y) {
return tile;
}
}
}
return null;
}
/**
* @author Jiaran
* GameInfo getter method
* deleted by Jiaran based on Duvall's suggestion. Delete this when
* every on is aware
**/
/*
* Model Getter methods
*/
public GameInfo getGameInfo() {
return gameInfo;
}
}
|
package gameEngine.model;
import gameEngine.factory.GridFactory;
import gameEngine.factory.towerfactory.TowerFactory;
import gameEngine.model.tower.Tower;
import gameEngine.model.warehouse.EnemyWarehouse;
import gameEngine.model.warehouse.TowerWarehouse;
import gameEngine.parser.Parser;
import java.awt.Dimension;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import jgame.impl.JGEngineInterface;
public class Model {
/**
* @author Yuhua
*
* warehouse - store different kinds of tower, enemy warehouse
*
*/
private Scanner scanner;
private Parser parser;
private GameInfo gameInfo;
private TowerWarehouse towerWarehouse;
private EnemyWarehouse enemyWarehouse;
private GridFactory gridFactory;
private LinkedList<Tile> path;
private JGEngineInterface myEng;
private Rule rule; //how each waves created, ruleStart, ruleStop
// private Rule rule;
public Model () {
rule = new Rule();
}
public void newGame(File jsonFile) throws Exception{
// For test convenience
// jsonFile = new File(System.getProperty("user.dir") + "/src/gameEngine/test/testTowerEnemyBullet/mygame.json");
scanner = new Scanner(jsonFile);
parser = new Parser(scanner);
gridFactory = new GridFactory(parser);
gridFactory.initialize();
path = gridFactory.getPathList();
// 2 create factory by
towerWarehouse = new TowerWarehouse(parser);
enemyWarehouse = new EnemyWarehouse(parser, path);
gameInfo = new GameInfo(1000, 1000, 1000, null);
}
public void startGame(){
towerWarehouse.create("DefaultTower"); // test, should be called within Rule
Wave w = new Wave("1", 10, 500, 1000, enemyWarehouse);
rule.addWave(w);
rule.ruleStart();
}
public List<Tile> getPathList() {
return path;
}
/**
* return all kinds of TowerFactory
*/
public List<TowerFactory> getTowerFactory () {
return towerWarehouse.getTowerFactory();
}
// Jiaran purchase, get tower info. If something is wrong plz contact
public boolean purchaseTower (int x, int y, String name) {
return towerWarehouse.create(x, y, name,gameInfo);
}
//Jiaran Im thinking maybe this should return a TowerInfo instead of Tower
// Tower can implemetns Towerinfo which has getDescription,getDamage....
// now it is not functional because no myEng, we need discussion on this.
public Tower getTowerInfo (int x, int y) {
Detector<Tower> d= new Detector<Tower>(myEng,Tower.class);
return d.getOneTargetInRange(x, y, 10);
}
/*
* GameInfo getter method
*/
public int getMoney () {
return gameInfo.getGold();
}
public int getLife () {
return gameInfo.getLife();
}
public String getBGImage () {
return gameInfo.getBGImage();
}
}
|
package org.elasticsearch.indices.recovery;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.RateLimiter;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.StepListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.ThreadedActionListener;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.CheckedRunnable;
import org.elasticsearch.common.StopWatch;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.bytes.ReleasableBytesReference;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.CancellableThreads;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.common.util.concurrent.ListenableFuture;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.RecoveryEngineException;
import org.elasticsearch.index.seqno.ReplicationTracker;
import org.elasticsearch.index.seqno.RetentionLease;
import org.elasticsearch.index.seqno.RetentionLeaseNotFoundException;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardClosedException;
import org.elasticsearch.index.shard.IndexShardRelocatedException;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetadata;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.RemoteTransportException;
import org.elasticsearch.transport.Transports;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.stream.StreamSupport;
/**
* RecoverySourceHandler handles the three phases of shard recovery, which is
* everything relating to copying the segment files as well as sending translog
* operations across the wire once the segments have been copied.
*
* Note: There is always one source handler per recovery that handles all the
* file and translog transfer. This handler is completely isolated from other recoveries
* while the {@link RateLimiter} passed via {@link RecoverySettings} is shared across recoveries
* originating from this nodes to throttle the number bytes send during file transfer. The transaction log
* phase bypasses the rate limiter entirely.
*/
public class RecoverySourceHandler {
protected final Logger logger;
// Shard that is going to be recovered (the "source")
private final IndexShard shard;
private final int shardId;
// Request containing source and target node information
private final StartRecoveryRequest request;
private final int chunkSizeInBytes;
private final RecoveryTargetHandler recoveryTarget;
private final int maxConcurrentFileChunks;
private final int maxConcurrentOperations;
private final ThreadPool threadPool;
private final CancellableThreads cancellableThreads = new CancellableThreads();
private final List<Closeable> resources = new CopyOnWriteArrayList<>();
private final ListenableFuture<RecoveryResponse> future = new ListenableFuture<>();
public RecoverySourceHandler(IndexShard shard, RecoveryTargetHandler recoveryTarget, ThreadPool threadPool,
StartRecoveryRequest request, int fileChunkSizeInBytes, int maxConcurrentFileChunks,
int maxConcurrentOperations) {
this.shard = shard;
this.recoveryTarget = recoveryTarget;
this.threadPool = threadPool;
this.request = request;
this.shardId = this.request.shardId().id();
this.logger = Loggers.getLogger(getClass(), request.shardId(), "recover to " + request.targetNode().getName());
this.chunkSizeInBytes = fileChunkSizeInBytes;
this.maxConcurrentFileChunks = maxConcurrentFileChunks;
this.maxConcurrentOperations = maxConcurrentOperations;
}
public StartRecoveryRequest getRequest() {
return request;
}
public void addListener(ActionListener<RecoveryResponse> listener) {
future.addListener(listener, EsExecutors.newDirectExecutorService());
}
/**
* performs the recovery from the local engine to the target
*/
public void recoverToTarget(ActionListener<RecoveryResponse> listener) {
addListener(listener);
final Closeable releaseResources = () -> IOUtils.close(resources);
try {
cancellableThreads.setOnCancel((reason, beforeCancelEx) -> {
final RuntimeException e;
if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us
e = new IndexShardClosedException(shard.shardId(), "shard is closed and recovery was canceled reason [" + reason + "]");
} else {
e = new CancellableThreads.ExecutionCancelledException("recovery was canceled reason [" + reason + "]");
}
if (beforeCancelEx != null) {
e.addSuppressed(beforeCancelEx);
}
IOUtils.closeWhileHandlingException(releaseResources, () -> future.onFailure(e));
throw e;
});
final Consumer<Exception> onFailure = e -> {
assert Transports.assertNotTransportThread(RecoverySourceHandler.this + "[onFailure]");
IOUtils.closeWhileHandlingException(releaseResources, () -> future.onFailure(e));
};
final SetOnce<RetentionLease> retentionLeaseRef = new SetOnce<>();
runUnderPrimaryPermit(() -> {
final IndexShardRoutingTable routingTable = shard.getReplicationGroup().getRoutingTable();
ShardRouting targetShardRouting = routingTable.getByAllocationId(request.targetAllocationId());
if (targetShardRouting == null) {
logger.debug("delaying recovery of {} as it is not listed as assigned to target node {}", request.shardId(),
request.targetNode());
throw new DelayRecoveryException("source node does not have the shard listed in its state as allocated on the node");
}
assert targetShardRouting.initializing() : "expected recovery target to be initializing but was " + targetShardRouting;
retentionLeaseRef.set(
shard.getRetentionLeases().get(ReplicationTracker.getPeerRecoveryRetentionLeaseId(targetShardRouting)));
}, shardId + " validating recovery target ["+ request.targetAllocationId() + "] registered ",
shard, cancellableThreads, logger);
final Closeable retentionLock = shard.acquireHistoryRetentionLock();
resources.add(retentionLock);
final long startingSeqNo;
final boolean isSequenceNumberBasedRecovery
= request.startingSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO
&& isTargetSameHistory()
&& shard.hasCompleteHistoryOperations("peer-recovery", request.startingSeqNo())
&& ((retentionLeaseRef.get() == null && shard.useRetentionLeasesInPeerRecovery() == false) ||
(retentionLeaseRef.get() != null && retentionLeaseRef.get().retainingSequenceNumber() <= request.startingSeqNo()));
// NB check hasCompleteHistoryOperations when computing isSequenceNumberBasedRecovery, even if there is a retention lease,
// because when doing a rolling upgrade from earlier than 7.4 we may create some leases that are initially unsatisfied. It's
// possible there are other cases where we cannot satisfy all leases, because that's not a property we currently expect to hold.
// Also it's pretty cheap when soft deletes are enabled, and it'd be a disaster if we tried a sequence-number-based recovery
// without having a complete history.
if (isSequenceNumberBasedRecovery && retentionLeaseRef.get() != null) {
// all the history we need is retained by an existing retention lease, so we do not need a separate retention lock
retentionLock.close();
logger.trace("history is retained by {}", retentionLeaseRef.get());
} else {
// all the history we need is retained by the retention lock, obtained before calling shard.hasCompleteHistoryOperations()
// and before acquiring the safe commit we'll be using, so we can be certain that all operations after the safe commit's
// local checkpoint will be retained for the duration of this recovery.
logger.trace("history is retained by retention lock");
}
final StepListener<SendFileResult> sendFileStep = new StepListener<>();
final StepListener<TimeValue> prepareEngineStep = new StepListener<>();
final StepListener<SendSnapshotResult> sendSnapshotStep = new StepListener<>();
final StepListener<Void> finalizeStep = new StepListener<>();
if (isSequenceNumberBasedRecovery) {
logger.trace("performing sequence numbers based recovery. starting at [{}]", request.startingSeqNo());
startingSeqNo = request.startingSeqNo();
if (retentionLeaseRef.get() == null) {
createRetentionLease(startingSeqNo, sendFileStep.map(ignored -> SendFileResult.EMPTY));
} else {
sendFileStep.onResponse(SendFileResult.EMPTY);
}
} else {
final Engine.IndexCommitRef safeCommitRef;
try {
safeCommitRef = acquireSafeCommit(shard);
resources.add(safeCommitRef);
} catch (final Exception e) {
throw new RecoveryEngineException(shard.shardId(), 1, "snapshot failed", e);
}
// Try and copy enough operations to the recovering peer so that if it is promoted to primary then it has a chance of being
// able to recover other replicas using operations-based recoveries. If we are not using retention leases then we
// conservatively copy all available operations. If we are using retention leases then "enough operations" is just the
// operations from the local checkpoint of the safe commit onwards, because when using soft deletes the safe commit retains
// at least as much history as anything else. The safe commit will often contain all the history retained by the current set
// of retention leases, but this is not guaranteed: an earlier peer recovery from a different primary might have created a
// retention lease for some history that this primary already discarded, since we discard history when the global checkpoint
// advances and not when creating a new safe commit. In any case this is a best-effort thing since future recoveries can
// always fall back to file-based ones, and only really presents a problem if this primary fails before things have settled
// down.
startingSeqNo = Long.parseLong(safeCommitRef.getIndexCommit().getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) + 1L;
logger.trace("performing file-based recovery followed by history replay starting at [{}]", startingSeqNo);
try {
final int estimateNumOps = estimateNumberOfHistoryOperations(startingSeqNo);
final Releasable releaseStore = acquireStore(shard.store());
resources.add(releaseStore);
sendFileStep.whenComplete(r -> IOUtils.close(safeCommitRef, releaseStore), e -> {
try {
IOUtils.close(safeCommitRef, releaseStore);
} catch (Exception ex) {
logger.warn("releasing snapshot caused exception", ex);
}
});
final StepListener<ReplicationResponse> deleteRetentionLeaseStep = new StepListener<>();
runUnderPrimaryPermit(() -> {
try {
// If the target previously had a copy of this shard then a file-based recovery might move its global
// checkpoint backwards. We must therefore remove any existing retention lease so that we can create a
// new one later on in the recovery.
shard.removePeerRecoveryRetentionLease(request.targetNode().getId(),
new ThreadedActionListener<>(logger, shard.getThreadPool(), ThreadPool.Names.GENERIC,
deleteRetentionLeaseStep, false));
} catch (RetentionLeaseNotFoundException e) {
logger.debug("no peer-recovery retention lease for " + request.targetAllocationId());
deleteRetentionLeaseStep.onResponse(null);
}
}, shardId + " removing retention lease for [" + request.targetAllocationId() + "]",
shard, cancellableThreads, logger);
deleteRetentionLeaseStep.whenComplete(ignored -> {
assert Transports.assertNotTransportThread(RecoverySourceHandler.this + "[phase1]");
phase1(safeCommitRef.getIndexCommit(), startingSeqNo, () -> estimateNumOps, sendFileStep);
}, onFailure);
} catch (final Exception e) {
throw new RecoveryEngineException(shard.shardId(), 1, "sendFileStep failed", e);
}
}
assert startingSeqNo >= 0 : "startingSeqNo must be non negative. got: " + startingSeqNo;
sendFileStep.whenComplete(r -> {
assert Transports.assertNotTransportThread(RecoverySourceHandler.this + "[prepareTargetForTranslog]");
// For a sequence based recovery, the target can keep its local translog
prepareTargetForTranslog(estimateNumberOfHistoryOperations(startingSeqNo), prepareEngineStep);
}, onFailure);
prepareEngineStep.whenComplete(prepareEngineTime -> {
assert Transports.assertNotTransportThread(RecoverySourceHandler.this + "[phase2]");
/*
* add shard to replication group (shard will receive replication requests from this point on) now that engine is open.
* This means that any document indexed into the primary after this will be replicated to this replica as well
* make sure to do this before sampling the max sequence number in the next step, to ensure that we send
* all documents up to maxSeqNo in phase2.
*/
runUnderPrimaryPermit(() -> shard.initiateTracking(request.targetAllocationId()),
shardId + " initiating tracking of " + request.targetAllocationId(), shard, cancellableThreads, logger);
final long endingSeqNo = shard.seqNoStats().getMaxSeqNo();
logger.trace("snapshot for recovery; current size is [{}]", estimateNumberOfHistoryOperations(startingSeqNo));
final Translog.Snapshot phase2Snapshot =
shard.newChangesSnapshot("peer-recovery", startingSeqNo, Long.MAX_VALUE, false, false);
resources.add(phase2Snapshot);
retentionLock.close();
// we have to capture the max_seen_auto_id_timestamp and the max_seq_no_of_updates to make sure that these values
// are at least as high as the corresponding values on the primary when any of these operations were executed on it.
final long maxSeenAutoIdTimestamp = shard.getMaxSeenAutoIdTimestamp();
final long maxSeqNoOfUpdatesOrDeletes = shard.getMaxSeqNoOfUpdatesOrDeletes();
final RetentionLeases retentionLeases = shard.getRetentionLeases();
final long mappingVersionOnPrimary = shard.indexSettings().getIndexMetadata().getMappingVersion();
phase2(startingSeqNo, endingSeqNo, phase2Snapshot, maxSeenAutoIdTimestamp, maxSeqNoOfUpdatesOrDeletes,
retentionLeases, mappingVersionOnPrimary, sendSnapshotStep);
}, onFailure);
// Recovery target can trim all operations >= startingSeqNo as we have sent all these operations in the phase 2
final long trimAboveSeqNo = startingSeqNo - 1;
sendSnapshotStep.whenComplete(r -> finalizeRecovery(r.targetLocalCheckpoint, trimAboveSeqNo, finalizeStep), onFailure);
finalizeStep.whenComplete(r -> {
final long phase1ThrottlingWaitTime = 0L; // TODO: return the actual throttle time
final SendSnapshotResult sendSnapshotResult = sendSnapshotStep.result();
final SendFileResult sendFileResult = sendFileStep.result();
final RecoveryResponse response = new RecoveryResponse(sendFileResult.phase1FileNames, sendFileResult.phase1FileSizes,
sendFileResult.phase1ExistingFileNames, sendFileResult.phase1ExistingFileSizes, sendFileResult.totalSize,
sendFileResult.existingTotalSize, sendFileResult.took.millis(), phase1ThrottlingWaitTime,
prepareEngineStep.result().millis(), sendSnapshotResult.sentOperations, sendSnapshotResult.tookTime.millis());
try {
future.onResponse(response);
} finally {
IOUtils.close(resources);
}
}, onFailure);
} catch (Exception e) {
IOUtils.closeWhileHandlingException(releaseResources, () -> future.onFailure(e));
}
}
private boolean isTargetSameHistory() {
final String targetHistoryUUID = request.metadataSnapshot().getHistoryUUID();
assert targetHistoryUUID != null : "incoming target history missing";
return targetHistoryUUID.equals(shard.getHistoryUUID());
}
private int estimateNumberOfHistoryOperations(long startingSeqNo) throws IOException {
try (Translog.Snapshot snapshot = shard.newChangesSnapshot("peer-recover", startingSeqNo, Long.MAX_VALUE, false, true)) {
return snapshot.totalOperations();
}
}
static void runUnderPrimaryPermit(CancellableThreads.Interruptible runnable, String reason,
IndexShard primary, CancellableThreads cancellableThreads, Logger logger) {
cancellableThreads.execute(() -> {
CompletableFuture<Releasable> permit = new CompletableFuture<>();
final ActionListener<Releasable> onAcquired = new ActionListener<Releasable>() {
@Override
public void onResponse(Releasable releasable) {
if (permit.complete(releasable) == false) {
releasable.close();
}
}
@Override
public void onFailure(Exception e) {
permit.completeExceptionally(e);
}
};
primary.acquirePrimaryOperationPermit(onAcquired, ThreadPool.Names.SAME, reason);
try (Releasable ignored = FutureUtils.get(permit)) {
// check that the IndexShard still has the primary authority. This needs to be checked under operation permit to prevent
// races, as IndexShard will switch its authority only when it holds all operation permits, see IndexShard.relocated()
if (primary.isRelocatedPrimary()) {
throw new IndexShardRelocatedException(primary.shardId());
}
runnable.run();
} finally {
// just in case we got an exception (likely interrupted) while waiting for the get
permit.whenComplete((r, e) -> {
if (r != null) {
r.close();
}
if (e != null) {
logger.trace("suppressing exception on completion (it was already bubbled up or the operation was aborted)", e);
}
});
}
});
}
/**
* Increases the store reference and returns a {@link Releasable} that will decrease the store reference using the generic thread pool.
* We must never release the store using an interruptible thread as we can risk invalidating the node lock.
*/
private Releasable acquireStore(Store store) {
store.incRef();
return Releasables.releaseOnce(() -> runWithGenericThreadPool(store::decRef));
}
/**
* Releasing a safe commit can access some commit files. It's better not to use {@link CancellableThreads} to interact
* with the file systems due to interrupt (see {@link org.apache.lucene.store.NIOFSDirectory} javadocs for more detail).
* This method acquires a safe commit and wraps it to make sure that it will be released using the generic thread pool.
*/
private Engine.IndexCommitRef acquireSafeCommit(IndexShard shard) {
final Engine.IndexCommitRef commitRef = shard.acquireSafeIndexCommit();
final AtomicBoolean closed = new AtomicBoolean(false);
return new Engine.IndexCommitRef(commitRef.getIndexCommit(), () -> {
if (closed.compareAndSet(false, true)) {
runWithGenericThreadPool(commitRef::close);
}
});
}
private void runWithGenericThreadPool(CheckedRunnable<Exception> task) {
final PlainActionFuture<Void> future = new PlainActionFuture<>();
assert threadPool.generic().isShutdown() == false;
// TODO: We shouldn't use the generic thread pool here as we already execute this from the generic pool.
// While practically unlikely at a min pool size of 128 we could technically block the whole pool by waiting on futures
// below and thus make it impossible for the store release to execute which in turn would block the futures forever
threadPool.generic().execute(ActionRunnable.run(future, task));
FutureUtils.get(future);
}
static final class SendFileResult {
final List<String> phase1FileNames;
final List<Long> phase1FileSizes;
final long totalSize;
final List<String> phase1ExistingFileNames;
final List<Long> phase1ExistingFileSizes;
final long existingTotalSize;
final TimeValue took;
SendFileResult(List<String> phase1FileNames, List<Long> phase1FileSizes, long totalSize,
List<String> phase1ExistingFileNames, List<Long> phase1ExistingFileSizes, long existingTotalSize, TimeValue took) {
this.phase1FileNames = phase1FileNames;
this.phase1FileSizes = phase1FileSizes;
this.totalSize = totalSize;
this.phase1ExistingFileNames = phase1ExistingFileNames;
this.phase1ExistingFileSizes = phase1ExistingFileSizes;
this.existingTotalSize = existingTotalSize;
this.took = took;
}
static final SendFileResult EMPTY = new SendFileResult(Collections.emptyList(), Collections.emptyList(), 0L,
Collections.emptyList(), Collections.emptyList(), 0L, TimeValue.ZERO);
}
/**
* Perform phase1 of the recovery operations. Once this {@link IndexCommit}
* snapshot has been performed no commit operations (files being fsync'd)
* are effectively allowed on this index until all recovery phases are done
* <p>
* Phase1 examines the segment files on the target node and copies over the
* segments that are missing. Only segments that have the same size and
* checksum can be reused
*/
void phase1(IndexCommit snapshot, long startingSeqNo, IntSupplier translogOps, ActionListener<SendFileResult> listener) {
cancellableThreads.checkForCancel();
final Store store = shard.store();
try {
StopWatch stopWatch = new StopWatch().start();
final Store.MetadataSnapshot recoverySourceMetadata;
try {
recoverySourceMetadata = store.getMetadata(snapshot);
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
shard.failShard("recovery", ex);
throw ex;
}
for (String name : snapshot.getFileNames()) {
final StoreFileMetadata md = recoverySourceMetadata.get(name);
if (md == null) {
logger.info("Snapshot differs from actual index for file: {} meta: {}", name, recoverySourceMetadata.asMap());
throw new CorruptIndexException("Snapshot differs from actual index - maybe index was removed metadata has " +
recoverySourceMetadata.asMap().size() + " files", name);
}
}
if (canSkipPhase1(recoverySourceMetadata, request.metadataSnapshot()) == false) {
final List<String> phase1FileNames = new ArrayList<>();
final List<Long> phase1FileSizes = new ArrayList<>();
final List<String> phase1ExistingFileNames = new ArrayList<>();
final List<Long> phase1ExistingFileSizes = new ArrayList<>();
// Total size of segment files that are recovered
long totalSizeInBytes = 0;
// Total size of segment files that were able to be re-used
long existingTotalSizeInBytes = 0;
// Generate a "diff" of all the identical, different, and missing
// segment files on the target node, using the existing files on
// the source node
final Store.RecoveryDiff diff = recoverySourceMetadata.recoveryDiff(request.metadataSnapshot());
for (StoreFileMetadata md : diff.identical) {
phase1ExistingFileNames.add(md.name());
phase1ExistingFileSizes.add(md.length());
existingTotalSizeInBytes += md.length();
if (logger.isTraceEnabled()) {
logger.trace("recovery [phase1]: not recovering [{}], exist in local store and has checksum [{}]," +
" size [{}]", md.name(), md.checksum(), md.length());
}
totalSizeInBytes += md.length();
}
List<StoreFileMetadata> phase1Files = new ArrayList<>(diff.different.size() + diff.missing.size());
phase1Files.addAll(diff.different);
phase1Files.addAll(diff.missing);
for (StoreFileMetadata md : phase1Files) {
if (request.metadataSnapshot().asMap().containsKey(md.name())) {
logger.trace("recovery [phase1]: recovering [{}], exists in local store, but is different: remote [{}], local [{}]",
md.name(), request.metadataSnapshot().asMap().get(md.name()), md);
} else {
logger.trace("recovery [phase1]: recovering [{}], does not exist in remote", md.name());
}
phase1FileNames.add(md.name());
phase1FileSizes.add(md.length());
totalSizeInBytes += md.length();
}
logger.trace("recovery [phase1]: recovering_files [{}] with total_size [{}], reusing_files [{}] with total_size [{}]",
phase1FileNames.size(), new ByteSizeValue(totalSizeInBytes),
phase1ExistingFileNames.size(), new ByteSizeValue(existingTotalSizeInBytes));
final StepListener<Void> sendFileInfoStep = new StepListener<>();
final StepListener<Void> sendFilesStep = new StepListener<>();
final StepListener<RetentionLease> createRetentionLeaseStep = new StepListener<>();
final StepListener<Void> cleanFilesStep = new StepListener<>();
cancellableThreads.checkForCancel();
recoveryTarget.receiveFileInfo(phase1FileNames, phase1FileSizes, phase1ExistingFileNames,
phase1ExistingFileSizes, translogOps.getAsInt(), sendFileInfoStep);
sendFileInfoStep.whenComplete(r ->
sendFiles(store, phase1Files.toArray(new StoreFileMetadata[0]), translogOps, sendFilesStep), listener::onFailure);
sendFilesStep.whenComplete(r -> createRetentionLease(startingSeqNo, createRetentionLeaseStep), listener::onFailure);
createRetentionLeaseStep.whenComplete(retentionLease ->
{
final long lastKnownGlobalCheckpoint = shard.getLastKnownGlobalCheckpoint();
assert retentionLease == null || retentionLease.retainingSequenceNumber() - 1 <= lastKnownGlobalCheckpoint
: retentionLease + " vs " + lastKnownGlobalCheckpoint;
// Establishes new empty translog on the replica with global checkpoint set to lastKnownGlobalCheckpoint. We want
// the commit we just copied to be a safe commit on the replica, so why not set the global checkpoint on the replica
// to the max seqno of this commit? Because (in rare corner cases) this commit might not be a safe commit here on
// the primary, and in these cases the max seqno would be too high to be valid as a global checkpoint.
cleanFiles(store, recoverySourceMetadata, translogOps, lastKnownGlobalCheckpoint, cleanFilesStep);
},
listener::onFailure);
final long totalSize = totalSizeInBytes;
final long existingTotalSize = existingTotalSizeInBytes;
cleanFilesStep.whenComplete(r -> {
final TimeValue took = stopWatch.totalTime();
logger.trace("recovery [phase1]: took [{}]", took);
listener.onResponse(new SendFileResult(phase1FileNames, phase1FileSizes, totalSize, phase1ExistingFileNames,
phase1ExistingFileSizes, existingTotalSize, took));
}, listener::onFailure);
} else {
logger.trace("skipping [phase1] since source and target have identical sync id [{}]", recoverySourceMetadata.getSyncId());
// but we must still create a retention lease
final StepListener<RetentionLease> createRetentionLeaseStep = new StepListener<>();
createRetentionLease(startingSeqNo, createRetentionLeaseStep);
createRetentionLeaseStep.whenComplete(retentionLease -> {
final TimeValue took = stopWatch.totalTime();
logger.trace("recovery [phase1]: took [{}]", took);
listener.onResponse(new SendFileResult(Collections.emptyList(), Collections.emptyList(), 0L, Collections.emptyList(),
Collections.emptyList(), 0L, took));
}, listener::onFailure);
}
} catch (Exception e) {
throw new RecoverFilesRecoveryException(request.shardId(), 0, new ByteSizeValue(0L), e);
}
}
void createRetentionLease(final long startingSeqNo, ActionListener<RetentionLease> listener) {
runUnderPrimaryPermit(() -> {
// Clone the peer recovery retention lease belonging to the source shard. We are retaining history between the the local
// checkpoint of the safe commit we're creating and this lease's retained seqno with the retention lock, and by cloning an
// existing lease we (approximately) know that all our peers are also retaining history as requested by the cloned lease. If
// the recovery now fails before copying enough history over then a subsequent attempt will find this lease, determine it is
// not enough, and fall back to a file-based recovery.
// (approximately) because we do not guarantee to be able to satisfy every lease on every peer.
logger.trace("cloning primary's retention lease");
try {
final StepListener<ReplicationResponse> cloneRetentionLeaseStep = new StepListener<>();
final RetentionLease clonedLease
= shard.cloneLocalPeerRecoveryRetentionLease(request.targetNode().getId(),
new ThreadedActionListener<>(logger, shard.getThreadPool(),
ThreadPool.Names.GENERIC, cloneRetentionLeaseStep, false));
logger.trace("cloned primary's retention lease as [{}]", clonedLease);
cloneRetentionLeaseStep.addListener(listener.map(rr -> clonedLease));
} catch (RetentionLeaseNotFoundException e) {
// it's possible that the primary has no retention lease yet if we are doing a rolling upgrade from a version before
// 7.4, and in that case we just create a lease using the local checkpoint of the safe commit which we're using for
// recovery as a conservative estimate for the global checkpoint.
assert shard.indexSettings().getIndexVersionCreated().before(Version.V_7_4_0)
|| shard.indexSettings().isSoftDeleteEnabled() == false;
final StepListener<ReplicationResponse> addRetentionLeaseStep = new StepListener<>();
final long estimatedGlobalCheckpoint = startingSeqNo - 1;
final RetentionLease newLease = shard.addPeerRecoveryRetentionLease(request.targetNode().getId(),
estimatedGlobalCheckpoint, new ThreadedActionListener<>(logger, shard.getThreadPool(),
ThreadPool.Names.GENERIC, addRetentionLeaseStep, false));
addRetentionLeaseStep.addListener(listener.map(rr -> newLease));
logger.trace("created retention lease with estimated checkpoint of [{}]", estimatedGlobalCheckpoint);
}
}, shardId + " establishing retention lease for [" + request.targetAllocationId() + "]",
shard, cancellableThreads, logger);
}
boolean canSkipPhase1(Store.MetadataSnapshot source, Store.MetadataSnapshot target) {
if (source.getSyncId() == null || source.getSyncId().equals(target.getSyncId()) == false) {
return false;
}
if (source.getNumDocs() != target.getNumDocs()) {
throw new IllegalStateException("try to recover " + request.shardId() + " from primary shard with sync id but number " +
"of docs differ: " + source.getNumDocs() + " (" + request.sourceNode().getName() + ", primary) vs " + target.getNumDocs()
+ "(" + request.targetNode().getName() + ")");
}
SequenceNumbers.CommitInfo sourceSeqNos = SequenceNumbers.loadSeqNoInfoFromLuceneCommit(source.getCommitUserData().entrySet());
SequenceNumbers.CommitInfo targetSeqNos = SequenceNumbers.loadSeqNoInfoFromLuceneCommit(target.getCommitUserData().entrySet());
if (sourceSeqNos.localCheckpoint != targetSeqNos.localCheckpoint || targetSeqNos.maxSeqNo != sourceSeqNos.maxSeqNo) {
final String message = "try to recover " + request.shardId() + " with sync id but " +
"seq_no stats are mismatched: [" + source.getCommitUserData() + "] vs [" + target.getCommitUserData() + "]";
assert false : message;
throw new IllegalStateException(message);
}
return true;
}
void prepareTargetForTranslog(int totalTranslogOps, ActionListener<TimeValue> listener) {
StopWatch stopWatch = new StopWatch().start();
final ActionListener<Void> wrappedListener = ActionListener.wrap(
nullVal -> {
stopWatch.stop();
final TimeValue tookTime = stopWatch.totalTime();
logger.trace("recovery [phase1]: remote engine start took [{}]", tookTime);
listener.onResponse(tookTime);
},
e -> listener.onFailure(new RecoveryEngineException(shard.shardId(), 1, "prepare target for translog failed", e)));
// Send a request preparing the new shard's translog to receive operations. This ensures the shard engine is started and disables
// garbage collection (not the JVM's GC!) of tombstone deletes.
logger.trace("recovery [phase1]: prepare remote engine for translog");
cancellableThreads.checkForCancel();
recoveryTarget.prepareForTranslogOperations(totalTranslogOps, wrappedListener);
}
/**
* Perform phase two of the recovery process.
* <p>
* Phase two uses a snapshot of the current translog *without* acquiring the write lock (however, the translog snapshot is
* point-in-time view of the translog). It then sends each translog operation to the target node so it can be replayed into the new
* shard.
*
* @param startingSeqNo the sequence number to start recovery from, or {@link SequenceNumbers#UNASSIGNED_SEQ_NO} if all
* ops should be sent
* @param endingSeqNo the highest sequence number that should be sent
* @param snapshot a snapshot of the translog
* @param maxSeenAutoIdTimestamp the max auto_id_timestamp of append-only requests on the primary
* @param maxSeqNoOfUpdatesOrDeletes the max seq_no of updates or deletes on the primary after these operations were executed on it.
* @param listener a listener which will be notified with the local checkpoint on the target.
*/
void phase2(
final long startingSeqNo,
final long endingSeqNo,
final Translog.Snapshot snapshot,
final long maxSeenAutoIdTimestamp,
final long maxSeqNoOfUpdatesOrDeletes,
final RetentionLeases retentionLeases,
final long mappingVersion,
final ActionListener<SendSnapshotResult> listener) throws IOException {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
logger.trace("recovery [phase2]: sending transaction log operations (from [" + startingSeqNo + "] to [" + endingSeqNo + "]");
final StopWatch stopWatch = new StopWatch().start();
final StepListener<Void> sendListener = new StepListener<>();
final OperationBatchSender sender = new OperationBatchSender(startingSeqNo, endingSeqNo, snapshot, maxSeenAutoIdTimestamp,
maxSeqNoOfUpdatesOrDeletes, retentionLeases, mappingVersion, sendListener);
sendListener.whenComplete(
ignored -> {
final long skippedOps = sender.skippedOps.get();
final int totalSentOps = sender.sentOps.get();
final long targetLocalCheckpoint = sender.targetLocalCheckpoint.get();
assert snapshot.totalOperations() == snapshot.skippedOperations() + skippedOps + totalSentOps
: String.format(Locale.ROOT, "expected total [%d], overridden [%d], skipped [%d], total sent [%d]",
snapshot.totalOperations(), snapshot.skippedOperations(), skippedOps, totalSentOps);
stopWatch.stop();
final TimeValue tookTime = stopWatch.totalTime();
logger.trace("recovery [phase2]: took [{}]", tookTime);
listener.onResponse(new SendSnapshotResult(targetLocalCheckpoint, totalSentOps, tookTime));
}, listener::onFailure);
sender.start();
}
private static class OperationChunkRequest implements MultiChunkTransfer.ChunkRequest {
final List<Translog.Operation> operations;
final boolean lastChunk;
OperationChunkRequest(List<Translog.Operation> operations, boolean lastChunk) {
this.operations = operations;
this.lastChunk = lastChunk;
}
@Override
public boolean lastChunk() {
return lastChunk;
}
}
private class OperationBatchSender extends MultiChunkTransfer<Translog.Snapshot, OperationChunkRequest> {
private final long startingSeqNo;
private final long endingSeqNo;
private final Translog.Snapshot snapshot;
private final long maxSeenAutoIdTimestamp;
private final long maxSeqNoOfUpdatesOrDeletes;
private final RetentionLeases retentionLeases;
private final long mappingVersion;
private int lastBatchCount = 0; // used to estimate the count of the subsequent batch.
private final AtomicInteger skippedOps = new AtomicInteger();
private final AtomicInteger sentOps = new AtomicInteger();
private final AtomicLong targetLocalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
OperationBatchSender(long startingSeqNo, long endingSeqNo, Translog.Snapshot snapshot, long maxSeenAutoIdTimestamp,
long maxSeqNoOfUpdatesOrDeletes, RetentionLeases retentionLeases, long mappingVersion,
ActionListener<Void> listener) {
super(logger, threadPool.getThreadContext(), listener, maxConcurrentOperations, List.of(snapshot));
this.startingSeqNo = startingSeqNo;
this.endingSeqNo = endingSeqNo;
this.snapshot = snapshot;
this.maxSeenAutoIdTimestamp = maxSeenAutoIdTimestamp;
this.maxSeqNoOfUpdatesOrDeletes = maxSeqNoOfUpdatesOrDeletes;
this.retentionLeases = retentionLeases;
this.mappingVersion = mappingVersion;
}
@Override
protected synchronized OperationChunkRequest nextChunkRequest(Translog.Snapshot snapshot) throws IOException {
// We need to synchronized Snapshot#next() because it's called by different threads through sendBatch.
// Even though those calls are not concurrent, Snapshot#next() uses non-synchronized state and is not multi-thread-compatible.
assert Transports.assertNotTransportThread("[phase2]");
cancellableThreads.checkForCancel();
final List<Translog.Operation> ops = lastBatchCount > 0 ? new ArrayList<>(lastBatchCount) : new ArrayList<>();
long batchSizeInBytes = 0L;
Translog.Operation operation;
while ((operation = snapshot.next()) != null) {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
final long seqNo = operation.seqNo();
if (seqNo < startingSeqNo || seqNo > endingSeqNo) {
skippedOps.incrementAndGet();
continue;
}
ops.add(operation);
batchSizeInBytes += operation.estimateSize();
sentOps.incrementAndGet();
// check if this request is past bytes threshold, and if so, send it off
if (batchSizeInBytes >= chunkSizeInBytes) {
break;
}
}
lastBatchCount = ops.size();
return new OperationChunkRequest(ops, operation == null);
}
@Override
protected void executeChunkRequest(OperationChunkRequest request, ActionListener<Void> listener) {
cancellableThreads.checkForCancel();
recoveryTarget.indexTranslogOperations(
request.operations,
snapshot.totalOperations(),
maxSeenAutoIdTimestamp,
maxSeqNoOfUpdatesOrDeletes,
retentionLeases,
mappingVersion,
listener.delegateFailure((l, newCheckpoint) -> {
targetLocalCheckpoint.updateAndGet(curr -> SequenceNumbers.max(curr, newCheckpoint));
l.onResponse(null);
}));
}
@Override
protected void handleError(Translog.Snapshot snapshot, Exception e) {
throw new RecoveryEngineException(shard.shardId(), 2, "failed to send/replay operations", e);
}
@Override
public void close() throws IOException {
snapshot.close();
}
}
void finalizeRecovery(long targetLocalCheckpoint, long trimAboveSeqNo, ActionListener<Void> listener) {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
cancellableThreads.checkForCancel();
StopWatch stopWatch = new StopWatch().start();
logger.trace("finalizing recovery");
/*
* Before marking the shard as in-sync we acquire an operation permit. We do this so that there is a barrier between marking a
* shard as in-sync and relocating a shard. If we acquire the permit then no relocation handoff can complete before we are done
* marking the shard as in-sync. If the relocation handoff holds all the permits then after the handoff completes and we acquire
* the permit then the state of the shard will be relocated and this recovery will fail.
*/
runUnderPrimaryPermit(() -> shard.markAllocationIdAsInSync(request.targetAllocationId(), targetLocalCheckpoint),
shardId + " marking " + request.targetAllocationId() + " as in sync", shard, cancellableThreads, logger);
final long globalCheckpoint = shard.getLastKnownGlobalCheckpoint(); // this global checkpoint is persisted in finalizeRecovery
final StepListener<Void> finalizeListener = new StepListener<>();
cancellableThreads.checkForCancel();
recoveryTarget.finalizeRecovery(globalCheckpoint, trimAboveSeqNo, finalizeListener);
finalizeListener.whenComplete(r -> {
runUnderPrimaryPermit(() -> shard.updateGlobalCheckpointForShard(request.targetAllocationId(), globalCheckpoint),
shardId + " updating " + request.targetAllocationId() + "'s global checkpoint", shard, cancellableThreads, logger);
if (request.isPrimaryRelocation()) {
logger.trace("performing relocation hand-off");
// this acquires all IndexShard operation permits and will thus delay new recoveries until it is done
cancellableThreads.execute(() -> shard.relocated(request.targetAllocationId(), recoveryTarget::handoffPrimaryContext,
ActionListener.wrap(v -> {
cancellableThreads.checkForCancel();
completeFinalizationListener(listener, stopWatch);
}, listener::onFailure)));
/*
* if the recovery process fails after disabling primary mode on the source shard, both relocation source and
* target are failed (see {@link IndexShard#updateRoutingEntry}).
*/
} else {
completeFinalizationListener(listener, stopWatch);
}
}, listener::onFailure);
}
private void completeFinalizationListener(ActionListener<Void> listener, StopWatch stopWatch) {
stopWatch.stop();
logger.trace("finalizing recovery took [{}]", stopWatch.totalTime());
listener.onResponse(null);
}
static final class SendSnapshotResult {
final long targetLocalCheckpoint;
final int sentOperations;
final TimeValue tookTime;
SendSnapshotResult(final long targetLocalCheckpoint, final int sentOperations, final TimeValue tookTime) {
this.targetLocalCheckpoint = targetLocalCheckpoint;
this.sentOperations = sentOperations;
this.tookTime = tookTime;
}
}
/**
* Cancels the recovery and interrupts all eligible threads.
*/
public void cancel(String reason) {
cancellableThreads.cancel(reason);
recoveryTarget.cancel();
}
@Override
public String toString() {
return "ShardRecoveryHandler{" +
"shardId=" + request.shardId() +
", sourceNode=" + request.sourceNode() +
", targetNode=" + request.targetNode() +
'}';
}
private static class FileChunk implements MultiChunkTransfer.ChunkRequest, Releasable {
final StoreFileMetadata md;
final BytesReference content;
final long position;
final boolean lastChunk;
final Releasable onClose;
FileChunk(StoreFileMetadata md, BytesReference content, long position, boolean lastChunk, Releasable onClose) {
this.md = md;
this.content = content;
this.position = position;
this.lastChunk = lastChunk;
this.onClose = onClose;
}
@Override
public boolean lastChunk() {
return lastChunk;
}
@Override
public void close() {
onClose.close();
}
}
void sendFiles(Store store, StoreFileMetadata[] files, IntSupplier translogOps, ActionListener<Void> listener) {
ArrayUtil.timSort(files, Comparator.comparingLong(StoreFileMetadata::length)); // send smallest first
Releasable temporaryStoreRef = acquireStore(store);
try {
final Releasable storeRef = temporaryStoreRef;
final MultiChunkTransfer<StoreFileMetadata, FileChunk> multiFileSender =
new MultiChunkTransfer<>(logger, threadPool.getThreadContext(), listener, maxConcurrentFileChunks, Arrays.asList(files)) {
final Deque<byte[]> buffers = new ConcurrentLinkedDeque<>();
IndexInput currentInput = null;
long offset = 0;
@Override
protected void onNewResource(StoreFileMetadata md) throws IOException {
offset = 0;
IOUtils.close(currentInput);
currentInput = store.directory().openInput(md.name(), IOContext.READONCE);
}
@Override
protected FileChunk nextChunkRequest(StoreFileMetadata md) throws IOException {
assert Transports.assertNotTransportThread("read file chunk");
cancellableThreads.checkForCancel();
final byte[] buffer = Objects.requireNonNullElseGet(buffers.pollFirst(), () -> new byte[chunkSizeInBytes]);
final int toRead = Math.toIntExact(Math.min(md.length() - offset, buffer.length));
currentInput.readBytes(buffer, 0, toRead, false);
final boolean lastChunk = offset + toRead == md.length();
final FileChunk chunk = new FileChunk(md, new BytesArray(buffer, 0, toRead), offset, lastChunk,
() -> buffers.addFirst(buffer));
offset += toRead;
return chunk;
}
@Override
protected void executeChunkRequest(FileChunk request, ActionListener<Void> listener) {
cancellableThreads.checkForCancel();
final ReleasableBytesReference content = new ReleasableBytesReference(request.content, request);
recoveryTarget.writeFileChunk(
request.md, request.position, content, request.lastChunk,
translogOps.getAsInt(), ActionListener.runBefore(listener, content::close));
}
@Override
protected void handleError(StoreFileMetadata md, Exception e) throws Exception {
handleErrorOnSendFiles(store, e, new StoreFileMetadata[]{md});
}
@Override
public void close() throws IOException {
IOUtils.close(currentInput, storeRef);
}
};
resources.add(multiFileSender);
temporaryStoreRef = null; // now owned by multiFileSender, tracked in resources, so won't be leaked
multiFileSender.start();
} finally {
Releasables.close(temporaryStoreRef);
}
}
private void cleanFiles(Store store, Store.MetadataSnapshot sourceMetadata, IntSupplier translogOps,
long globalCheckpoint, ActionListener<Void> listener) {
// Send the CLEAN_FILES request, which takes all of the files that
// were transferred and renames them from their temporary file
// names to the actual file names. It also writes checksums for
// the files after they have been renamed.
// Once the files have been renamed, any other files that are not
// related to this recovery (out of date segments, for example)
// are deleted
cancellableThreads.checkForCancel();
recoveryTarget.cleanFiles(translogOps.getAsInt(), globalCheckpoint, sourceMetadata,
listener.delegateResponse((l, e) -> ActionListener.completeWith(l, () -> {
StoreFileMetadata[] mds = StreamSupport.stream(sourceMetadata.spliterator(), false).toArray(StoreFileMetadata[]::new);
ArrayUtil.timSort(mds, Comparator.comparingLong(StoreFileMetadata::length)); // check small files first
handleErrorOnSendFiles(store, e, mds);
throw e;
})));
}
private void handleErrorOnSendFiles(Store store, Exception e, StoreFileMetadata[] mds) throws Exception {
final IOException corruptIndexException = ExceptionsHelper.unwrapCorruption(e);
assert Transports.assertNotTransportThread(RecoverySourceHandler.this + "[handle error on send/clean files]");
if (corruptIndexException != null) {
Exception localException = null;
for (StoreFileMetadata md : mds) {
cancellableThreads.checkForCancel();
logger.debug("checking integrity for file {} after remove corruption exception", md);
if (store.checkIntegrityNoException(md) == false) { // we are corrupted on the primary -- fail!
logger.warn("{} Corrupted file detected {} checksum mismatch", shardId, md);
if (localException == null) {
localException = corruptIndexException;
}
failEngine(corruptIndexException);
}
}
if (localException != null) {
throw localException;
} else { // corruption has happened on the way to replica
RemoteTransportException remoteException = new RemoteTransportException(
"File corruption occurred on recovery but checksums are ok", null);
remoteException.addSuppressed(e);
logger.warn(() -> new ParameterizedMessage("{} Remote file corruption on node {}, recovering {}. local checksum OK",
shardId, request.targetNode(), mds), corruptIndexException);
throw remoteException;
}
}
throw e;
}
protected void failEngine(IOException cause) {
shard.failShard("recovery", cause);
}
}
|
package com.intellij.ide;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
import com.intellij.openapi.vfs.newvfs.RefreshSession;
import org.jetbrains.annotations.NotNull;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class SaveAndSyncHandler implements ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.SaveAndSyncHandler");
private Runnable myIdleListener;
private PropertyChangeListener myGeneralSettingsListener;
public SaveAndSyncHandler(final FrameStateManager frameStateManager,
final FileDocumentManager fileDocumentManager,
final GeneralSettings generalSettings) {
myIdleListener = new Runnable() {
public void run() {
if (generalSettings.isAutoSaveIfInactive() && canSyncOrSave()) {
fileDocumentManager.saveAllDocuments();
}
}
};
IdeEventQueue.getInstance().addIdleListener(
myIdleListener,
generalSettings.getInactiveTimeout() * 1000
);
myGeneralSettingsListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (GeneralSettings.PROP_INACTIVE_TIMEOUT.equals(e.getPropertyName())) {
IdeEventQueue eventQueue = IdeEventQueue.getInstance();
eventQueue.removeIdleListener(myIdleListener);
Integer timeout = (Integer)e.getNewValue();
eventQueue.addIdleListener(myIdleListener, timeout.intValue() * 1000);
}
}
};
generalSettings.addPropertyChangeListener(myGeneralSettingsListener);
frameStateManager.addListener(new FrameStateListener() {
public void onFrameDeactivated() {
if (canSyncOrSave()) {
saveProjectsAndDocuments();
}
}
public void onFrameActivated() {
refreshFiles();
}
});
}
@NotNull
public String getComponentName() {
return "SaveAndSyncHandler";
}
public void initComponent() {
}
public void disposeComponent() {
GeneralSettings.getInstance().removePropertyChangeListener(myGeneralSettingsListener);
IdeEventQueue.getInstance().removeIdleListener(myIdleListener);
}
private static boolean canSyncOrSave() {
return !LaterInvocator.isInModalContext() && !ProgressManager.getInstance().hasModalProgressIndicator();
}
private static void saveProjectsAndDocuments() {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: save()");
}
if (ApplicationManager.getApplication().isDisposed()) return;
if (GeneralSettings.getInstance().isSaveOnFrameDeactivation()) {
FileDocumentManager.getInstance().saveAllDocuments();
}
Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
for (Project project : openProjects) {
if (LOG.isDebugEnabled()) {
LOG.debug("save project: " + project);
}
project.save();
}
if (LOG.isDebugEnabled()) {
LOG.debug("save application settings");
}
ApplicationManagerEx.getApplicationEx().saveSettings();
if (LOG.isDebugEnabled()) {
LOG.debug("exit: save()");
}
}
private static void refreshFiles() {
if (ApplicationManager.getApplication().isDisposed()) return;
if (LOG.isDebugEnabled()) {
LOG.debug("enter: synchronize()");
}
if (canSyncOrSave()) {
refreshOpenFiles();
}
if (GeneralSettings.getInstance().isSyncOnFrameActivation()) {
if (LOG.isDebugEnabled()) {
LOG.debug("refresh VFS");
}
VirtualFileManager.getInstance().refresh(true);
}
if (LOG.isDebugEnabled()) {
LOG.debug("exit: synchronize()");
}
}
public static void refreshOpenFiles() {
// Refresh open files synchronously so it doesn't wait for potentially longish refresh request in the queue to finish
final RefreshSession session = RefreshQueue.getInstance().createSession(false, false, null);
for (Project project : ProjectManagerEx.getInstanceEx().getOpenProjects()) {
VirtualFile[] files = FileEditorManager.getInstance(project).getSelectedFiles();
for (VirtualFile file : files) {
if (file instanceof NewVirtualFile) {
session.addFile(file);
}
}
}
session.launch();
}
}
|
package org.jboss.as.server.deployment.integration;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.module.TempFileProviderService;
import org.jboss.as.server.deployment.module.VFSResourceLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.ResourceLoader;
import org.jboss.modules.ResourceLoaderSpec;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
import java.io.Closeable;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Recognize Seam deployments and add org.jboss.seam.int module to it.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class SeamProcessor implements DeploymentUnitProcessor {
public static final String SEAM_PROPERTIES = "seam.properties";
public static final String SEAM_PROPERTIES_META_INF = "META-INF/" + SEAM_PROPERTIES;
public static final String SEAM_PROPERTIES_WEB_INF = "WEB-INF/classes/" + SEAM_PROPERTIES;
public static final String SEAM_COMPONENTS = "components.xml";
public static final String SEAM_COMPONENTS_META_INF = "META-INF/" + SEAM_COMPONENTS;
public static final String SEAM_COMPONENTS_WEB_INF = "WEB-INF/" + SEAM_COMPONENTS;
public static final String[] SEAM_FILES = new String[]{
SEAM_PROPERTIES,
SEAM_PROPERTIES_META_INF,
SEAM_PROPERTIES_WEB_INF,
SEAM_COMPONENTS_META_INF,
SEAM_COMPONENTS_WEB_INF
};
public static final String SEAM_INT_JAR = "jboss-seam-int.jar";
public static final ModuleIdentifier EXT_CONTENT_MODULE = ModuleIdentifier.create("org.jboss.integration.ext-content");
public static final ModuleIdentifier VFS_MODULE = ModuleIdentifier.create("org.jboss.vfs");
private ServiceTarget serviceTarget; // service target from the service that added this dup
private ResourceLoaderSpec seamIntResourceLoader;
public SeamProcessor(ServiceTarget serviceTarget) {
this.serviceTarget = serviceTarget;
}
/**
* Lookup Seam integration resource loader.
*
* @return the Seam integration resource loader
* @throws DeploymentUnitProcessingException
* for any error
*/
protected synchronized ResourceLoaderSpec getSeamIntResourceLoader() throws DeploymentUnitProcessingException {
try {
if (seamIntResourceLoader == null) {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE);
URL url = extModule.getExportedResource(SEAM_INT_JAR);
if (url == null)
throw new DeploymentUnitProcessingException("No Seam Integration jar present: " + extModule);
File file = new File(url.toURI());
VirtualFile vf = VFS.getChild(file.toURI());
final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());
Service<Closeable> mountHandleService = new Service<Closeable>() {
public void start(StartContext startContext) throws StartException {
}
public void stop(StopContext stopContext) {
VFSUtils.safeClose(mountHandle);
}
public Closeable getValue() throws IllegalStateException, IllegalArgumentException {
return mountHandle;
}
};
ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR), mountHandleService);
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
serviceTarget = null; // our cleanup service install work is done
ResourceLoader resourceLoader = new VFSResourceLoader(SEAM_INT_JAR, vf);
seamIntResourceLoader = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader);
}
return seamIntResourceLoader;
} catch (Exception e) {
throw new DeploymentUnitProcessingException(e);
}
}
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() == null) {
return;
}
final List<DeploymentUnit> deploymentUnits = new ArrayList<DeploymentUnit>();
deploymentUnits.add(deploymentUnit);
deploymentUnits.addAll(deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS));
for (DeploymentUnit unit : deploymentUnits) {
final ResourceRoot mainRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (mainRoot == null)
continue;
VirtualFile root = mainRoot.getRoot();
for (String path : SEAM_FILES) {
if (root.getChild(path).exists()) {
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, VFS_MODULE, false, false, false));
moduleSpecification.addResourceLoader(getSeamIntResourceLoader());
return;
}
}
}
}
public void undeploy(DeploymentUnit context) {
}
}
|
package org.realityforge.gwt.appcache.server;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.testng.annotations.Test;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class ManifestServletTest
{
static class TestManifestServlet
extends AbstractManifestServlet
{
private ServletContext _servletContext;
@Override
public ServletContext getServletContext()
{
if ( null == _servletContext )
{
_servletContext = mock( ServletContext.class );
}
return _servletContext;
}
}
@Test
public void serveStringManifest()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final HttpServletResponse response = mock( HttpServletResponse.class );
final ServletOutputStream output = mock( ServletOutputStream.class );
when( response.getOutputStream() ).thenReturn( output );
servlet.serveStringManifest( response, "DD" );
verify( response ).setDateHeader( eq( "Date" ), anyLong() );
verify( response ).setDateHeader( eq( "Last-Modified" ), anyLong() );
verify( response ).setDateHeader( "Expires", 0 );
verify( response ).setHeader( "Cache-control", "no-cache, no-store, must-revalidate, pre-check=0, post-check=0" );
verify( response ).setHeader( "Pragma", "no-cache" );
verify( response ).setContentType( "text/cache-manifest" );
verify( output ).write( "DD".getBytes( "US-ASCII" ) );
}
@Test
public void loadManifest()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final String expectedManifest = "XXXX\n";
final File manifestFile = createFile( "manifest", "appcache", expectedManifest );
when( servlet.getServletContext().getRealPath( "/foo/myapp/12345.appcache" ) ).
thenReturn( manifestFile.getAbsolutePath() );
final String manifest = servlet.loadManifest( "/foo/", "myapp", "12345" );
assertEquals( manifest, expectedManifest );
}
@Test
public void calculateBindingPropertiesForClient()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
servlet.addPropertyProvider( new TestPropertyProvider( "X", "1" ) );
servlet.addPropertyProvider( new TestPropertyProvider( "Y", "2" ) );
final HttpServletRequest request = mock( HttpServletRequest.class );
final List<BindingProperty> properties = servlet.calculateBindingPropertiesForClient( request );
assertEquals( properties.size(), 2 );
final BindingProperty property1 = properties.get( 0 );
final BindingProperty property2 = properties.get( 1 );
assertEquals( property1.getName(), "X" );
assertEquals( property1.getValue(), "1" );
assertEquals( property2.getName(), "Y" );
assertEquals( property2.getValue(), "2" );
}
@Test
public void getModuleName()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final HttpServletRequest mock = mock( HttpServletRequest.class );
when( mock.getServletPath() ).thenReturn( "/myapp.appcache" );
assertEquals( servlet.getModuleName( mock ), "myapp" );
}
@Test( expectedExceptions = ServletException.class )
public void getModuleName_missingMapping()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final HttpServletRequest mock = mock( HttpServletRequest.class );
when( mock.getServletPath() ).thenReturn( null );
servlet.getModuleName( mock );
}
@Test( expectedExceptions = ServletException.class )
public void getModuleName_badMapping()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final HttpServletRequest mock = mock( HttpServletRequest.class );
when( mock.getServletPath() ).thenReturn( "/XXXX.cache" );
servlet.getModuleName( mock );
}
@Test
public void getBindingMap()
throws Exception
{
final TestManifestServlet servlet = new TestManifestServlet();
final ServletContext servletContext = servlet.getServletContext();
final String permutationContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><permutations></permutations>\n";
final File permutations = createFile( "permutations", "xml", permutationContent );
assertTrue( permutations.setLastModified( 0 ) );
when( servletContext.getRealPath( "/foo/myapp/permutations.xml" ) ).thenReturn( permutations.getAbsolutePath() );
final Map<String, List<BindingProperty>> bindings = servlet.getBindingMap( "/foo/", "myapp" );
assertNotNull( bindings );
assertTrue( bindings == servlet.getBindingMap( "/foo/", "myapp" ) );
assertTrue( permutations.setLastModified( Long.MAX_VALUE ) );
assertFalse( bindings == servlet.getBindingMap( "/foo/", "myapp" ) );
assertTrue( permutations.delete() );
}
@Test
public void getPermutationStrongName_simpleMultiValued()
throws Exception
{
final String strongPermutation = "C7D408F8EFA266A7F9A31209F8AA7446";
final String permutationContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<permutations>\n" +
" <permutation name=\"" + strongPermutation + "\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" </permutation>\n" +
"</permutations>\n";
final ArrayList<BindingProperty> computedBindings = new ArrayList<BindingProperty>();
computedBindings.add( new BindingProperty( "user.agent", "ie9" ) );
ensureStrongPermutationReturned( permutationContent, computedBindings, strongPermutation );
}
@Test
public void getPermutationStrongName_multiplePermutations()
throws Exception
{
final String strongPermutation = "C7D408F8EFA266A7F9A31209F8AA7446";
final String permutationContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<permutations>\n" +
" <permutation name=\"" + strongPermutation + "\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" </permutation>\n" +
" <permutation name=\"Other\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" <screen.size>biggo</screen.size>\n" +
" </permutation>\n" +
"</permutations>\n";
final ArrayList<BindingProperty> computedBindings = new ArrayList<BindingProperty>();
computedBindings.add( new BindingProperty( "user.agent", "ie9" ) );
ensureStrongPermutationReturned( permutationContent, computedBindings, strongPermutation );
}
@Test
public void getPermutationStrongName_multiplePermutationsAndSelectMostSpecific()
throws Exception
{
final String strongPermutation = "C7D408F8EFA266A7F9A31209F8AA7446";
final String permutationContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<permutations>\n" +
" <permutation name=\"" + strongPermutation + "\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" <screen.size>biggo</screen.size>\n" +
" <color.depth>much</color.depth>\n" +
" </permutation>\n" +
" <permutation name=\"Other\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" </permutation>\n" +
" <permutation name=\"Other2\">\n" +
" <user.agent>ie8,ie9,safari,ie10,gecko1_8</user.agent>\n" +
" <screen.size>biggo</screen.size>\n" +
" </permutation>\n" +
"</permutations>\n";
final ArrayList<BindingProperty> computedBindings = new ArrayList<BindingProperty>();
computedBindings.add( new BindingProperty( "user.agent", "ie9" ) );
computedBindings.add( new BindingProperty( "screen.size", "biggo" ) );
computedBindings.add( new BindingProperty( "color.depth", "much" ) );
ensureStrongPermutationReturned( permutationContent, computedBindings, strongPermutation );
}
private void ensureStrongPermutationReturned( final String permutationContent,
final List<BindingProperty> computedBindings,
final String expected )
throws IOException, ServletException
{
final TestManifestServlet servlet = new TestManifestServlet();
final ServletContext servletContext = servlet.getServletContext();
final File permutations = createFile( "permutations", "xml", permutationContent );
when( servletContext.getRealPath( "/foo/myapp/permutations.xml" ) ).thenReturn( permutations.getAbsolutePath() );
final String permutationStrongName = servlet.getPermutationStrongName( "/foo/", "myapp", computedBindings );
assertEquals( permutationStrongName, expected );
}
private File createFile( final String prefix, final String extension, final String content )
throws IOException
{
final File permutations = File.createTempFile( prefix, extension );
permutations.deleteOnExit();
final FileOutputStream outputStream = new FileOutputStream( permutations );
outputStream.write( content.getBytes() );
outputStream.close();
return permutations;
}
}
|
package com.badlogic.gradletest;
import com.badlogic.gdx.*;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.*;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class HelloApp extends ApplicationAdapter {
public static final int RADIUS = 8;
public static final int TYPE_BASIC = 0;
public static final int TYPE_P = 1;
public static final int SCREEN_HEIGHT = 480;
public static final int SCREEN_WIDTH = 800;
/**
* The fraction of original speed/direction retained after collision.
*/
public static final float CONFIG_RETAIN_ENERGY_FRACTION = 0.5f;
/**
* The size of newly generated speed after collision.
*/
public static final float CONFIG_ENERGY_NEW = 0.66f;
public static final float CONFIG_CRASH_DISTANCE = 1f;
public static final int CONFIG_NUM_SPAWNED_PARTICLES = 3;
// particle size
public static final float P_SIZE = 0.5f;
// target size
public static final float SIZE_T = 1f;
enum State {
START,
READY,
GOING;
}
private SpriteBatch batch;
private Texture img;
private OrthographicCamera camera;
private Rectangle bucket;
private Sound dropSound;
private Music rainMusic;
private Model model;
private ModelInstance instance;
private ModelBatch modelBatch;
private PerspectiveCamera cam;
private Environment environment;
private CameraInputController camController;
private List<Thing> things = new ArrayList<Thing>();
private Model sphereModel;
private ModelInstance sphereInstance;
private long frame;
private Material thingMaterial;
private Texture imgfg;
private ShapeRenderer shapeRenderer;
private Model projectileModel;
private float flash = 0;
private Vector3 swipe;
private HelloApp.Thing firstParticle;
private BitmapFont bitmapFont;
private Texture imgReset;
private Texture imgInfo;
private long score;
private State state = State.START;
@Override
public void create() {
batch = new SpriteBatch();
modelBatch = new ModelBatch();
shapeRenderer = new ShapeRenderer();
img = new Texture("background.png");
imgfg = new Texture("foreground.png");
imgReset = new Texture("reset.png");
imgInfo = new Texture("info.png");
bitmapFont = new BitmapFont();
// try {
// new FreeTypeFontGenerator(Gdx.files.internal("test.fnt"));
// } catch(Exception e) {
// e.printStackTrace();
// Bullet.init();
camera = new OrthographicCamera();
camera.setToOrtho(false, SCREEN_WIDTH, SCREEN_HEIGHT);
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// cam.position.set(10f, 10f, 10f);
cam.position.set(0f, 0f, 15f);
cam.lookAt(0, 0, 0);
cam.near = 0.1f;
cam.far = 300f;
cam.update();
bucket = new Rectangle();
bucket.x = SCREEN_WIDTH / 2 - 64 / 2;
bucket.y = 20;
bucket.width = 64;
bucket.height = 64;
// Thing e1 = new Thing();
// things.add(e1);
// e1.quat.set(new Vector3(1, 0, 0), 1);
// e1.quatv.set(new Vector3(1, 1, 1), 1f);
// Thing e = new Thing();
// e.quatv.set(new Vector3(0, 0, 5), 1);
// things.add(e);
// Thing e3 = new Thing();
// e3.quatv.set(new Vector3(1, 0.1f, 0), 1);
// things.add(e3);
// Thing e4 = new Thing();
// e4.setDirection(new Vector3(0, 0, 1));
// Vector3 direction = new Vector3(0, 0, 1);
// e4.getDirection(direction);
// things.add(e4);
// load the drop sound effect and the rain background "music"
dropSound = Gdx.audio.newSound(Gdx.files.internal("clap.wav"));
rainMusic = Gdx.audio.newMusic(Gdx.files.internal("noise.wav")); // can be mp3
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
ModelBuilder modelBuilder = new ModelBuilder();
thingMaterial = new Material(ColorAttribute.createDiffuse(Color.GREEN));
model = modelBuilder.createBox(SIZE_T, SIZE_T, SIZE_T,
thingMaterial,
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
instance = new ModelInstance(model);
sphereModel = modelBuilder.createSphere(3f, 3f, 3f, 20, 20,
// new Material(ColorAttribute.createDiffuse(Color.ORANGE)),
new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.5f)),
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
sphereInstance = new ModelInstance(sphereModel);
projectileModel = modelBuilder.createSphere(P_SIZE, P_SIZE, P_SIZE, 5, 5,
new Material(ColorAttribute.createDiffuse(Color.RED)),
// new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.1f)),
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
// start the playback of the background music immediately
rainMusic.setLooping(true);
rainMusic.play();
camController = new CameraInputController(cam);
// camController
Gdx.input.setInputProcessor(new InputMultiplexer(
camController,
new InputAdapter() {
@Override
public boolean keyDown(int keycode) {
// dropSound.play();
return super.keyDown(keycode);
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
super.touchDown(screenX, screenY, pointer, button);
if (isInState(State.READY)) {
swipe = new Vector3(screenX, screenY, 0);
Vector3 pos1 = new Vector3(0, 0, 1);
pos1.prj(cam.view.cpy().inv());
// pos1.prj(cam.view);
firstParticle = shootP(pos1, new Vector3());
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
super.touchUp(screenX, screenY, pointer, button);
if (isInState(State.START)) {
state = State.READY;
} else if (isInState(State.READY)) {
swipe.sub(screenX, screenY, 0);
swipe.x *= -1;
swipe.prj(cam.view.cpy().inv());
// cam.unproject(swipe);
swipe.nor();
// shootP(getRandomVector(), getRandomVector());
firstParticle.setDirection(swipe);
// float pan = (2f * screenX / Gdx.graphics.getWidth()) - 1;
// Gdx.app.log("touch ", "pan " + pan);
// dropSound.play((float) screenY / Gdx.graphics.getHeight(), 1, pan);
playHitSound(firstParticle.pos, cam);
state = State.GOING;
} else if (isInState(State.GOING)) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
if (SCREEN_WIDTH - 64 < touchPos.x && SCREEN_HEIGHT - 64 < touchPos.y) {
reset();
state = State.READY;
}
}
// shootP(new Vector3(0, 0, 1), swipe);
return true;
}
}));
reset();
}
private void reset() {
score = 0;
things.clear();
for (int i = 0; i < 10; i++) {
Thing t = new Thing(TYPE_BASIC);
// t.setDirection(randomize(new Vector3()));
randomize(t.pos, 1f);
t.adjustToSphere();
things.add(t);
}
}
private Vector3 getRandomVector() {
return getRandomVector(1f);
}
private Vector3 getRandomVector(float m) {
return randomize(new Vector3(), m);
}
@Override
public void render() {
frame++;
// frame = 1;
camController.update();
camera.update();
Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClearColor(0.5f * flash, 0.7f + 0.5f * flash, 0.6f + 0.5f * flash, 0.0f);
// Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT
// | GL10.GL_ALPHA_BITS
);
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
bucket.x = touchPos.x - 64 / 2;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) bucket.x -= 200 * Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) bucket.x += 200 * Gdx.graphics.getDeltaTime();
if (bucket.x < 0) bucket.x = 0;
if (bucket.x > SCREEN_WIDTH - 64) bucket.x = SCREEN_WIDTH - 64;
drawBackground();
batch.setProjectionMatrix(camera.combined);
// batch.begin();
// batch.draw(img, bucket.x, bucket.y);
// batch.end();
updateThings();
checkCollisions1();
checkCollisionsP();
// modelBatch.begin(cam);
// instance.transform.idt();
// modelBatch.render(instance, environment);
// instance.transform.setToTranslation(1, 0, 0);
// modelBatch.render(instance, environment);
// instance.transform.setToTranslation(0, 0, 1);
// modelBatch.render(instance, environment);
// instance.transform.setToTranslation(2, 0, 0);
// modelBatch.render(instance, environment);
// modelBatch.end();
// instance.materials.
drawThings();
drawCore();
drawForeground();
// drawShapes();
// drawFlashes(flash);
flash *= 0.95f;
}
private void updateThings() {
for (Iterator<Thing> iterator = things.iterator(); iterator.hasNext(); ) {
Thing thing = iterator.next();
if (thing.dead) {
iterator.remove();
} else {
thing.update();
}
}
}
private void checkCollisions1() {
for (int i = 0; i < things.size(); i++) {
Thing thing1 = things.get(i);
for (int j = i + 1; j < things.size(); j++) {
Thing thing2 = things.get(j);
// collision(thing1, thing2);
}
}
}
private void checkCollisionsP() {
final List<Thing> snapshot = new ArrayList<Thing>(things);
for (Thing thingP : snapshot) {
if (thingP.type == TYPE_P) {
for (Thing thingT : snapshot) {
if (thingT.type == TYPE_BASIC) {
collisionP(thingP, thingT);
}
}
}
}
}
private void drawThings() {
modelBatch.begin(cam);
for (Thing thing : things) {
// if (frame % 60 == 0) {
// thing.modelInstance.materials.get(0).set(ColorAttribute.createDiffuse(new Color(MathUtils.random(), MathUtils.random(), MathUtils.random(), MathUtils.random())));
thing.getTransform(thing.modelInstance.transform);
modelBatch.render(thing.modelInstance, environment);
}
modelBatch.end();
}
private void drawCore() {
// if (frame % 2 == 1)
{
Gdx.gl.glEnable(GL10.GL_BLEND);
modelBatch.begin(cam);
sphereInstance.transform.setToScaling(2, 2, 2);
modelBatch.render(sphereInstance, environment);
modelBatch.end();
Gdx.gl.glDisable(GL10.GL_BLEND);
}
}
private void drawBackground() {
batch.begin();
// batch.draw(img, 0, 0);
batch.draw(img, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
batch.end();
}
private void drawForeground() {
batch.setProjectionMatrix(camera.combined);
batch.begin();
// batch.
// batch.draw(imgfg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(imgfg, 0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
if (isInState(State.GOING)) {
batch.draw(imgReset, SCREEN_WIDTH - 64, SCREEN_HEIGHT - 64, 64, 64);
drawScore();
}
if (isInState(State.START)) {
batch.draw(imgInfo, 0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
}
batch.end();
}
private boolean isInState(State... states) {
for (State s : states) {
if (s == state) {
return true;
}
}
return false;
}
private void drawScore() {
bitmapFont.draw(batch, "particles: " + score, 30, 450);
}
private void drawShapes() {
float x = 5;
float y = 5;
float x2 = 10;
float y2 = 10;
float radius = 3;
float width = 3;
float height = 3;
// shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.setColor(1, 1, 0, 1);
shapeRenderer.line(x, y, x2, y2);
shapeRenderer.line(x, y, 1, x2, y2, 1);
shapeRenderer.rect(x, y, width, height);
shapeRenderer.circle(x, y, radius);
shapeRenderer.end();
}
private void drawFlashes(float flash) {
float x = 5;
float y = 5;
float x2 = 10;
float y2 = 10;
float radius = 3;
float width = 100;
float height = 100;
// shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(flash, 1, 0, flash);
// shapeRenderer.line(x, y, x2, y2);
// shapeRenderer.line(x, y, 1, x2, y2, 1);
shapeRenderer.rect(x, y, width, height);
shapeRenderer.circle(x, y, radius);
shapeRenderer.end();
}
private void collision(Thing thing1, Thing thing2) {
if (thing1 == thing2) {
return;
}
if (thing1.pos.dst2(thing2.pos) < 1) {
Vector3 pos = new Vector3(thing1.pos);
// cam.project(pos);
// pos.prj(cam.combined);
pos.prj(cam.view);
// float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1;
float volume = (float) Math.exp(0.1f * pos.z);
Gdx.app.log("touch ", "collision " + pos + " vol " + volume);
dropSound.play(volume, 1, pos.x);
thing1.setDirection(getRandomVector());
thing2.setDirection(getRandomVector());
}
}
/**
* @param thingP projectile
* @param thingT target - what is being hit
*/
private void collisionP(Thing thingP, Thing thingT) {
assert thingP.type == TYPE_P;
assert thingT.type == TYPE_BASIC;
if (thingT.dead) {
// continue - lets have bigger bonus
// return;
}
if (thingP.pos.dst2(thingT.pos) < CONFIG_CRASH_DISTANCE * CONFIG_CRASH_DISTANCE) {
playHitSound(thingT.pos, cam);
thingP.dead = true;
thingT.dead = true;
flash += 1f;
Vector3 direction = thingP.getDirection(new Vector3());
direction.scl(CONFIG_RETAIN_ENERGY_FRACTION);
// retained energy:
// shootP(thingt.pos, direction);
for (int i = 0; i < CONFIG_NUM_SPAWNED_PARTICLES; i++) {
shootP(thingT.pos, getRandomVector(CONFIG_ENERGY_NEW).add(direction));
score++;
}
}
}
private Thing shootP(Vector3 from, Vector3 direction) {
Thing t = new Thing(TYPE_P);
// t.setDirection(randomize(new Vector3()));
t.pos.set(from);
t.adjustToSphere();
t.setDirection(direction);
things.add(t);
return t;
}
/**
* Plays sound in world depending on where camera is
*
* @param worldPos
* @param povCam
*/
private void playHitSound(Vector3 worldPos, PerspectiveCamera povCam) {
Vector3 camPos = new Vector3(worldPos);
// cam.project(pos);
// pos.prj(cam.combined);
// position in camera coordinates
camPos.prj(povCam.view);
// float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1;
float volume = (float) Math.exp(0.1f * camPos.z);
Gdx.app.log("touch ", "collision " + camPos + " vol " + volume);
dropSound.play(volume, 1, camPos.x);
}
private Vector3 randomize(Vector3 random, float m) {
return random.set(MathUtils.random(-m, m), MathUtils.random(-m, m), MathUtils.random(-m, m));
}
class Thing {
final Vector3 pos = new Vector3(5, 0, 0);
final Quaternion quat = new Quaternion();
final Quaternion quatv = new Quaternion();
final int type;
boolean dead = false;
ModelInstance modelInstance;
Thing(int type) {
this.type = type;
switch (type) {
case TYPE_BASIC:
modelInstance = new ModelInstance(model);
break;
case TYPE_P:
modelInstance = new ModelInstance(projectileModel);
break;
}
}
public void update() {
Quaternion q = new Quaternion();
q.slerp(quatv, 1f);
quat.mul(q);
pos.mul(q);
}
private void getTransform(Matrix4 transform) {
transform.idt();
// transform.translate(5, 0, 0);
transform.setTranslation(pos);
// transform.setTranslation(pos) ;
// transform.translate(pos);
transform.rotate(quat);
// Vector3 vector3 = new Vector3();
// thing.quat.getAxisAngle(vector3);
}
/**
* Sets absolute direction of movement
*
* @param direction
*/
public void setDirection(Vector3 direction) {
Vector3 axis = new Vector3(pos);
axis.crs(direction);
float speed = direction.len();
quatv.set(axis, speed);
}
/**
* Absolute direction of movement
*
* @param direction
*/
public Vector3 getDirection(Vector3 direction) {
// predict move to find the direction
direction.set(pos).mul(quatv).sub(pos);
// apply correction from length per step to angular speed in degrees per step
direction.scl(180f / (MathUtils.PI * RADIUS));
return direction;
}
void adjustToSphere() {
pos.nor().scl(RADIUS);
}
}
}
|
package cucumber.runtime.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
class FileResource implements Resource {
private final File root;
private final File file;
private final boolean classpathFileResource;
static FileResource createFileResource(File root, File file) {
return new FileResource(root, file, false);
}
static FileResource createClasspathFileResource(File root, File file) {
return new FileResource(root, file, true);
}
private FileResource(File root, File file, boolean classpathFileResource) {
this.root = root;
this.file = file;
this.classpathFileResource = classpathFileResource;
if (!file.getAbsolutePath().startsWith(root.getAbsolutePath())) {
throw new IllegalArgumentException(file.getAbsolutePath() + " is not a parent of " + root.getAbsolutePath());
}
}
@Override
public String getPath() {
if (classpathFileResource) {
String relativePath = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1);
return relativePath.replace(File.separatorChar, '/');
} else {
return file.getPath();
}
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(file);
}
}
|
package hudson.tools;
import hudson.Extension;
import hudson.model.Node;
import hudson.model.TaskListener;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Semaphore;
/**
* Actually runs installations.
* @since 1.305
*/
@Extension
public class InstallerTranslator extends ToolLocationTranslator {
private static final Map<Node,Map<ToolInstallation,Semaphore>> mutexByNode = new WeakHashMap<Node,Map<ToolInstallation,Semaphore>>();
public String getToolHome(Node node, ToolInstallation tool, TaskListener log) throws IOException, InterruptedException {
InstallSourceProperty isp = tool.getProperties().get(InstallSourceProperty.class);
if (isp == null) {
return null;
}
for (ToolInstaller installer : isp.installers) {
if (installer.appliesTo(node)) {
Map<ToolInstallation, Semaphore> mutexByTool;
Semaphore semaphore;
synchronized(mutexByNode) {
mutexByTool = mutexByNode.get(node);
if (mutexByTool == null) {
mutexByNode.put(node, mutexByTool = new WeakHashMap<ToolInstallation, Semaphore>());
mutexByTool.put(tool, semaphore = new Semaphore(1));
} else {
semaphore = mutexByTool.get(tool);
}
}
semaphore.acquire();
try {
return installer.performInstallation(tool, node, log).getRemote();
} finally {
semaphore.release();
}
}
}
return null;
}
}
|
package com.google.sps.agents;
// Imports the Google Cloud client library
import com.google.gson.Gson;
import com.google.maps.errors.ApiException;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.sps.data.Video;
import com.google.sps.utils.WorkoutUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Workout Agent: finds relevant workout videos through Youtube and schedules workout plans. Also
* tracks workouts for user.
*/
public class WorkoutAgent implements Agent {
private static Logger log = LoggerFactory.getLogger(Workout.class);
private final String intentName;
private String output = null;
private String display = null;
private String redirect = null;
private String workoutType = "";
private String workoutLength = "";
private String youtubeChannel = "";
private final int numVideos = 5;
private String amount = "";
private String unit = "";
private Video video;
private String channelTitle;
private String title;
private String description;
private String thumbnail;
private String videoId;
public Workout(String intentName, Map<String, Value> parameters)
throws IllegalStateException, IOException, ApiException, InterruptedException,
ArrayIndexOutOfBoundsException {
this.intentName = intentName;
setParameters(parameters);
}
@Override
public void setParameters(Map<String, Value> parameters)
throws IllegalStateException, IOException, ApiException, InterruptedException,
ArrayIndexOutOfBoundsException {
if (intentName.contains("find")) {
workoutFind(parameters);
} else if (intentName.contains("schedule")) {
workoutSchedule(parameters);
}
}
@Override
public String getOutput() {
return output;
}
@Override
public String getDisplay() {
return display;
}
@Override
public String getRedirect() {
return redirect;
}
/**
* Private workoutFind method, that displays workouts specified by user request. Method sets
* parameters for workoutLength, workoutType, and youtubeChannel based on Dialogflow detection and
* makes calls to set display and set output. parameters map needs to include duration struct to
* set String workoutLength, String workoutType, and String youtubeChannel
*
* @param parameters parameter Map from Dialogflow
*/
private void workoutFind(Map<String, Value> parameters) throws IOException {
String duration = parameters.get("duration").getStringValue();
if (!duration.equals("")) {
Struct durationStruct = parameters.get("duration").getStructValue();
Map<String, Value> durationMap = durationStruct.getFieldsMap();
amount = String.valueOf(Math.round(durationMap.get("amount").getNumberValue()));
unit = durationMap.get("unit").getStringValue();
}
workoutLength = amount + " " + unit;
workoutType = parameters.get("workout-type").getStringValue();
youtubeChannel = parameters.get("youtube-channel").getStringValue();
// Set output
setWorkoutFindOutput();
// Set display
setWorkoutFindDisplay();
}
/**
* Private setworkoutFindOutput method, that sets the agent output based on set parameters for
* workoutLength, workoutType, and youtubeChannel from workoutFind method
*/
private void setWorkoutFindOutput() {
output = "Here are videos for: " + workoutLength + " " + workoutType + " workouts";
if (!youtubeChannel.equals("")) {
output += " from " + youtubeChannel;
}
}
/**
* Private setworkoutFindDisplay method, that sets the agent display to JSON string by makifn YT
* Data API call from WorkoutUtils to get passed into workout.js
*/
private void setWorkoutFindDisplay() throws IOException {
// Make API call to WorkoutUtils to get json object of videos
workoutLength = workoutLength.replaceAll("\\s", "");
workoutType = workoutType.replaceAll("\\s", "");
youtubeChannel = youtubeChannel.replaceAll("\\s", "");
JSONObject json =
WorkoutUtils.getJSONObject(workoutLength, workoutType, youtubeChannel, numVideos);
JSONArray videos = json.getJSONArray("items");
List<Video> videoList = new ArrayList<>();
for (int i = 0; i < numVideos; i++) {
String videoString = new Gson().toJson(videos.get(i));
setVideoParameters(videoString);
video = new Video(channelTitle, title, description, thumbnail, videoId);
videoList.add(video);
}
display = new Gson().toJson(videoList);
}
private void setVideoParameters(String videoString) {
JSONObject videoJSONObject = new JSONObject(videoString).getJSONObject("map");
JSONObject id = videoJSONObject.getJSONObject("id").getJSONObject("map");
videoId = new Gson().toJson(id.get("videoId"));
JSONObject snippet = videoJSONObject.getJSONObject("snippet").getJSONObject("map");
description = new Gson().toJson(snippet.get("description"));
title = new Gson().toJson(snippet.get("title"));
channelTitle = new Gson().toJson(snippet.get("channelTitle"));
JSONObject thumbnailJSONObject =
snippet.getJSONObject("thumbnails").getJSONObject("map").getJSONObject("medium");
JSONObject thumbnailURL = thumbnailJSONObject.getJSONObject("map");
thumbnail = new Gson().toJson(thumbnailURL.get("url"));
}
/**
* TODO: Private workoutSchedule method
*
* @param parameters parameter Map from Dialogflow
*/
private void workoutSchedule(Map<String, Value> parameters) {
return;
}
}
|
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyc.testing.tests;
import org.junit.*;
import wyc.testing.TestHarness;
public class ExtendedValidTests extends TestHarness {
public ExtendedValidTests() {
super("../../tests/ext/valid","../../tests/ext/valid","sysout");
}
@Test public void Assume_Valid_1_RuntimeTest() { verifyPassTest("Assume_Valid_1"); }
@Test public void BoolAssign_Valid_3_RuntimeTest() { verifyPassTest("BoolAssign_Valid_3"); }
@Test public void BoolAssign_Valid_4_RuntimeTest() { verifyPassTest("BoolAssign_Valid_4"); }
@Test public void BoolRequires_Valid_1_RuntimeTest() { verifyPassTest("BoolRequires_Valid_1"); }
@Ignore("Known Issue")
@Test public void Complex_Valid_3_RuntimeTest() { verifyPassTest("Complex_Valid_3"); }
@Ignore("Issue #233")
@Test public void Complex_Valid_4_RuntimeTest() { verifyPassTest("Complex_Valid_4"); }
@Ignore("Requires Maps")
@Test public void ConstrainedDictionary_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedDictionary_Valid_1"); }
@Test public void ConstrainedInt_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_1"); }
@Test public void ConstrainedInt_Valid_10_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_10"); }
@Test public void ConstrainedInt_Valid_11_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_11"); }
@Test public void ConstrainedInt_Valid_12_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_12"); }
@Ignore("Requires Modulus") @Test public void ConstrainedInt_Valid_13_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_13"); }
@Test public void ConstrainedInt_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_3"); }
@Test public void ConstrainedInt_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_4"); }
@Ignore("Unknown")
@Test public void ConstrainedInt_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_5"); }
@Ignore("Set Types")
@Test public void ConstrainedInt_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_6"); }
@Ignore("Unknown")
@Test public void ConstrainedInt_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_7"); }
@Test public void ConstrainedInt_Valid_8_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_8"); }
@Test public void ConstrainedInt_Valid_9_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_9"); }
@Test public void ConstrainedList_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_1"); }
@Test public void ConstrainedList_Valid_2_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_2"); }
@Test public void ConstrainedList_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_3"); }
@Test public void ConstrainedList_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_4"); }
@Ignore("Length >= 0")
@Test public void ConstrainedList_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_5"); }
@Ignore("Length >= 0")
@Test public void ConstrainedList_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_6"); }
@Ignore("Unknown")
@Test public void ConstrainedList_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_7"); }
@Ignore("Length => Some")
@Test public void ConstrainedList_Valid_8_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_8"); }
@Test public void ConstrainedList_Valid_9_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_9"); }
@Test public void ConstrainedList_Valid_10_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_10"); }
@Test public void ConstrainedList_Valid_11_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_11"); }
@Ignore("Issue #228")
@Test public void ConstrainedList_Valid_12_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_12"); }
@Test public void ConstrainedList_Valid_13_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_13"); }
//@Ignore("Issue #229")
@Test public void ConstrainedList_Valid_14_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_14"); }
//@Ignore("Issue #230")
@Test public void ConstrainedList_Valid_15_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_15"); }
@Test public void ConstrainedList_Valid_16_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_16"); }
//@Ignore("Issue #210")
@Test public void ConstrainedList_Valid_17_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_17"); }
//@Ignore("Issue #229")
@Test public void ConstrainedList_Valid_18_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_18"); }
@Test public void ConstrainedList_Valid_19_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_19"); }
//@Ignore("Unclassified")
@Test public void ConstrainedList_Valid_20_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_20"); }
//@Ignore("Issue #225")
@Test public void ConstrainedList_Valid_21_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_21"); }
@Test public void ConstrainedList_Valid_22_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_22"); }
@Ignore("Future Work") @Test public void ConstrainedNegation_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedNegation_Valid_1"); }
@Test public void ConstrainedRecord_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_4"); }
@Test public void ConstrainedRecord_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_5"); }
@Ignore("Timeout")
@Test public void ConstrainedRecord_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_6"); }
@Ignore("Unclassified")
@Test public void ConstrainedRecord_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_7"); }
@Test public void ConstrainedSet_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_1"); }
@Test public void ConstrainedSet_Valid_2_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_2"); }
@Test public void ConstrainedSet_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_3"); }
@Test public void ConstrainedSet_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_4"); }
@Test public void ConstrainedTuple_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedTuple_Valid_1"); }
@Test public void Ensures_Valid_1_RuntimeTest() { verifyPassTest("Ensures_Valid_1"); }
@Test public void Ensures_Valid_2_RuntimeTest() { verifyPassTest("Ensures_Valid_2"); }
@Ignore("Issue #234")
@Test public void Ensures_Valid_3_RuntimeTest() { verifyPassTest("Ensures_Valid_3"); }
@Test public void Ensures_Valid_4_RuntimeTest() { verifyPassTest("Ensures_Valid_4"); }
@Test public void Ensures_Valid_5_RuntimeTest() { verifyPassTest("Ensures_Valid_5"); }
@Test public void For_Valid_2_RuntimeTest() { verifyPassTest("For_Valid_2"); }
@Test public void For_Valid_3_RuntimeTest() { verifyPassTest("For_Valid_3"); }
@Test public void For_Valid_4_RuntimeTest() { verifyPassTest("For_Valid_4"); }
@Ignore("Timeout") @Test public void For_Valid_5_RuntimeTest() { verifyPassTest("For_Valid_5"); }
@Ignore("Requires Overloading") @Test public void Function_Valid_11_RuntimeTest() { verifyPassTest("Function_Valid_11"); }
@Test public void Function_Valid_12_RuntimeTest() { verifyPassTest("Function_Valid_12"); }
@Test public void Function_Valid_14_RuntimeTest() { verifyPassTest("Function_Valid_14"); }
@Ignore("Issue #290")
@Test public void Function_Valid_15_RuntimeTest() { verifyPassTest("Function_Valid_15"); }
@Test public void Function_Valid_2_RuntimeTest() { verifyPassTest("Function_Valid_2"); }
@Test public void Function_Valid_3_RuntimeTest() { verifyPassTest("Function_Valid_3"); }
@Test public void Function_Valid_4_RuntimeTest() { verifyPassTest("Function_Valid_4"); }
@Ignore("Issue #234")
@Test public void Function_Valid_5_RuntimeTest() { verifyPassTest("Function_Valid_5"); }
@Ignore("Issue #234")
@Test public void Function_Valid_6_RuntimeTest() { verifyPassTest("Function_Valid_6"); }
@Ignore("Requires Overloading") @Test public void Function_Valid_8_RuntimeTest() { verifyPassTest("Function_Valid_8"); }
@Ignore("Issue #289")
@Test public void Function_Valid_9_RuntimeTest() { verifyPassTest("Function_Valid_9"); }
@Test public void IntDefine_Valid_1_RuntimeTest() { verifyPassTest("IntDefine_Valid_1"); }
@Test public void IntDiv_Valid_1_RuntimeTest() { verifyPassTest("IntDiv_Valid_1"); }
@Ignore("Issue #183") @Test public void IntDiv_Valid_2_RuntimeTest() { verifyPassTest("IntDiv_Valid_2"); }
@Ignore("Requires Lambdas") @Test public void Lambda_Valid_1_RuntimeTest() { verifyPassTest("Lambda_Valid_1"); }
@Test public void ListAccess_Valid_1_RuntimeTest() { verifyPassTest("ListAccess_Valid_1"); }
@Test public void ListAccess_Valid_2_RuntimeTest() { verifyPassTest("ListAccess_Valid_2"); }
@Ignore("Timeout, Issue #231")
@Test public void ListAppend_Valid_5_RuntimeTest() { verifyPassTest("ListAppend_Valid_5"); }
@Ignore("Timeout, Issue #231")
@Test public void ListAppend_Valid_6_RuntimeTest() { verifyPassTest("ListAppend_Valid_6"); }
@Test public void ListAppend_Valid_7_RuntimeTest() { verifyPassTest("ListAppend_Valid_7"); }
@Ignore("Issue #231")
@Test public void ListAppend_Valid_8_RuntimeTest() { verifyPassTest("ListAppend_Valid_8"); }
@Ignore("Issue #231")
@Test public void ListAppend_Valid_9_RuntimeTest() { verifyPassTest("ListAppend_Valid_9"); }
@Test public void ListAssign_Valid_5_RuntimeTest() { verifyPassTest("ListAssign_Valid_5"); }
@Test public void ListAssign_Valid_6_RuntimeTest() { verifyPassTest("ListAssign_Valid_6"); }
@Test public void ListGenerator_Valid_1_RuntimeTest() { verifyPassTest("ListGenerator_Valid_1"); }
@Test public void ListGenerator_Valid_2_RuntimeTest() { verifyPassTest("ListGenerator_Valid_2"); }
@Test public void ListLength_Valid_1_RuntimeTest() { verifyPassTest("ListLength_Valid_1"); }
@Ignore("Issue #287")
@Test public void ListSublist_Valid_1_RuntimeTest() { verifyPassTest("ListSublist_Valid_1"); }
@Ignore("Issue #287")
@Test public void ListSublist_Valid_2_RuntimeTest() { verifyPassTest("ListSublist_Valid_2"); }
@Ignore("Issue #288") @Test public void Method_Valid_1_RuntimeTest() { verifyPassTest("Method_Valid_1"); }
@Test public void Process_Valid_2_RuntimeTest() { verifyPassTest("Process_Valid_2"); }
@Test public void Quantifiers_Valid_1_RuntimeTest() { verifyPassTest("Quantifiers_Valid_1"); }
@Test public void Range_Valid_1_RuntimeTest() { verifyPassTest("Range_Valid_1"); }
@Test public void RealDiv_Valid_1_RuntimeTest() { verifyPassTest("RealDiv_Valid_1"); }
@Test public void RealDiv_Valid_2_RuntimeTest() { verifyPassTest("RealDiv_Valid_2"); }
@Ignore("Known Issue") @Test public void RealDiv_Valid_3_RuntimeTest() { verifyPassTest("RealDiv_Valid_3"); }
@Test public void RealNeg_Valid_1_RuntimeTest() { verifyPassTest("RealNeg_Valid_1"); }
@Ignore("Issue #183") @Test public void RealSub_Valid_1_RuntimeTest() { verifyPassTest("RealSub_Valid_1"); }
@Test public void RecordAssign_Valid_1_RuntimeTest() { verifyPassTest("RecordAssign_Valid_1"); }
@Test public void RecordAssign_Valid_2_RuntimeTest() { verifyPassTest("RecordAssign_Valid_2"); }
@Test public void RecordAssign_Valid_4_RuntimeTest() { verifyPassTest("RecordAssign_Valid_4"); }
@Test public void RecordAssign_Valid_5_RuntimeTest() { verifyPassTest("RecordAssign_Valid_5"); }
@Test public void RecordDefine_Valid_1_RuntimeTest() { verifyPassTest("RecordDefine_Valid_1"); }
@Test public void RecursiveType_Valid_3_RuntimeTest() { verifyPassTest("RecursiveType_Valid_3"); }
@Test public void RecursiveType_Valid_5_RuntimeTest() { verifyPassTest("RecursiveType_Valid_5"); }
@Test public void RecursiveType_Valid_6_RuntimeTest() { verifyPassTest("RecursiveType_Valid_6"); }
@Test public void RecursiveType_Valid_8_RuntimeTest() { verifyPassTest("RecursiveType_Valid_8"); }
@Ignore("Requires Type Test") @Test public void RecursiveType_Valid_9_RuntimeTest() { verifyPassTest("RecursiveType_Valid_9"); }
@Test public void Requires_Valid_1_RuntimeTest() { verifyPassTest("Requires_Valid_1"); }
@Test public void SetAssign_Valid_1_RuntimeTest() { verifyPassTest("SetAssign_Valid_1"); }
@Ignore("Issue #234")
@Test public void SetComprehension_Valid_6_RuntimeTest() { verifyPassTest("SetComprehension_Valid_6"); }
@Ignore("Issue #234")
@Test public void SetComprehension_Valid_7_RuntimeTest() { verifyPassTest("SetComprehension_Valid_7"); }
@Test public void SetDefine_Valid_1_RuntimeTest() { verifyPassTest("SetDefine_Valid_1"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_1_RuntimeTest() { verifyPassTest("SetIntersection_Valid_1"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_2_RuntimeTest() { verifyPassTest("SetIntersection_Valid_2"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_3_RuntimeTest() { verifyPassTest("SetIntersection_Valid_3"); }
@Test public void SetSubset_Valid_1_RuntimeTest() { verifyPassTest("SetSubset_Valid_1"); }
@Test public void SetSubset_Valid_2_RuntimeTest() { verifyPassTest("SetSubset_Valid_2"); }
@Test public void SetSubset_Valid_3_RuntimeTest() { verifyPassTest("SetSubset_Valid_3"); }
@Test public void SetSubset_Valid_4_RuntimeTest() { verifyPassTest("SetSubset_Valid_4"); }
@Test public void SetSubset_Valid_5_RuntimeTest() { verifyPassTest("SetSubset_Valid_5"); }
@Test public void SetSubset_Valid_6_RuntimeTest() { verifyPassTest("SetSubset_Valid_6"); }
@Test public void SetSubset_Valid_7_RuntimeTest() { verifyPassTest("SetSubset_Valid_7"); }
@Ignore("Issue #235")
@Test public void SetUnion_Valid_5_RuntimeTest() { verifyPassTest("SetUnion_Valid_5"); }
@Ignore("Issue #235")
@Test public void SetUnion_Valid_6_RuntimeTest() { verifyPassTest("SetUnion_Valid_6"); }
@Test public void String_Valid_1_RuntimeTest() { verifyPassTest("String_Valid_1"); }
@Test public void Subtype_Valid_3_RuntimeTest() { verifyPassTest("Subtype_Valid_3"); }
@Test public void Subtype_Valid_4_RuntimeTest() { verifyPassTest("Subtype_Valid_4"); }
@Test public void Subtype_Valid_5_RuntimeTest() { verifyPassTest("Subtype_Valid_5"); }
@Test public void Subtype_Valid_6_RuntimeTest() { verifyPassTest("Subtype_Valid_6"); }
@Test public void Subtype_Valid_7_RuntimeTest() { verifyPassTest("Subtype_Valid_7"); }
@Test public void Subtype_Valid_8_RuntimeTest() { verifyPassTest("Subtype_Valid_8"); }
@Test public void Subtype_Valid_9_RuntimeTest() { verifyPassTest("Subtype_Valid_9"); }
@Ignore("Issue #222")
@Test public void Switch_Valid_1_RuntimeTest() { verifyPassTest("Switch_Valid_1"); }
@Ignore("Issue #222")
@Test public void Switch_Valid_2_RuntimeTest() { verifyPassTest("Switch_Valid_2"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_1_RuntimeTest() { verifyPassTest("TypeEquals_Valid_1"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_10_RuntimeTest() { verifyPassTest("TypeEquals_Valid_10"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_13_RuntimeTest() { verifyPassTest("TypeEquals_Valid_13"); }
@Test public void TypeEquals_Valid_5_RuntimeTest() { verifyPassTest("TypeEquals_Valid_5"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_6_RuntimeTest() { verifyPassTest("TypeEquals_Valid_6"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_8_RuntimeTest() { verifyPassTest("TypeEquals_Valid_8"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_9_RuntimeTest() { verifyPassTest("TypeEquals_Valid_9"); }
@Test public void TypeEquals_Valid_14_RuntimeTest() { verifyPassTest("TypeEquals_Valid_14"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_15_RuntimeTest() { verifyPassTest("TypeEquals_Valid_15"); }
@Test public void UnionType_Valid_12_RuntimeTest() { verifyPassTest("UnionType_Valid_12"); }
@Test public void UnionType_Valid_4_RuntimeTest() { verifyPassTest("UnionType_Valid_4"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_5_RuntimeTest() { verifyPassTest("UnionType_Valid_5"); }
@Test public void UnionType_Valid_6_RuntimeTest() { verifyPassTest("UnionType_Valid_6"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_7_RuntimeTest() { verifyPassTest("UnionType_Valid_7"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_8_RuntimeTest() { verifyPassTest("UnionType_Valid_8"); }
@Test public void VarDecl_Valid_2_RuntimeTest() { verifyPassTest("VarDecl_Valid_2"); }
@Test public void While_Valid_2_RuntimeTest() { verifyPassTest("While_Valid_2"); }
@Ignore("Issue #231")
@Test public void While_Valid_3_RuntimeTest() { verifyPassTest("While_Valid_3"); }
@Test public void While_Valid_4_RuntimeTest() { verifyPassTest("While_Valid_4"); }
@Test public void While_Valid_5_RuntimeTest() { verifyPassTest("While_Valid_5"); }
@Ignore("Issue #231")
@Test public void While_Valid_6_RuntimeTest() { verifyPassTest("While_Valid_6"); }
@Test public void While_Valid_7_RuntimeTest() { verifyPassTest("While_Valid_7"); }
@Ignore("Issue #225")
@Test public void While_Valid_8_RuntimeTest() { verifyPassTest("While_Valid_8"); }
@Test public void While_Valid_9_RuntimeTest() { verifyPassTest("While_Valid_9"); }
}
|
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyc.testing.tests;
import org.junit.*;
import wyc.testing.TestHarness;
public class ExtendedValidTests extends TestHarness {
public ExtendedValidTests() {
super("../../tests/ext/valid","../../tests/ext/valid","sysout");
}
@Test public void Assume_Valid_1_RuntimeTest() { verifyPassTest("Assume_Valid_1"); }
@Test public void BoolAssign_Valid_3_RuntimeTest() { verifyPassTest("BoolAssign_Valid_3"); }
@Test public void BoolAssign_Valid_4_RuntimeTest() { verifyPassTest("BoolAssign_Valid_4"); }
@Test public void BoolRequires_Valid_1_RuntimeTest() { verifyPassTest("BoolRequires_Valid_1"); }
@Ignore("Known Issue") @Test public void Complex_Valid_3_RuntimeTest() { verifyPassTest("Complex_Valid_3"); }
@Ignore("Issue #233") @Test public void Complex_Valid_4_RuntimeTest() { verifyPassTest("Complex_Valid_4"); }
@Ignore("Requires Maps") @Test public void ConstrainedDictionary_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedDictionary_Valid_1"); }
@Test public void ConstrainedInt_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_1"); }
@Test public void ConstrainedInt_Valid_10_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_10"); }
@Test public void ConstrainedInt_Valid_11_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_11"); }
@Test public void ConstrainedInt_Valid_12_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_12"); }
@Ignore("Requires Modulus") @Test public void ConstrainedInt_Valid_13_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_13"); }
@Test public void ConstrainedInt_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_3"); }
@Test public void ConstrainedInt_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_4"); }
@Test public void ConstrainedInt_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_5"); }
@Ignore("Infinite loop?") @Test public void ConstrainedInt_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_6"); }
@Test public void ConstrainedInt_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_7"); }
@Test public void ConstrainedInt_Valid_8_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_8"); }
@Test public void ConstrainedInt_Valid_9_RuntimeTest() { verifyPassTest("ConstrainedInt_Valid_9"); }
@Test public void ConstrainedList_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_1"); }
@Test public void ConstrainedList_Valid_2_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_2"); }
@Test public void ConstrainedList_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_3"); }
@Test public void ConstrainedList_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_4"); }
@Ignore("Issue #210") @Test public void ConstrainedList_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_5"); }
@Ignore("Issue #210") @Test public void ConstrainedList_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_6"); }
@Test public void ConstrainedList_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_7"); }
@Ignore("Issue #209") @Test public void ConstrainedList_Valid_8_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_8"); }
@Test public void ConstrainedList_Valid_9_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_9"); }
@Test public void ConstrainedList_Valid_10_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_10"); }
@Ignore("Issue #229") @Test public void ConstrainedList_Valid_11_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_11"); }
@Ignore("Issue #228") @Test public void ConstrainedList_Valid_12_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_12"); }
@Ignore("Issue #230") @Test public void ConstrainedList_Valid_13_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_13"); }
@Ignore("Issue #229") @Test public void ConstrainedList_Valid_14_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_14"); }
@Ignore("Issue #230") @Test public void ConstrainedList_Valid_15_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_15"); }
@Test public void ConstrainedList_Valid_16_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_16"); }
@Ignore("Issue #210") @Test public void ConstrainedList_Valid_17_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_17"); }
@Ignore("Issue #229") @Test public void ConstrainedList_Valid_18_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_18"); }
@Test public void ConstrainedList_Valid_19_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_19"); }
@Ignore("Unclassified") @Test public void ConstrainedList_Valid_20_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_20"); }
@Ignore("Issue #225") @Test public void ConstrainedList_Valid_21_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_21"); }
@Test public void ConstrainedList_Valid_22_RuntimeTest() { verifyPassTest("ConstrainedList_Valid_22"); }
@Ignore("Future Work") @Test public void ConstrainedNegation_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedNegation_Valid_1"); }
@Test public void ConstrainedRecord_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_4"); }
@Test public void ConstrainedRecord_Valid_5_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_5"); }
@Ignore("Timeout") @Test public void ConstrainedRecord_Valid_6_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_6"); }
@Ignore("Unclassified") @Test public void ConstrainedRecord_Valid_7_RuntimeTest() { verifyPassTest("ConstrainedRecord_Valid_7"); }
@Test public void ConstrainedSet_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_1"); }
@Test public void ConstrainedSet_Valid_2_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_2"); }
@Test public void ConstrainedSet_Valid_3_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_3"); }
@Test public void ConstrainedSet_Valid_4_RuntimeTest() { verifyPassTest("ConstrainedSet_Valid_4"); }
@Test public void ConstrainedTuple_Valid_1_RuntimeTest() { verifyPassTest("ConstrainedTuple_Valid_1"); }
@Test public void Ensures_Valid_1_RuntimeTest() { verifyPassTest("Ensures_Valid_1"); }
@Test public void Ensures_Valid_2_RuntimeTest() { verifyPassTest("Ensures_Valid_2"); }
@Ignore("Issue #234") @Test public void Ensures_Valid_3_RuntimeTest() { verifyPassTest("Ensures_Valid_3"); }
@Test public void Ensures_Valid_4_RuntimeTest() { verifyPassTest("Ensures_Valid_4"); }
@Test public void Ensures_Valid_5_RuntimeTest() { verifyPassTest("Ensures_Valid_5"); }
@Test public void For_Valid_2_RuntimeTest() { verifyPassTest("For_Valid_2"); }
@Test public void For_Valid_3_RuntimeTest() { verifyPassTest("For_Valid_3"); }
@Test public void For_Valid_4_RuntimeTest() { verifyPassTest("For_Valid_4"); }
@Test public void For_Valid_5_RuntimeTest() { verifyPassTest("For_Valid_5"); }
@Ignore("Requires Overloading") @Test public void Function_Valid_11_RuntimeTest() { verifyPassTest("Function_Valid_11"); }
@Test public void Function_Valid_12_RuntimeTest() { verifyPassTest("Function_Valid_12"); }
@Test public void Function_Valid_14_RuntimeTest() { verifyPassTest("Function_Valid_14"); }
@Ignore("Issue #230") @Test public void Function_Valid_15_RuntimeTest() { verifyPassTest("Function_Valid_15"); }
@Test public void Function_Valid_2_RuntimeTest() { verifyPassTest("Function_Valid_2"); }
@Test public void Function_Valid_3_RuntimeTest() { verifyPassTest("Function_Valid_3"); }
@Test public void Function_Valid_4_RuntimeTest() { verifyPassTest("Function_Valid_4"); }
@Ignore("Issue #234") @Test public void Function_Valid_5_RuntimeTest() { verifyPassTest("Function_Valid_5"); }
@Ignore("Issue #234") @Test public void Function_Valid_6_RuntimeTest() { verifyPassTest("Function_Valid_6"); }
@Ignore("Requires Overloading") @Test public void Function_Valid_8_RuntimeTest() { verifyPassTest("Function_Valid_8"); }
@Test public void Function_Valid_9_RuntimeTest() { verifyPassTest("Function_Valid_9"); }
@Test public void IntDefine_Valid_1_RuntimeTest() { verifyPassTest("IntDefine_Valid_1"); }
@Test public void IntDiv_Valid_1_RuntimeTest() { verifyPassTest("IntDiv_Valid_1"); }
@Test public void IntDiv_Valid_2_RuntimeTest() { verifyPassTest("IntDiv_Valid_2"); }
@Ignore("Requires Lambdas") @Test public void Lambda_Valid_1_RuntimeTest() { verifyPassTest("Lambda_Valid_1"); }
@Test public void ListAccess_Valid_1_RuntimeTest() { verifyPassTest("ListAccess_Valid_1"); }
@Test public void ListAccess_Valid_2_RuntimeTest() { verifyPassTest("ListAccess_Valid_2"); }
@Test public void ListAppend_Valid_5_RuntimeTest() { verifyPassTest("ListAppend_Valid_5"); }
@Test public void ListAppend_Valid_6_RuntimeTest() { verifyPassTest("ListAppend_Valid_6"); }
@Test public void ListAppend_Valid_7_RuntimeTest() { verifyPassTest("ListAppend_Valid_7"); }
@Test public void ListAppend_Valid_8_RuntimeTest() { verifyPassTest("ListAppend_Valid_8"); }
@Ignore("Issue #231") @Test public void ListAppend_Valid_9_RuntimeTest() { verifyPassTest("ListAppend_Valid_9"); }
@Test public void ListAssign_Valid_5_RuntimeTest() { verifyPassTest("ListAssign_Valid_5"); }
@Test public void ListAssign_Valid_6_RuntimeTest() { verifyPassTest("ListAssign_Valid_6"); }
@Test public void ListGenerator_Valid_1_RuntimeTest() { verifyPassTest("ListGenerator_Valid_1"); }
@Test public void ListGenerator_Valid_2_RuntimeTest() { verifyPassTest("ListGenerator_Valid_2"); }
@Test public void ListLength_Valid_1_RuntimeTest() { verifyPassTest("ListLength_Valid_1"); }
@Ignore("Issue #230") @Test public void ListSublist_Valid_1_RuntimeTest() { verifyPassTest("ListSublist_Valid_1"); }
@Ignore("Issue #230") @Test public void ListSublist_Valid_2_RuntimeTest() { verifyPassTest("ListSubList_Valid_2"); }
@Test public void Method_Valid_1_RuntimeTest() { verifyPassTest("Method_Valid_1"); }
@Test public void Process_Valid_2_RuntimeTest() { verifyPassTest("Process_Valid_2"); }
@Test public void Quantifiers_Valid_1_RuntimeTest() { verifyPassTest("Quantifiers_Valid_1"); }
@Ignore("Issue #237") @Test public void Range_Valid_1_RuntimeTest() { verifyPassTest("Range_Valid_1"); }
@Test public void RealDiv_Valid_1_RuntimeTest() { verifyPassTest("RealDiv_Valid_1"); }
@Test public void RealDiv_Valid_2_RuntimeTest() { verifyPassTest("RealDiv_Valid_2"); }
@Ignore("Known Issue") @Test public void RealDiv_Valid_3_RuntimeTest() { verifyPassTest("RealDiv_Valid_3"); }
@Test public void RealNeg_Valid_1_RuntimeTest() { verifyPassTest("RealNeg_Valid_1"); }
@Test public void RealSub_Valid_1_RuntimeTest() { verifyPassTest("RealSub_Valid_1"); }
@Test public void RecordAssign_Valid_1_RuntimeTest() { verifyPassTest("RecordAssign_Valid_1"); }
@Test public void RecordAssign_Valid_2_RuntimeTest() { verifyPassTest("RecordAssign_Valid_2"); }
@Test public void RecordAssign_Valid_4_RuntimeTest() { verifyPassTest("RecordAssign_Valid_4"); }
@Test public void RecordAssign_Valid_5_RuntimeTest() { verifyPassTest("RecordAssign_Valid_5"); }
@Test public void RecordDefine_Valid_1_RuntimeTest() { verifyPassTest("RecordDefine_Valid_1"); }
@Test public void RecursiveType_Valid_3_RuntimeTest() { verifyPassTest("RecursiveType_Valid_3"); }
@Test public void RecursiveType_Valid_5_RuntimeTest() { verifyPassTest("RecursiveType_Valid_5"); }
@Test public void RecursiveType_Valid_6_RuntimeTest() { verifyPassTest("RecursiveType_Valid_6"); }
@Test public void RecursiveType_Valid_8_RuntimeTest() { verifyPassTest("RecursiveType_Valid_8"); }
@Ignore("Requires Type Test") @Test public void RecursiveType_Valid_9_RuntimeTest() { verifyPassTest("RecursiveType_Valid_9"); }
@Test public void Requires_Valid_1_RuntimeTest() { verifyPassTest("Requires_Valid_1"); }
@Test public void SetAssign_Valid_1_RuntimeTest() { verifyPassTest("SetAssign_Valid_1"); }
@Ignore("Issue #234") @Test public void SetComprehension_Valid_6_RuntimeTest() { verifyPassTest("SetComprehension_Valid_6"); }
@Test public void SetComprehension_Valid_7_RuntimeTest() { verifyPassTest("SetComprehension_Valid_7"); }
@Test public void SetDefine_Valid_1_RuntimeTest() { verifyPassTest("SetDefine_Valid_1"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_1_RuntimeTest() { verifyPassTest("SetIntersection_Valid_1"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_2_RuntimeTest() { verifyPassTest("SetIntersection_Valid_2"); }
@Ignore("Known Issue") @Test public void SetIntersection_Valid_3_RuntimeTest() { verifyPassTest("SetIntersection_Valid_3"); }
@Test public void SetSubset_Valid_1_RuntimeTest() { verifyPassTest("SetSubset_Valid_1"); }
@Test public void SetSubset_Valid_2_RuntimeTest() { verifyPassTest("SetSubset_Valid_2"); }
@Test public void SetSubset_Valid_3_RuntimeTest() { verifyPassTest("SetSubset_Valid_3"); }
@Test public void SetSubset_Valid_4_RuntimeTest() { verifyPassTest("SetSubset_Valid_4"); }
@Test public void SetSubset_Valid_5_RuntimeTest() { verifyPassTest("SetSubset_Valid_5"); }
@Test public void SetSubset_Valid_6_RuntimeTest() { verifyPassTest("SetSubset_Valid_6"); }
@Test public void SetSubset_Valid_7_RuntimeTest() { verifyPassTest("SetSubset_Valid_7"); }
@Ignore("Issue #235") @Test public void SetUnion_Valid_5_RuntimeTest() { verifyPassTest("SetUnion_Valid_5"); }
@Test public void SetUnion_Valid_6_RuntimeTest() { verifyPassTest("SetUnion_Valid_6"); }
@Test public void String_Valid_1_RuntimeTest() { verifyPassTest("String_Valid_1"); }
@Test public void Subtype_Valid_3_RuntimeTest() { verifyPassTest("Subtype_Valid_3"); }
@Test public void Subtype_Valid_4_RuntimeTest() { verifyPassTest("Subtype_Valid_4"); }
@Test public void Subtype_Valid_5_RuntimeTest() { verifyPassTest("Subtype_Valid_5"); }
@Test public void Subtype_Valid_6_RuntimeTest() { verifyPassTest("Subtype_Valid_6"); }
@Test public void Subtype_Valid_7_RuntimeTest() { verifyPassTest("Subtype_Valid_7"); }
@Test public void Subtype_Valid_8_RuntimeTest() { verifyPassTest("Subtype_Valid_8"); }
@Test public void Subtype_Valid_9_RuntimeTest() { verifyPassTest("Subtype_Valid_9"); }
@Ignore("Issue #222") @Test public void Switch_Valid_1_RuntimeTest() { verifyPassTest("Switch_Valid_1"); }
@Ignore("Issue #222") @Test public void Switch_Valid_2_RuntimeTest() { verifyPassTest("Switch_Valid_2"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_1_RuntimeTest() { verifyPassTest("TypeEquals_Valid_1"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_10_RuntimeTest() { verifyPassTest("TypeEquals_Valid_10"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_13_RuntimeTest() { verifyPassTest("TypeEquals_Valid_13"); }
@Test public void TypeEquals_Valid_5_RuntimeTest() { verifyPassTest("TypeEquals_Valid_5"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_6_RuntimeTest() { verifyPassTest("TypeEquals_Valid_6"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_8_RuntimeTest() { verifyPassTest("TypeEquals_Valid_8"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_9_RuntimeTest() { verifyPassTest("TypeEquals_Valid_9"); }
@Test public void TypeEquals_Valid_14_RuntimeTest() { verifyPassTest("TypeEquals_Valid_14"); }
@Ignore("Requires Type Test") @Test public void TypeEquals_Valid_15_RuntimeTest() { verifyPassTest("TypeEquals_Valid_15"); }
@Test public void UnionType_Valid_12_RuntimeTest() { verifyPassTest("UnionType_Valid_12"); }
@Test public void UnionType_Valid_4_RuntimeTest() { verifyPassTest("UnionType_Valid_4"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_5_RuntimeTest() { verifyPassTest("UnionType_Valid_5"); }
@Test public void UnionType_Valid_6_RuntimeTest() { verifyPassTest("UnionType_Valid_6"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_7_RuntimeTest() { verifyPassTest("UnionType_Valid_7"); }
@Ignore("Requires Type Test") @Test public void UnionType_Valid_8_RuntimeTest() { verifyPassTest("UnionType_Valid_8"); }
@Test public void VarDecl_Valid_2_RuntimeTest() { verifyPassTest("VarDecl_Valid_2"); }
@Test public void While_Valid_2_RuntimeTest() { verifyPassTest("While_Valid_2"); }
@Test public void While_Valid_3_RuntimeTest() { verifyPassTest("While_Valid_3"); }
@Test public void While_Valid_4_RuntimeTest() { verifyPassTest("While_Valid_4"); }
@Test public void While_Valid_5_RuntimeTest() { verifyPassTest("While_Valid_5"); }
@Test public void While_Valid_6_RuntimeTest() { verifyPassTest("While_Valid_6"); }
@Test public void While_Valid_7_RuntimeTest() { verifyPassTest("While_Valid_7"); }
@Ignore("Issue #225") @Test public void While_Valid_8_RuntimeTest() { verifyPassTest("While_Valid_8"); }
@Test public void While_Valid_9_RuntimeTest() { verifyPassTest("While_Valid_9"); }
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyil.checks;
import static wybs.lang.SyntaxError.internalFailure;
import static wybs.lang.SyntaxError.syntaxError;
import static wyil.util.ErrorMessages.errorMessage;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.*;
import wybs.lang.*;
import wybs.util.Pair;
import wybs.util.Trie;
import wyil.lang.*;
import wyil.util.ErrorMessages;
import wycs.io.WycsFilePrinter;
import wycs.lang.*;
import wycs.transforms.ConstraintInline;
import wycs.transforms.VerificationCheck;
import wycs.util.Exprs;
/**
* Responsible for converting a given Wyil bytecode into an appropriate
* constraint which encodes its semantics.
*
* @author David J. Pearce
*
*/
public class VerificationTransformer {
private final Builder builder;
// private final WyilFile.Case method;
private final WycsFile wycsFile;
private final String filename;
private final boolean assume;
public VerificationTransformer(Builder builder, WycsFile wycsFile,
String filename, boolean assume) {
this.builder = builder;
this.filename = filename;
this.assume = assume;
this.wycsFile = wycsFile;
}
public String filename() {
return filename;
}
public void end(VerificationBranch.LoopScope scope,
VerificationBranch branch) {
// not sure what really needs to be done here, in fact.
}
public void exit(VerificationBranch.LoopScope scope,
VerificationBranch branch) {
branch.addAll(scope.constraints);
}
public void end(VerificationBranch.ForScope scope, VerificationBranch branch) {
// we need to build up a quantified formula here.
ArrayList<Expr> constraints = new ArrayList<Expr>();
constraints.addAll(scope.constraints);
constraints.remove(0); // remove artificial constraint that idx in src
Expr root = Expr.Nary(Expr.Nary.Op.AND, constraints, branch.entry()
.attributes());
Pair<TypePattern, Expr>[] vars = new Pair[] { new Pair<TypePattern, Expr>(
new TypePattern.Leaf(null, scope.index.name), scope.source) };
if (scope.loop.type instanceof Type.EffectiveList) {
// substitute for root to workaround limitation of whiley source
// with respect to iterating over lists
HashMap<String, Expr> binding = new HashMap<String, Expr>();
binding.put(scope.index.name,
Expr.TupleLoad(Expr.Variable(scope.index.name), 1));
root = root.substitute(binding);
}
branch.add(Expr.ForAll(vars, root, branch.entry().attributes()));
}
public void exit(VerificationBranch.ForScope scope,
VerificationBranch branch) {
ArrayList<Expr> constraints = new ArrayList<Expr>();
constraints.addAll(scope.constraints);
constraints.remove(0); // remove artificial constraint that idx in src
Expr root = Expr.Nary(Expr.Nary.Op.AND, constraints, branch.entry()
.attributes());
Pair<TypePattern, Expr>[] vars = new Pair[] { new Pair<TypePattern, Expr>(
new TypePattern.Leaf(null, scope.index.name), scope.source) };
if (scope.loop.type instanceof Type.EffectiveList) {
// substitute for root to workaround limitation of whiley source
// with respect to iterating over lists
HashMap<String, Expr> binding = new HashMap<String, Expr>();
binding.put(scope.index.name,
Expr.TupleLoad(Expr.Variable(scope.index.name), 1));
root = root.substitute(binding);
}
branch.add(Expr.Exists(vars, root, branch.entry().attributes()));
}
public void exit(VerificationBranch.TryScope scope,
VerificationBranch branch) {
}
protected void transform(Code.Assert code, VerificationBranch branch) {
Expr test = buildTest(code.op, code.leftOperand, code.rightOperand,
code.type, branch);
if (!assume) {
// We need the entry branch to determine the parameter types.
Expr assumptions = branch.constraints();
Expr implication = Expr.Binary(Expr.Binary.Op.IMPLIES, assumptions,
test);
Expr assertion = buildAssertion(0, implication, branch);
wycsFile.add(wycsFile.new Assert(code.msg, assertion, branch
.entry().attributes()));
}
branch.add(test);
}
protected Expr buildAssertion(int index, Expr implication,
VerificationBranch branch) {
if (index < branch.nScopes()) {
Expr contents = buildAssertion(index + 1, implication, branch);
VerificationBranch.Scope scope = branch.scope(index);
if (scope instanceof VerificationBranch.EntryScope) {
VerificationBranch.EntryScope es = (VerificationBranch.EntryScope) scope;
Pair<TypePattern, Expr>[] vars = convertParameters(es.declaration);
return Expr.ForAll(vars, contents);
} else if (scope instanceof VerificationBranch.ForScope) {
VerificationBranch.ForScope ls = (VerificationBranch.ForScope) scope;
SyntacticType type = convert(ls.loop.type.element(),branch.entry());
TypePattern tp = new TypePattern.Leaf(type,ls.index.name);
if (ls.loop.type instanceof Type.EffectiveList) {
// FIXME: hack to work around limitations of whiley for
// loops.
TypePattern.Leaf idx = new TypePattern.Leaf(
new SyntacticType.Primitive(SemanticType.Int), null);
tp = new TypePattern.Tuple(new TypePattern[] { idx, tp },
null);
}
Pair<TypePattern,Expr>[] vars = new Pair[]{
new Pair<TypePattern,Expr>(tp,ls.source)
};
return Expr.ForAll(vars, contents);
} else {
return contents;
}
} else {
return implication;
}
}
protected void transform(Code.Assume code, VerificationBranch branch) {
// At this point, what we do is invert the condition being asserted and
// check that it is unsatisfiable.
Expr test = buildTest(code.op, code.leftOperand, code.rightOperand,
code.type, branch);
branch.add(test);
}
protected void transform(Code.Assign code, VerificationBranch branch) {
branch.write(code.target, branch.read(code.operand));
}
protected void transform(Code.BinArithOp code, VerificationBranch branch) {
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
Expr.Binary.Op op;
switch (code.kind) {
case ADD:
op = Expr.Binary.Op.ADD;
break;
case SUB:
op = Expr.Binary.Op.SUB;
break;
case MUL:
op = Expr.Binary.Op.MUL;
break;
case DIV:
op = Expr.Binary.Op.DIV;
break;
case RANGE:
branch.write(code.target,
Exprs.ListRange(lhs, rhs, branch.entry().attributes()));
return;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target,
Expr.Binary(op, lhs, rhs, branch.entry().attributes()));
}
protected void transform(Code.BinListOp code, VerificationBranch branch) {
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
switch (code.kind) {
case APPEND:
// do nothing
break;
case LEFT_APPEND:
rhs = Exprs.List(new Expr[] { rhs }, branch.entry().attributes());
break;
case RIGHT_APPEND:
lhs = Exprs.List(new Expr[] { lhs }, branch.entry().attributes());
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target,
Exprs.ListAppend(lhs, rhs, branch.entry().attributes()));
}
protected void transform(Code.BinSetOp code, VerificationBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
Expr val;
switch (code.kind) {
case UNION:
val = Exprs.SetUnion(lhs, rhs, attributes);
break;
case LEFT_UNION:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Exprs.SetUnion(lhs, rhs, attributes);
break;
case RIGHT_UNION:
lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch
.entry().attributes());
val = Exprs.SetUnion(lhs, rhs, attributes);
break;
case INTERSECTION:
val = Exprs.SetIntersection(lhs, rhs, attributes);
break;
case LEFT_INTERSECTION:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Exprs.SetIntersection(lhs, rhs, attributes);
break;
case RIGHT_INTERSECTION:
lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch
.entry().attributes());
val = Exprs.SetIntersection(lhs, rhs, attributes);
break;
case LEFT_DIFFERENCE:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Exprs.SetDifference(lhs, rhs, attributes);
break;
case DIFFERENCE:
val = Exprs.SetDifference(lhs, rhs, attributes);
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target, val);
}
protected void transform(Code.BinStringOp code, VerificationBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
switch (code.kind) {
case APPEND:
// do nothing
break;
case LEFT_APPEND:
rhs = Exprs.List(new Expr[] { rhs }, attributes);
break;
case RIGHT_APPEND:
lhs = Exprs.List(new Expr[] { lhs }, attributes);
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target, Exprs.ListAppend(lhs, rhs, attributes));
}
protected void transform(Code.Convert code, VerificationBranch branch) {
Expr result = branch.read(code.operand);
// TODO: actually implement some or all coercions?
branch.write(code.target, result);
}
protected void transform(Code.Const code, VerificationBranch branch) {
Value val = convert(code.constant, branch.entry());
branch.write(code.target,
Expr.Constant(val, branch.entry().attributes()));
}
protected void transform(Code.Debug code, VerificationBranch branch) {
// do nout
}
protected void transform(Code.Dereference code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.FieldLoad code, VerificationBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
Expr src = branch.read(code.operand);
branch.write(code.target, Exprs.FieldOf(src, code.field, attributes));
}
protected void transform(Code.If code, VerificationBranch falseBranch,
VerificationBranch trueBranch) {
// First, cover true branch
Expr.Binary trueTest = buildTest(code.op, code.leftOperand,
code.rightOperand, code.type, trueBranch);
trueBranch.add(trueTest);
falseBranch.add(invert(trueTest));
}
protected void transform(Code.IfIs code, VerificationBranch falseBranch,
VerificationBranch trueBranch) {
// TODO
}
protected void transform(Code.IndirectInvoke code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.Invoke code, VerificationBranch branch)
throws Exception {
Collection<Attribute> attributes = branch.entry().attributes();
int[] code_operands = code.operands;
if (code.target != Code.NULL_REG) {
// Need to assume the post-condition holds.
Block postcondition = findPostcondition(code.name, code.type,
branch.entry());
Expr[] operands = new Expr[code_operands.length];
for (int i = 0; i != code_operands.length; ++i) {
operands[i] = branch.read(code_operands[i]);
}
Expr argument = Expr.Nary(Expr.Nary.Op.TUPLE, operands, attributes);
branch.write(code.target, Expr.FunCall(code.name.toString(),
new SyntacticType[0], argument, attributes));
if (postcondition != null) {
// operands = Arrays.copyOf(operands, operands.length);
Expr[] arguments = new Expr[operands.length + 1];
System.arraycopy(operands, 0, arguments, 1, operands.length);
arguments[0] = branch.read(code.target);
Expr constraint = transformExternalBlock(postcondition,
arguments, branch);
// assume the post condition holds
branch.add(constraint);
}
}
}
protected void transform(Code.Invert code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.IndexOf code, VerificationBranch branch) {
Expr src = branch.read(code.leftOperand);
Expr idx = branch.read(code.rightOperand);
branch.write(code.target,
Exprs.IndexOf(src, idx, branch.entry().attributes()));
}
protected void transform(Code.LengthOf code, VerificationBranch branch) {
Expr src = branch.read(code.operand);
branch.write(code.target, Expr.Unary(Expr.Unary.Op.LENGTHOF, src,
branch.entry().attributes()));
}
protected void transform(Code.Loop code, VerificationBranch branch) {
// FIXME: assume loop invariant?
}
protected void transform(Code.Move code, VerificationBranch branch) {
branch.write(code.target, branch.read(code.operand));
}
protected void transform(Code.NewMap code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.NewList code, VerificationBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target, Exprs.List(vals, branch.entry().attributes()));
}
protected void transform(Code.NewSet code, VerificationBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target,
Expr.Nary(Expr.Nary.Op.SET, vals, branch.entry().attributes()));
}
protected void transform(Code.NewRecord code, VerificationBranch branch) {
int[] code_operands = code.operands;
Type.Record type = code.type;
ArrayList<String> fields = new ArrayList<String>(type.fields().keySet());
Collections.sort(fields);
Expr[] vals = new Expr[fields.size()];
for (int i = 0; i != fields.size(); ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target, Exprs.Record(fields
.toArray(new String[vals.length]), vals, branch.entry()
.attributes()));
}
protected void transform(Code.NewObject code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.NewTuple code, VerificationBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target, Expr.Nary(Expr.Nary.Op.TUPLE, vals, branch
.entry().attributes()));
}
protected void transform(Code.Nop code, VerificationBranch branch) {
// do nout
}
protected void transform(Code.Return code, VerificationBranch branch) {
// nothing to do
}
protected void transform(Code.SubString code, VerificationBranch branch) {
Expr src = branch.read(code.operands[0]);
Expr start = branch.read(code.operands[1]);
Expr end = branch.read(code.operands[2]);
Expr result = Exprs.SubList(src, start, end, branch.entry()
.attributes());
branch.write(code.target, result);
}
protected void transform(Code.SubList code, VerificationBranch branch) {
Expr src = branch.read(code.operands[0]);
Expr start = branch.read(code.operands[1]);
Expr end = branch.read(code.operands[2]);
Expr result = Exprs.SubList(src, start, end, branch.entry()
.attributes());
branch.write(code.target, result);
}
protected void transform(Code.Throw code, VerificationBranch branch) {
// TODO
}
protected void transform(Code.TupleLoad code, VerificationBranch branch) {
Expr src = branch.read(code.operand);
Expr result = Expr.TupleLoad(src, code.index, branch.entry()
.attributes());
branch.write(code.target, result);
}
protected void transform(Code.TryCatch code, VerificationBranch branch) {
// FIXME: do something here?
}
protected void transform(Code.UnArithOp code, VerificationBranch branch) {
if (code.kind == Code.UnArithKind.NEG) {
Expr operand = branch.read(code.operand);
branch.write(code.target, Expr.Unary(Expr.Unary.Op.NEG, operand,
branch.entry().attributes()));
} else {
// TODO
}
}
protected void transform(Code.Update code, VerificationBranch branch) {
Expr result = branch.read(code.operand);
Expr source = branch.read(code.target);
branch.write(code.target,
updateHelper(code.iterator(), source, result, branch));
}
protected Expr updateHelper(Iterator<Code.LVal> iter, Expr source,
Expr result, VerificationBranch branch) {
if (!iter.hasNext()) {
return result;
} else {
Collection<Attribute> attributes = branch.entry().attributes();
Code.LVal lv = iter.next();
if (lv instanceof Code.RecordLVal) {
Code.RecordLVal rlv = (Code.RecordLVal) lv;
result = updateHelper(iter,
Exprs.FieldOf(source, rlv.field, attributes), result,
branch);
return Exprs.FieldUpdate(source, rlv.field, result, attributes);
} else if (lv instanceof Code.ListLVal) {
Code.ListLVal rlv = (Code.ListLVal) lv;
Expr index = branch.read(rlv.indexOperand);
result = updateHelper(iter,
Exprs.IndexOf(source, index, attributes), result,
branch);
return Exprs.ListUpdate(source, index, result, attributes);
} else if (lv instanceof Code.MapLVal) {
return source; // TODO
} else if (lv instanceof Code.StringLVal) {
return source; // TODO
} else {
return source; // TODO
}
}
}
protected Block findPrecondition(NameID name, Type.FunctionOrMethod fun,
SyntacticElement elem) throws Exception {
Path.Entry<WyilFile> e = builder.namespace().get(name.module(),
WyilFile.ContentType);
if (e == null) {
syntaxError(
errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module()
.toString()), filename, elem);
}
WyilFile m = e.read();
WyilFile.MethodDeclaration method = m.method(name.name(), fun);
for (WyilFile.Case c : method.cases()) {
// FIXME: this is a hack for now
return c.precondition();
}
return null;
}
protected Block findPostcondition(NameID name, Type.FunctionOrMethod fun,
SyntacticElement elem) throws Exception {
Path.Entry<WyilFile> e = builder.namespace().get(name.module(),
WyilFile.ContentType);
if (e == null) {
syntaxError(
errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module()
.toString()), filename, elem);
}
WyilFile m = e.read();
WyilFile.MethodDeclaration method = m.method(name.name(), fun);
for (WyilFile.Case c : method.cases()) {
// FIXME: this is a hack for now
return c.postcondition();
}
return null;
}
protected Expr transformExternalBlock(Block externalBlock, Expr[] operands,
VerificationBranch branch) {
// first, generate a constraint representing the post-condition.
VerificationBranch master = new VerificationBranch(externalBlock);
// second, set initial environment
for (int i = 0; i != operands.length; ++i) {
master.write(i, operands[i]);
}
return master.transform(new VerificationTransformer(builder, wycsFile,
filename, true));
}
/**
* Generate a formula representing a condition from an Code.IfCode or
* Code.Assert bytecodes.
*
* @param op
* @param stack
* @param elem
* @return
*/
private Expr.Binary buildTest(Code.Comparator cop, int leftOperand,
int rightOperand, Type type, VerificationBranch branch) {
Expr lhs = branch.read(leftOperand);
Expr rhs = branch.read(rightOperand);
Expr.Binary.Op op;
switch (cop) {
case EQ:
op = Expr.Binary.Op.EQ;
break;
case NEQ:
op = Expr.Binary.Op.NEQ;
break;
case GTEQ:
op = Expr.Binary.Op.GTEQ;
break;
case GT:
op = Expr.Binary.Op.GT;
break;
case LTEQ:
op = Expr.Binary.Op.LTEQ;
break;
case LT:
op = Expr.Binary.Op.LT;
break;
case SUBSET:
op = Expr.Binary.Op.SUBSET;
break;
case SUBSETEQ:
op = Expr.Binary.Op.SUBSETEQ;
break;
case ELEMOF:
op = Expr.Binary.Op.IN;
break;
default:
internalFailure("unknown comparator (" + cop + ")", filename,
branch.entry());
return null;
}
return Expr.Binary(op, lhs, rhs, branch.entry().attributes());
}
/**
* Generate the logically inverted expression corresponding to this
* comparator.
*
* @param cop
* @param leftOperand
* @param rightOperand
* @param type
* @param branch
* @return
*/
private Expr invert(Expr.Binary test) {
Expr.Binary.Op op;
switch (test.op) {
case EQ:
op = Expr.Binary.Op.NEQ;
break;
case NEQ:
op = Expr.Binary.Op.EQ;
break;
case GTEQ:
op = Expr.Binary.Op.LT;
break;
case GT:
op = Expr.Binary.Op.LTEQ;
break;
case LTEQ:
op = Expr.Binary.Op.GT;
break;
case LT:
op = Expr.Binary.Op.GTEQ;
break;
case SUBSET:
op = Expr.Binary.Op.SUPSETEQ;
break;
case SUBSETEQ:
op = Expr.Binary.Op.SUPSET;
break;
case SUPSET:
op = Expr.Binary.Op.SUBSETEQ;
break;
case SUPSETEQ:
op = Expr.Binary.Op.SUBSET;
break;
case IN:
op = Expr.Binary.Op.IN;
return Expr.Unary(
Expr.Unary.Op.NOT,
Expr.Binary(op, test.leftOperand, test.rightOperand,
test.attributes()), test.attributes());
default:
internalFailure("unknown comparator (" + test.op + ")", filename,
test);
return null;
}
return Expr.Binary(op, test.leftOperand, test.rightOperand,
test.attributes());
}
public Value convert(Constant c, SyntacticElement elem) {
if (c instanceof Constant.Null) {
// TODO: is this the best translation?
return wycs.lang.Value.Integer(BigInteger.ZERO);
} else if (c instanceof Constant.Bool) {
Constant.Bool cb = (Constant.Bool) c;
return wycs.lang.Value.Bool(cb.value);
} else if (c instanceof Constant.Byte) {
Constant.Byte cb = (Constant.Byte) c;
return wycs.lang.Value.Integer(BigInteger.valueOf(cb.value));
} else if (c instanceof Constant.Char) {
Constant.Char cb = (Constant.Char) c;
return wycs.lang.Value.Integer(BigInteger.valueOf(cb.value));
} else if (c instanceof Constant.Integer) {
Constant.Integer cb = (Constant.Integer) c;
return wycs.lang.Value.Integer(cb.value);
} else if (c instanceof Constant.Rational) {
Constant.Rational cb = (Constant.Rational) c;
return wycs.lang.Value.Rational(cb.value);
} else if (c instanceof Constant.Strung) {
Constant.Strung cb = (Constant.Strung) c;
String str = cb.value;
ArrayList<Value> pairs = new ArrayList<Value>();
for (int i = 0; i != str.length(); ++i) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(Value.Integer(BigInteger.valueOf(i)));
pair.add(Value.Integer(BigInteger.valueOf(str.charAt(i))));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.List) {
Constant.List cb = (Constant.List) c;
List<Constant> cb_values = cb.values;
ArrayList<Value> pairs = new ArrayList<Value>();
for (int i = 0; i != cb_values.size(); ++i) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(Value.Integer(BigInteger.valueOf(i)));
pair.add(convert(cb_values.get(i), elem));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.Map) {
Constant.Map cb = (Constant.Map) c;
ArrayList<Value> pairs = new ArrayList<Value>();
for (Map.Entry<Constant, Constant> e : cb.values.entrySet()) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(convert(e.getKey(), elem));
pair.add(convert(e.getValue(), elem));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.Set) {
Constant.Set cb = (Constant.Set) c;
ArrayList<Value> values = new ArrayList<Value>();
for (Constant v : cb.values) {
values.add(convert(v, elem));
}
return wycs.lang.Value.Set(values);
} else if (c instanceof Constant.Tuple) {
Constant.Tuple cb = (Constant.Tuple) c;
ArrayList<Value> values = new ArrayList<Value>();
for (Constant v : cb.values) {
values.add(convert(v, elem));
}
return wycs.lang.Value.Tuple(values);
} else {
internalFailure("unknown constant encountered (" + c + ")",
filename, elem);
return null;
}
}
private Pair<TypePattern, Expr>[] convertParameters(
WyilFile.MethodDeclaration decl) {
Type.FunctionOrMethod tfm = decl.type();
ArrayList<Type> parameters = tfm.params();
Pair<TypePattern, Expr>[] types = new Pair[parameters.size()];
for (int i = 0; i != types.length; ++i) {
SyntacticType t = convert(parameters.get(i), decl);
TypePattern.Leaf l = new TypePattern.Leaf(t, "r" + i);
types[i] = new Pair<TypePattern, Expr>(l, null);
}
return types;
}
private SyntacticType convert(Type t, SyntacticElement elem) {
// FIXME: this is fundamentally broken in the case of recursive types.
if (t instanceof Type.Any) {
return new SyntacticType.Primitive(SemanticType.Any);
} else if (t instanceof Type.Void) {
return new SyntacticType.Primitive(SemanticType.Void);
} else if (t instanceof Type.Bool) {
return new SyntacticType.Primitive(SemanticType.Bool);
} else if (t instanceof Type.Char) {
return new SyntacticType.Primitive(SemanticType.Int);
} else if (t instanceof Type.Int) {
return new SyntacticType.Primitive(SemanticType.Int);
} else if (t instanceof Type.Real) {
return new SyntacticType.Primitive(SemanticType.Real);
} else if (t instanceof Type.Set) {
Type.Set st = (Type.Set) t;
SyntacticType element = convert(st.element(), elem);
return new SyntacticType.Set(element);
} else if (t instanceof Type.List) {
Type.List lt = (Type.List) t;
SyntacticType element = convert(lt.element(), elem);
// ugly.
return new SyntacticType.Set(new SyntacticType.Tuple(
new SyntacticType[] {
new SyntacticType.Primitive(SemanticType.Int),
element }));
} else if (t instanceof Type.Tuple) {
Type.Tuple tt = (Type.Tuple) t;
SyntacticType[] elements = new SyntacticType[tt.size()];
for (int i = 0; i != tt.size(); ++i) {
elements[i] = convert(tt.element(i), elem);
}
return new SyntacticType.Tuple(elements);
} else if (t instanceof Type.Record) {
Type.Record rt = (Type.Record) t;
// FIXME: this is *completely* broken
return new SyntacticType.Set(new SyntacticType.Tuple(
new SyntacticType[] {
new SyntacticType.Primitive(SemanticType.String),
new SyntacticType.Primitive(SemanticType.Any) }));
} else {
internalFailure("unknown type encountered (" + t + ")", filename,
elem);
return null;
}
}
}
|
package hey.rich.countit;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Timer extends StandOutWindow {
private static final String LOG_TAG = "Timer";
private TextView mTimerText;
private ImageView mStartStopView;
private ImageView mLapResetView;
private ImageView mCloseView;
/** Contains various states application can be in */
private static enum STATE {
RUNNING, STOPPED;
}
/**
* If true when {@link updateValue()} is called and {@link mCurretState} is
* set to STATE.STOPPED, current time will be cleared/reset to 0
*/
private boolean mClearTimer = false;
/** Current state of the application */
private STATE mCurrentState;
private long mStartTime = 0L;
private long mCurrentTime = 0L;
private int mId;
@Override
public String getAppName() {
return "Timer";
}
@Override
public int getAppIcon() {
return android.R.drawable.ic_menu_more;
}
@Override
public void createAndAttachView(int id, FrameLayout frame) {
mId = id;
Log.d(LOG_TAG, "Created timer with id: " + id);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_timer, frame, true);
mStartStopView = (ImageView) view
.findViewById(R.id.imageButtonPlayStop);
mLapResetView = (ImageView) view.findViewById(R.id.imageButtonLapReset);
mCloseView = (ImageView) view.findViewById(R.id.timer_close);
// Set default state to stoped
mCurrentState = STATE.STOPPED;
mTimerText = (TextView) view.findViewById(R.id.timer);
setUpViewElements();
/*
* When creating the timer, we don't want any "current time" as we are
* only ever going to be created from the button press in the main
* activity, if we are ever killed and then restored it is not currently
* expected of us to keep the previous value of the timer.
*
* So we reset the current time to 0, if this is not present, when we
* update the timer from this call, we will be calling updateTimer with
* the state equal to STATE.STOPPED, this means that we will be saving
* the current time something we do not want or need to do - this leads
* to overflow and an incorrect timer value.
*/
mCurrentTime = 0L;
updateTimer();
mCurrentTime = 0L;
}
// Called before this window is closed
@Override
public boolean onClose(int id, Window window){
// State should be stoped
mCurrentState = STATE.STOPPED;
// update Timer one last time
updateTimer();
return false;
}
/**
* Sets up all of the elements in the current view.
* <p>
* Currently this is just: stop/start button, lap/reset button, and the
* actual timer (Chronometer).
* <p>
* In the future there will be: ListView that contains the actual "laps"
*/
private void setUpViewElements() {
// Set the format of the timer
// TODO: make this customizable
mStartStopView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: UPDATE BUTTONS HAHA
// Check state
Log.d(LOG_TAG, "Clicked stop/start button");
if (mCurrentState == STATE.STOPPED) {
mCurrentState = STATE.RUNNING;
updateTimer();
} else if (mCurrentState == STATE.RUNNING) {
mCurrentState = STATE.STOPPED;
updateTimer();
} else {
// Invalid state
throw new RuntimeException("Invalid state: "
+ mCurrentState.toString());
}
}
});
mLapResetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Check state
Log.d(LOG_TAG, "Clicked lap/reset button");
if (mCurrentState == STATE.STOPPED) {
// Reset time
if (!mClearTimer) {
// Only allow user to reset time if it is not already
// reset
mClearTimer = true;
updateTimer();
}
} else if (mCurrentState == STATE.RUNNING) {
// Create a lap
// TODO: implement lap things
}
}
});
mCloseView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Close the window he-yo
close(mId);
}
});
}
// Timer
private static java.util.Timer mTimer = new java.util.Timer();
// TODO: Should be a much nicer way to do this
private void updateTimer() {
if (mCurrentState == STATE.RUNNING) {
// TODO: Think of a nice way to: update clearing flag here as well
// as only call this the first time we want to clear timer - not
// calling this so many times.
// Start the timer
if (mClearTimer) {
mStartTime = System.currentTimeMillis();
mClearTimer = false;
} else {
mStartTime = System.currentTimeMillis() - mCurrentTime;
}
mTimer = new java.util.Timer();
mTimer.schedule(new CustomTimerTask(), 0, 10);
} else if (mCurrentState == STATE.STOPPED) {
// Stopping timer
if (mClearTimer) {
mCurrentTime = 0L;
mTimerText.setText(String.format("%d:%02d:%02d", 0, 0, 0));
} else {
mTimer.cancel();
mTimer.purge();
mCurrentTime = System.currentTimeMillis() - mStartTime;
}
} else {
if (mCurrentState == null) {
throw new RuntimeException("Current state is null");
}
// Invalid state
throw new RuntimeException("Invalid state: "
+ mCurrentState.toString());
}
updateButtonIcons();
}
/** Updates the button icons based on state {@link mCurrentState} */
private void updateButtonIcons() {
if (mCurrentState == STATE.RUNNING) {
mStartStopView.setImageResource(android.R.drawable.ic_media_pause);
mLapResetView.setImageResource(android.R.drawable.ic_menu_save);
} else if (mCurrentState == STATE.STOPPED) {
mStartStopView.setImageResource(android.R.drawable.ic_media_play);
mLapResetView.setImageResource(android.R.drawable.ic_menu_revert);
} else {
if (mCurrentState == null) {
throw new RuntimeException("Current state is null");
}
throw new RuntimeException("Invalid state: "
+ mCurrentState.toString());
}
}
/**
* Updates the timer Textview {@link mTimerText} based on
* {@link mCurrentTime}
*/
private void updateTime(long time) {
int milliSeconds = (int) (time % 1000);
milliSeconds /= 10;
int seconds = (int) (time / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
updateTimerText(minutes, seconds, milliSeconds);
}
final Handler h = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - mStartTime;
// Only care about every 10 milliseconds
updateTime(millis);
return false;
}
});
/**
* Updates the text view {@link mTimerText} in the specified format. TODO:
* Multiple formats here!
*
* @param minutes
* Number of minutes
* @param seconds
* Number of seconds
* @param milliSeconds
* Number of milliSeconds
*/
private void updateTimerText(long minutes, long seconds, long milliSeconds) {
if (mTimerText != null) {
mTimerText.setText(String.format("%d:%02d:%02d", minutes, seconds,
milliSeconds));
}
}
// tells handler to send a message
class CustomTimerTask extends TimerTask {
@Override
public void run() {
h.sendEmptyMessage(0);
}
}
// Make every window essentially the same size
@Override
public StandOutLayoutParams getParams(int id, Window window) {
return new StandOutLayoutParams(id, 400, 300,
StandOutLayoutParams.CENTER,
StandOutLayoutParams.CENTER, 100, 100);
}
// / We want system window decorations, we want to drag the body, we want
// the ability to hide windows, and we want to tap the window to bring to
// front
@Override
public int getFlags(int id) {
return StandOutFlags.FLAG_BODY_MOVE_ENABLE
| StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE
| StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE;
}
@Override
public String getPersistentNotificationMessage(int id) {
return "Click to close " + getAppName();
}
@Override
public String getPersistentNotificationTitle(int id) {
return getAppName() + " Running";
}
@Override
public Intent getPersistentNotificationIntent(int id) {
return StandOutWindow.getCloseIntent(this, Timer.class, id);
}
@Override
public Animation getShowAnimation(int id) {
if (isExistingId(id)) {
// restore
return AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left);
} else {
// show
return super.getShowAnimation(id);
}
}
@Override
public Animation getHideAnimation(int id) {
return AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right);
}
@Override
public List<DropDownListItem> getDropDownItems(int id) {
List<DropDownListItem> items = new ArrayList<DropDownListItem>();
items.add(new DropDownListItem(android.R.drawable.ic_menu_help,
"About", new Runnable() {
@Override
public void run() {
Toast.makeText(Timer.this,
getAppName() + " is a timer!",
Toast.LENGTH_SHORT).show();
}
}));
items.add(new DropDownListItem(android.R.drawable.ic_menu_preferences,
"Settings", new Runnable() {
@Override
public void run() {
// TODO: Add some settings here!
Toast.makeText(Timer.this, "No settings yet",
Toast.LENGTH_SHORT).show();
}
}));
return items;
}
}
|
package org.batfish.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.output.WriterOutputStream;
import org.batfish.client.Settings.RunMode;
import org.batfish.common.BatfishException;
import org.batfish.common.BfConsts;
import org.batfish.common.BatfishLogger;
import org.batfish.common.WorkItem;
import org.batfish.common.CoordConsts.WorkStatusCode;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.common.util.CommonUtil;
import org.batfish.common.util.ZipUtility;
import org.batfish.datamodel.answers.Answer;
import org.batfish.datamodel.questions.EnvironmentCreationQuestion;
import org.batfish.datamodel.questions.QuestionType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;
public class Client {
private static final String COMMAND_ANSWER = "answer";
private static final String COMMAND_ANSWER_DIFF = "answer-diff";
private static final String COMMAND_CAT = "cat";
private static final String COMMAND_CHECK_API_KEY = "checkapikey";
private static final String COMMAND_CLEAR_SCREEN = "cls";
private static final String COMMAND_DEL_CONTAINER = "del-container";
private static final String COMMAND_DEL_ENVIRONMENT = "del-environment";
private static final String COMMAND_DEL_QUESTION = "del-question";
private static final String COMMAND_DEL_TESTRIG = "del-testrig";
private static final String COMMAND_DIR = "dir";
private static final String COMMAND_ECHO = "echo";
private static final String COMMAND_EXIT = "exit";
private static final String COMMAND_GEN_DIFF_DP = "generate-diff-dataplane";
private static final String COMMAND_GEN_DP = "generate-dataplane";
private static final String COMMAND_GET = "get";
private static final String COMMAND_GET_DIFF = "get-diff";
private static final String COMMAND_HELP = "help";
private static final String COMMAND_INIT_CONTAINER = "init-container";
private static final String COMMAND_INIT_DIFF_ENV = "init-diff-environment";
private static final String COMMAND_INIT_DIFF_TESTRIG = "init-diff-testrig";
private static final String COMMAND_INIT_TESTRIG = "init-testrig";
private static final String COMMAND_LIST_CONTAINERS = "list-containers";
private static final String COMMAND_LIST_ENVIRONMENTS = "list-environments";
private static final String COMMAND_LIST_QUESTIONS = "list-questions";
private static final String COMMAND_LIST_TESTRIGS = "list-testrigs";
private static final String COMMAND_PROMPT = "prompt";
private static final String COMMAND_PWD = "pwd";
private static final String COMMAND_QUIT = "quit";
private static final String COMMAND_SET_BATFISH_LOGLEVEL = "set-batfish-loglevel";
private static final String COMMAND_SET_CONTAINER = "set-container";
private static final String COMMAND_SET_DIFF_ENV = "set-diff-environment";
private static final String COMMAND_SET_DIFF_TESTRIG = "set-diff-testrig";
private static final String COMMAND_SET_ENV = "set-environment";
private static final String COMMAND_SET_LOGLEVEL = "set-loglevel";
private static final String COMMAND_SET_PRETTY_PRINT = "set-pretty-print";
private static final String COMMAND_SET_TESTRIG = "set-testrig";
private static final String COMMAND_SHOW_API_KEY = "show-api-key";
private static final String COMMAND_SHOW_BATFISH_LOGLEVEL = "show-batfish-loglevel";
private static final String COMMAND_SHOW_CONTAINER = "show-container";
private static final String COMMAND_SHOW_COORDINATOR_HOST = "show-coordinator-host";
private static final String COMMAND_SHOW_LOGLEVEL = "show-loglevel";
private static final String COMMAND_SHOW_DIFF_TESTRIG = "show-diff-testrig";
private static final String COMMAND_SHOW_TESTRIG = "show-testrig";
private static final String COMMAND_TEST = "test";
private static final String COMMAND_UPLOAD_CUSTOM_OBJECT = "upload-custom";
private static final String DEFAULT_CONTAINER_PREFIX = "cp";
private static final String DEFAULT_DIFF_ENV_PREFIX = "env_";
private static final String DEFAULT_ENV_NAME = BfConsts.RELPATH_DEFAULT_ENVIRONMENT_NAME;
private static final String DEFAULT_QUESTION_PREFIX = "q";
private static final String DEFAULT_TESTRIG_PREFIX = "tr_";
private static final Map<String, String> MAP_COMMANDS = initCommands();
private static Map<String, String> initCommands() {
Map<String, String> descs = new TreeMap<String, String>();
descs.put(COMMAND_ANSWER, COMMAND_ANSWER
+ " <question-file> [param1=value1 [param2=value2] ...]\n"
+ "\t Answer the question in the file for the default environment");
descs.put(
COMMAND_ANSWER_DIFF,
COMMAND_ANSWER_DIFF
+ " <question-file> [param1=value1 [param2=value2] ...]\n"
+ "\t Answer the question in the file for the differential environment");
descs.put(COMMAND_CAT, COMMAND_CAT + " <filename>\n"
+ "\t Print the contents of the file");
// descs.put(COMMAND_CHANGE_DIR, COMMAND_CHANGE_DIR
// + " <dirname>\n"
// + "\t Change the working directory");
descs.put(COMMAND_CLEAR_SCREEN, COMMAND_CLEAR_SCREEN + "\n"
+ "\t Clear screen");
descs.put(COMMAND_DEL_CONTAINER, COMMAND_DEL_CONTAINER
+ "<container-name>" + "\t Delete the specified container");
descs.put(COMMAND_DEL_ENVIRONMENT, COMMAND_DEL_ENVIRONMENT
+ "<environment-name>" + "\t Delete the specified environment");
descs.put(COMMAND_DEL_QUESTION, COMMAND_DEL_QUESTION + "<question-name>"
+ "\t Delete the specified question");
descs.put(COMMAND_DEL_TESTRIG, COMMAND_DEL_TESTRIG + "<testrig-name>"
+ "\t Delete the specified testrig");
descs.put(COMMAND_DIR, COMMAND_DIR + "<dir>"
+ "\t List directory contents");
descs.put(COMMAND_ECHO, COMMAND_ECHO + "<message>"
+ "\t Echo the message");
descs.put(COMMAND_EXIT, COMMAND_EXIT + "\n"
+ "\t Terminate interactive client session");
descs.put(COMMAND_GEN_DIFF_DP, COMMAND_GEN_DIFF_DP + "\n"
+ "\t Generate dataplane for the differential environment");
descs.put(COMMAND_GEN_DP, COMMAND_GEN_DP + "\n"
+ "\t Generate dataplane for the default environment");
descs.put(COMMAND_GET, COMMAND_GET
+ " <question-type> [param1=value1 [param2=value2] ...]\n"
+ "\t Answer the question by type for the differential environment");
descs.put(COMMAND_GET_DIFF, COMMAND_GET_DIFF
+ " <question-file> [param1=value1 [param2=value2] ...]\n"
+ "\t Answer the question by type for the differential environment");
descs.put(COMMAND_HELP, COMMAND_HELP + "\n"
+ "\t Print the list of supported commands");
descs.put(COMMAND_CHECK_API_KEY, COMMAND_CHECK_API_KEY
+ "\t Check if API Key is valid");
descs.put(COMMAND_INIT_CONTAINER, COMMAND_INIT_CONTAINER
+ " [<container-name-prefix>]\n" + "\t Initialize a new container");
descs.put(
COMMAND_INIT_DIFF_ENV,
COMMAND_INIT_DIFF_ENV
+ " [-nodataplane] <environment zipfile or directory> [<environment-name>]\n"
+ "\t Initialize the differential environment");
descs.put(
COMMAND_INIT_DIFF_TESTRIG,
COMMAND_INIT_DIFF_TESTRIG
+ " [-nodataplane] <testrig zipfile or directory> [<environment name>]\n"
+ "\t Initialize the diff testrig with default environment");
descs.put(
COMMAND_INIT_TESTRIG,
COMMAND_INIT_TESTRIG
+ " [-nodataplane] <testrig zipfile or directory> [<environment name>]\n"
+ "\t Initialize the testrig with default environment");
descs.put(COMMAND_LIST_CONTAINERS, COMMAND_LIST_CONTAINERS + "\n"
+ "\t List the containers to which you have access");
descs.put(COMMAND_LIST_ENVIRONMENTS, COMMAND_LIST_ENVIRONMENTS + "\n"
+ "\t List the environments under current container and testrig");
descs.put(COMMAND_LIST_QUESTIONS, COMMAND_LIST_QUESTIONS + "\n"
+ "\t List the questions under current container and testrig");
descs.put(COMMAND_LIST_TESTRIGS, COMMAND_LIST_TESTRIGS + "\n"
+ "\t List the testrigs within the current container");
descs.put(COMMAND_PROMPT, COMMAND_PROMPT + "\n"
+ "\t Prompts for user to press enter");
descs.put(COMMAND_PWD, COMMAND_PWD + "\n"
+ "\t Prints the working directory");
descs.put(COMMAND_QUIT, COMMAND_QUIT + "\n"
+ "\t Terminate interactive client session");
descs.put(COMMAND_SET_BATFISH_LOGLEVEL, COMMAND_SET_BATFISH_LOGLEVEL
+ " <debug|info|output|warn|error>\n"
+ "\t Set the batfish loglevel. Default is warn");
descs.put(COMMAND_SET_CONTAINER, COMMAND_SET_CONTAINER
+ " <container-name>\n" + "\t Set the current container");
descs.put(COMMAND_SET_DIFF_ENV, COMMAND_SET_DIFF_ENV
+ " <environment-name>\n" + "\t Set the differential environment");
descs.put(COMMAND_SET_DIFF_TESTRIG, COMMAND_SET_DIFF_TESTRIG
+ " <testrig-name> [environment name]\n"
+ "\t Set the differential testrig");
descs.put(COMMAND_SET_ENV, COMMAND_SET_ENV + " <environment-name>\n"
+ "\t Set the current base environment");
descs.put(COMMAND_SET_LOGLEVEL, COMMAND_SET_LOGLEVEL
+ " <debug|info|output|warn|error>\n"
+ "\t Set the client loglevel. Default is output");
descs.put(COMMAND_SET_PRETTY_PRINT, COMMAND_SET_PRETTY_PRINT
+ " <true|false>\n"
+ "\t Whether to pretty print answers");
descs.put(COMMAND_SET_TESTRIG, COMMAND_SET_TESTRIG
+ " <testrig-name> [environment name]\n"
+ "\t Set the base testrig");
descs.put(COMMAND_SHOW_API_KEY, COMMAND_SHOW_API_KEY + "\n"
+ "\t Show API Key");
descs.put(COMMAND_SHOW_BATFISH_LOGLEVEL, COMMAND_SHOW_BATFISH_LOGLEVEL
+ "\n" + "\t Show current batfish loglevel");
descs.put(COMMAND_SHOW_CONTAINER, COMMAND_SHOW_CONTAINER + "\n"
+ "\t Show active container");
descs.put(COMMAND_SHOW_COORDINATOR_HOST, COMMAND_SHOW_COORDINATOR_HOST
+ "\n" + "\t Show coordinator host");
descs.put(COMMAND_SHOW_LOGLEVEL, COMMAND_SHOW_LOGLEVEL + "\n"
+ "\t Show current client loglevel");
descs.put(COMMAND_SHOW_DIFF_TESTRIG, COMMAND_SHOW_DIFF_TESTRIG + "\n"
+ "\t Show differential testrig and environment");
descs.put(COMMAND_SHOW_TESTRIG, COMMAND_SHOW_TESTRIG + "\n"
+ "\t Show base testrig and environment");
descs.put(COMMAND_TEST, COMMAND_TEST
+ " <reference file> <command> \n"
+ "\t Show base testrig and environment");
descs.put(COMMAND_UPLOAD_CUSTOM_OBJECT, COMMAND_UPLOAD_CUSTOM_OBJECT
+ " <object-name> <object-file>\n" + "\t Uploads a custom object");
return descs;
}
private String _currContainerName = null;
private String _currDiffEnv = null;
private String _currDiffTestrig;
private String _currEnv = null;
private String _currTestrig = null;
private BatfishLogger _logger;
private BfCoordPoolHelper _poolHelper;
private ConsoleReader _reader;
private Settings _settings;
private BfCoordWorkHelper _workHelper;
public Client(Settings settings) {
_settings = settings;
switch (_settings.getRunMode()) {
case batch:
if (_settings.getBatchCommandFile() == null) {
System.err
.println("org.batfish.client: Command file not specified while running in batch mode.");
System.err
.printf(
"Use '-%s <cmdfile>' if you want batch mode, or '-%s interactive' if you want interactive mode\n",
Settings.ARG_COMMAND_FILE, Settings.ARG_RUN_MODE);
System.exit(1);
}
_logger = new BatfishLogger(_settings.getLogLevel(), false,
_settings.getLogFile(), false, false);
break;
case genquestions:
if (_settings.getQuestionsDir() == null) {
System.err
.println("org.batfish.client: Out dir not specified while running in genquestions mode.");
System.err
.printf(
"Use '-%s <cmdfile>'\n",
Settings.ARG_QUESTIONS_DIR);
System.exit(1);
}
_logger = new BatfishLogger(_settings.getLogLevel(), false,
_settings.getLogFile(), false, false);
break;
case interactive:
try {
_reader = new ConsoleReader();
_reader.setPrompt("batfish> ");
_reader.setExpandEvents(false);
List<Completer> completors = new LinkedList<Completer>();
completors.add(new StringsCompleter(MAP_COMMANDS.keySet()));
for (Completer c : completors) {
_reader.addCompleter(c);
}
PrintWriter pWriter = new PrintWriter(_reader.getOutput(), true);
OutputStream os = new WriterOutputStream(pWriter);
PrintStream ps = new PrintStream(os, true);
_logger = new BatfishLogger(_settings.getLogLevel(), false, ps);
}
catch (Exception e) {
System.err.printf("Could not initialize client: %s\n",
e.getMessage());
System.exit(1);
}
break;
default:
System.err.println("org.batfish.client: Unknown run mode.");
System.exit(1);
}
}
public Client(String[] args) throws Exception {
this(new Settings(args));
}
private boolean answerFile(String questionFile, String paramsLine,
boolean isDiff, FileWriter outWriter) throws Exception {
if (!new File(questionFile).exists()) {
throw new FileNotFoundException("Question file not found: "
+ questionFile);
}
String questionName = DEFAULT_QUESTION_PREFIX + "_"
+ UUID.randomUUID().toString();
File paramsFile = createTempFile("parameters", paramsLine);
paramsFile.deleteOnExit();
// upload the question
boolean resultUpload = _workHelper.uploadQuestion(_currContainerName,
_currTestrig, questionName, questionFile,
paramsFile.getAbsolutePath());
if (!resultUpload) {
return false;
}
_logger.debug("Uploaded question. Answering now.\n");
// delete the temporary params file
if (paramsFile != null) {
paramsFile.delete();
}
// answer the question
WorkItem wItemAs = (isDiff) ? _workHelper.getWorkItemAnswerDiffQuestion(
questionName, _currContainerName, _currTestrig, _currEnv,
_currDiffTestrig, _currDiffEnv) : _workHelper
.getWorkItemAnswerQuestion(questionName, _currContainerName,
_currTestrig, _currEnv, _currDiffTestrig, _currDiffEnv);
return execute(wItemAs, outWriter);
}
private boolean answerType(String questionType, String paramsLine,
boolean isDiff, FileWriter outWriter) throws Exception {
Map<String, String> parameters = parseParams(paramsLine);
String questionString;
String parametersString = "";
if (questionType.startsWith("
try {
questionString = QuestionHelper.resolveMacro(questionType, paramsLine);
}
catch (BatfishException e) {
_logger.errorf("Could not resolve macro: %s\n", e.getMessage());
return false;
}
}
else {
questionString = QuestionHelper.getQuestionString(questionType,
isDiff);
_logger.debugf("Question Json:\n%s\n", questionString);
parametersString = QuestionHelper.getParametersString(parameters);
_logger.debugf("Parameters Json:\n%s\n", parametersString);
}
File questionFile = createTempFile("question", questionString);
boolean result = answerFile(questionFile.getAbsolutePath(),
parametersString, isDiff, outWriter);
if (questionFile != null) {
questionFile.delete();
}
return result;
}
private File createTempFile(String filePrefix, String content)
throws IOException {
File tempFile = Files.createTempFile(filePrefix, null).toFile();
tempFile.deleteOnExit();
_logger.debugf("Creating temporary %s file: %s\n", filePrefix,
tempFile.getAbsolutePath());
FileWriter writer = new FileWriter(tempFile);
writer.write(content + "\n");
writer.close();
return tempFile;
}
private boolean execute(WorkItem wItem, FileWriter outWriter) throws Exception {
wItem.addRequestParam(BfConsts.ARG_LOG_LEVEL,
_settings.getBatfishLogLevel());
_logger.info("work-id is " + wItem.getId() + "\n");
boolean queueWorkResult = _workHelper.queueWork(wItem);
_logger.info("Queuing result: " + queueWorkResult + "\n");
if (!queueWorkResult) {
return queueWorkResult;
}
WorkStatusCode status = _workHelper.getWorkStatus(wItem.getId());
while (status != WorkStatusCode.TERMINATEDABNORMALLY
&& status != WorkStatusCode.TERMINATEDNORMALLY
&& status != WorkStatusCode.ASSIGNMENTERROR) {
_logger.output(". ");
_logger.infof("status: %s\n", status);
Thread.sleep(1 * 1000);
status = _workHelper.getWorkStatus(wItem.getId());
}
_logger.output("\n");
_logger.infof("final status: %s\n", status);
// get the answer
String ansFileName = wItem.getId() + BfConsts.SUFFIX_ANSWER_JSON_FILE;
String downloadedAnsFile = _workHelper.getObject(
wItem.getContainerName(), wItem.getTestrigName(), ansFileName);
if (downloadedAnsFile == null) {
_logger
.errorf(
"Failed to get answer file %s. Fix batfish and remove the statement below this line\n",
ansFileName);
// return false;
}
else {
String answerString = CommonUtil
.readFile(Paths.get(downloadedAnsFile));
//check if we need to pretty things
String answerStringToPrint = answerString;
if (_settings.getPrettyPrintAnswers()) {
ObjectMapper mapper = new BatfishObjectMapper();
Answer answer = mapper.readValue(answerString, Answer.class);
answerStringToPrint = answer.prettyPrint();
}
if (outWriter == null) {
_logger.output(answerStringToPrint + "\n");
}
else {
outWriter.write(answerStringToPrint);
}
//tests serialization/deserialization when running in debug mode
if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) {
try {
ObjectMapper mapper = new BatfishObjectMapper();
Answer answer = mapper.readValue(answerString, Answer.class);
String newAnswerString = mapper.writeValueAsString(answer);
JsonNode tree = mapper.readTree(answerString);
JsonNode newTree = mapper.readTree(newAnswerString);
if (!CommonUtil.checkJsonEqual(tree, newTree)) {
// if (!tree.equals(newTree)) {
_logger
.errorf(
"Original and recovered Json are different. Recovered = %s\n",
newAnswerString);
}
}
catch (Exception e) {
_logger.outputf("Could NOT deserialize Json to Answer: %s\n",
e.getMessage());
}
}
}
// get and print the log when in debugging mode
if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) {
_logger.output("
String logFileName = wItem.getId() + BfConsts.SUFFIX_LOG_FILE;
String downloadedFile = _workHelper.getObject(wItem.getContainerName(),
wItem.getTestrigName(), logFileName);
if (downloadedFile == null) {
_logger.errorf("Failed to get log file %s\n", logFileName);
return false;
}
else {
try (BufferedReader br = new BufferedReader(new FileReader(
downloadedFile))) {
String line = null;
while ((line = br.readLine()) != null) {
_logger.output(line + "\n");
}
}
}
}
// TODO: remove the log file?
if (status == WorkStatusCode.TERMINATEDNORMALLY) {
return true;
}
else {
// _logger.errorf("WorkItem failed: %s", wItem);
return false;
}
}
private boolean generateDataplane(FileWriter outWriter) throws Exception {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
// generate the data plane
WorkItem wItemGenDp = _workHelper.getWorkItemGenerateDataPlane(
_currContainerName, _currTestrig, _currEnv);
return execute(wItemGenDp, outWriter);
}
private boolean generateDiffDataplane(FileWriter outWriter) throws Exception {
if (!isSetDiffEnvironment() || !isSetTestrig() || !isSetContainer(true)) {
return false;
}
WorkItem wItemGenDdp = _workHelper.getWorkItemGenerateDiffDataPlane(
_currContainerName, _currTestrig, _currEnv, _currDiffEnv);
return execute(wItemGenDdp, outWriter);
}
private void generateQuestions() {
File questionsDir = Paths.get(_settings.getQuestionsDir()).toFile();
if (!questionsDir.exists()) {
if (!questionsDir.mkdirs()) {
_logger.errorf("Could not create questions dir %s\n",
_settings.getQuestionsDir());
System.exit(1);
}
}
for (QuestionType qType : QuestionType.values()) {
try {
String questionString = QuestionHelper.getQuestionString(qType);
String qFile = Paths
.get(_settings.getQuestionsDir(),
qType.questionTypeName() + ".json").toFile()
.getAbsolutePath();
PrintWriter writer = new PrintWriter(qFile);
writer.write(questionString);
writer.close();
}
catch (Exception e) {
_logger.errorf("Could not write question %s: %s\n",
qType.questionTypeName(), e.getMessage());
}
}
}
private List<String> getCommandOptions(String[] words) {
List<String> options = new LinkedList<String>();
int currIndex = 1;
while (currIndex < words.length && words[currIndex].startsWith("-")) {
options.add(words[currIndex]);
currIndex++;
}
return options;
}
private List<String> getCommandParameters(String[] words, int numOptions) {
List<String> parameters = new LinkedList<String>();
for (int index = numOptions + 1; index < words.length; index++) {
parameters.add(words[index]);
}
return parameters;
}
public BatfishLogger getLogger() {
return _logger;
}
private void initHelpers() {
String workMgr = _settings.getCoordinatorHost() + ":"
+ _settings.getCoordinatorWorkPort();
String poolMgr = _settings.getCoordinatorHost() + ":"
+ _settings.getCoordinatorPoolPort();
_workHelper = new BfCoordWorkHelper(workMgr, _logger, _settings);
_poolHelper = new BfCoordPoolHelper(poolMgr);
int numTries = 0;
while (true) {
try {
numTries++;
if (_workHelper.isReachable()) {
// print this message only we might have printed unable to
// connect message earlier
if (numTries > 1) {
_logger.outputf("Connected to coordinator after %d tries\n",
numTries);
}
break;
}
Thread.sleep(1 * 1000); // 1 second
}
catch (Exception e) {
_logger.errorf(
"Exeption while checking reachability to coordinator: ",
e.getMessage());
System.exit(1);
}
}
}
private boolean isSetContainer(boolean printError) {
if (!_settings.getSanityCheck()) {
return true;
}
if (_currContainerName == null) {
if (printError) {
_logger.errorf("Active container is not set\n");
}
return false;
}
return true;
}
private boolean isSetDiffEnvironment() {
if (!_settings.getSanityCheck()) {
return true;
}
if (_currDiffTestrig == null) {
_logger.errorf("Active diff testrig is not set\n");
return false;
}
if (_currDiffEnv == null) {
_logger.errorf("Active diff environment is not set\n");
return false;
}
return true;
}
private boolean isSetTestrig() {
if (!_settings.getSanityCheck()) {
return true;
}
if (_currTestrig == null) {
_logger.errorf("Active testrig is not set.\n");
_logger
.errorf(
"Specify testrig on command line (-%s <testrigdir>) or use command (%s [-nodataplane] <testrigdir>)\n",
Settings.ARG_TESTRIG_DIR, COMMAND_INIT_TESTRIG);
return false;
}
return true;
}
private Map<String, String> parseParams(String paramsLine) {
Map<String, String> parameters = new HashMap<String, String>();
Pattern pattern = Pattern.compile("([\\w_]+)\\s*=\\s*(.+)");
String[] params = paramsLine.split("\\|");
_logger.debugf("Found %d parameters\n", params.length);
for (String param : params) {
Matcher matcher = pattern.matcher(param);
while (matcher.find()) {
String key = matcher.group(1).trim();
String value = matcher.group(2).trim();
_logger.debugf("key=%s value=%s\n", key, value);
parameters.put(key, value);
}
}
return parameters;
}
private void printUsage() {
for (Map.Entry<String, String> entry : MAP_COMMANDS.entrySet()) {
_logger.output(entry.getValue() + "\n\n");
}
}
private boolean processCommand(String command) {
String line = command.trim();
if (line.length() == 0 || line.startsWith("
return true;
}
_logger.debug("Doing command: " + line + "\n");
String[] words = line.split("\\s+");
if (!validCommandUsage(words)) {
return false;
}
return processCommand(words, null);
}
private boolean processCommand(String[] words, FileWriter outWriter) {
try {
List<String> options = getCommandOptions(words);
List<String> parameters = getCommandParameters(words, options.size());
String command = words[0];
switch (command) {
// this is a hidden command for testing
case "add-worker": {
boolean result = _poolHelper.addBatfishWorker(words[1]);
_logger.output("Result: " + result + "\n");
return true;
}
case COMMAND_ANSWER: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String questionFile = parameters.get(0);
String paramsLine = CommonUtil.joinStrings(" ",
Arrays.copyOfRange(words, 2 + options.size(), words.length));
return answerFile(questionFile, paramsLine, false, outWriter);
}
case COMMAND_ANSWER_DIFF: {
if (!isSetDiffEnvironment() || !isSetTestrig()
|| !isSetContainer(true)) {
return false;
}
String questionFile = parameters.get(0);
String paramsLine = CommonUtil.joinStrings(" ",
Arrays.copyOfRange(words, 2 + options.size(), words.length));
return answerFile(questionFile, paramsLine, true, outWriter);
}
case COMMAND_CAT: {
String filename = words[1];
try (BufferedReader br = new BufferedReader(
new FileReader(filename))) {
String line = null;
while ((line = br.readLine()) != null) {
_logger.output(line + "\n");
}
}
return true;
}
case COMMAND_DEL_CONTAINER: {
String containerName = parameters.get(0);
boolean result = _workHelper.delContainer(containerName);
_logger.outputf("Result of deleting container: %s\n", result);
return true;
}
case COMMAND_DEL_ENVIRONMENT: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String envName = parameters.get(0);
boolean result = _workHelper.delEnvironment(_currContainerName,
_currTestrig, envName);
_logger.outputf("Result of deleting environment: %s\n", result);
return true;
}
case COMMAND_DEL_QUESTION: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String qName = parameters.get(0);
boolean result = _workHelper.delQuestion(_currContainerName,
_currTestrig, qName);
_logger.outputf("Result of deleting question: %s\n", result);
return true;
}
case COMMAND_DEL_TESTRIG: {
if (!isSetContainer(true)) {
return false;
}
String testrigName = parameters.get(0);
boolean result = _workHelper.delTestrig(_currContainerName,
testrigName);
_logger.outputf("Result of deleting testrig: %s\n", result);
return true;
}
case COMMAND_DIR: {
String dirname = (parameters.size() == 1) ? parameters.get(0) : ".";
File currDirectory = new File(dirname);
for (File file : currDirectory.listFiles()) {
_logger.output(file.getName() + "\n");
}
return true;
}
case COMMAND_ECHO: {
_logger.outputf(
"%s\n",
CommonUtil.joinStrings(" ",
Arrays.copyOfRange(words, 1, words.length)));
return true;
}
case COMMAND_EXIT:
case COMMAND_QUIT: {
System.exit(0);
return true;
}
case COMMAND_GEN_DP: {
return generateDataplane(outWriter);
}
case COMMAND_GEN_DIFF_DP: {
return generateDiffDataplane(outWriter);
}
case COMMAND_GET:
case COMMAND_GET_DIFF: {
boolean isDiff = (command == COMMAND_GET_DIFF);
if (!isSetTestrig() || !isSetContainer(true) ||
(isDiff && !isSetDiffEnvironment())) {
return false;
}
String questionType = parameters.get(0);
String paramsLine = CommonUtil.joinStrings(" ",
Arrays.copyOfRange(words, 2 + options.size(), words.length));
if (QuestionType.fromName(questionType) == QuestionType.ENVIRONMENT_CREATION) {
String diffEnvName = DEFAULT_DIFF_ENV_PREFIX +
UUID.randomUUID().toString();
String prefixString = (paramsLine.trim().length() > 0)? " | " : "";
paramsLine += String.format("%s %s=%s", prefixString,
EnvironmentCreationQuestion.ENVIRONMENT_NAME_VAR,
diffEnvName);
System.err.println("paramsline = " + paramsLine);
if (!answerType(questionType, paramsLine, isDiff, outWriter)) {
return false;
}
_currDiffEnv = diffEnvName;
_currDiffTestrig = _currTestrig;
_logger.outputf("Active diff testrig->environment is now %s->%s\n",
_currDiffTestrig, _currDiffEnv);
return true;
}
else {
return answerType(questionType, paramsLine, isDiff, outWriter);
}
}
case COMMAND_HELP: {
printUsage();
return true;
}
case COMMAND_CHECK_API_KEY: {
String isValid = _workHelper.checkApiKey();
_logger.outputf("Api key validitiy: %s\n", isValid);
return true;
}
case COMMAND_INIT_CONTAINER: {
String containerPrefix = (words.length > 1) ? words[1]
: DEFAULT_CONTAINER_PREFIX;
_currContainerName = _workHelper.initContainer(containerPrefix);
_logger.outputf("Active container set to %s\n", _currContainerName);
return true;
}
case COMMAND_INIT_DIFF_ENV: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
// check if we are being asked to not generate the dataplane
boolean generateDiffDataplane = true;
if (options.size() == 1) {
if (options.get(0).equals("-nodataplane")) {
generateDiffDataplane = false;
}
else {
_logger.outputf("Unknown option %s\n", options.get(0));
return false;
}
}
String diffEnvLocation = parameters.get(0);
String diffEnvName = (parameters.size() > 1) ? parameters.get(1)
: DEFAULT_DIFF_ENV_PREFIX + UUID.randomUUID().toString();
if (!uploadTestrigOrEnv(diffEnvLocation, diffEnvName, false)) {
return false;
}
_currDiffEnv = diffEnvName;
_currDiffTestrig = _currTestrig;
_logger.outputf("Active diff testrig->environment is now %s->%s\n",
_currDiffTestrig, _currDiffEnv);
WorkItem wItemGenDdp = _workHelper
.getWorkItemCompileDiffEnvironment(_currContainerName,
_currDiffTestrig, _currEnv, _currDiffEnv);
if (!execute(wItemGenDdp, outWriter)) {
return false;
}
if (generateDiffDataplane) {
_logger.output("Generating delta dataplane\n");
if (!generateDiffDataplane(outWriter)) {
return false;
}
_logger.output("Generated delta dataplane\n");
}
return true;
}
case COMMAND_INIT_DIFF_TESTRIG:
case COMMAND_INIT_TESTRIG: {
boolean generateDataplane = true;
if (options.size() == 1) {
if (options.get(0).equals("-nodataplane")) {
generateDataplane = false;
}
else {
_logger.outputf("Unknown option %s\n", options.get(0));
return false;
}
}
String testrigLocation = parameters.get(0);
String testrigName = (parameters.size() > 1) ? parameters.get(1)
: DEFAULT_TESTRIG_PREFIX + UUID.randomUUID().toString();
// initialize the container if it hasn't been init'd before
if (!isSetContainer(false)) {
_currContainerName = _workHelper
.initContainer(DEFAULT_CONTAINER_PREFIX);
_logger.outputf("Init'ed and set active container to %s\n",
_currContainerName);
}
if (!uploadTestrigOrEnv(testrigLocation, testrigName, true)) {
return false;
}
_logger.output("Uploaded testrig. Parsing now.\n");
WorkItem wItemParse = _workHelper.getWorkItemParse(
_currContainerName, testrigName);
if (!execute(wItemParse, outWriter)) {
return false;
}
if (command.equals(COMMAND_INIT_TESTRIG)) {
_currTestrig = testrigName;
_currEnv = DEFAULT_ENV_NAME;
_logger.outputf("Base testrig is now %s\n", _currTestrig);
}
else {
_currDiffTestrig = testrigName;
_currDiffEnv = DEFAULT_ENV_NAME;
_logger.outputf("Diff testrig is now %s\n", _currTestrig);
}
if (generateDataplane) {
_logger.output("Generating dataplane now\n");
if (!generateDataplane(outWriter)) {
return false;
}
_logger.output("Generated dataplane\n");
}
return true;
}
case COMMAND_LIST_CONTAINERS: {
String[] containerList = _workHelper.listContainers();
_logger.outputf("Containers: %s\n", Arrays.toString(containerList));
return true;
}
case COMMAND_LIST_ENVIRONMENTS: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String[] environmentList = _workHelper.listEnvironments(
_currContainerName, _currTestrig);
_logger.outputf("Environments: %s\n",
Arrays.toString(environmentList));
return true;
}
case COMMAND_LIST_QUESTIONS: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String[] questionList = _workHelper.listQuestions(
_currContainerName, _currTestrig);
_logger.outputf("Questions: %s\n", Arrays.toString(questionList));
return true;
}
case COMMAND_LIST_TESTRIGS: {
Map<String, String> testrigs = _workHelper
.listTestrigs(_currContainerName);
if (testrigs != null) {
for (String testrigName : testrigs.keySet()) {
_logger.outputf("Testrig: %s\n%s\n", testrigName,
testrigs.get(testrigName));
}
}
return true;
}
case COMMAND_PROMPT: {
if (_settings.getRunMode() == RunMode.interactive) {
_logger.output("\n\n[Press enter to proceed]\n\n");
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
in.readLine();
}
return true;
}
case COMMAND_PWD: {
final String dir = System.getProperty("user.dir");
_logger.output("working directory = " + dir + "\n");
return true;
}
case COMMAND_SET_BATFISH_LOGLEVEL: {
String logLevelStr = parameters.get(0).toLowerCase();
if (!BatfishLogger.isValidLogLevel(logLevelStr)) {
_logger.errorf("Undefined loglevel value: %s\n", logLevelStr);
return false;
}
_settings.setBatfishLogLevel(logLevelStr);
_logger.output("Changed batfish loglevel to " + logLevelStr + "\n");
return true;
}
case COMMAND_SET_CONTAINER: {
_currContainerName = parameters.get(0);
_logger.outputf("Active container is now set to %s\n",
_currContainerName);
return true;
}
case COMMAND_SET_DIFF_ENV: {
_currDiffEnv = parameters.get(0);
if (_currDiffTestrig == null) {
_currDiffTestrig = _currTestrig;
}
_logger.outputf("Active diff testrig->environment is now %s->%s\n",
_currDiffTestrig, _currDiffEnv);
return true;
}
case COMMAND_SET_ENV: {
if (!isSetTestrig()) {
return false;
}
_currEnv = parameters.get(0);
_logger.outputf("Base testrig->env is now %s->%s\n", _currTestrig,
_currEnv);
return true;
}
case COMMAND_SET_DIFF_TESTRIG: {
_currDiffTestrig = parameters.get(0);
_currDiffEnv = (parameters.size() > 1) ? parameters.get(1)
: DEFAULT_ENV_NAME;
_logger.outputf("Diff testrig->env is now %s->%s\n",
_currDiffTestrig, _currDiffEnv);
return true;
}
case COMMAND_SET_LOGLEVEL: {
String logLevelStr = parameters.get(0).toLowerCase();
if (!BatfishLogger.isValidLogLevel(logLevelStr)) {
_logger.errorf("Undefined loglevel value: %s\n", logLevelStr);
return false;
}
_logger.setLogLevel(logLevelStr);
_settings.setLogLevel(logLevelStr);
_logger.output("Changed client loglevel to " + logLevelStr + "\n");
return true;
}
case COMMAND_SET_PRETTY_PRINT: {
String ppStr = parameters.get(0).toLowerCase();
boolean prettyPrint = Boolean.parseBoolean(ppStr);
_settings.setPrettyPrintAnswers(prettyPrint);
_logger.output("Set pretty printing answers to " + ppStr + "\n");
return true;
}
case COMMAND_SET_TESTRIG: {
if (!isSetContainer(true)) {
return false;
}
_currTestrig = parameters.get(0);
_currEnv = (parameters.size() > 1) ? parameters.get(1)
: DEFAULT_ENV_NAME;
_logger.outputf("Base testrig->env is now %s->%s\n", _currTestrig,
_currEnv);
return true;
}
case COMMAND_SHOW_API_KEY: {
_logger.outputf("Current API Key is %s\n", _settings.getApiKey());
return true;
}
case COMMAND_SHOW_BATFISH_LOGLEVEL: {
_logger.outputf("Current batfish log level is %s\n",
_settings.getBatfishLogLevel());
return true;
}
case COMMAND_SHOW_CONTAINER: {
_logger.outputf("Current container is %s\n", _currContainerName);
return true;
}
case COMMAND_SHOW_COORDINATOR_HOST: {
_logger.outputf("Current coordinator host is %s\n",
_settings.getCoordinatorHost());
return true;
}
case COMMAND_SHOW_LOGLEVEL: {
_logger.outputf("Current client log level is %s\n",
_logger.getLogLevelStr());
return true;
}
case COMMAND_SHOW_DIFF_TESTRIG: {
if (!isSetDiffEnvironment()) {
return false;
}
_logger.outputf("Diff testrig->environment is %s->%s\n",
_currDiffTestrig, _currDiffEnv);
return true;
}
case COMMAND_SHOW_TESTRIG: {
if (!isSetTestrig()) {
return false;
}
_logger.outputf("Base testrig->environment is %s->%s\n",
_currTestrig, _currEnv);
return true;
}
case COMMAND_TEST: {
String referenceFileName = parameters.get(0);
String[] testCommand = parameters.subList(1, parameters.size())
.toArray(new String[0]);
_logger.debugf("Ref file is %s. \n", referenceFileName, parameters.size());
_logger.debugf("Test command is %s\n", Arrays.toString(testCommand));
File referenceFile = new File(referenceFileName);
if (!referenceFile.exists()) {
_logger.errorf("Reference file does not exist: %s\n", referenceFileName);
return false;
}
File testoutFile = Files.createTempFile("test", "out").toFile();
testoutFile.deleteOnExit();
FileWriter testoutWriter = new FileWriter(testoutFile);
processCommand(testCommand, testoutWriter);
testoutWriter.close();
boolean testPassed = false;
try {
String referenceOutput = CommonUtil.readFile(Paths.get(referenceFileName));
String testOutput = CommonUtil.readFile(Paths.get(testoutFile.getAbsolutePath()));
ObjectMapper mapper = new BatfishObjectMapper();
JsonNode referenceJson = mapper.readTree(referenceOutput);
JsonNode testJson = mapper.readTree(testOutput);
if (CommonUtil.checkJsonEqual(referenceJson, testJson)) {
testPassed = true;
}
}
catch (Exception e) {
_logger.errorf("Exception in comparing test results: ", e.getMessage());
}
if (testPassed) {
_logger.outputf("Test result for %s: Pass\n", referenceFileName);
}
else {
String outFileName = referenceFile + ".testout";
Files.move(Paths.get(testoutFile.getAbsolutePath()),
Paths.get(referenceFile + ".testout"),
StandardCopyOption.REPLACE_EXISTING);
_logger.outputf("Test result for %s: Fail\n", referenceFileName);
_logger.outputf("Copied output to %s\n", outFileName);
}
return true;
}
case COMMAND_UPLOAD_CUSTOM_OBJECT: {
if (!isSetTestrig() || !isSetContainer(true)) {
return false;
}
String objectName = parameters.get(0);
String objectFile = parameters.get(1);
// upload the object
return _workHelper.uploadCustomObject(_currContainerName,
_currTestrig, objectName, objectFile);
}
default:
_logger.error("Unsupported command " + words[0] + "\n");
_logger.error("Type 'help' to see the list of valid commands\n");
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
private boolean processCommands(List<String> commands) {
for (String command : commands) {
if (!processCommand(command)) {
return false;
}
}
return true;
}
public void run(List<String> initialCommands) {
initHelpers();
_logger.debugf("Will use coordinator at %s:
(_settings.getUseSsl()) ? "https" : "http",
_settings.getCoordinatorHost());
if (!processCommands(initialCommands)) {
return;
}
// set container if specified
if (_settings.getContainerId() != null) {
if (!processCommand(COMMAND_SET_CONTAINER + " "
+ _settings.getContainerId())) {
return;
}
}
// set testrig if dir or id is specified
if (_settings.getTestrigDir() != null) {
if (_settings.getTestrigId() != null) {
System.err
.println("org.batfish.client: Cannot supply both testrigDir and testrigId.");
System.exit(1);
}
if (!processCommand(COMMAND_INIT_TESTRIG + " -nodataplane "
+ _settings.getTestrigDir())) {
return;
}
}
if (_settings.getTestrigId() != null) {
if (!processCommand(COMMAND_SET_TESTRIG + " "
+ _settings.getTestrigId())) {
return;
}
}
switch (_settings.getRunMode()) {
case batch:
List<String> commands = null;
try {
commands = Files.readAllLines(
Paths.get(_settings.getBatchCommandFile()),
StandardCharsets.US_ASCII);
}
catch (Exception e) {
System.err.printf("Exception in reading command file %s: %s",
_settings.getBatchCommandFile(), e.getMessage());
System.exit(1);
}
processCommands(commands);
break;
case genquestions:
generateQuestions();
break;
case interactive:
runInteractive();
break;
default:
System.err.println("org.batfish.client: Unknown run mode.");
System.exit(1);
}
}
private void runInteractive() {
try {
String rawLine;
while ((rawLine = _reader.readLine()) != null) {
String line = rawLine.trim();
if (line.length() == 0) {
continue;
}
if (line.equals(COMMAND_CLEAR_SCREEN)) {
_reader.clearScreen();
continue;
}
String[] words = line.split("\\s+");
if (words.length > 0) {
if (validCommandUsage(words)) {
processCommand(words, null);
}
}
}
}
catch (Throwable t) {
t.printStackTrace();
}
}
private boolean uploadTestrigOrEnv(String fileOrDir,
String testrigOrEnvName, boolean isTestrig) throws Exception {
File filePointer = new File(fileOrDir);
String uploadFilename = fileOrDir;
if (filePointer.isDirectory()) {
File uploadFile = File.createTempFile("testrigOrEnv", "zip");
uploadFile.deleteOnExit();
uploadFilename = uploadFile.getAbsolutePath();
ZipUtility.zipFiles(filePointer.getAbsolutePath(), uploadFilename);
}
boolean result = (isTestrig) ? _workHelper.uploadTestrig(
_currContainerName, testrigOrEnvName, uploadFilename) : _workHelper
.uploadEnvironment(_currContainerName, _currTestrig,
testrigOrEnvName, uploadFilename);
// unequal means we must have created a temporary file
if (uploadFilename != fileOrDir) {
new File(uploadFilename).delete();
}
return result;
}
private boolean validCommandUsage(String[] words) {
return true;
}
}
|
package ibis.ipl.server;
import ibis.ipl.registry.ControlPolicy;
import ibis.ipl.registry.central.server.CentralRegistryService;
import ibis.ipl.registry.gossip.BootstrapService;
import ibis.ipl.support.management.ManagementService;
import ibis.smartsockets.SmartSocketsProperties;
import ibis.smartsockets.direct.DirectSocketAddress;
import ibis.smartsockets.hub.Hub;
import ibis.smartsockets.hub.servicelink.ServiceLink;
import ibis.smartsockets.virtual.VirtualSocketFactory;
import ibis.util.ClassLister;
import ibis.util.TypedProperties;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main Ibis Server class.
*
* @ibis.experimental
*/
public final class Server implements ServerInterface {
public static final String ADDRESS_LINE_PREFIX = "IBIS SERVER RUNNING ON: ";
public static final String ADDRESS_LINE_POSTFIX = "EOA";
private static final Logger logger = LoggerFactory.getLogger(Server.class);
private final VirtualSocketFactory virtualSocketFactory;
private final Hub hub;
private final ServerConnectionHandler connectionHandler;
private final DirectSocketAddress address;
private final CentralRegistryService registryService;
private final BootstrapService bootstrapService;
private final ManagementService managementService;
// services specified by user (either in jars or loaded over the network)
private final Map<String, Service> services;
private final boolean hubOnly;
private final boolean remote;
public Server(Properties properties) throws Exception {
this(properties, null);
}
/**
* Create a server with the given server properties.
*/
@SuppressWarnings("unchecked")
public Server(Properties properties, ControlPolicy policy) throws Exception {
services = new HashMap<String, Service>();
// get default properties.
TypedProperties typedProperties = ServerProperties
.getHardcodedProperties();
// add specified properties
typedProperties.addProperties(properties);
if (logger.isDebugEnabled()) {
TypedProperties serverProperties = typedProperties
.filter("ibis.server");
logger.debug("Settings for server:\n" + serverProperties);
}
// create the virtual socket factory
ibis.smartsockets.util.TypedProperties smartProperties = new ibis.smartsockets.util.TypedProperties();
smartProperties.putAll(SmartSocketsProperties.getDefaultProperties());
String hubs = typedProperties
.getProperty(ServerProperties.HUB_ADDRESSES);
if (hubs != null) {
smartProperties.put(SmartSocketsProperties.HUB_ADDRESSES, hubs);
}
String hubAddressFile = typedProperties
.getProperty(ServerProperties.HUB_ADDRESS_FILE);
if (hubAddressFile != null) {
smartProperties.put(SmartSocketsProperties.HUB_ADDRESS_FILE,
hubAddressFile);
}
if (typedProperties.getBooleanProperty(ServerProperties.PRINT_STATS)) {
smartProperties.put(SmartSocketsProperties.HUB_STATISTICS, "true");
smartProperties.put(SmartSocketsProperties.HUB_STATS_INTERVAL,
"60000");
}
hubOnly = typedProperties.getBooleanProperty(ServerProperties.HUB_ONLY);
remote = typedProperties.getBooleanProperty(ServerProperties.REMOTE);
String vizInfo = properties.getProperty(ServerProperties.VIZ_INFO);
if (hubOnly) {
if (vizInfo != null) {
smartProperties.put(SmartSocketsProperties.HUB_VIZ_INFO,
vizInfo);
}
virtualSocketFactory = null;
smartProperties.put(SmartSocketsProperties.HUB_PORT,
typedProperties.getProperty(ServerProperties.PORT));
hub = new Hub(smartProperties);
address = hub.getHubAddress();
connectionHandler = null;
registryService = null;
bootstrapService = null;
managementService = null;
} else {
if (vizInfo == null) {
vizInfo = "S^Ibis Server";
}
smartProperties.put(SmartSocketsProperties.HUB_VIZ_INFO, vizInfo);
// create server socket
hub = null;
smartProperties.put(SmartSocketsProperties.PORT_RANGE,
typedProperties.getProperty(ServerProperties.PORT));
if (typedProperties.getBooleanProperty(ServerProperties.START_HUB)) {
smartProperties.put(SmartSocketsProperties.START_HUB, "true");
smartProperties
.put(SmartSocketsProperties.HUB_DELEGATE, "true");
}
// create a factory, or get an existing one from SmartSockets
VirtualSocketFactory factory = VirtualSocketFactory
.getSocketFactory("ibis");
if (factory == null) {
factory = VirtualSocketFactory.getOrCreateSocketFactory("ibis",
smartProperties, true);
} else if (hubs != null) {
factory.addHubs(hubs.split(","));
}
this.virtualSocketFactory = factory;
address = virtualSocketFactory.getLocalHost();
try {
ServiceLink sl = virtualSocketFactory.getServiceLink();
if (sl != null) {
if (typedProperties
.getBooleanProperty(ServerProperties.START_HUB)) {
sl.registerProperty("smartsockets.viz", "invisible");
} else {
sl.registerProperty("smartsockets.viz", vizInfo);
}
} else {
logger
.warn("could not set smartsockets viz property: could not get smartsockets service link");
}
} catch (Throwable e) {
logger.warn("could not register smartsockets viz property", e);
}
// create default services
registryService = new CentralRegistryService(typedProperties,
virtualSocketFactory, policy);
services.put(registryService.getServiceName(), registryService);
bootstrapService = new BootstrapService(typedProperties,
virtualSocketFactory);
services.put(bootstrapService.getServiceName(), bootstrapService);
managementService = new ManagementService(typedProperties,
virtualSocketFactory);
services.put(managementService.getServiceName(), managementService);
// create user specified services
ClassLister classLister = ClassLister.getClassLister(null);
Class[] serviceClassList;
if (typedProperties.containsKey(ServerProperties.SERVICES)) {
String[] services = typedProperties
.getStringList(ServerProperties.SERVICES);
if (services == null) {
serviceClassList = classLister.getClassList("Ibis-Service",
Service.class).toArray(new Class[0]);
} else {
serviceClassList = new Class[services.length];
for (int i = 0; i < services.length; i++) {
serviceClassList[i] = Class.forName(services[i]);
}
}
} else {
serviceClassList = classLister.getClassList("Ibis-Service",
Service.class).toArray(new Class[0]);
}
for (int i = 0; i < serviceClassList.length; i++) {
try {
Service service = (Service) serviceClassList[i]
.getConstructor(
new Class[] { TypedProperties.class,
VirtualSocketFactory.class })
.newInstance(
new Object[] { typedProperties,
virtualSocketFactory });
services.put(service.getServiceName(), service);
} catch (InvocationTargetException e) {
if (e.getCause() == null) {
logger.warn("Could not create service "
+ serviceClassList[i] + ":", e);
} else {
logger.warn("Could not create service "
+ serviceClassList[i] + ":", e.getCause());
}
} catch (Throwable e) {
logger.warn("Could not create service "
+ serviceClassList[i] + ":", e);
}
}
// start handling remote requests
connectionHandler = new ServerConnectionHandler(this, factory);
}
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#getRegistryService()
*/
public CentralRegistryService getRegistryService() {
return registryService;
}
BootstrapService getBootstrapService() {
return bootstrapService;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#getManagementService()
*/
public ManagementService getManagementService() {
return managementService;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#getAddress()
*/
public String getAddress() {
return address.toString();
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#getServiceNames()
*/
public String[] getServiceNames() {
return services.keySet().toArray(new String[0]);
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#getHubs()
*/
public String[] getHubs() {
DirectSocketAddress[] hubs;
if (hubOnly) {
hubs = hub.knownHubs();
} else {
hubs = virtualSocketFactory.getKnownHubs();
}
ArrayList<String> result = new ArrayList<String>();
if (hubs != null) {
for (DirectSocketAddress hub : hubs) {
result.add(hub.toString());
}
}
return result.toArray(new String[0]);
}
/*
* (non-Javadoc)
*
* @seeibis.ipl.server.ServerInterface#addHubs(ibis.smartsockets.direct.
* DirectSocketAddress)
*/
public void addHubs(DirectSocketAddress... hubAddresses) {
if (hubOnly) {
hub.addHubs(hubAddresses);
} else {
virtualSocketFactory.addHubs(hubAddresses);
}
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#addHubs(java.lang.String)
*/
public void addHubs(String... hubAddresses) {
if (hubOnly) {
hub.addHubs(hubAddresses);
} else {
virtualSocketFactory.addHubs(hubAddresses);
}
}
public String toString() {
if (hubOnly) {
return "Hub running on " + getAddress();
}
String message = "Ibis server running on " + getAddress()
+ "\nList of Services:";
for (Service service : services.values()) {
message += "\n " + service.toString();
}
return message;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.server.ServerInterface#end(long)
*/
public void end(long timeout) {
long deadline = System.currentTimeMillis() + timeout;
if (timeout == 0) {
deadline = Long.MAX_VALUE;
} else if (timeout == -1) {
deadline = 0;
}
if (connectionHandler != null) {
connectionHandler.end();
}
for (Service service : services.values()) {
service.end(deadline);
}
if (hubOnly) {
hub.end();
} else {
virtualSocketFactory.end();
}
}
private boolean hasRemote() {
return remote;
}
private static void printUsage(PrintStream out) {
out.println("Start a server for Ibis.");
out.println();
out.println("USAGE: ibis-server [OPTIONS]");
out.println();
out.println("--no-hub\t\t\tDo not start a hub.");
out
.println("--hub-only\t\t\tOnly start a hub, not the rest of the server.");
out
.println("--hub-addresses HUB[,HUB]\tAdditional hubs to connect to.");
out
.println("--hub-address-file [FILE_NAME]\tWrite the addresses of the hub to the given");
out.println("\t\t\t\tfile. The file is deleted on exit.");
out.println("--port PORT\t\t\tPort used for the server.");
out
.println("--remote\t\t\tListen to commands for this server on stdin.");
out.println();
out.println("Output Options:");
out.println("--events\t\t\tPrint events.");
out
.println("--errors\t\t\tPrint details of errors (such as stacktraces).");
out.println("--stats\t\t\t\tPrint statistics once in a while.");
out.println("--help | -h | /?\t\tThis message.");
}
private void waitUntilFinished() {
try {
int read = 0;
while (read != -1) {
read = System.in.read();
}
} catch (IOException e) {
// IGNORE
}
}
private static class Shutdown extends Thread {
private final Server server;
Shutdown(Server server) {
this.server = server;
}
public void run() {
server.end(-1);
}
}
/**
* Run the ibis server
*/
public static void main(String[] args) {
TypedProperties properties = new TypedProperties();
properties.putAll(System.getProperties());
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("--no-hub")) {
properties.setProperty(ServerProperties.START_HUB, "false");
} else if (args[i].equalsIgnoreCase("--hub-only")) {
properties.setProperty(ServerProperties.HUB_ONLY, "true");
} else if (args[i].equalsIgnoreCase("--hub-addresses")) {
i++;
properties.setProperty(ServerProperties.HUB_ADDRESSES, args[i]);
} else if (args[i].equalsIgnoreCase("--hub-address-file")) {
i++;
properties.setProperty(ServerProperties.HUB_ADDRESS_FILE,
args[i]);
} else if (args[i].equalsIgnoreCase("--port")) {
i++;
properties.put(ServerProperties.PORT, args[i]);
} else if (args[i].equalsIgnoreCase("--events")) {
properties.setProperty(ServerProperties.PRINT_EVENTS, "true");
} else if (args[i].equalsIgnoreCase("--errors")) {
properties.setProperty(ServerProperties.PRINT_ERRORS, "true");
} else if (args[i].equalsIgnoreCase("--stats")) {
properties.setProperty(ServerProperties.PRINT_STATS, "true");
} else if (args[i].equalsIgnoreCase("--remote")) {
properties.setProperty(ServerProperties.REMOTE, "true");
} else if (args[i].equalsIgnoreCase("--help")
|| args[i].equalsIgnoreCase("-help")
|| args[i].equalsIgnoreCase("-h")
|| args[i].equalsIgnoreCase("/?")) {
printUsage(System.err);
System.exit(0);
} else {
System.err.println("Unknown argument: " + args[i]);
printUsage(System.err);
System.exit(1);
}
}
Server server = null;
try {
server = new Server(properties);
} catch (Throwable t) {
System.err.println("Could not start Server");
t.printStackTrace();
System.exit(1);
}
// register shutdown hook
try {
Runtime.getRuntime().addShutdownHook(new Shutdown(server));
} catch (Exception e) {
System.err.println("warning: could not registry shutdown hook");
}
if (server.hasRemote()) {
System.out.println(ADDRESS_LINE_PREFIX + server.getAddress()
+ ADDRESS_LINE_POSTFIX);
System.out.flush();
server.waitUntilFinished();
} else {
System.err.println(server.toString());
String knownHubs = null;
while (true) {
String[] hubs = server.getHubs();
if (hubs.length != 0) {
String newKnownHubs = hubs[0].toString();
for (int i = 1; i < hubs.length; i++) {
newKnownHubs += "," + hubs[i].toString();
}
if (!newKnownHubs.equals(knownHubs)) {
knownHubs = newKnownHubs;
System.err.println("Known hubs now: " + knownHubs);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
server.end(-1);
}
public VirtualSocketFactory getSocketFactory() {
return virtualSocketFactory;
}
}
|
package info.tregmine;
import info.tregmine.api.*;
import info.tregmine.commands.*;
import info.tregmine.database.*;
import info.tregmine.database.db.DBContextFactory;
import info.tregmine.events.CallEventListener;
import info.tregmine.listeners.*;
import info.tregmine.quadtree.IntersectionException;
import info.tregmine.tools.*;
import info.tregmine.zones.*;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
import java.util.logging.*;
import org.bukkit.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.maxmind.geoip.LookupService;
/**
* @author Ein Andersson
* @author Emil Hernvall
*/
public class Tregmine extends JavaPlugin
{
public final static int VERSION = 0;
public final static int AMOUNT = 0;
public final static Logger LOGGER = Logger.getLogger("Minecraft");
private IContextFactory contextFactory;
private Server server;
private WebServer webServer;
private Map<String, TregminePlayer> players;
private Map<Integer, TregminePlayer> playersById;
private Map<Location, Integer> blessedBlocks;
private Map<Location, FishyBlock> fishyBlocks;
private Map<String, ZoneWorld> worlds;
private Map<Integer, Zone> zones;
private List<String> insults;
private List<String> quitMessages;
private Queue<TregminePlayer> mentors;
private Queue<TregminePlayer> students;
private LookupService cl = null;
@Override
public void onLoad()
{
File folder = getDataFolder();
Tregmine.LOGGER.info("Data folder is: " + folder);
reloadConfig();
FileConfiguration config = getConfig();
contextFactory = new DBContextFactory(config, this);
// Set up all data structures
players = new HashMap<>();
playersById = new HashMap<>();
mentors = new LinkedList<>();
students = new LinkedList<>();
worlds = new TreeMap<>(
new Comparator<String>() {
@Override
public int compare(String a, String b)
{
return a.compareToIgnoreCase(b);
}
});
zones = new HashMap<>();
Player[] players = getServer().getOnlinePlayers();
for (Player player : players) {
try {
TregminePlayer tp =
addPlayer(player, player.getAddress().getAddress());
if (tp.getRank() == Rank.TOURIST) {
students.offer(tp);
}
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
try {
cl = new LookupService(new File(folder,"GeoIPCity.dat"),
LookupService.GEOIP_MEMORY_CACHE);
} catch (IOException e) {
Tregmine.LOGGER.warning("GeoIPCity.dat was not found! " +
"Geo location will not function as expected.");
}
}
@Override
public void onEnable()
{
this.server = getServer();
try (IContext ctx = contextFactory.createContext()) {
IBlessedBlockDAO blessedBlockDAO = ctx.getBlessedBlockDAO();
this.blessedBlocks = blessedBlockDAO.load(getServer());
LOGGER.info("Loaded " + blessedBlocks.size() + " blessed blocks");
IFishyBlockDAO fishyBlockDAO = ctx.getFishyBlockDAO();
this.fishyBlocks = fishyBlockDAO.loadFishyBlocks(getServer());
LOGGER.info("Loaded " + fishyBlocks.size() + " fishy blocks");
IMiscDAO miscDAO = ctx.getMiscDAO();
this.insults = miscDAO.loadInsults();
this.quitMessages = miscDAO.loadQuitMessages();
LOGGER.info("Loaded " + insults.size() + " insults and " + quitMessages.size() + " quit messages");
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Set up web server
webServer = new WebServer(this);
webServer.start();
// Register all listeners
PluginManager pluginMgm = server.getPluginManager();
pluginMgm.registerEvents(new BlessedBlockListener(this), this);
pluginMgm.registerEvents(new BoxFillBlockListener(this), this);
pluginMgm.registerEvents(new ChatListener(this), this);
pluginMgm.registerEvents(new CompassListener(this), this);
pluginMgm.registerEvents(new PlayerLookupListener(this), this);
pluginMgm.registerEvents(new SetupListener(this), this);
pluginMgm.registerEvents(new SignColorListener(), this);
pluginMgm.registerEvents(new TabListener(this), this);
pluginMgm.registerEvents(new TauntListener(this), this);
pluginMgm.registerEvents(new TregmineBlockListener(this), this);
pluginMgm.registerEvents(new TregminePlayerListener(this), this);
pluginMgm.registerEvents(new ZoneBlockListener(this), this);
pluginMgm.registerEvents(new ZoneEntityListener(this), this);
pluginMgm.registerEvents(new ZonePlayerListener(this), this);
pluginMgm.registerEvents(new FishyBlockListener(this), this);
pluginMgm.registerEvents(new InventoryListener(this), this);
pluginMgm.registerEvents(new DonationSigns(this), this);
pluginMgm.registerEvents(new ExpListener(this), this);
pluginMgm.registerEvents(new ItemFrameListener(this), this);
pluginMgm.registerEvents(new EggListener(this), this);
pluginMgm.registerEvents(new PistonListener(this), this);
pluginMgm.registerEvents(new ToolCraft(this), this);
pluginMgm.registerEvents(new LumberListener(this), this);
pluginMgm.registerEvents(new VeinListener(this), this);
pluginMgm.registerEvents(new CallEventListener(this), this);
pluginMgm.registerEvents(new PortalListener(this), this);
pluginMgm.registerEvents(new BankListener(this), this);
// Declaration of all commands
getCommand("admins").setExecutor(
new NotifyCommand(this, "admins") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.JUNIOR_ADMIN ||
player.getRank() == Rank.SENIOR_ADMIN;
}
@Override
public ChatColor getColor()
{
return ChatColor.DARK_RED;
}
});
getCommand("guardians").setExecutor(
new NotifyCommand(this, "guardians") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.GUARDIAN ||
player.getRank() == Rank.JUNIOR_ADMIN ||
player.getRank() == Rank.SENIOR_ADMIN;
}
@Override
public ChatColor getColor()
{
return ChatColor.DARK_BLUE;
}
});
getCommand("action").setExecutor(new ActionCommand(this));
getCommand("alert").setExecutor(new AlertCommand(this));
getCommand("badge").setExecutor(new BadgeCommand(this));
getCommand("ban").setExecutor(new BanCommand(this));
getCommand("bless").setExecutor(new BlessCommand(this));
getCommand("blockhere").setExecutor(new BlockHereCommand(this));
getCommand("brush").setExecutor(new BrushCommand(this));
getCommand("channel").setExecutor(new ChannelCommand(this));
getCommand("channelview").setExecutor(new ChannelViewCommand(this));
getCommand("clean").setExecutor(new CleanInventoryCommand(this));
getCommand("cname").setExecutor(new ChangeNameCommand(this));
getCommand("createmob").setExecutor(new CreateMobCommand(this));
getCommand("createwarp").setExecutor(new CreateWarpCommand(this));
getCommand("creative").setExecutor(new GameModeCommand(this, "creative", GameMode.CREATIVE));
getCommand("fill").setExecutor(new FillCommand(this, "fill"));
getCommand("fly").setExecutor(new FlyCommand(this));
getCommand("force").setExecutor(new ForceCommand(this));
getCommand("forceblock").setExecutor(new ForceShieldCommand(this));
getCommand("give").setExecutor(new GiveCommand(this));
getCommand("head").setExecutor(new HeadCommand(this));
getCommand("hide").setExecutor(new HideCommand(this));
getCommand("home").setExecutor(new HomeCommand(this));
getCommand("ignore").setExecutor(new IgnoreCommand(this));
getCommand("inv").setExecutor(new InventoryCommand(this));
getCommand("invlog").setExecutor(new InventoryLogCommand(this));
getCommand("item").setExecutor(new ItemCommand(this));
getCommand("keyword").setExecutor(new KeywordCommand(this));
getCommand("kick").setExecutor(new KickCommand(this));
getCommand("lot").setExecutor(new LotCommand(this));
getCommand("lottery").setExecutor(new LotteryCommand(this));
getCommand("mentor").setExecutor(new MentorCommand(this));
getCommand("msg").setExecutor(new MsgCommand(this));
getCommand("newspawn").setExecutor(new NewSpawnCommand(this));
getCommand("normal").setExecutor(new NormalCommand(this));
getCommand("nuke").setExecutor(new NukeCommand(this));
getCommand("password").setExecutor(new PasswordCommand(this));
getCommand("pos").setExecutor(new PositionCommand(this));
getCommand("quitmessage").setExecutor(new QuitMessageCommand(this));
getCommand("regeneratechunk").setExecutor(new RegenerateChunkCommand(this));
getCommand("remitems").setExecutor(new RemItemsCommand(this));
getCommand("repair").setExecutor(new ToolRepairCommand(this));
getCommand("report").setExecutor(new ReportCommand(this));
getCommand("say").setExecutor(new SayCommand(this));
getCommand("seen").setExecutor(new SeenCommand(this));
getCommand("sell").setExecutor(new SellCommand(this));
getCommand("sendto").setExecutor(new SendToCommand(this));
getCommand("setbiome").setExecutor(new SetBiomeCommand(this));
getCommand("setspawner").setExecutor(new SetSpawnerCommand(this));
getCommand("spawn").setExecutor(new SpawnCommand(this));
getCommand("summon").setExecutor(new SummonCommand(this));
getCommand("support").setExecutor(new SupportCommand(this));
getCommand("survival").setExecutor(new GameModeCommand(this, "survival", GameMode.SURVIVAL));
getCommand("testfill").setExecutor(new FillCommand(this, "testfill"));
getCommand("time").setExecutor(new TimeCommand(this));
getCommand("tool").setExecutor(new ToolSpawnCommand(this));
getCommand("town").setExecutor(new ZoneCommand(this, "town"));
getCommand("tp").setExecutor(new TeleportCommand(this));
getCommand("tpshield").setExecutor(new TeleportShieldCommand(this));
getCommand("tpto").setExecutor(new TeleportToCommand(this));
getCommand("trade").setExecutor(new TradeCommand(this));
getCommand("update").setExecutor(new UpdateCommand(this));
getCommand("vanish").setExecutor(new VanishCommand(this));
getCommand("wallet").setExecutor(new WalletCommand(this));
getCommand("warn").setExecutor(new WarnCommand(this));
getCommand("warp").setExecutor(new WarpCommand(this));
getCommand("weather").setExecutor(new WeatherCommand(this));
getCommand("webkick").setExecutor(new WebKickCommand(this));
getCommand("who").setExecutor(new WhoCommand(this));
getCommand("zone").setExecutor(new ZoneCommand(this, "zone"));
ToolCraftRegistry.RegisterRecipes(getServer()); // Registers all tool recipes
for (TregminePlayer player : getOnlinePlayers()) {
player.sendMessage(ChatColor.AQUA + "Tregmine successfully loaded. Version " + getDescription().getVersion());
}
}
// run when plugin is disabled
@Override
public void onDisable()
{
server.getScheduler().cancelTasks(this);
// Add a record of logout to db for all players
for (TregminePlayer player : getOnlinePlayers()) {
player.saveInventory(player.getCurrentInventory());
removePlayer(player);
}
try {
webServer.stop();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to start web server!", e);
}
}
public WebServer getWebServer()
{
return webServer;
}
public IContextFactory getContextFactory()
{
return contextFactory;
}
public IContext createContext()
throws DAOException
{
return contextFactory.createContext();
}
// Data structure accessors
public Map<Location, Integer> getBlessedBlocks()
{
return blessedBlocks;
}
public Map<Location, FishyBlock> getFishyBlocks()
{
return fishyBlocks;
}
public Queue<TregminePlayer> getMentorQueue()
{
return mentors;
}
public Queue<TregminePlayer> getStudentQueue()
{
return students;
}
public List<String> getInsults()
{
return insults;
}
public List<String> getQuitMessages()
{
return quitMessages;
}
// Player methods
public void reloadPlayer(TregminePlayer player)
{
try {
addPlayer(player.getDelegate(), player.getAddress().getAddress());
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
public List<TregminePlayer> getOnlinePlayers()
{
List<TregminePlayer> players = new ArrayList<>();
for (Player player : server.getOnlinePlayers()) {
players.add(getPlayer(player));
}
return players;
}
public TregminePlayer addPlayer(Player srcPlayer, InetAddress addr)
throws PlayerBannedException
{
if (players.containsKey(srcPlayer.getName())) {
return players.get(srcPlayer.getName());
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
TregminePlayer player = playerDAO.getPlayer(srcPlayer.getPlayer());
if (player == null) {
player = playerDAO.createPlayer(srcPlayer);
}
player.removeFlag(TregminePlayer.Flags.SOFTWARNED);
player.removeFlag(TregminePlayer.Flags.HARDWARNED);
IPlayerReportDAO reportDAO = ctx.getPlayerReportDAO();
List<PlayerReport> reports = reportDAO.getReportsBySubject(player);
for (PlayerReport report : reports) {
Date validUntil = report.getValidUntil();
if (validUntil == null) {
continue;
}
if (validUntil.getTime() < System.currentTimeMillis()) {
continue;
}
if (report.getAction() == PlayerReport.Action.SOFTWARN) {
player.setFlag(TregminePlayer.Flags.SOFTWARNED);
}
else if (report.getAction() == PlayerReport.Action.HARDWARN) {
player.setFlag(TregminePlayer.Flags.HARDWARNED);
}
else if (report.getAction() == PlayerReport.Action.BAN) {
throw new PlayerBannedException(report.getMessage());
}
}
player.setIp(addr.getHostAddress());
player.setHost(addr.getCanonicalHostName());
if (cl != null) {
com.maxmind.geoip.Location l1 = cl.getLocation(player.getIp());
if (l1 != null) {
Tregmine.LOGGER.info(player.getName() + ": " + l1.countryName +
", " + l1.city + ", " + player.getIp() + ", " +
player.getHost());
player.setCountry(l1.countryName);
player.setCity(l1.city);
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, false, onlinePlayerCount);
player.setTemporaryChatName(player.getNameColor()
+ player.getName());
players.put(player.getName(), player);
playersById.put(player.getId(), player);
return player;
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public void removePlayer(TregminePlayer player)
{
try (IContext ctx = contextFactory.createContext()) {
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, true, onlinePlayerCount);
IPlayerDAO playerDAO = ctx.getPlayerDAO();
playerDAO.updatePlayTime(player);
} catch (DAOException e) {
throw new RuntimeException(e);
}
player.setValid(false);
players.remove(player.getName());
playersById.remove(player.getId());
mentors.remove(player);
students.remove(player);
}
public TregminePlayer getPlayer(String name)
{
return players.get(name);
}
public TregminePlayer getPlayer(Player player)
{
return players.get(player.getName());
}
public TregminePlayer getPlayer(int id)
{
return playersById.get(id);
}
public TregminePlayer getPlayerOffline(String name)
{
if (players.containsKey(name)) {
return players.get(name);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(name);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public TregminePlayer getPlayerOffline(int id)
{
if (playersById.containsKey(id)) {
return playersById.get(id);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(id);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public List<TregminePlayer> matchPlayer(String pattern)
{
List<Player> matches = server.matchPlayer(pattern);
if (matches.size() == 0) {
return new ArrayList<>();
}
List<TregminePlayer> decoratedMatches = new ArrayList<>();
for (Player match : matches) {
TregminePlayer decoratedMatch = getPlayer(match);
if (decoratedMatch == null) {
continue;
}
decoratedMatches.add(decoratedMatch);
}
return decoratedMatches;
}
// Zone methods
public ZoneWorld getWorld(World world)
{
ZoneWorld zoneWorld = worlds.get(world.getName());
// lazy load zone worlds as required
if (zoneWorld == null) {
try (IContext ctx = contextFactory.createContext()) {
IZonesDAO dao = ctx.getZonesDAO();
zoneWorld = new ZoneWorld(world);
List<Zone> zones = dao.getZones(world.getName());
for (Zone zone : zones) {
try {
zoneWorld.addZone(zone);
this.zones.put(zone.getId(), zone);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load zone " + zone.getName()
+ " with id " + zone.getId() + ".");
}
}
List<Lot> lots = dao.getLots(world.getName());
for (Lot lot : lots) {
try {
zoneWorld.addLot(lot);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load lot " + lot.getName()
+ " with id " + lot.getId() + ".");
}
}
worlds.put(world.getName(), zoneWorld);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
return zoneWorld;
}
public Zone getZone(int zoneId)
{
return zones.get(zoneId);
}
// Auto Save Alert
@EventHandler
public void autoSave(WorldSaveEvent event){
Bukkit.broadcastMessage(ChatColor.DARK_RED + "Tregmine is saving, You may experience some slowness.");
}
}
|
/*
$Log$
Revision 1.2 1999/06/30 12:24:54 rimassa
Fixed a bug dealing with unlimited message queues.
Revision 1.1 1999/03/25 16:50:44 rimassa
This class implements a message queue for an agent, that can be either bounded
or unbounded and adopts a FIFO replacement policy.
*/
package jade.core;
import java.util.Iterator;
import java.util.LinkedList;
import jade.lang.acl.ACLMessage;
class MessageQueue {
private LinkedList list;
private int maxSize;
public MessageQueue(int size) {
maxSize = size;
list = new LinkedList();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void setMaxSize(int newSize) throws IllegalArgumentException {
if(newSize < 0)
throw new IllegalArgumentException("Negative message queue size is not allowed.");
maxSize = newSize;
}
public int getMaxSize() {
return maxSize;
}
public void addFirst(ACLMessage msg) {
if((maxSize != 0) && (list.size() >= maxSize))
list.removeFirst(); // FIFO replacement policy
list.addFirst(msg);
}
public void addLast(ACLMessage msg) {
if((maxSize != 0) && (list.size() >= maxSize))
list.removeFirst(); // FIFO replacement policy
list.addLast(msg);
}
public ACLMessage removeFirst() {
return (ACLMessage)list.removeFirst();
}
public boolean remove(ACLMessage item) {
return list.remove(item);
}
public Iterator iterator() {
return list.iterator();
}
}
|
package japura.Tribes;
import japura.MonoUtil.MonoConf;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.Bukkit;
import org.bukkit.entity.EntityType;
import org.json.simple.JSONObject;
public class AutoSave extends BukkitRunnable{
private final Tribes plugin;
public AutoSave(Tribes plugin) {
this.plugin = plugin;
Tribes.log("Tribe AutoSave runner spawned");
}
public void run() {
Player[] users = Bukkit.getOnlinePlayers();
for (Player user : users)
user.sendMessage("&6Tribes performing automatic save...");
Tribes.log("tribe autosave starting");
plugin.verifyTribes();
plugin.saveData();
plugin.verifyTribes();
Tribes.log("tribe autosave ending");
for (Player user : users)
user.sendMessage("&6Tribes save complete.");
}
}
|
package nut.xml.pull;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
//import nut.xml.XmlReader;
//import ab.nut.util.ReaderFactory;
//import java.util.Hashtable;
//TODO best handling of interning issues
// have isAllNewStringInterned ???
//TODO handling surrogate pairs: http://www.unicode.org/unicode/faq/utf_bom.html
//TODO review code for use of bufAbsoluteStart when keeping pos between next()/fillBuf()
/**
* Absolutely minimal implementation of XMLPULL V1 API. Encoding handling done with XmlReader
*/
public class XmlPullParser
{
/** This constant represents the default namespace (empty string "") */
String NO_NAMESPACE = "";
// EVENT TYPES as reported by next()
/**
* Signalize that parser is at the very beginning of the document
* and nothing was read yet.
* This event type can only be observed by calling getEvent()
* before the first call to next(), nextToken, or nextTag()</a>).
*
* @see #next
* @see #nextToken
*/
public static int START_DOCUMENT = 0;
/**
* Logical end of the xml document. Returned from getEventType, next()
* and nextToken()
* when the end of the input document has been reached.
* <p><strong>NOTE:</strong> calling again
* <a href="#next()">next()</a> or <a href="#nextToken()">nextToken()</a>
* will result in exception being thrown.
*
* @see #next
* @see #nextToken
*/
public static int END_DOCUMENT = 1;
/**
* Returned from getEventType(),
* <a href="#next()">next()</a>, <a href="#nextToken()">nextToken()</a> when
* a start tag was read.
* The name of start tag is available from getName(), its namespace and prefix are
* available from getNamespace() and getPrefix()
* if <a href='#FEATURE_PROCESS_NAMESPACES'>namespaces are enabled</a>.
* See getAttribute* methods to retrieve element attributes.
* See getNamespace* methods to retrieve newly declared namespaces.
*
* @see #next
* @see #nextToken
* @see #getName
* @see #getPrefix
* @see #getNamespace
* @see #getAttributeCount
* @see #getDepth
* @see #getNamespaceCount
* @see #getNamespace
* @see #FEATURE_PROCESS_NAMESPACES
*/
public static int START_TAG = 2;
/**
* Returned from getEventType(), <a href="#next()">next()</a>, or
* <a href="#nextToken()">nextToken()</a> when an end tag was read.
* The name of start tag is available from getName(), its
* namespace and prefix are
* available from getNamespace() and getPrefix().
*
* @see #next
* @see #nextToken
* @see #getName
* @see #getPrefix
* @see #getNamespace
* @see #FEATURE_PROCESS_NAMESPACES
*/
public static int END_TAG = 3;
/**
* Character data was read and will is available by calling getText().
* <p><strong>Please note:</strong> <a href="#next()">next()</a> will
* accumulate multiple
* events into one TEXT event, skipping IGNORABLE_WHITESPACE,
* PROCESSING_INSTRUCTION and COMMENT events,
* In contrast, <a href="#nextToken()">nextToken()</a> will stop reading
* text when any other event is observed.
* Also, when the state was reached by calling next(), the text value will
* be normalized, whereas getText() will
* return unnormalized content in the case of nextToken(). This allows
* an exact roundtrip without changing line ends when examining low
* level events, whereas for high level applications the text is
* normalized appropriately.
*
* @see #next
* @see #nextToken
* @see #getText
*/
public static int TEXT = 4;
// additional events exposed by lower level nextToken()
/**
* A CDATA sections was just read;
* this token is available only from calls to <a href="#nextToken()">nextToken()</a>.
* A call to next() will accumulate various text events into a single event
* of type TEXT. The text contained in the CDATA section is available
* by calling getText().
*
* @see #nextToken
* @see #getText
*/
int CDSECT = 5;
/**
* An entity reference was just read;
* this token is available from <a href="#nextToken()">nextToken()</a>
* only. The entity name is available by calling getName(). If available,
* the replacement text can be obtained by calling getTextt(); otherwise,
* the user is responsible for resolving the entity reference.
* This event type is never returned from next(); next() will
* accumulate the replacement text and other text
* events to a single TEXT event.
*
* @see #nextToken
* @see #getText
*/
int ENTITY_REF = 6;
/**
* Ignorable whitespace was just read.
* This token is available only from <a href="#nextToken()">nextToken()</a>).
* For non-validating
* parsers, this event is only reported by nextToken() when outside
* the root element.
* Validating parsers may be able to detect ignorable whitespace at
* other locations.
* The ignorable whitespace string is available by calling getText()
*
* <p><strong>NOTE:</strong> this is different from calling the
* isWhitespace() method, since text content
* may be whitespace but not ignorable.
*
* Ignorable whitespace is skipped by next() automatically; this event
* type is never returned from next().
*
* @see #nextToken
* @see #getText
*/
int IGNORABLE_WHITESPACE = 7;
/**
* An XML processing instruction declaration was just read. This
* event type is available only via <a href="#nextToken()">nextToken()</a>.
* getText() will return text that is inside the processing instruction.
* Calls to next() will skip processing instructions automatically.
* @see #nextToken
* @see #getText
*/
int PROCESSING_INSTRUCTION = 8;
/**
* An XML comment was just read. This event type is this token is
* available via <a href="#nextToken()">nextToken()</a> only;
* calls to next() will skip comments automatically.
* The content of the comment can be accessed using the getText()
* method.
*
* @see #nextToken
* @see #getText
*/
int COMMENT = 9;
/**
* An XML document type declaration was just read. This token is
* available from <a href="#nextToken()">nextToken()</a> only.
* The unparsed text inside the doctype is available via
* the getText() method.
*
* @see #nextToken
* @see #getText
*/
int DOCDECL = 10;
/**
* This array can be used to convert the event type integer constants
* such as START_TAG or TEXT to
* to a string. For example, the value of TYPES[START_TAG] is
* the string "START_TAG".
*
* This array is intended for diagnostic output only. Relying
* on the contents of the array may be dangerous since malicious
* applications may alter the array, although it is final, due
* to limitations of the Java language.
*/
String [] TYPES = {
"START_DOCUMENT",
"END_DOCUMENT",
"START_TAG",
"END_TAG",
"TEXT",
"CDSECT",
"ENTITY_REF",
"IGNORABLE_WHITESPACE",
"PROCESSING_INSTRUCTION",
"COMMENT",
"DOCDECL"
};
// namespace related features
/**
* This feature determines whether the parser processes
* namespaces. As for all features, the default value is false.
* <p><strong>NOTE:</strong> The value can not be changed during
* parsing an must be set before parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_PROCESS_NAMESPACES =
"http://xmlpull.org/v1/doc/features.html#process-namespaces";
/**
* This feature determines whether namespace attributes are
* exposed via the attribute access methods. Like all features,
* the default value is false. This feature cannot be changed
* during parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_REPORT_NAMESPACE_ATTRIBUTES =
"http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes";
/**
* This feature determines whether the document declaration
* is processed. If set to false,
* the DOCDECL event type is reported by nextToken()
* and ignored by next().
*
* If this featue is activated, then the document declaration
* must be processed by the parser.
*
* <p><strong>Please note:</strong> If the document type declaration
* was ignored, entity references may cause exceptions
* later in the parsing process.
* The default value of this feature is false. It cannot be changed
* during parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_PROCESS_DOCDECL =
"http://xmlpull.org/v1/doc/features.html#process-docdecl";
/**
* If this feature is activated, all validation errors as
* defined in the XML 1.0 sepcification are reported.
* This implies that FEATURE_PROCESS_DOCDECL is true and both, the
* internal and external document type declaration will be processed.
* <p><strong>Please Note:</strong> This feature can not be changed
* during parsing. The default value is false.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_VALIDATION =
"http://xmlpull.org/v1/doc/features.html#validation";
//NOTE: no interning of those strings --> by Java leng spec they MUST be already interned
protected final static String XML_URI = "http:
protected final static String XMLNS_URI = "http:
protected final static String FEATURE_XML_ROUNDTRIP=
//"http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
"http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
protected final static String FEATURE_NAMES_INTERNED =
"http://xmlpull.org/v1/doc/features.html#names-interned";
protected final static String PROPERTY_XMLDECL_VERSION =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-version";
protected final static String PROPERTY_XMLDECL_STANDALONE =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone";
protected final static String PROPERTY_XMLDECL_CONTENT =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-content";
protected final static String PROPERTY_LOCATION =
"http://xmlpull.org/v1/doc/properties.html#location";
/**
* Implementation notice:
* the is instance variable that controls if newString() is interning.
* <p><b>NOTE:</b> newStringIntern <b>always</b> returns interned strings
* and newString MAY return interned String depending on this variable.
* <p><b>NOTE:</b> by default in this minimal implementation it is false!
*/
protected boolean allStringsInterned;
protected void resetStringCache() {
//System.out.println("resetStringCache() minimum called");
}
protected String newString(char[] cbuf, int off, int len) {
return new String(cbuf, off, len);
}
protected String newStringIntern(char[] cbuf, int off, int len) {
return (new String(cbuf, off, len)).intern();
}
private static final boolean TRACE_SIZING = false;
// NOTE: features are not resetable and typically defaults to false ...
protected boolean processNamespaces;
protected boolean roundtripSupported;
// global parser state
protected String location;
protected int lineNumber;
protected int columnNumber;
protected boolean seenRoot;
protected boolean reachedEnd;
protected int eventType;
protected boolean emptyElementTag;
// element stack
protected int depth;
protected char[] elRawName[];
protected int elRawNameEnd[];
protected int elRawNameLine[];
protected String elName[];
protected String elPrefix[];
protected String elUri[];
//protected String elValue[];
protected int elNamespaceCount[];
/**
* Make sure that we have enough space to keep element stack if passed size.
* It will always create one additional slot then current depth
*/
protected void ensureElementsCapacity() {
final int elStackSize = elName != null ? elName.length : 0;
if( (depth + 1) >= elStackSize) {
// we add at least one extra slot ...
final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25
if(TRACE_SIZING) {
System.err.println("TRACE_SIZING elStackSize "+elStackSize+" ==> "+newSize);
}
final boolean needsCopying = elStackSize > 0;
String[] arr = null;
// resue arr local variable slot
arr = new String[newSize];
if(needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize);
elName = arr;
arr = new String[newSize];
if(needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize);
elPrefix = arr;
arr = new String[newSize];
if(needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize);
elUri = arr;
int[] iarr = new int[newSize];
if(needsCopying) {
System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize);
} else {
// special initialization
iarr[0] = 0;
}
elNamespaceCount = iarr;
//TODO: avoid using element raw name ...
iarr = new int[newSize];
if(needsCopying) {
System.arraycopy(elRawNameEnd, 0, iarr, 0, elStackSize);
}
elRawNameEnd = iarr;
iarr = new int[newSize];
if(needsCopying) {
System.arraycopy(elRawNameLine, 0, iarr, 0, elStackSize);
}
elRawNameLine = iarr;
final char[][] carr = new char[newSize][];
if(needsCopying) {
System.arraycopy(elRawName, 0, carr, 0, elStackSize);
}
elRawName = carr;
// arr = new String[newSize];
// if(needsCopying) System.arraycopy(elLocalName, 0, arr, 0, elStackSize);
// elLocalName = arr;
// arr = new String[newSize];
// if(needsCopying) System.arraycopy(elDefaultNs, 0, arr, 0, elStackSize);
// elDefaultNs = arr;
// int[] iarr = new int[newSize];
// if(needsCopying) System.arraycopy(elNsStackPos, 0, iarr, 0, elStackSize);
// for (int i = elStackSize; i < iarr.length; i++)
// iarr[i] = (i > 0) ? -1 : 0;
// elNsStackPos = iarr;
//assert depth < elName.length;
}
}
// attribute stack
protected int attributeCount;
protected String attributeName[];
protected int attributeNameHash[];
//protected int attributeNameStart[];
//protected int attributeNameEnd[];
protected String attributePrefix[];
protected String attributeUri[];
protected String attributeValue[];
//protected int attributeValueStart[];
//protected int attributeValueEnd[];
/**
* Make sure that in attributes temporary array is enough space.
*/
protected void ensureAttributesCapacity(int size) {
final int attrPosSize = attributeName != null ? attributeName.length : 0;
if(size >= attrPosSize) {
final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
if(TRACE_SIZING) {
System.err.println("TRACE_SIZING attrPosSize "+attrPosSize+" ==> "+newSize);
}
final boolean needsCopying = attrPosSize > 0;
String[] arr = null;
arr = new String[newSize];
if(needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize);
attributeName = arr;
arr = new String[newSize];
if(needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize);
attributePrefix = arr;
arr = new String[newSize];
if(needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize);
attributeUri = arr;
arr = new String[newSize];
if(needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize);
attributeValue = arr;
if( ! allStringsInterned ) {
final int[] iarr = new int[newSize];
if(needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize);
attributeNameHash = iarr;
}
arr = null;
// //assert attrUri.length > size
}
}
// namespace stack
protected int namespaceEnd;
protected String namespacePrefix[];
protected int namespacePrefixHash[];
protected String namespaceUri[];
protected void ensureNamespacesCapacity(int size) {
final int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0;
if(size >= namespaceSize) {
final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
if(TRACE_SIZING) {
System.err.println("TRACE_SIZING namespaceSize "+namespaceSize+" ==> "+newSize);
}
final String[] newNamespacePrefix = new String[newSize];
final String[] newNamespaceUri = new String[newSize];
if(namespacePrefix != null) {
System.arraycopy(
namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd);
System.arraycopy(
namespaceUri, 0, newNamespaceUri, 0, namespaceEnd);
}
namespacePrefix = newNamespacePrefix;
namespaceUri = newNamespaceUri;
if( ! allStringsInterned ) {
final int[] newNamespacePrefixHash = new int[newSize];
if(namespacePrefixHash != null) {
System.arraycopy(
namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd);
}
namespacePrefixHash = newNamespacePrefixHash;
}
//prefixesSize = newSize;
// //assert nsPrefixes.length > size && nsPrefixes.length == newSize
}
}
/**
* simplistic implementation of hash function that has <b>constant</b>
* time to compute - so it also means diminishing hash quality for long strings
* but for XML parsing it should be good enough ...
*/
protected static final int fastHash( char ch[], int off, int len ) {
if(len == 0) return 0;
//assert len >0
int hash = ch[off]; // hash at beginning
//try {
hash = (hash << 7) + ch[ off + len - 1 ]; // hash at the end
//} catch(ArrayIndexOutOfBoundsException aie) {
// aie.printStackTrace(); //should never happen ...
// throw new RuntimeException("this is violation of pre-condition");
if(len > 16) hash = (hash << 7) + ch[ off + (len / 4)]; // 1/4 from beginning
if(len > 8) hash = (hash << 7) + ch[ off + (len / 2)]; // 1/2 of string size ...
// notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value
// so max result == 29 bits so it is quite just below 31 bits for long (2^32) ...
//assert hash >= 0;
return hash;
}
// entity replacement stack
protected int entityEnd;
protected String entityName[];
protected char[] entityNameBuf[];
protected String entityReplacement[];
protected char[] entityReplacementBuf[];
protected int entityNameHash[];
protected void ensureEntityCapacity() {
final int entitySize = entityReplacementBuf != null ? entityReplacementBuf.length : 0;
if(entityEnd >= entitySize) {
final int newSize = entityEnd > 7 ? 2 * entityEnd : 8; // = lucky 7 + 1 //25
if(TRACE_SIZING) {
System.err.println("TRACE_SIZING entitySize "+entitySize+" ==> "+newSize);
}
final String[] newEntityName = new String[newSize];
final char[] newEntityNameBuf[] = new char[newSize][];
final String[] newEntityReplacement = new String[newSize];
final char[] newEntityReplacementBuf[] = new char[newSize][];
if(entityName != null) {
System.arraycopy(entityName, 0, newEntityName, 0, entityEnd);
System.arraycopy(entityNameBuf, 0, newEntityNameBuf, 0, entityEnd);
System.arraycopy(entityReplacement, 0, newEntityReplacement, 0, entityEnd);
System.arraycopy(entityReplacementBuf, 0, newEntityReplacementBuf, 0, entityEnd);
}
entityName = newEntityName;
entityNameBuf = newEntityNameBuf;
entityReplacement = newEntityReplacement;
entityReplacementBuf = newEntityReplacementBuf;
if( ! allStringsInterned ) {
final int[] newEntityNameHash = new int[newSize];
if(entityNameHash != null) {
System.arraycopy(entityNameHash, 0, newEntityNameHash, 0, entityEnd);
}
entityNameHash = newEntityNameHash;
}
}
}
// input buffer management
protected static final int READ_CHUNK_SIZE = 8*1024; //max data chars in one read() call
protected Reader reader;
protected String inputEncoding;
protected int bufLoadFactor = 95;
//protected int bufHardLimit; // only matters when expanding
protected char buf[] = new char[
Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 256 ];
protected int bufSoftLimit = ( bufLoadFactor * buf.length ) /100; // desirable size of buffer
protected boolean preventBufferCompaction;
protected int bufAbsoluteStart; // this is buf
protected int bufStart;
protected int bufEnd;
protected int pos;
protected int posStart;
protected int posEnd;
protected char pc[] = new char[
Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 64 ];
protected int pcStart;
protected int pcEnd;
// parsing state
//protected boolean needsMore;
//protected boolean seenMarkup;
protected boolean usePC;
protected boolean seenStartTag;
protected boolean seenEndTag;
protected boolean pastEndTag;
protected boolean seenAmpersand;
protected boolean seenMarkup;
protected boolean seenDocdecl;
// transient variable set during each call to next/Token()
protected boolean tokenize;
protected String text;
protected String entityRefName;
protected String xmlDeclVersion;
protected Boolean xmlDeclStandalone;
protected String xmlDeclContent;
protected void reset() {
//System.out.println("reset() called");
location = null;
lineNumber = 1;
columnNumber = 0;
seenRoot = false;
reachedEnd = false;
eventType = START_DOCUMENT;
emptyElementTag = false;
depth = 0;
attributeCount = 0;
namespaceEnd = 0;
entityEnd = 0;
reader = null;
inputEncoding = null;
preventBufferCompaction = false;
bufAbsoluteStart = 0;
bufEnd = bufStart = 0;
pos = posStart = posEnd = 0;
pcEnd = pcStart = 0;
usePC = false;
seenStartTag = false;
seenEndTag = false;
pastEndTag = false;
seenAmpersand = false;
seenMarkup = false;
seenDocdecl = false;
xmlDeclVersion = null;
xmlDeclStandalone = null;
xmlDeclContent = null;
resetStringCache();
}
public XmlPullParser() {
}
/**
* Method setFeature
*
* @param name a String
* @param state a boolean
*
* @throws XmlPullParserException
*
*/
public void setFeature(String name,
boolean state) throws XmlPullParserException
{
if(name == null) throw new IllegalArgumentException("feature name should not be null");
if(FEATURE_PROCESS_NAMESPACES.equals(name)) {
if(eventType != START_DOCUMENT) throw new XmlPullParserException(
"namespace processing feature can only be changed before parsing", this, null);
processNamespaces = state;
// } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) {
// if(type != START_DOCUMENT) throw new XmlPullParserException(
// "namespace reporting feature can only be changed before parsing", this, null);
// reportNsAttribs = state;
} else if(FEATURE_NAMES_INTERNED.equals(name)) {
if(state != false) {
throw new XmlPullParserException(
"interning names in this implementation is not supported");
}
} else if(FEATURE_PROCESS_DOCDECL.equals(name)) {
if(state != false) {
throw new XmlPullParserException(
"processing DOCDECL is not supported");
}
//} else if(REPORT_DOCDECL.equals(name)) {
// paramNotifyDoctype = state;
} else if(FEATURE_XML_ROUNDTRIP.equals(name)) {
//if(state == false) {
// throw new XmlPullParserException(
// "roundtrip feature can not be switched off");
roundtripSupported = state;
} else {
throw new XmlPullParserException("unsupporte feature "+name);
}
}
/** Unknown properties are <string>always</strong> returned as false */
public boolean getFeature(String name)
{
if(name == null) throw new IllegalArgumentException("feature name should not be nulll");
if(FEATURE_PROCESS_NAMESPACES.equals(name)) {
return processNamespaces;
// } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) {
// return reportNsAttribs;
} else if(FEATURE_NAMES_INTERNED.equals(name)) {
return false;
} else if(FEATURE_PROCESS_DOCDECL.equals(name)) {
return false;
//} else if(REPORT_DOCDECL.equals(name)) {
// return paramNotifyDoctype;
} else if(FEATURE_XML_ROUNDTRIP.equals(name)) {
//return true;
return roundtripSupported;
}
return false;
}
public void setProperty(String name,
Object value)
throws XmlPullParserException
{
if(PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new XmlPullParserException("unsupported property: '"+name+"'");
}
}
public Object getProperty(String name)
{
if(name == null) throw new IllegalArgumentException("property name should not be nulll");
if(PROPERTY_XMLDECL_VERSION.equals(name)) {
return xmlDeclVersion;
} else if(PROPERTY_XMLDECL_STANDALONE.equals(name)) {
return xmlDeclStandalone;
} else if(PROPERTY_XMLDECL_CONTENT.equals(name)) {
return xmlDeclContent;
} else if(PROPERTY_LOCATION.equals(name)) {
return location;
}
return null;
}
public void setInput(Reader in) throws XmlPullParserException
{
reset();
reader = in;
}
public void setInput(java.io.InputStream inputStream, String inputEncoding)
throws XmlPullParserException
{
if(inputStream == null) {
throw new IllegalArgumentException("input stream can not be null");
}
Reader reader;
try {
if(inputEncoding != null) {
reader = new InputStreamReader(inputStream, inputEncoding);
//ReaderFactory.newReader(inputStream, inputEncoding);
} else {
reader = new InputStreamReader(inputStream);
//ReaderFactory.newXmlReader(inputStream);
}
} catch (UnsupportedEncodingException une) {
throw new XmlPullParserException(
"could not create reader for encoding "+inputEncoding+" : "+une, this, une);
}
setInput(reader);
//must be here as reset() was called in setInput() and has set this.inputEncoding to null ...
this.inputEncoding = inputEncoding;
}
public String getInputEncoding() {
return inputEncoding;
}
public void defineEntityReplacementText(String entityName,
String replacementText)
throws XmlPullParserException
{
// throw new XmlPullParserException("not allowed");
if ( !replacementText.startsWith( "&#" ) && this.entityName != null && replacementText.length() > 1 )
{
String tmp = replacementText.substring( 1, replacementText.length() - 1 );
for ( int i = 0; i < this.entityName.length; i++ )
{
if ( this.entityName[i] != null && this.entityName[i].equals( tmp ) )
{
replacementText = this.entityReplacement[i];
}
}
}
//protected char[] entityReplacement[];
ensureEntityCapacity();
// this is to make sure that if interning works we will take advantage of it ...
this.entityName[entityEnd] = newString(entityName.toCharArray(), 0, entityName.length());
entityNameBuf[entityEnd] = entityName.toCharArray();
entityReplacement[entityEnd] = replacementText;
entityReplacementBuf[entityEnd] = replacementText.toCharArray();
if(!allStringsInterned) {
entityNameHash[ entityEnd ] =
fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length);
}
++entityEnd;
//TODO disallow < or & in entity replacement text (or ]]>???)
// TOOD keepEntityNormalizedForAttributeValue cached as well ...
}
public int getNamespaceCount(int depth)
throws XmlPullParserException
{
if(processNamespaces == false || depth == 0) {
return 0;
}
//int maxDepth = eventType == END_TAG ? this.depth + 1 : this.depth;
if(depth < 0 || depth > this.depth) throw new IllegalArgumentException(
"napespace count mayt be for depth 0.."+this.depth+" not "+depth);
return elNamespaceCount[ depth ];
}
public String getNamespacePrefix(int pos)
throws XmlPullParserException
{
//int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd;
//if(pos < end) {
if(pos < namespaceEnd) {
return namespacePrefix[ pos ];
} else {
throw new XmlPullParserException(
"position "+pos+" exceeded number of available namespaces "+namespaceEnd);
}
}
public String getNamespaceUri(int pos) throws XmlPullParserException
{
//int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd;
//if(pos < end) {
if(pos < namespaceEnd) {
return namespaceUri[ pos ];
} else {
throw new XmlPullParserException(
"position "+pos+" exceedded number of available namespaces "+namespaceEnd);
}
}
public String getNamespace( String prefix )
//throws XmlPullParserException
{
//int count = namespaceCount[ depth ];
if(prefix != null) {
for( int i = namespaceEnd -1; i >= 0; i
if( prefix.equals( namespacePrefix[ i ] ) ) {
return namespaceUri[ i ];
}
}
if("xml".equals( prefix )) {
return XML_URI;
} else if("xmlns".equals( prefix )) {
return XMLNS_URI;
}
} else {
for( int i = namespaceEnd -1; i >= 0; i
if( namespacePrefix[ i ] == null) { //"") { //null ) { //TODO check FIXME Alek
return namespaceUri[ i ];
}
}
}
return null;
}
public int getDepth()
{
return depth;
}
private static int findFragment(int bufMinPos, char[] b, int start, int end) {
//System.err.println("bufStart="+bufStart+" b="+printable(new String(b, start, end - start))+" start="+start+" end="+end);
if(start < bufMinPos) {
start = bufMinPos;
if(start > end) start = end;
return start;
}
if(end - start > 65) {
start = end - 10; // try to find good location
}
int i = start + 1;
while(--i > bufMinPos) {
if((end - i) > 65) break;
final char c = b[i];
if(c == '<' && (start - i) > 10) break;
}
return i;
}
/**
* Return string describing current position of parsers as
* text 'STATE [seen %s...] @line:column'.
*/
public String getPositionDescription ()
{
String fragment = null;
if(posStart <= pos) {
final int start = findFragment(0, buf, posStart, pos);
//System.err.println("start="+start);
if(start < pos) {
fragment = new String(buf, start, pos - start);
}
if(bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment;
}
// return " at line "+tokenizerPosRow
// +" and column "+(tokenizerPosCol-1)
// +(fragment != null ? " seen "+printable(fragment)+"..." : "");
return " "+TYPES[ eventType ] +
(fragment != null ? " seen "+printable(fragment)+"..." : "")
+" "+(location != null ? location : "")
+"@"+getLineNumber()+":"+getColumnNumber();
}
public int getLineNumber()
{
return lineNumber;
}
public int getColumnNumber()
{
return columnNumber;
}
public boolean isWhitespace() throws XmlPullParserException
{
if(eventType == TEXT || eventType == CDSECT) {
if(usePC) {
for (int i = pcStart; i <pcEnd; i++)
{
if(!isS(pc[ i ])) return false;
}
return true;
} else {
for (int i = posStart; i <posEnd; i++)
{
if(!isS(buf[ i ])) return false;
}
return true;
}
} else if(eventType == IGNORABLE_WHITESPACE) {
return true;
}
throw new XmlPullParserException("no content available to check for whitespaces");
}
public String getText()
{
if(eventType == START_DOCUMENT || eventType == END_DOCUMENT) {
//throw new XmlPullParserException("no content available to read");
// if(roundtripSupported) {
// text = new String(buf, posStart, posEnd - posStart);
// } else {
return null;
} else if(eventType == ENTITY_REF) {
return text;
}
if(text == null) {
if(!usePC || eventType == START_TAG || eventType == END_TAG) {
text = new String(buf, posStart, posEnd - posStart);
} else {
text = new String(pc, pcStart, pcEnd - pcStart);
}
}
return text;
}
public char[] getTextCharacters(int [] holderForStartAndLength)
{
if( eventType == TEXT ) {
if(usePC) {
holderForStartAndLength[0] = pcStart;
holderForStartAndLength[1] = pcEnd - pcStart;
return pc;
} else {
holderForStartAndLength[0] = posStart;
holderForStartAndLength[1] = posEnd - posStart;
return buf;
}
} else if( eventType == START_TAG
|| eventType == END_TAG
|| eventType == CDSECT
|| eventType == COMMENT
|| eventType == ENTITY_REF
|| eventType == PROCESSING_INSTRUCTION
|| eventType == IGNORABLE_WHITESPACE
|| eventType == DOCDECL)
{
holderForStartAndLength[0] = posStart;
holderForStartAndLength[1] = posEnd - posStart;
return buf;
} else if(eventType == START_DOCUMENT
|| eventType == END_DOCUMENT) {
//throw new XmlPullParserException("no content available to read");
holderForStartAndLength[0] = holderForStartAndLength[1] = -1;
return null;
} else {
throw new IllegalArgumentException("unknown text eventType: "+eventType);
}
// String s = getText();
// char[] cb = null;
// if(s!= null) {
// cb = s.toCharArray();
// holderForStartAndLength[0] = 0;
// holderForStartAndLength[1] = s.length();
// } else {
// return cb;
}
public String getNamespace()
{
if(eventType == START_TAG) {
//return processNamespaces ? elUri[ depth - 1 ] : NO_NAMESPACE;
return processNamespaces ? elUri[ depth ] : NO_NAMESPACE;
} else if(eventType == END_TAG) {
return processNamespaces ? elUri[ depth ] : NO_NAMESPACE;
}
return null;
// String prefix = elPrefix[ maxDepth ];
// if(prefix != null) {
// for( int i = namespaceEnd -1; i >= 0; i--) {
// if( prefix.equals( namespacePrefix[ i ] ) ) {
// return namespaceUri[ i ];
// } else {
// for( int i = namespaceEnd -1; i >= 0; i--) {
// if( namespacePrefix[ i ] == null ) {
// return namespaceUri[ i ];
// return "";
}
public String getName()
{
if(eventType == START_TAG) {
//return elName[ depth - 1 ] ;
return elName[ depth ] ;
} else if(eventType == END_TAG) {
return elName[ depth ] ;
} else if(eventType == ENTITY_REF) {
if(entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
return entityRefName;
} else {
return null;
}
}
public String getPrefix()
{
if(eventType == START_TAG) {
//return elPrefix[ depth - 1 ] ;
return elPrefix[ depth ] ;
} else if(eventType == END_TAG) {
return elPrefix[ depth ] ;
}
return null;
// if(eventType != START_TAG && eventType != END_TAG) return null;
// int maxDepth = eventType == END_TAG ? depth : depth - 1;
// return elPrefix[ maxDepth ];
}
public boolean isEmptyElementTag() throws XmlPullParserException
{
if(eventType != START_TAG) throw new XmlPullParserException(
"parser must be on START_TAG to check for empty element", this, null);
return emptyElementTag;
}
public int getAttributeCount()
{
if(eventType != START_TAG) return -1;
return attributeCount;
}
public String getAttributeNamespace(int index)
{
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(processNamespaces == false) return NO_NAMESPACE;
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return attributeUri[ index ];
}
public String getAttributeName(int index)
{
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return attributeName[ index ];
}
public String getAttributePrefix(int index)
{
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(processNamespaces == false) return null;
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return attributePrefix[ index ];
}
public String getAttributeType(int index) {
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return "CDATA";
}
public boolean isAttributeDefault(int index) {
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return false;
}
public String getAttributeValue(int index)
{
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.."+(attributeCount-1)+" and not "+index);
return attributeValue[ index ];
}
public String getAttributeValue(String namespace,
String name)
{
if(eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes"+getPositionDescription());
if(name == null) {
throw new IllegalArgumentException("attribute name can not be null");
}
// TODO make check if namespace is interned!!! etc. for names!!!
if(processNamespaces) {
if(namespace == null) {
namespace = "";
}
for(int i = 0; i < attributeCount; ++i) {
if((namespace == attributeUri[ i ] ||
namespace.equals(attributeUri[ i ]) )
//(namespace != null && namespace.equals(attributeUri[ i ]))
// taking advantage of String.intern()
&& name.equals(attributeName[ i ]) )
{
return attributeValue[i];
}
}
} else {
if(namespace != null && namespace.length() == 0) {
namespace = null;
}
if(namespace != null) throw new IllegalArgumentException(
"when namespaces processing is disabled attribute namespace must be null");
for(int i = 0; i < attributeCount; ++i) {
if(name.equals(attributeName[i]))
{
return attributeValue[i];
}
}
}
return null;
}
public int getEventType()
throws XmlPullParserException
{
return eventType;
}
public void require(int type, String namespace, String name)
throws XmlPullParserException, IOException
{
if(processNamespaces == false && namespace != null) {
throw new XmlPullParserException(
"processing namespaces must be enabled on parser (or factory)"+
" to have possible namespaces delcared on elements"
+(" (postion:"+ getPositionDescription())+")");
}
if (type != getEventType()
|| (namespace != null && !namespace.equals (getNamespace()))
|| (name != null && !name.equals (getName ())) )
{
throw new XmlPullParserException (
"expected event "+TYPES[ type ]
+(name != null ? " with name '"+name+"'" : "")
+(namespace != null && name != null ? " and" : "")
+(namespace != null ? " with namespace '"+namespace+"'" : "")
+" but got"
+(type != getEventType() ? " "+TYPES[ getEventType() ] : "")
+(name != null && getName() != null && !name.equals (getName ())
? " name '"+getName()+"'" : "")
+(namespace != null && name != null
&& getName() != null && !name.equals (getName ())
&& getNamespace() != null && !namespace.equals (getNamespace())
? " and" : "")
+(namespace != null && getNamespace() != null && !namespace.equals (getNamespace())
? " namespace '"+getNamespace()+"'" : "")
+(" (postion:"+ getPositionDescription())+")");
}
}
/**
* Skip sub tree that is currently porser positioned on.
* <br>NOTE: parser must be on START_TAG and when funtion returns
* parser will be positioned on corresponding END_TAG
*/
public void skipSubTree()
throws XmlPullParserException, IOException
{
require(START_TAG, null, null);
int level = 1;
while(level > 0) {
int eventType = next();
if(eventType == END_TAG) {
--level;
} else if(eventType == START_TAG) {
++level;
}
}
}
// public String readText() throws XmlPullParserException, IOException
// if (getEventType() != TEXT) return "";
// String result = getText();
// next();
// return result;
public String nextText() throws XmlPullParserException, IOException
{
// String result = null;
// boolean onStartTag = false;
// if(eventType == START_TAG) {
// onStartTag = true;
// next();
// if(eventType == TEXT) {
// result = getText();
// next();
// } else if(onStartTag && eventType == END_TAG) {
// result = "";
// } else {
// throw new XmlPullParserException(
// "parser must be on START_TAG or TEXT to read text", this, null);
// if(eventType != END_TAG) {
// throw new XmlPullParserException(
// "event TEXT it must be immediately followed by END_TAG", this, null);
// return result;
if(getEventType() != START_TAG) {
throw new XmlPullParserException(
"parser must be on START_TAG to read next text", this, null);
}
int eventType = next();
if(eventType == TEXT) {
final String result = getText();
eventType = next();
if(eventType != END_TAG) {
throw new XmlPullParserException(
"TEXT must be immediately followed by END_TAG and not "
+TYPES[ getEventType() ], this, null);
}
return result;
} else if(eventType == END_TAG) {
return "";
} else {
throw new XmlPullParserException(
"parser must be on START_TAG or TEXT to read text", this, null);
}
}
public int nextTag() throws XmlPullParserException, IOException
{
next();
if(eventType == TEXT && isWhitespace()) { // skip whitespace
next();
}
if (eventType != START_TAG && eventType != END_TAG) {
throw new XmlPullParserException("expected START_TAG or END_TAG not "
+TYPES[ getEventType() ], this, null);
}
return eventType;
}
public int next()
throws XmlPullParserException, IOException
{
tokenize = false;
return nextImpl();
}
public int nextToken()
throws XmlPullParserException, IOException
{
tokenize = true;
return nextImpl();
}
protected int nextImpl()
throws XmlPullParserException, IOException
{
text = null;
pcEnd = pcStart = 0;
usePC = false;
bufStart = posEnd;
if(pastEndTag) {
pastEndTag = false;
--depth;
namespaceEnd = elNamespaceCount[ depth ]; // less namespaces available
}
if(emptyElementTag) {
emptyElementTag = false;
pastEndTag = true;
return eventType = END_TAG;
}
// [1] document ::= prolog element Misc*
if(depth > 0) {
if(seenStartTag) {
seenStartTag = false;
return eventType = parseStartTag();
}
if(seenEndTag) {
seenEndTag = false;
return eventType = parseEndTag();
}
// ASSUMPTION: we are _on_ first character of content or markup!!!!
// [43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*
char ch;
if(seenMarkup) { // we have read ahead ...
seenMarkup = false;
ch = '<';
} else if(seenAmpersand) {
seenAmpersand = false;
ch = '&';
} else {
ch = more();
}
posStart = pos - 1; // VERY IMPORTANT: this is correct start of event!!!
// when true there is some potential event TEXT to return - keep gathering
boolean hadCharData = false;
// when true TEXT data is not continuous (like <![CDATA[text]]>) and requires PC merging
boolean needsMerging = false;
MAIN_LOOP:
while(true) {
// work on MARKUP
if(ch == '<') {
if(hadCharData) {
//posEnd = pos - 1;
if(tokenize) {
seenMarkup = true;
return eventType = TEXT;
}
}
ch = more();
if(ch == '/') {
if(!tokenize && hadCharData) {
seenEndTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseEndTag();
} else if(ch == '!') {
ch = more();
if(ch == '-') {
// note: if(tokenize == false) posStart/End is NOT changed!!!!
parseComment();
if(tokenize) return eventType = COMMENT;
if( !usePC && hadCharData ) {
needsMerging = true;
} else {
posStart = pos; //completely ignore comment
}
} else if(ch == '[') {
//posEnd = pos - 3;
// must remember previous posStart/End as it merges with content of CDATA
//int oldStart = posStart + bufAbsoluteStart;
//int oldEnd = posEnd + bufAbsoluteStart;
parseCDSect(hadCharData);
if(tokenize) return eventType = CDSECT;
final int cdStart = posStart;
final int cdEnd = posEnd;
final int cdLen = cdEnd - cdStart;
if(cdLen > 0) { // was there anything inside CDATA section?
hadCharData = true;
if(!usePC) {
needsMerging = true;
}
}
// posStart = oldStart;
// posEnd = oldEnd;
// if(cdLen > 0) { // was there anything inside CDATA section?
// if(hadCharData) {
// // do merging if there was anything in CDSect!!!!
// // if(!usePC) {
// // // posEnd is correct already!!!
// // if(posEnd > posStart) {
// // joinPC();
// // } else {
// // usePC = true;
// // pcStart = pcEnd = 0;
// // if(pcEnd + cdLen >= pc.length) ensurePC(pcEnd + cdLen);
// // // copy [cdStart..cdEnd) into PC
// // System.arraycopy(buf, cdStart, pc, pcEnd, cdLen);
// // pcEnd += cdLen;
// if(!usePC) {
// needsMerging = true;
// posStart = cdStart;
// posEnd = cdEnd;
// } else {
// if(!usePC) {
// needsMerging = true;
// posStart = cdStart;
// posEnd = cdEnd;
// hadCharData = true;
// //hadCharData = true;
// } else {
// if( !usePC && hadCharData ) {
// needsMerging = true;
} else {
throw new XmlPullParserException(
"unexpected character in markup "+printable(ch), this, null);
}
} else if(ch == '?') {
parsePI();
if(tokenize) return eventType = PROCESSING_INSTRUCTION;
if( !usePC && hadCharData ) {
needsMerging = true;
} else {
posStart = pos; //completely ignore PI
}
} else if( isNameStartChar(ch) ) {
if(!tokenize && hadCharData) {
seenStartTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseStartTag();
} else {
throw new XmlPullParserException(
"unexpected character in markup "+printable(ch), this, null);
}
// do content comapctation if it makes sense!!!!
} else if(ch == '&') {
// work on ENTITTY
//posEnd = pos - 1;
if(tokenize && hadCharData) {
seenAmpersand = true;
return eventType = TEXT;
}
final int oldStart = posStart + bufAbsoluteStart;
final int oldEnd = posEnd + bufAbsoluteStart;
final char[] resolvedEntity = parseEntityRef();
if(tokenize) return eventType = ENTITY_REF;
// check if replacement text can be resolved !!!
if(resolvedEntity == null) {
if(entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
throw new XmlPullParserException(
"could not resolve entity named '"+printable(entityRefName)+"'",
this, null);
}
//int entStart = posStart;
//int entEnd = posEnd;
posStart = oldStart - bufAbsoluteStart;
posEnd = oldEnd - bufAbsoluteStart;
if(!usePC) {
if(hadCharData) {
joinPC(); // posEnd is already set correctly!!!
needsMerging = false;
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
// write into PC replacement text - do merge for replacement text!!!!
for (int i = 0; i < resolvedEntity.length; i++)
{
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = resolvedEntity[ i ];
}
hadCharData = true;
//assert needsMerging == false;
} else {
if(needsMerging) {
//assert usePC == false;
joinPC(); // posEnd is already set correctly!!!
//posStart = pos - 1;
needsMerging = false;
}
//no MARKUP not ENTITIES so work on character data ...
// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
hadCharData = true;
boolean normalizedCR = false;
final boolean normalizeInput = tokenize == false || roundtripSupported == false;
// use loop locality here!!!!
boolean seenBracket = false;
boolean seenBracketBracket = false;
do {
// check that ]]> does not show in
if(ch == ']') {
if(seenBracket) {
seenBracketBracket = true;
} else {
seenBracket = true;
}
} else if(seenBracketBracket && ch == '>') {
throw new XmlPullParserException(
"characters ]]> are not allowed in content", this, null);
} else {
if(seenBracket) {
seenBracketBracket = seenBracket = false;
}
// assert seenTwoBrackets == seenBracket == false;
}
if(normalizeInput) {
// deal with normalization issues ...
if(ch == '\r') {
normalizedCR = true;
posEnd = pos -1;
// posEnd is already set
if(!usePC) {
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
// if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); }
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
ch = more();
} while(ch != '<' && ch != '&');
posEnd = pos - 1;
continue MAIN_LOOP; // skip ch = more() from below - we are already ahead ...
}
ch = more();
} // endless while(true)
} else {
if(seenRoot) {
return parseEpilog();
} else {
return parseProlog();
}
}
}
protected int parseProlog()
throws XmlPullParserException, IOException
{
// [2] prolog: ::= XMLDecl? Misc* (doctypedecl Misc*)? and look for [39] element
char ch;
if(seenMarkup) {
ch = buf[ pos - 1 ];
} else {
ch = more();
}
if(eventType == START_DOCUMENT) {
// bootstrap parsing with getting first character input!
// deal with BOM
// detect BOM and crop it (Unicode int Order Mark)
if(ch == '\uFFFE') {
throw new XmlPullParserException(
"first character in input was UNICODE noncharacter (0xFFFE)"+
"- input requires int swapping", this, null);
}
if(ch == '\uFEFF') {
// skipping UNICODE int Order Mark (so called BOM)
ch = more();
}
}
seenMarkup = false;
boolean gotS = false;
posStart = pos - 1;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
while(true) {
// deal with Misc
// [27] Misc ::= Comment | PI | S
// deal with docdecl --> mark it!
// else parseStartTag seen <[^/]
if(ch == '<') {
if(gotS && tokenize) {
posEnd = pos - 1;
seenMarkup = true;
return eventType = IGNORABLE_WHITESPACE;
}
ch = more();
if(ch == '?') {
// check if it is 'xml'
// deal with XMLDecl
boolean isXMLDecl = parsePI();
if(tokenize) {
if (isXMLDecl) {
return eventType = START_DOCUMENT;
}
return eventType = PROCESSING_INSTRUCTION;
}
} else if(ch == '!') {
ch = more();
if(ch == 'D') {
if(seenDocdecl) {
throw new XmlPullParserException(
"only one docdecl allowed in XML document", this, null);
}
seenDocdecl = true;
parseDocdecl();
if(tokenize) return eventType = DOCDECL;
} else if(ch == '-') {
parseComment();
if(tokenize) return eventType = COMMENT;
} else {
throw new XmlPullParserException(
"unexpected markup <!"+printable(ch), this, null);
}
} else if(ch == '/') {
throw new XmlPullParserException(
"expected start tag name and not "+printable(ch), this, null);
} else if(isNameStartChar(ch)) {
seenRoot = true;
return parseStartTag();
} else {
throw new XmlPullParserException(
"expected start tag name and not "+printable(ch), this, null);
}
} else if(isS(ch)) {
gotS = true;
if(normalizeIgnorableWS) {
if(ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is already set
if(!usePC) {
posEnd = pos -1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
} else {
throw new XmlPullParserException(
"only whitespace content allowed before start tag and not "+printable(ch),
this, null);
}
ch = more();
}
}
protected int parseEpilog()
throws XmlPullParserException, IOException
{
if(eventType == END_DOCUMENT) {
throw new XmlPullParserException("already reached end of XML input", this, null);
}
if(reachedEnd) {
return eventType = END_DOCUMENT;
}
boolean gotS = false;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
try {
// epilog: Misc*
char ch;
if(seenMarkup) {
ch = buf[ pos - 1 ];
} else {
ch = more();
}
seenMarkup = false;
posStart = pos - 1;
if(!reachedEnd) {
while(true) {
// deal with Misc
// [27] Misc ::= Comment | PI | S
if(ch == '<') {
if(gotS && tokenize) {
posEnd = pos - 1;
seenMarkup = true;
return eventType = IGNORABLE_WHITESPACE;
}
ch = more();
if(reachedEnd) {
break;
}
if(ch == '?') {
// check if it is 'xml'
// deal with XMLDecl
parsePI();
if(tokenize) return eventType = PROCESSING_INSTRUCTION;
} else if(ch == '!') {
ch = more();
if(reachedEnd) {
break;
}
if(ch == 'D') {
parseDocdecl(); //FIXME
if(tokenize) return eventType = DOCDECL;
} else if(ch == '-') {
parseComment();
if(tokenize) return eventType = COMMENT;
} else {
throw new XmlPullParserException(
"unexpected markup <!"+printable(ch), this, null);
}
} else if(ch == '/') {
throw new XmlPullParserException(
"end tag not allowed in epilog but got "+printable(ch), this, null);
} else if(isNameStartChar(ch)) {
throw new XmlPullParserException(
"start tag not allowed in epilog but got "+printable(ch), this, null);
} else {
throw new XmlPullParserException(
"in epilog expected ignorable content and not "+printable(ch),
this, null);
}
} else if(isS(ch)) {
gotS = true;
if(normalizeIgnorableWS) {
if(ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is already set
if(!usePC) {
posEnd = pos -1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
} else {
throw new XmlPullParserException(
"in epilog non whitespace content is not allowed but got "+printable(ch),
this, null);
}
ch = more();
if(reachedEnd) {
break;
}
}
}
// throw Exception("unexpected content in epilog
// catch EOFException return END_DOCUMENT
//try {
} catch(EOFException ex) {
reachedEnd = true;
}
if(reachedEnd) {
if(tokenize && gotS) {
posEnd = pos; // well - this is LAST available character pos
return eventType = IGNORABLE_WHITESPACE;
}
return eventType = END_DOCUMENT;
} else {
throw new XmlPullParserException("internal error in parseEpilog");
}
}
public int parseEndTag() throws XmlPullParserException, IOException {
//ASSUMPTION ch is past "</"
// [42] ETag ::= '</' Name S? '>'
char ch = more();
if(!isNameStartChar(ch)) {
throw new XmlPullParserException(
"expected name start and not "+printable(ch), this, null);
}
posStart = pos - 3;
final int nameStart = pos - 1 + bufAbsoluteStart;
do {
ch = more();
} while(isNameChar(ch));
// now we go one level down -- do checks
//--depth; //FIXME
// check that end tag name is the same as start tag
//String name = new String(buf, nameStart - bufAbsoluteStart,
// (pos - 1) - (nameStart - bufAbsoluteStart));
//int last = pos - 1;
int off = nameStart - bufAbsoluteStart;
//final int len = last - off;
final int len = (pos - 1) - off;
final char[] cbuf = elRawName[depth];
if(elRawNameEnd[depth] != len) {
// construct strings for exception
final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
final String endname = new String(buf, off, len);
throw new XmlPullParserException(
"end tag name </"+endname+"> must match start tag name <"+startname+">"
+" from line "+elRawNameLine[depth], this, null);
}
for (int i = 0; i < len; i++)
{
if(buf[off++] != cbuf[i]) {
// construct strings for exception
final String startname = new String(cbuf, 0, len);
final String endname = new String(buf, off - i - 1, len);
throw new XmlPullParserException(
"end tag name </"+endname+"> must be the same as start tag <"+startname+">"
+" from line "+elRawNameLine[depth], this, null);
}
}
while(isS(ch)) { ch = more(); } // skip additional white spaces
if(ch != '>') {
throw new XmlPullParserException(
"expected > to finsh end tag not "+printable(ch)
+" from line "+elRawNameLine[depth], this, null);
}
//namespaceEnd = elNamespaceCount[ depth ]; //FIXME
posEnd = pos;
pastEndTag = true;
return eventType = END_TAG;
}
public int parseStartTag() throws XmlPullParserException, IOException {
//ASSUMPTION ch is past <T
// [40] STag ::= '<' Name (S Attribute)* S? '>'
// [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
++depth; //FIXME
posStart = pos - 2;
emptyElementTag = false;
attributeCount = 0;
// retrieve name
final int nameStart = pos - 1 + bufAbsoluteStart;
int colonPos = -1;
char ch = buf[ pos - 1];
if(ch == ':' && processNamespaces) throw new XmlPullParserException(
"when namespaces processing enabled colon can not be at element name start",
this, null);
while(true) {
ch = more();
if(!isNameChar(ch)) break;
if(ch == ':' && processNamespaces) {
if(colonPos != -1) throw new XmlPullParserException(
"only one colon is allowed in name of element when namespaces are enabled",
this, null);
colonPos = pos - 1 + bufAbsoluteStart;
}
}
// retrieve name
ensureElementsCapacity();
//TODO check for efficient interning and then use elRawNameInterned!!!!
int elLen = (pos - 1) - (nameStart - bufAbsoluteStart);
if(elRawName[ depth ] == null || elRawName[ depth ].length < elLen) {
elRawName[ depth ] = new char[ 2 * elLen ];
}
System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[ depth ], 0, elLen);
elRawNameEnd[ depth ] = elLen;
elRawNameLine[ depth ] = lineNumber;
String name = null;
// work on prefixes and namespace URI
String prefix = null;
if(processNamespaces) {
if(colonPos != -1) {
prefix = elPrefix[ depth ] = newString(buf, nameStart - bufAbsoluteStart,
colonPos - nameStart);
name = elName[ depth ] = newString(buf, colonPos + 1 - bufAbsoluteStart,
//(pos -1) - (colonPos + 1));
pos - 2 - (colonPos - bufAbsoluteStart));
} else {
prefix = elPrefix[ depth ] = null;
name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen);
}
} else {
name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen);
}
while(true) {
while(isS(ch)) { ch = more(); } // skip additional white spaces
if(ch == '>') {
break;
} else if(ch == '/') {
if(emptyElementTag) throw new XmlPullParserException(
"repeated / in tag declaration", this, null);
emptyElementTag = true;
ch = more();
if(ch != '>') throw new XmlPullParserException(
"expected > to end empty tag not "+printable(ch), this, null);
break;
} else if(isNameStartChar(ch)) {
ch = parseAttribute();
ch = more();
continue;
} else {
throw new XmlPullParserException(
"start tag unexpected character "+printable(ch), this, null);
}
//ch = more(); // skip space
}
// now when namespaces were declared we can resolve them
if(processNamespaces) {
String uri = getNamespace(prefix);
if(uri == null) {
if(prefix == null) { // no prefix and no uri => use default namespace
uri = NO_NAMESPACE;
} else {
throw new XmlPullParserException(
"could not determine namespace bound to element prefix "+prefix,
this, null);
}
}
elUri[ depth ] = uri;
//String uri = getNamespace(prefix);
//if(uri == null && prefix == null) { // no prefix and no uri => use default namespace
// uri = "";
// resolve attribute namespaces
for (int i = 0; i < attributeCount; i++)
{
final String attrPrefix = attributePrefix[ i ];
if(attrPrefix != null) {
final String attrUri = getNamespace(attrPrefix);
if(attrUri == null) {
throw new XmlPullParserException(
"could not determine namespace bound to attribute prefix "+attrPrefix,
this, null);
}
attributeUri[ i ] = attrUri;
} else {
attributeUri[ i ] = NO_NAMESPACE;
}
}
//TODO
//[ WFC: Unique Att Spec ]
// check namespaced attribute uniqueness contraint!!!
for (int i = 1; i < attributeCount; i++)
{
for (int j = 0; j < i; j++)
{
if( attributeUri[j] == attributeUri[i]
&& (allStringsInterned && attributeName[j].equals(attributeName[i])
|| (!allStringsInterned
&& attributeNameHash[ j ] == attributeNameHash[ i ]
&& attributeName[j].equals(attributeName[i])) )
) {
// prepare data for nice error messgae?
String attr1 = attributeName[j];
if(attributeUri[j] != null) attr1 = attributeUri[j]+":"+attr1;
String attr2 = attributeName[i];
if(attributeUri[i] != null) attr2 = attributeUri[i]+":"+attr2;
throw new XmlPullParserException(
"duplicated attributes "+attr1+" and "+attr2, this, null);
}
}
}
} else { // ! processNamespaces
//[ WFC: Unique Att Spec ]
// check raw attribute uniqueness contraint!!!
for (int i = 1; i < attributeCount; i++)
{
for (int j = 0; j < i; j++)
{
if((allStringsInterned && attributeName[j].equals(attributeName[i])
|| (!allStringsInterned
&& attributeNameHash[ j ] == attributeNameHash[ i ]
&& attributeName[j].equals(attributeName[i])) )
) {
// prepare data for nice error messgae?
final String attr1 = attributeName[j];
final String attr2 = attributeName[i];
throw new XmlPullParserException(
"duplicated attributes "+attr1+" and "+attr2, this, null);
}
}
}
}
elNamespaceCount[ depth ] = namespaceEnd;
posEnd = pos;
return eventType = START_TAG;
}
protected char parseAttribute() throws XmlPullParserException, IOException
{
// parse attribute
// [41] Attribute ::= Name Eq AttValue
// [WFC: No External Entity References]
// [WFC: No < in Attribute Values]
final int prevPosStart = posStart + bufAbsoluteStart;
final int nameStart = pos - 1 + bufAbsoluteStart;
int colonPos = -1;
char ch = buf[ pos - 1 ];
if(ch == ':' && processNamespaces) throw new XmlPullParserException(
"when namespaces processing enabled colon can not be at attribute name start",
this, null);
boolean startsWithXmlns = processNamespaces && ch == 'x';
int xmlnsPos = 0;
ch = more();
while(isNameChar(ch)) {
if(processNamespaces) {
if(startsWithXmlns && xmlnsPos < 5) {
++xmlnsPos;
if(xmlnsPos == 1) { if(ch != 'm') startsWithXmlns = false; }
else if(xmlnsPos == 2) { if(ch != 'l') startsWithXmlns = false; }
else if(xmlnsPos == 3) { if(ch != 'n') startsWithXmlns = false; }
else if(xmlnsPos == 4) { if(ch != 's') startsWithXmlns = false; }
else if(xmlnsPos == 5) {
if(ch != ':') throw new XmlPullParserException(
"after xmlns in attribute name must be colon"
+"when namespaces are enabled", this, null);
//colonPos = pos - 1 + bufAbsoluteStart;
}
}
if(ch == ':') {
if(colonPos != -1) throw new XmlPullParserException(
"only one colon is allowed in attribute name"
+" when namespaces are enabled", this, null);
colonPos = pos - 1 + bufAbsoluteStart;
}
}
ch = more();
}
ensureAttributesCapacity(attributeCount);
String name = null;
String prefix = null;
// work on prefixes and namespace URI
if(processNamespaces) {
if(xmlnsPos < 4) startsWithXmlns = false;
if(startsWithXmlns) {
if(colonPos != -1) {
//prefix = attributePrefix[ attributeCount ] = null;
final int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
if(nameLen == 0) {
throw new XmlPullParserException(
"namespace prefix is required after xmlns: "
+" when namespaces are enabled", this, null);
}
name = //attributeName[ attributeCount ] =
newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
//pos - 1 - (colonPos + 1 - bufAbsoluteStart)
}
} else {
if(colonPos != -1) {
int prefixLen = colonPos - nameStart;
prefix = attributePrefix[ attributeCount ] =
newString(buf, nameStart - bufAbsoluteStart,prefixLen);
//colonPos - (nameStart - bufAbsoluteStart));
int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
name = attributeName[ attributeCount ] =
newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
//pos - 1 - (colonPos + 1 - bufAbsoluteStart));
//name.substring(0, colonPos-nameStart);
} else {
prefix = attributePrefix[ attributeCount ] = null;
name = attributeName[ attributeCount ] =
newString(buf, nameStart - bufAbsoluteStart,
pos - 1 - (nameStart - bufAbsoluteStart));
}
if(!allStringsInterned) {
attributeNameHash[ attributeCount ] = name.hashCode();
}
}
} else {
// retrieve name
name = attributeName[ attributeCount ] =
newString(buf, nameStart - bufAbsoluteStart,
pos - 1 - (nameStart - bufAbsoluteStart));
////assert name != null;
if(!allStringsInterned) {
attributeNameHash[ attributeCount ] = name.hashCode();
}
}
// [25] Eq ::= S? '=' S?
while(isS(ch)) { ch = more(); } // skip additional spaces
if(ch != '=') throw new XmlPullParserException(
"expected = after attribute name", this, null);
ch = more();
while(isS(ch)) { ch = more(); } // skip additional spaces
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
final char delimit = ch;
if(delimit != '"' && delimit != '\'') throw new XmlPullParserException(
"attribute value must start with quotation or apostrophe not "
+printable(delimit), this, null);
// parse until delimit or < and resolve Reference
//[67] Reference ::= EntityRef | CharRef
//int valueStart = pos + bufAbsoluteStart;
boolean normalizedCR = false;
usePC = false;
pcStart = pcEnd;
posStart = pos;
while(true) {
ch = more();
if(ch == delimit) {
break;
} if(ch == '<') {
throw new XmlPullParserException(
"markup not allowed inside attribute value - illegal < ", this, null);
} if(ch == '&') {
// extractEntityRef
posEnd = pos - 1;
if(!usePC) {
final boolean hadCharData = posEnd > posStart;
if(hadCharData) {
// posEnd is already set correctly!!!
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
final char[] resolvedEntity = parseEntityRef();
// check if replacement text can be resolved !!!
if(resolvedEntity == null) {
if(entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
throw new XmlPullParserException(
"could not resolve entity named '"+printable(entityRefName)+"'",
this, null);
}
// write into PC replacement text - do merge for replacement text!!!!
for (int i = 0; i < resolvedEntity.length; i++)
{
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = resolvedEntity[ i ];
}
} else if(ch == '\t' || ch == '\n' || ch == '\r') {
// do attribute value normalization
// as described in http://www.w3.org/TR/REC-xml#AVNormalize
// TODO add test for it form spec ...
// handle EOL normalization ...
if(!usePC) {
posEnd = pos - 1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcEnd = pcStart = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
if(ch != '\n' || !normalizedCR) {
pc[pcEnd++] = ' ';
}
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
}
normalizedCR = ch == '\r';
}
if(processNamespaces && startsWithXmlns) {
String ns = null;
if(!usePC) {
ns = newStringIntern(buf, posStart, pos - 1 - posStart);
} else {
ns = newStringIntern(pc, pcStart, pcEnd - pcStart);
}
ensureNamespacesCapacity(namespaceEnd);
int prefixHash = -1;
if(colonPos != -1) {
if(ns.length() == 0) {
throw new XmlPullParserException(
"non-default namespace can not be declared to be empty string", this, null);
}
// declare new namespace
namespacePrefix[ namespaceEnd ] = name;
if(!allStringsInterned) {
prefixHash = namespacePrefixHash[ namespaceEnd ] = name.hashCode();
}
} else {
// declare new default namespace...
namespacePrefix[ namespaceEnd ] = null; //""; //null; //TODO check FIXME Alek
if(!allStringsInterned) {
prefixHash = namespacePrefixHash[ namespaceEnd ] = -1;
}
}
namespaceUri[ namespaceEnd ] = ns;
// detect duplicate namespace declarations!!!
final int startNs = elNamespaceCount[ depth - 1 ];
for (int i = namespaceEnd - 1; i >= startNs; --i)
{
if(((allStringsInterned || name == null) && namespacePrefix[ i ] == name)
|| (!allStringsInterned && name != null &&
namespacePrefixHash[ i ] == prefixHash
&& name.equals(namespacePrefix[ i ])
))
{
final String s = name == null ? "default" : "'"+name+"'";
throw new XmlPullParserException(
"duplicated namespace declaration for "+s+" prefix", this, null);
}
}
++namespaceEnd;
} else {
if(!usePC) {
attributeValue[ attributeCount ] =
new String(buf, posStart, pos - 1 - posStart);
} else {
attributeValue[ attributeCount ] =
new String(pc, pcStart, pcEnd - pcStart);
}
++attributeCount;
}
posStart = prevPosStart - bufAbsoluteStart;
return ch;
}
protected char[] charRefOneCharBuf = new char[1];
protected char[] parseEntityRef()
throws XmlPullParserException, IOException
{
// entity reference http://www.w3.org/TR/2000/REC-xml-20001006#NT-Reference
// [67] Reference ::= EntityRef | CharRef
// ASSUMPTION just after &
entityRefName = null;
posStart = pos;
char ch = more();
StringBuffer sb = new StringBuffer();
if(ch == '
// parse character reference
char charRef = 0;
ch = more();
if(ch == 'x') {
//encoded in hex
while(true) {
ch = more();
if(ch >= '0' && ch <= '9') {
charRef = (char)(charRef * 16 + (ch - '0'));
sb.append( ch );
} else if(ch >= 'a' && ch <= 'f') {
charRef = (char)(charRef * 16 + (ch - ('a' - 10)));
sb.append( ch );
} else if(ch >= 'A' && ch <= 'F') {
charRef = (char)(charRef * 16 + (ch - ('A' - 10)));
sb.append( ch );
} else if(ch == ';') {
break;
} else {
throw new XmlPullParserException(
"character reference (with hex value) may not contain "
+printable(ch), this, null);
}
}
} else {
// encoded in decimal
while(true) {
if(ch >= '0' && ch <= '9') {
charRef = (char)(charRef * 10 + (ch - '0'));
} else if(ch == ';') {
break;
} else {
throw new XmlPullParserException(
"character reference (with decimal value) may not contain "
+printable(ch), this, null);
}
ch = more();
}
}
posEnd = pos - 1;
if ( sb.length() > 0 )
{
char[] tmp = toChars( Integer.parseInt( sb.toString(), 16 ) );
charRefOneCharBuf = tmp;
if ( tokenize )
{
text = newString( charRefOneCharBuf, 0, charRefOneCharBuf.length );
}
return charRefOneCharBuf;
}
charRefOneCharBuf[0] = charRef;
if(tokenize) {
text = newString(charRefOneCharBuf, 0, 1);
}
return charRefOneCharBuf;
} else {
// [68] EntityRef ::= '&' Name ';'
// scan anem until ;
if(!isNameStartChar(ch)) {
throw new XmlPullParserException(
"entity reference names can not start with character '"
+printable(ch)+"'", this, null);
}
while(true) {
ch = more();
if(ch == ';') {
break;
}
if(!isNameChar(ch)) {
throw new XmlPullParserException(
"entity reference name can not contain character "
+printable(ch)+"'", this, null);
}
}
posEnd = pos - 1;
// determine what name maps to
final int len = posEnd - posStart;
if(len == 2 && buf[posStart] == 'l' && buf[posStart+1] == 't') {
if(tokenize) {
text = "<";
}
charRefOneCharBuf[0] = '<';
return charRefOneCharBuf;
//if(paramPC || isParserTokenizing) {
// if(pcEnd >= pc.length) ensurePC();
// pc[pcEnd++] = '<';
} else if(len == 3 && buf[posStart] == 'a'
&& buf[posStart+1] == 'm' && buf[posStart+2] == 'p') {
if(tokenize) {
text = "&";
}
charRefOneCharBuf[0] = '&';
return charRefOneCharBuf;
} else if(len == 2 && buf[posStart] == 'g' && buf[posStart+1] == 't') {
if(tokenize) {
text = ">";
}
charRefOneCharBuf[0] = '>';
return charRefOneCharBuf;
} else if(len == 4 && buf[posStart] == 'a' && buf[posStart+1] == 'p'
&& buf[posStart+2] == 'o' && buf[posStart+3] == 's')
{
if(tokenize) {
text = "'";
}
charRefOneCharBuf[0] = '\'';
return charRefOneCharBuf;
} else if(len == 4 && buf[posStart] == 'q' && buf[posStart+1] == 'u'
&& buf[posStart+2] == 'o' && buf[posStart+3] == 't')
{
if(tokenize) {
text = "\"";
}
charRefOneCharBuf[0] = '"';
return charRefOneCharBuf;
} else {
final char[] result = lookuEntityReplacement(len);
if(result != null) {
return result;
}
}
if(tokenize) text = null;
return null;
}
}
protected char[] lookuEntityReplacement(int entitNameLen)
throws XmlPullParserException, IOException
{
if(!allStringsInterned) {
final int hash = fastHash(buf, posStart, posEnd - posStart);
LOOP:
for (int i = entityEnd - 1; i >= 0; --i)
{
if(hash == entityNameHash[ i ] && entitNameLen == entityNameBuf[ i ].length) {
final char[] entityBuf = entityNameBuf[ i ];
for (int j = 0; j < entitNameLen; j++)
{
if(buf[posStart + j] != entityBuf[j]) continue LOOP;
}
if(tokenize) text = entityReplacement[ i ];
return entityReplacementBuf[ i ];
}
}
} else {
entityRefName = newString(buf, posStart, posEnd - posStart);
for (int i = entityEnd - 1; i >= 0; --i)
{
// take advantage that interning for newStirng is enforced
if(entityRefName == entityName[ i ]) {
if(tokenize) text = entityReplacement[ i ];
return entityReplacementBuf[ i ];
}
}
}
return null;
}
protected void parseComment()
throws XmlPullParserException, IOException
{
// implements XML 1.0 Section 2.5 Comments
//ASSUMPTION: seen <!-
char ch = more();
if(ch != '-') throw new XmlPullParserException(
"expected <!-- for comment start", this, null);
if(tokenize) posStart = pos;
final int curLine = lineNumber;
final int curColumn = columnNumber;
try {
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
boolean seenDash = false;
boolean seenDashDash = false;
while(true) {
// scan until it hits -->
ch = more();
if(seenDashDash && ch != '>') {
throw new XmlPullParserException(
"in comment after two dashes (--) next character must be >"
+" not "+printable(ch), this, null);
}
if(ch == '-') {
if(!seenDash) {
seenDash = true;
} else {
seenDashDash = true;
seenDash = false;
}
} else if(ch == '>') {
if(seenDashDash) {
break; // found end sequence!!!!
} else {
seenDashDash = false;
}
seenDash = false;
} else {
seenDash = false;
}
if(normalizeIgnorableWS) {
if(ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is alreadys set
if(!usePC) {
posEnd = pos -1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
} catch(EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"comment started on line "+curLine+" and column "+curColumn+" was not closed",
this, ex);
}
if(tokenize) {
posEnd = pos - 3;
if(usePC) {
pcEnd -= 2;
}
}
}
protected boolean parsePI()
throws XmlPullParserException, IOException
{
// implements XML 1.0 Section 2.6 Processing Instructions
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
//ASSUMPTION: seen <?
if(tokenize) posStart = pos;
final int curLine = lineNumber;
final int curColumn = columnNumber;
int piTargetStart = pos + bufAbsoluteStart;
int piTargetEnd = -1;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
try {
boolean seenQ = false;
char ch = more();
if(isS(ch)) {
throw new XmlPullParserException(
"processing instruction PITarget must be exactly after <? and not white space character",
this, null);
}
while(true) {
// scan until it hits ?>
//ch = more();
if(ch == '?') {
seenQ = true;
} else if(ch == '>') {
if(seenQ) {
break; // found end sequence!!!!
}
seenQ = false;
} else {
if(piTargetEnd == -1 && isS(ch)) {
piTargetEnd = pos - 1 + bufAbsoluteStart;
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
if((piTargetEnd - piTargetStart) == 3) {
if((buf[piTargetStart] == 'x' || buf[piTargetStart] == 'X')
&& (buf[piTargetStart+1] == 'm' || buf[piTargetStart+1] == 'M')
&& (buf[piTargetStart+2] == 'l' || buf[piTargetStart+2] == 'L')
)
{
if(piTargetStart > 3) { //<?xml is allowed as first characters in input ...
throw new XmlPullParserException(
"processing instruction can not have PITarget with reserveld xml name",
this, null);
} else {
if(buf[piTargetStart] != 'x'
&& buf[piTargetStart+1] != 'm'
&& buf[piTargetStart+2] != 'l')
{
throw new XmlPullParserException(
"XMLDecl must have xml name in lowercase",
this, null);
}
}
parseXmlDecl(ch);
if(tokenize) posEnd = pos - 2;
final int off = piTargetStart - bufAbsoluteStart + 3;
final int len = pos - 2 - off;
xmlDeclContent = newString(buf, off, len);
return false;
}
}
}
seenQ = false;
}
if(normalizeIgnorableWS) {
if(ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is alreadys set
if(!usePC) {
posEnd = pos -1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
ch = more();
}
} catch(EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"processing instruction started on line "+curLine+" and column "+curColumn
+" was not closed",
this, ex);
}
if(piTargetEnd == -1) {
piTargetEnd = pos - 2 + bufAbsoluteStart;
//throw new XmlPullParserException(
// "processing instruction must have PITarget name", this, null);
}
piTargetStart -= bufAbsoluteStart;
piTargetEnd -= bufAbsoluteStart;
if(tokenize) {
posEnd = pos - 2;
if(normalizeIgnorableWS) {
--pcEnd;
}
}
return true;
}
// protected final static char[] VERSION = {'v','e','r','s','i','o','n'};
// protected final static char[] NCODING = {'n','c','o','d','i','n','g'};
// protected final static char[] TANDALONE = {'t','a','n','d','a','l','o','n','e'};
// protected final static char[] YES = {'y','e','s'};
// protected final static char[] NO = {'n','o'};
protected final static char[] VERSION = "version".toCharArray();
protected final static char[] NCODING = "ncoding".toCharArray();
protected final static char[] TANDALONE = "tandalone".toCharArray();
protected final static char[] YES = "yes".toCharArray();
protected final static char[] NO = "no".toCharArray();
protected void parseXmlDecl(char ch)
throws XmlPullParserException, IOException
{
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// first make sure that relative positions will stay OK
preventBufferCompaction = true;
bufStart = 0; // necessary to keep pos unchanged during expansion!
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
// parse is positioned just on first S past <?xml
ch = skipS(ch);
ch = requireInput(ch, VERSION);
// [25] Eq ::= S? '=' S?
ch = skipS(ch);
if(ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after version and not "+printable(ch), this, null);
}
ch = more();
ch = skipS(ch);
if(ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after version and not "
+printable(ch), this, null);
}
final char quotChar = ch;
//int versionStart = pos + bufAbsoluteStart; // required if preventBufferCompaction==false
final int versionStart = pos;
ch = more();
// [26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+
while(ch != quotChar) {
if((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9')
&& ch != '_' && ch != '.' && ch != ':' && ch != '-')
{
throw new XmlPullParserException(
"<?xml version value expected to be in ([a-zA-Z0-9_.:] | '-')"
+" not "+printable(ch), this, null);
}
ch = more();
}
final int versionEnd = pos - 1;
parseXmlDeclWithVersion(versionStart, versionEnd);
preventBufferCompaction = false; // allow again buffer commpaction - pos MAY chnage
}
//protected String xmlDeclVersion;
protected void parseXmlDeclWithVersion(int versionStart, int versionEnd)
throws XmlPullParserException, IOException
{
// check version is "1.0"
if((versionEnd - versionStart != 3)
|| buf[versionStart] != '1'
|| buf[versionStart+1] != '.'
|| buf[versionStart+2] != '0')
{
throw new XmlPullParserException(
"only 1.0 is supported as <?xml version not '"
+printable(new String(buf, versionStart, versionEnd - versionStart))+"'", this, null);
}
xmlDeclVersion = newString(buf, versionStart, versionEnd - versionStart);
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
char ch = more();
ch = skipS(ch);
if(ch == 'e') {
ch = more();
ch = requireInput(ch, NCODING);
ch = skipS(ch);
if(ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after encoding and not "+printable(ch), this, null);
}
ch = more();
ch = skipS(ch);
if(ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after encoding and not "
+printable(ch), this, null);
}
final char quotChar = ch;
final int encodingStart = pos;
ch = more();
// [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
if((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))
{
throw new XmlPullParserException(
"<?xml encoding name expected to start with [A-Za-z]"
+" not "+printable(ch), this, null);
}
ch = more();
while(ch != quotChar) {
if((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9')
&& ch != '.' && ch != '_' && ch != '-')
{
throw new XmlPullParserException(
"<?xml encoding value expected to be in ([A-Za-z0-9._] | '-')"
+" not "+printable(ch), this, null);
}
ch = more();
}
final int encodingEnd = pos - 1;
// TODO reconcile with setInput encodingName
inputEncoding = newString(buf, encodingStart, encodingEnd - encodingStart);
ch = more();
}
ch = skipS(ch);
// [32] SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
if(ch == 's') {
ch = more();
ch = requireInput(ch, TANDALONE);
ch = skipS(ch);
if(ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after standalone and not "+printable(ch),
this, null);
}
ch = more();
ch = skipS(ch);
if(ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after encoding and not "
+printable(ch), this, null);
}
char quotChar = ch;
int standaloneStart = pos;
ch = more();
if(ch == 'y') {
ch = requireInput(ch, YES);
//Boolean standalone = new Boolean(true);
xmlDeclStandalone = new Boolean(true);
} else if(ch == 'n') {
ch = requireInput(ch, NO);
//Boolean standalone = new Boolean(false);
xmlDeclStandalone = new Boolean(false);
} else {
throw new XmlPullParserException(
"expected 'yes' or 'no' after standalone and not "
+printable(ch), this, null);
}
if(ch != quotChar) {
throw new XmlPullParserException(
"expected "+quotChar+" after standalone value not "
+printable(ch), this, null);
}
ch = more();
}
ch = skipS(ch);
if(ch != '?') {
throw new XmlPullParserException(
"expected ?> as last part of <?xml not "
+printable(ch), this, null);
}
ch = more();
if(ch != '>') {
throw new XmlPullParserException(
"expected ?> as last part of <?xml not "
+printable(ch), this, null);
}
}
protected void parseDocdecl()
throws XmlPullParserException, IOException
{
//ASSUMPTION: seen <!D
char ch = more();
if(ch != 'O') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if(ch != 'C') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if(ch != 'T') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if(ch != 'Y') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if(ch != 'P') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if(ch != 'E') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
posStart = pos;
// do simple and crude scanning for end of doctype
// [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('['
// (markupdecl | DeclSep)* ']' S?)? '>'
int bracketLevel = 0;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
while(true) {
ch = more();
if(ch == '[') ++bracketLevel;
if(ch == ']') --bracketLevel;
if(ch == '>' && bracketLevel == 0) break;
if(normalizeIgnorableWS) {
if(ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is alreadys set
if(!usePC) {
posEnd = pos -1;
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
posEnd = pos - 1;
}
protected void parseCDSect(boolean hadCharData)
throws XmlPullParserException, IOException
{
// implements XML 1.0 Section 2.7 CDATA Sections
// [18] CDSect ::= CDStart CData CDEnd
// [19] CDStart ::= '<![CDATA['
// [20] CData ::= (Char* - (Char* ']]>' Char*))
// [21] CDEnd ::= ']]>'
//ASSUMPTION: seen <![
char ch = more();
if(ch != 'C') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if(ch != 'D') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if(ch != 'A') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if(ch != 'T') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if(ch != 'A') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if(ch != '[') throw new XmlPullParserException(
"expected <![CDATA[ for comment start", this, null);
//if(tokenize) {
final int cdStart = pos + bufAbsoluteStart;
final int curLine = lineNumber;
final int curColumn = columnNumber;
final boolean normalizeInput = tokenize == false || roundtripSupported == false;
try {
if(normalizeInput) {
if(hadCharData) {
if(!usePC) {
// posEnd is correct already!!!
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
}
}
boolean seenBracket = false;
boolean seenBracketBracket = false;
boolean normalizedCR = false;
while(true) {
// scan until it hits "]]>"
ch = more();
if(ch == ']') {
if(!seenBracket) {
seenBracket = true;
} else {
seenBracketBracket = true;
//seenBracket = false;
}
} else if(ch == '>') {
if(seenBracket && seenBracketBracket) {
break; // found end sequence!!!!
} else {
seenBracketBracket = false;
}
seenBracket = false;
} else {
if(seenBracket) {
seenBracket = false;
}
}
if(normalizeInput) {
// deal with normalization issues ...
if(ch == '\r') {
normalizedCR = true;
posStart = cdStart - bufAbsoluteStart;
posEnd = pos - 1; // posEnd is alreadys set
if(!usePC) {
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
} catch(EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"CDATA section started on line "+curLine+" and column "+curColumn+" was not closed",
this, ex);
}
if(normalizeInput) {
if(usePC) {
pcEnd = pcEnd - 2;
}
}
posStart = cdStart - bufAbsoluteStart;
posEnd = pos - 3;
}
protected void fillBuf() throws IOException, XmlPullParserException {
if(reader == null) throw new XmlPullParserException(
"reader must be set before parsing is started");
// see if we are in compaction area
if(bufEnd > bufSoftLimit) {
// expand buffer it makes sense!!!!
boolean compact = bufStart > bufSoftLimit;
boolean expand = false;
if(preventBufferCompaction) {
compact = false;
expand = true;
} else if(!compact) {
//freeSpace
if(bufStart < buf.length / 2) {
// less then half buffer available forcompactin --> expand instead!!!
expand = true;
} else {
// at least half of buffer can be reclaimed --> worthwhile effort!!!
compact = true;
}
}
// if buffer almost full then compact it
if(compact) {
//TODO: look on trashing
// //assert bufStart > 0
System.arraycopy(buf, bufStart, buf, 0, bufEnd - bufStart);
if(TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() compacting "+bufStart
+" bufEnd="+bufEnd
+" pos="+pos+" posStart="+posStart+" posEnd="+posEnd
+" buf first 100 chars:"+new String(buf, bufStart,
bufEnd - bufStart < 100 ? bufEnd - bufStart : 100 ));
} else if(expand) {
final int newSize = 2 * buf.length;
final char newBuf[] = new char[ newSize ];
if(TRACE_SIZING) System.out.println("TRACE_SIZING fillBuf() "+buf.length+" => "+newSize);
System.arraycopy(buf, bufStart, newBuf, 0, bufEnd - bufStart);
buf = newBuf;
if(bufLoadFactor > 0) {
bufSoftLimit = ( bufLoadFactor * buf.length ) /100;
}
} else {
throw new XmlPullParserException("internal error in fillBuffer()");
}
bufEnd -= bufStart;
pos -= bufStart;
posStart -= bufStart;
posEnd -= bufStart;
bufAbsoluteStart += bufStart;
bufStart = 0;
if(TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() after bufEnd="+bufEnd
+" pos="+pos+" posStart="+posStart+" posEnd="+posEnd
+" buf first 100 chars:"+new String(buf, 0, bufEnd < 100 ? bufEnd : 100));
}
// at least one charcter must be read or error
final int len = buf.length - bufEnd > READ_CHUNK_SIZE ? READ_CHUNK_SIZE : buf.length - bufEnd;
final int ret = reader.read(buf, bufEnd, len);
if(ret > 0) {
bufEnd += ret;
if(TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() after filling in buffer"
+" buf first 100 chars:"+new String(buf, 0, bufEnd < 100 ? bufEnd : 100));
return;
}
if(ret == -1) {
if(bufAbsoluteStart == 0 && pos == 0) {
throw new EOFException("input contained no data");
} else {
if(seenRoot && depth == 0) { // inside parsing epilog!!!
reachedEnd = true;
return;
} else {
StringBuffer expectedTagStack = new StringBuffer();
if(depth > 0) {
//final char[] cbuf = elRawName[depth];
//final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
expectedTagStack.append(" - expected end tag");
if(depth > 1) {
expectedTagStack.append("s"); //more than one end tag
}
expectedTagStack.append(" ");
for (int i = depth; i > 0; i
{
String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
expectedTagStack.append("</").append(tagName).append('>');
}
expectedTagStack.append(" to close");
for (int i = depth; i > 0; i
{
if(i != depth) {
expectedTagStack.append(" and"); //more than one end tag
}
String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
expectedTagStack.append(" start tag <"+tagName+">");
expectedTagStack.append(" from line "+elRawNameLine[i]);
}
expectedTagStack.append(", parser stopped on");
}
throw new EOFException("no more data available"
+expectedTagStack.toString()+getPositionDescription());
}
}
} else {
throw new IOException("error reading input, returned "+ret);
}
}
protected char more() throws IOException, XmlPullParserException {
if(pos >= bufEnd) {
fillBuf();
// this return value should be ignonored as it is used in epilog parsing ...
if(reachedEnd) return (char)-1;
}
final char ch = buf[pos++];
//line/columnNumber
if(ch == '\n') { ++lineNumber; columnNumber = 1; }
else { ++columnNumber; }
//System.out.print(ch);
return ch;
}
// /**
// * This function returns position of parser in XML input stream
// * (how many <b>characters</b> were processed.
// * <p><b>NOTE:</b> this logical position and not byte offset as encodings
// * such as UTF8 may use more than one byte to encode one character.
// */
// public int getCurrentInputPosition() {
// return pos + bufAbsoluteStart;
protected void ensurePC(int end) {
//assert end >= pc.length;
final int newSize = end > READ_CHUNK_SIZE ? 2 * end : 2 * READ_CHUNK_SIZE;
final char[] newPC = new char[ newSize ];
if(TRACE_SIZING) System.out.println("TRACE_SIZING ensurePC() "+pc.length+" ==> "+newSize+" end="+end);
System.arraycopy(pc, 0, newPC, 0, pcEnd);
pc = newPC;
//assert end < pc.length;
}
protected void joinPC() {
//assert usePC == false;
//assert posEnd > posStart;
final int len = posEnd - posStart;
final int newEnd = pcEnd + len + 1;
if(newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char
//assert newEnd < pc.length;
System.arraycopy(buf, posStart, pc, pcEnd, len);
pcEnd += len;
usePC = true;
}
protected char requireInput(char ch, char[] input)
throws XmlPullParserException, IOException
{
for (int i = 0; i < input.length; i++)
{
if(ch != input[i]) {
throw new XmlPullParserException(
"expected "+printable(input[i])+" in "+new String(input)
+" and not "+printable(ch), this, null);
}
ch = more();
}
return ch;
}
protected char requireNextS()
throws XmlPullParserException, IOException
{
final char ch = more();
if(!isS(ch)) {
throw new XmlPullParserException(
"white space is required and not "+printable(ch), this, null);
}
return skipS(ch);
}
protected char skipS(char ch)
throws XmlPullParserException, IOException
{
while(isS(ch)) { ch = more(); } // skip additional spaces
return ch;
}
protected static final int LOOKUP_MAX = 0x400;
protected static final char LOOKUP_MAX_CHAR = (char)LOOKUP_MAX;
// protected static int lookupNameStartChar[] = new int[ LOOKUP_MAX_CHAR / 32 ];
// protected static int lookupNameChar[] = new int[ LOOKUP_MAX_CHAR / 32 ];
protected static boolean lookupNameStartChar[] = new boolean[ LOOKUP_MAX ];
protected static boolean lookupNameChar[] = new boolean[ LOOKUP_MAX ];
private static final void setName(char ch)
//{ lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); }
{ lookupNameChar[ ch ] = true; }
private static final void setNameStart(char ch)
//{ lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); }
{ lookupNameStartChar[ ch ] = true; setName(ch); }
static {
setNameStart(':');
for (char ch = 'A'; ch <= 'Z'; ++ch) setNameStart(ch);
setNameStart('_');
for (char ch = 'a'; ch <= 'z'; ++ch) setNameStart(ch);
for (char ch = '\u00c0'; ch <= '\u02FF'; ++ch) setNameStart(ch);
for (char ch = '\u0370'; ch <= '\u037d'; ++ch) setNameStart(ch);
for (char ch = '\u037f'; ch < '\u0400'; ++ch) setNameStart(ch);
setName('-');
setName('.');
for (char ch = '0'; ch <= '9'; ++ch) setName(ch);
setName('\u00b7');
for (char ch = '\u0300'; ch <= '\u036f'; ++ch) setName(ch);
}
//private final static boolean isNameStartChar(char ch) {
protected boolean isNameStartChar(char ch) {
return (ch < LOOKUP_MAX_CHAR && lookupNameStartChar[ ch ])
|| (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027')
|| (ch >= '\u202A' && ch <= '\u218F')
|| (ch >= '\u2800' && ch <= '\uFFEF')
;
// if(ch < LOOKUP_MAX_CHAR) return lookupNameStartChar[ ch ];
// else return ch <= '\u2027'
// || (ch >= '\u202A' && ch <= '\u218F')
// || (ch >= '\u2800' && ch <= '\uFFEF')
//return false;
// return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':'
// || (ch >= '0' && ch <= '9');
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
// if(ch <= '\u2027') return true;
// //[#x202A-#x218F]
// if(ch < '\u202A') return false;
// if(ch <= '\u218F') return true;
// // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF]
// if(ch < '\u2800') return false;
// if(ch <= '\uFFEF') return true;
// return false;
// else return (supportXml11 && ( (ch < '\u2027') || (ch > '\u2029' && ch < '\u2200') ...
}
//private final static boolean isNameChar(char ch) {
protected boolean isNameChar(char ch) {
//return isNameStartChar(ch);
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
return (ch < LOOKUP_MAX_CHAR && lookupNameChar[ ch ])
|| (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027')
|| (ch >= '\u202A' && ch <= '\u218F')
|| (ch >= '\u2800' && ch <= '\uFFEF')
;
//return false;
// return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':'
// || (ch >= '0' && ch <= '9');
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
//else return
// else if(ch <= '\u2027') return true;
// //[#x202A-#x218F]
// else if(ch < '\u202A') return false;
// else if(ch <= '\u218F') return true;
// // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF]
// else if(ch < '\u2800') return false;
// else if(ch <= '\uFFEF') return true;
//else return false;
}
protected boolean isS(char ch) {
return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
// || (supportXml11 && (ch == '\u0085' || ch == '\u2028');
}
//protected boolean isChar(char ch) { return (ch < '\uD800' || ch > '\uDFFF')
// ch != '\u0000' ch < '\uFFFE'
//protected char printable(char ch) { return ch; }
protected String printable(char ch) {
if(ch == '\n') {
return "\\n";
} else if(ch == '\r') {
return "\\r";
} else if(ch == '\t') {
return "\\t";
} else if(ch == '\'') {
return "\\'";
} if(ch > 127 || ch < 32) {
return "\\u"+Integer.toHexString((int)ch);
}
return ""+ch;
}
protected String printable(String s) {
if(s == null) return null;
final int sLen = s.length();
StringBuffer buf = new StringBuffer(sLen + 10);
for(int i = 0; i < sLen; ++i) {
buf.append(printable(s.charAt(i)));
}
s = buf.toString();
return s;
}
// Imported code from ASF Harmony project rev 770909
private static int toCodePoint( char high, char low )
{
// See RFC 2781, Section 2.2
int h = ( high & 0x3FF ) << 10;
int l = low & 0x3FF;
return ( h | l ) + 0x10000;
}
private static final char MIN_HIGH_SURROGATE = '\uD800';
private static final char MAX_HIGH_SURROGATE = '\uDBFF';
private static boolean isHighSurrogate( char ch )
{
return ( MIN_HIGH_SURROGATE <= ch && MAX_HIGH_SURROGATE >= ch );
}
private static final int MIN_CODE_POINT = 0x000000;
private static final int MAX_CODE_POINT = 0x10FFFF;
private static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x10000;
private static boolean isValidCodePoint( int codePoint )
{
return ( MIN_CODE_POINT <= codePoint && MAX_CODE_POINT >= codePoint );
}
private static boolean isSupplementaryCodePoint( int codePoint )
{
return ( MIN_SUPPLEMENTARY_CODE_POINT <= codePoint && MAX_CODE_POINT >= codePoint );
}
/**
* TODO add javadoc
*
* @param codePoint
* @return
*/
public static char[] toChars( int codePoint )
{
if ( !isValidCodePoint( codePoint ) )
{
throw new IllegalArgumentException();
}
if ( isSupplementaryCodePoint( codePoint ) )
{
int cpPrime = codePoint - 0x10000;
int high = 0xD800 | ( ( cpPrime >> 10 ) & 0x3FF );
int low = 0xDC00 | ( cpPrime & 0x3FF );
return new char[] { (char) high, (char) low };
}
return new char[] { (char) codePoint };
}
}
|
package MWC.GUI.ETOPO;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.TreeMap;
import MWC.GUI.CanvasType;
import MWC.GUI.Editable;
import MWC.GUI.Chart.Painters.SpatialRasterPainter;
import MWC.GUI.Properties.LineWidthPropertyEditor;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public final class ETOPO_2_Minute extends SpatialRasterPainter
{
private static final long serialVersionUID = 1L;
public static final String SHADE_AS_NATURAL_EARTH = "ShadeAsNaturalEarth";
// member values
/**
* the filename of our data-file
*/
private static final String fName = "ETOPO2.raw";
/**
* the file-reader we are using
*/
private static java.io.RandomAccessFile ra = null;
/**
* whether to show land
*/
private boolean _showLand = true;
/**
* the path to the datafile
*/
private final String _thePath;
/**
* flag to ensure we only report missing data on the first occasion
*/
private boolean _reportedMissingData = false;
// constructor
public ETOPO_2_Minute(final String etopo_path)
{
super("ETOPO (2 Minute)");
// store the path to the data file
_thePath = etopo_path;
_contourDepths = DEFAULT_CONTOUR_DEPTHS;
}
// static accessor to see if our data-file is there
static public boolean dataFileExists(final String etopo_path)
{
boolean res = false;
final String thePath = etopo_path + "/" + fName;
final File testFile = new File(thePath);
if (testFile.exists())
res = true;
return res;
}
// member methods
/**
* override the parent paint method, so we can open/close the datafile
*
* @param dest
* where we're painting to
*/
public final void paint(final CanvasType dest)
{
// start the paint
openFile();
// hey, it's only worth plotting if we've got some data
if (!isDataLoaded())
return;
if (getVisible())
{
// clear the cache
_pointCache.clear();
// remember width
final float oldWid = dest.getLineWidth();
// set our line width
dest.setLineWidth(this.getLineThickness());
super.paint(dest);
// and restore the old one
dest.setLineWidth(oldWid);
}
// end the paint, by closing the file
// try {
// ra.close();
// catch (IOException e) {
// e.printStackTrace();
// long tNow = System.currentTimeMillis();
// System.out.println("Elapsed time:" + (tNow - tThen));
}
/** cache the values we read from file. At some resolutions
* we re-read the same depth cell many times.
*/
TreeMap<Integer, Integer> _pointCache = new TreeMap<Integer, Integer>();
// bathy provider support
/**
* provide the delta for the data (in degrees)
*/
public double getGridDelta()
{
return 1d / 30d;
}
/**
* whether the data has been loaded yet
*/
public boolean isDataLoaded()
{
// do an open, just to check
openFile();
return (ra != null);
}
/**
* we do want to double-buffer this layer - since it takes "so" long to create
*
*/
public boolean isBuffered()
{
return true;
}
/**
* function to retrieve a data value at the indicated index
*/
protected final double contour_valAt(final int i, final int j)
{
final double res;
final int index;
index = 2 * (j * getHorizontalNumber() + i);
res = getValueAtIndex(index);
return res;
}
/**
* function to retrieve the x-location for a specific array index
*/
protected final double contour_xValAt(final int i)
{
return getLongitudeFor(i);
}
/**
* function to retrieve the x-location for a specific array index
*/
protected final double contour_yValAt(final int i)
{
return getLatitudeFor(i);
}
/**
* how many horizonal data points are in our data
*/
private static int getHorizontalNumber()
{
return 10800;
}
// /**
// * how many vertical data points are in our data?
// */
// private static int getVerticalNumber()
// return 21600;
/**
* open our datafile in random access mode
*/
private final void openFile()
{
if (ra == null)
{
String thePath = null;
// just do a check to see if we have just the file or the whole path
final File testF = new File(_thePath);
if (testF.isFile())
{
thePath = _thePath;
}
else if (testF.isDirectory())
{
thePath = _thePath + "//" + fName;
}
if (thePath != null)
{
try
{
ra = new RandomAccessFile(thePath, "r");
}
catch (final IOException e)
{
if (_reportedMissingData)
{
MWC.GUI.Dialogs.DialogFactory.showMessage("File missing",
"2 minute ETOPO data not found at:" + thePath);
_reportedMissingData = true;
}
}
}
}
}
/* returns a color based on slope and elevation */
public final int getColor(final int elevation, final double lowerLimit,
final double upperLimit,
final SpatialRasterPainter.ColorConverter converter, final boolean useNE)
{
return getETOPOColor((short) elevation, lowerLimit, upperLimit, _showLand,
converter, useNE);
}
/* returns a color based on slope and elevation */
public static int getETOPOColor(final short elevation,
final double lowerLimit, final double upperLimit, final boolean showLand,
final SpatialRasterPainter.ColorConverter converter, final boolean useNE)
{
final int res;
if (useNE)
{
// see if we are above or beneath water level
if ((elevation > 0) && (showLand))
{
// ABOVE WATER
res = converter.convertColor(235, 219, 188);
}
else
{
// BELOW WATER
// switch to positive
double val = elevation;
if (val < lowerLimit)
val = lowerLimit;
final double x = val / lowerLimit;
final int red = (int) (169.0577 - 157.9448 * x + 19.64085 * Math.pow(x,
2));
final int green = (int) (197.4973 - 103.4937 * x - 2.004169 * Math.pow(
x, 2));
final int blue = (int) (227.4203 - (35.15651 * x) - (30.06253 * Math
.pow(x, 2)));
res = converter.convertColor(red, green, blue);
}
}
else
{
// see if we are above or beneath water level
if ((elevation > 0) && (showLand))
{
// ABOVE WATER
// switch to positive
double val = elevation;
if (val > upperLimit)
val = upperLimit;
final double proportion = val / upperLimit;
final double color_val = proportion * 125;
// limit the colour val to the minimum value
int green_tone = 255 - (int) color_val;
// just check we've got a valid colour
green_tone = Math.min(250, green_tone);
res = converter.convertColor(88, green_tone, 88);
}
else
{
// BELOW WATER
// switch to positive
double val = elevation;
if (val < lowerLimit)
val = lowerLimit;
final double proportion = val / lowerLimit;
final double color_val = proportion * ETOPOWrapper.BLUE_MULTIPLIER;
// limit the colour val to the minimum value
int blue_tone = 255 - (int) color_val;
// just check we've got a valid colour
blue_tone = Math.min(250, blue_tone);
final int green = (int) ETOPOWrapper.GREEN_BASE_VALUE + (int) (blue_tone
* ETOPOWrapper.GREEN_MULTIPLIER);
res = converter.convertColor(ETOPOWrapper.RED_COMPONENT, green,
blue_tone);
}
}
// so, just produce a shade of blue depending on how deep we are.
return res;
}
/**
* over-rideable method to constrain max value to zero (such as when not plotting land)
*
* @return yes/no
*/
protected final boolean zeroIsMax()
{
// if we are showing land, then we don't want zero to be the top value
return !_showLand;
}
/**
* @param val
* the location to get the depth for
* @return the depth (in m)
*/
public final int getValueAt(final WorldLocation val)
{
final int res;
// is it valid
if (!val.isValid())
{
res = 0;
}
else
{
// now get it's index
final int index = getIndex(val);
// and get the value itself
res = getValueAtIndex(index);
}
return res;
}
private int getValueAtIndex(final int index)
{
int res = 0;
// check the cache
final Integer cached = _pointCache.get(index);
if(cached != null)
{
return cached.intValue();
}
// just check we have the file open
openFile();
// just check we have a +ve (valid) index
if (index >= 0)
{
// and retrieve the value
try
{
ra.seek(index);
res = ra.readShort();
// rescale as appropriate
res = rescaleValue(res);
}
catch (final IOException e)
{
e.printStackTrace(); // To change body of catch statement use
// Options |
// File Templates.
}
}
// cache the value
_pointCache.put(index, res);
return res;
}
/**
* rescale the data-set, if necessary
*
* @param val
* the depth as read from file
* @return the rescaled depth (from feet to metres in this case)
*/
private static int rescaleValue(final int val)
{
// convert from feet to metres
// return (int)MWC.Algorithms.Conversions.ft2m(val);
return val;
}
/**
* get the index for a particular point
*
* @param val
* the location we want the index for
* @return the index into the array for this position
*/
private int getIndex(final WorldLocation val)
{
final int res;
// and the res
res = 2 * ((getLatIndex(val) * getHorizontalNumber()) + getLongIndex(val));
return res;
}
/**
* get the longitude for the indicated index
*/
static double getLongitudeFor(final int index)
{
double res;
// convert to mins
res = index * 2;
// add 1 for luck
res += 1;
// convert to degs
res /= 60;
// put in hemisphere
res -= 180;
return res;
}
/**
* get the latitude for the indicated index
*/
static double getLatitudeFor(final int index)
{
double res;
res = index;
// convert to mins
res *= 2;
// add 1 for luck
res += 1;
// convert to degs
res /= 60;
// put in hemisphere
if (res > 90)
{
res = -(res - 90);
}
else
{
res = 90 - res;
}
return res;
}
/**
* get the lat component of this location
*/
protected final int getLatIndex(final WorldLocation val)
{
// get the components
double lat = val.getLat();
final int lat_index;
// work out how far down the lat is
if (lat > 0)
{
// convert to down
lat = 90d - lat;
}
else
lat = 90 + Math.abs(lat);
// convert to mins
lat = lat * 60;
// convert to 2 mins intervals
lat = lat / 2;
lat_index = (int) lat;
return lat_index;
}
/**
* get the long component of this location
*/
protected final int getLongIndex(final WorldLocation val)
{
// get the components
double lon = val.getLong();
final int long_index;
// work out how far acrss the lat is
if (lon < 0)
{
lon = 180 + lon;
}
else
lon = 180 + lon;
// convert to secs
lon = lon * 60;
// convert to 2 sec intervals
lon = lon / 2;
long_index = (int) lon;
return long_index;
}
/**
* accessor for whether to show land
*/
public final boolean getShowLand()
{
return _showLand;
}
/**
* setter for whether to show land
*/
public final void setShowLand(final boolean val)
{
_showLand = val;
}
// editor support
public final Editable.EditorType getInfo()
{
if (_myEditor == null)
_myEditor = new MARTOPOInfo(this);
return _myEditor;
}
public final class MARTOPOInfo extends Editable.EditorType implements
java.io.Serializable
{
private static final long serialVersionUID = 1L;
public MARTOPOInfo(final ETOPO_2_Minute data)
{
super(data, data.getName(), "");
}
public final java.beans.PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final java.beans.PropertyDescriptor[] res =
{prop("Visible", "whether this layer is visible", VISIBILITY),
displayLongProp("KeyLocation", "Key location",
"the current location of the color-key",
KeyLocationPropertyEditor.class, EditorType.FORMAT), prop(
"Color", "the color of the color-key", EditorType.FORMAT),
displayProp("ShowLand", "Show land", "whether to shade land-data",
EditorType.FORMAT), displayLongProp("LineThickness",
"Line thickness", "the thickness to plot the scale border",
LineWidthPropertyEditor.class, EditorType.FORMAT),
displayProp("BathyRes", "Bathy resolution",
"the size of the grid at which to plot the shaded bathy (larger blocks gives faster performance)",
EditorType.FORMAT), displayProp("BathyVisible", "Bathy visible",
"whether to show the gridded contours", VISIBILITY),
displayProp("ContourDepths", "Contour depths",
"the contour depths to plot", EditorType.FORMAT), displayProp(
"ContoursVisible", "Contours visible",
"whether to show the contours", VISIBILITY), displayProp(
"ContourGridInterval", "Contour grid interval",
"the interval at which to calculate the contours (larger interval leads to faster performance)",
EditorType.FORMAT), displayProp("ContourOptimiseGrid",
"Optimise grid interval",
"whether the grid interval should be optimised",
EditorType.FORMAT)};
return res;
}
catch (final java.beans.IntrospectionException e)
{
e.printStackTrace();
return super.getPropertyDescriptors();
}
}
}
// testing for this class
static public final class Etopo2Test extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public String _etopoPath;
public Etopo2Test(final String val)
{
super(val);
final String pathFromProp = System.getProperty("etopoDir");
if (pathFromProp == null)
{
// are we in OS?
final String sys = System.getProperty("os.name");
if ("Mac OS X".equals(sys))
_etopoPath = "../deploy/";
else
_etopoPath = "C:\\Program Files\\Debrief 2003\\etopo";
}
else
_etopoPath = pathFromProp;
}
public final void testMyParams()
{
ETOPO_2_Minute ed = new ETOPO_2_Minute(null);
ed.setName("blank");
editableTesterSupport.testParams(ed, this);
ed = null;
}
// TODO FIX-TEST
// check data
public void NtestFindData()
{
// String thefile = THE_PATH;
assertTrue("Failed to find the 2 minute dataset:" + _etopoPath,
ETOPO_2_Minute.dataFileExists(_etopoPath));
}
public void testConversions()
{
final ETOPO_2_Minute e2m = new ETOPO_2_Minute(_etopoPath);
WorldLocation loc = new WorldLocation(54, -3, 0);
int lat = e2m.getLatIndex(loc);
int lon = e2m.getLongIndex(loc);
double dLat = ETOPO_2_Minute.getLatitudeFor(lat);
double dLong = ETOPO_2_Minute.getLongitudeFor(lon);
WorldLocation loc2 = new WorldLocation(dLat, dLong, 0);
System.out.println("dist:" + loc2.subtract(loc).getRange());
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(-54, -3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(-54, 3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
loc = new WorldLocation(54, 3, 0);
lat = e2m.getLatIndex(loc);
lon = e2m.getLongIndex(loc);
dLat = ETOPO_2_Minute.getLatitudeFor(lat);
dLong = ETOPO_2_Minute.getLongitudeFor(lon);
loc2 = new WorldLocation(dLat, dLong, 0);
assertTrue("points close enough, original: " + loc + " res:" + loc2, loc2
.subtract(loc).getRange() < 1);
// assertEquals(loc, loc2);
}
}
public static WorldArea theArea = null;
}
|
package org.openntf.arpa;
import java.io.Serializable;
import java.util.HashMap;
import java.util.logging.Logger;
/**
* NamePartsMap carries the various component string values that make up a name.
*
* @author Devin S. Olson (dolson@czarnowski.com)
*
*/
public class NamePartsMap extends HashMap<NamePartsMap.Key, String> implements Serializable {
public static enum Key {
Abbreviated, Addr821, Addr822Comment1, Addr822Comment2, Addr822Comment3, Addr822LocalPart, Addr822Phrase, ADMD, Canonical, Common, Country, Generation, Given, Initials, Keyword, Language, Organization, OrgUnit1, OrgUnit2, OrgUnit3, OrgUnit4, PRMD, Surname, IDprefix, SourceString;
@Override
public String toString() {
return this.name();
}
public String getInfo() {
return this.getDeclaringClass() + "." + this.getClass() + ":" + this.name();
}
};
public static enum CanonicalKey {
CN("Common Name"), OU("Organizational Unit"), O("Organization"), C("Country Code");
private String _label;
public String getLabel() {
return this._label;
}
private void setLabel(final String label) {
this._label = label;
}
private CanonicalKey(final String label) {
this.setLabel(label);
}
}
private static final Logger log_ = Logger.getLogger(NamePartsMap.class.getName());
private static final long serialVersionUID = 1L;
private RFC822name _rfc822name;
/**
* * Zero-Argument Default Constructor
*/
public NamePartsMap() {
super();
}
public RFC822name getRFC822name() {
if (null == this._rfc822name) {
this._rfc822name = new RFC822name();
}
return this._rfc822name;
}
public void setRFC822name(final RFC822name rfc822name) {
this._rfc822name = rfc822name;
}
/**
* Clears the object.
*/
@Override
public void clear() {
super.clear();
if (null != this._rfc822name) {
this._rfc822name.clear();
}
}
@Override
public String get(final Object key) {
return (key instanceof NamePartsMap.Key) ? this.get((NamePartsMap.Key) key) : "";
}
public String get(final NamePartsMap.Key key) {
if (null != key) {
switch (key) {
case Abbreviated: {
String common = this.get(NamePartsMap.Key.Common);
String ou1 = this.get(NamePartsMap.Key.OrgUnit1);
String ou2 = this.get(NamePartsMap.Key.OrgUnit2);
String ou3 = this.get(NamePartsMap.Key.OrgUnit3);
String ou4 = this.get(NamePartsMap.Key.OrgUnit4);
String organization = this.get(NamePartsMap.Key.Organization);
String country = this.get(NamePartsMap.Key.Country);
StringBuffer sb = new StringBuffer("");
if (!ISO.isBlankString(common)) {
sb.append(common);
}
if (!ISO.isBlankString(ou4)) {
sb.append("/OU=" + ou4);
}
if (!ISO.isBlankString(ou3)) {
sb.append("/" + ou3);
}
if (!ISO.isBlankString(ou2)) {
sb.append("/" + ou2);
}
if (!ISO.isBlankString(ou1)) {
sb.append("/" + ou1);
}
if (!ISO.isBlankString(organization)) {
sb.append("/" + organization);
}
if (!ISO.isBlankString(country)) {
sb.append("/" + country);
}
return sb.toString();
}
case Addr821:
return this.getRFC822name().getAddr821();
case Addr822Comment1:
return this.getRFC822name().getAddr822Comment1();
case Addr822Comment2:
return this.getRFC822name().getAddr822Comment2();
case Addr822Comment3:
return this.getRFC822name().getAddr822Comment3();
case Addr822LocalPart:
return this.getRFC822name().getAddr822LocalPart();
case Addr822Phrase:
return this.getRFC822name().getAddr822Phrase();
case Canonical: {
String common = this.get(NamePartsMap.Key.Common);
String ou1 = this.get(NamePartsMap.Key.OrgUnit1);
String ou2 = this.get(NamePartsMap.Key.OrgUnit2);
String ou3 = this.get(NamePartsMap.Key.OrgUnit3);
String ou4 = this.get(NamePartsMap.Key.OrgUnit4);
String organization = this.get(NamePartsMap.Key.Organization);
String country = this.get(NamePartsMap.Key.Country);
StringBuffer sb = new StringBuffer("");
if (!ISO.isBlankString(common)) {
sb.append("CN=" + common);
}
if (!ISO.isBlankString(ou4)) {
sb.append("/OU=" + ou4);
}
if (!ISO.isBlankString(ou3)) {
sb.append("/OU=" + ou3);
}
if (!ISO.isBlankString(ou2)) {
sb.append("/OU=" + ou2);
}
if (!ISO.isBlankString(ou1)) {
sb.append("/OU=" + ou1);
}
if (!ISO.isBlankString(organization)) {
sb.append("/O=" + organization);
}
if (!ISO.isBlankString(country)) {
sb.append("/C=" + country);
}
return sb.toString();
}
default:
final String result = super.get(key);
return (null == result) ? "" : result;
}
}
return "";
}
@Override
public String put(final NamePartsMap.Key key, final String value) {
if (null != key) {
if (ISO.isBlankString(value)) {
if (this.containsKey(key)) {
this.remove(key);
}
return "";
}
switch (key) {
case Abbreviated: {
this.parse(value);
return this.get(Key.Abbreviated);
}
case Addr821:
return this.getRFC822name().getAddr821();
case Addr822Comment1:
return this.getRFC822name().getAddr822Comment1();
case Addr822Comment2:
return this.getRFC822name().getAddr822Comment2();
case Addr822Comment3:
return this.getRFC822name().getAddr822Comment3();
case Addr822LocalPart:
return this.getRFC822name().getAddr822LocalPart();
case Addr822Phrase:
return this.getRFC822name().getAddr822Phrase();
case Canonical: {
this.parse(value);
return this.get(Key.Canonical);
}
default:
final String result = super.put(key, value);
return (null == result) ? "" : result;
}
}
return "";
}
/**
* Retrieves and sets the various name values by parsing an input source string.
*
* @param source
* String from which to parse the name values.
*/
private void parse(final String source) {
String common = "";
String[] ous = new String[] { "", "", "", "" };
String organization = "";
String country = "";
if ((!ISO.isBlankString(source)) && (source.indexOf('/') > 0)) {
// break the source into it's component words and parse them
String[] words = source.split("/");
int length = words.length;
if (length > 0) {
int idx = 0;
if (source.indexOf('=') > 0) {
// use canonical logic
for (int i = words.length - 1; i >= 0; i
String[] nibbles = words[i].trim().split("=");
String key = nibbles[0];
String value = nibbles[1];
if (CanonicalKey.C.name().equals(key)) {
country = value;
} else if (CanonicalKey.O.name().equals(key)) {
organization = value;
} else if (CanonicalKey.OU.name().equals(key)) {
ous[idx] = value;
idx++;
} else if (CanonicalKey.CN.name().equals(key)) {
common = value;
}
}
} else {
// use abbreviated logic
common = words[0].trim();
if (length > 1) {
int orgpos = length;
organization = words[orgpos];
if (ISO.isCountryCode(organization)) {
// Organization could be a country code,
// Need to add logic to figure it out here and reset the organization position if needed
}
int oupos = orgpos - 1;
while (oupos > 0) {
ous[idx] = words[oupos];
oupos
idx++;
if (idx > 3) {
break;
}
}
}
}
}
}
this.put(Key.Common, common);
this.put(Key.OrgUnit1, ous[0]);
this.put(Key.OrgUnit2, ous[1]);
this.put(Key.OrgUnit3, ous[2]);
this.put(Key.OrgUnit4, ous[3]);
this.put(Key.Organization, organization);
this.put(Key.Country, country);
// if ((null != source) && (source.length() > 0)) {
// final String pattern = "^.*<.*>.*$";
// /*
// * Match Pattern: anytext<anytext>anytext
// *
// * pattern definition:
// *
// * ^ match the beginning of the string
// *
// * . match any single character
// *
// * * match the preceding match character zero or more times.
// *
// * < match a less than character
// *
// * . match any single character
// *
// * * match the preceding match character zero or more times.
// *
// * > match a greater than character
// *
// * . match any single character
// *
// * * match the preceding match character zero or more times.
// *
// * $ match the preceding match instructions against the end of the string.
// */
// if (source.matches(pattern)) {
// // test matches anytext<anytext>anytext
// // get the three primary chunks as phrase<internetaddress>comments from the source
// int idxLT = source.indexOf('<');
// int idxGT = source.indexOf('>', idxLT);
// // parse the phrase part
// String phrase = (idxLT > 0) ? source.substring(0, idxLT).trim() : "";
// if (phrase.length() > 0) {
// this.put(Key.Phrase, phrase.replaceAll("\"", "").trim());
// // parse the internetaddress part
// String internetaddress = (idxGT > (idxLT + 1)) ? source.substring(idxLT + 1, idxGT).trim() : "";
// if ((internetaddress.length() > 0) && (internetaddress.indexOf('@') >= 0)) {
// String[] chunks = internetaddress.split("@");
// if (null != chunks) {
// if (null != chunks[0]) {
// this.put(Key.Local, chunks[0].trim());
// if ((2 <= chunks.length) && (null != chunks[1])) {
// this.put(Key.Domain, chunks[1].trim());
// // parse the comments part
// String comments = (idxGT < source.length()) ? source.substring(idxGT).trim() : "";
// if (comments.length() > 0) {
// int idxParenOpen = comments.indexOf('(');
// int idxParenClose = comments.indexOf(')');
// if ((idxParenOpen < 0) || (idxParenClose < 0) || (idxParenClose < idxParenOpen)) {
// // treat the entire comments string as a single comment.
// this.setAddr822Comment(1, comments.replaceAll("(", "").replaceAll(")", "").trim());
// } else {
// for (int commentnumber = 1; commentnumber < 4; commentnumber++) {
// String comment = comments.substring(idxParenOpen, idxParenClose).trim();
// this.setAddr822Comment(commentnumber, comment);
// idxParenOpen = comments.indexOf('(', idxParenClose);
// if (idxParenOpen < idxParenClose) {
// break;
// idxParenClose = comments.indexOf(')', idxParenOpen);
// if (idxParenClose < idxParenOpen) {
// break;
}
}
|
package org.apps8os.trafficsense.first;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class RouteService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
ServiceSingleton container=ServiceSingleton.getInstance();
Route route = container.getRoute();
PebbleUiController pebbleUi = container.getPebbleUiController();
//gets the time of the first waypoint
long timeToNextWaypoint = timeStringToDate(route.getSegmentList().get(0).getWaypointList().get(0).getWaypointTime()).getTime();
long timeToGetOfBus = timeStringToDate(route.getSegmentList().get(0).getLastWaypoint().getWaypointTime()).getTime();
long timeToDestination=timeStringToDate(route.getArrivalTime()).getTime();
}
private Date timeStringToDate(String timeStr){
Date date = null;
try {
date = new SimpleDateFormat("EEEE dd.M.yyyy kk:mm", Locale.ENGLISH).parse(timeStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
/**
* Broadcast receiver that receives intents indicating that next stop has been reached.
*If it is the last waypoint it set the next segment as the current segment and set the timer
*for it. In any case it gets the next waypoint
*in the segment and sets the alarm to indicate when we are there.
*/
class NextWaypointReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
ServiceSingleton container=ServiceSingleton.getInstance();
//get the next waypoint
Waypoint nextWaypoint = container.getRoute().getCurrentSegment().setNextWaypoint();
//if waypoint is null then get the next segment
if(nextWaypoint==null){
Segment nextSegment = container.getRoute().setNextSegment();
//if the nextSegment is null then we have reached the end of the route
if(nextSegment == null){
/**
* Set end of route code here
*/
return;
}
// since we are in a new segment we need to set the alarm that indicates its end
long timeToNextSegment = timeStringToDate(nextSegment.getLastWaypoint().getWaypointTime()).getTime();
Intent i = new Intent(getApplicationContext(),RouteService.class);
i.setAction("trafficsense.NextSegmentAlarm");
PendingIntent o = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
//set the alarm manager the new segment
AlarmManager am = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timeToNextSegment, o);
nextWaypoint=nextSegment.getCurrentWaypoint();
}
//set the alarm for the next waypoint
long timeToNextWaypoint=timeStringToDate(nextWaypoint.getWaypointTime()).getTime();
Intent i = new Intent(getApplicationContext(),RouteService.class);
i.setAction("trafficsense.NextWaypointAlarm");
PendingIntent o = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
//set the alarm manager
AlarmManager am = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timeToNextWaypoint, o);
}
}
/**
* Broadcast receiver for receiving timer updates that indicate current segment has ended.
*
*/
class NextSegmentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
// do something
}
}
}
|
package zielu.gittoolbox.ui.blame;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.CommittedChangesProvider;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.impl.AbstractVcsHelperImpl;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.Gray;
import com.intellij.ui.HyperlinkAdapter;
import com.intellij.ui.JBColor;
import com.intellij.vcs.log.impl.VcsLogContentUtil;
import com.intellij.vcs.log.ui.AbstractVcsLogUi;
import com.intellij.vcsUtil.VcsUtil;
import java.awt.datatransfer.StringSelection;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.swing.JComponent;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import zielu.gittoolbox.ResBundle;
import zielu.gittoolbox.revision.RevisionInfo;
import zielu.gittoolbox.revision.RevisionService;
class BlamePopup {
private static final Logger LOG = Logger.getInstance(BlamePopup.class);
private static final JBColor BACKGROUND = new JBColor(Gray._224, Gray._92);
private static final String REVEAL_IN_LOG = "reveal-in-log";
private static final String AFFECTED_FILES = "affected-files";
private static final String COPY_REVISION = "copy-revision";
private final Project project;
private final VirtualFile file;
private final RevisionInfo revisionInfo;
private Balloon balloon;
BlamePopup(@NotNull Project project, @NotNull VirtualFile file, @NotNull RevisionInfo revisionInfo) {
this.project = project;
this.file = file;
this.revisionInfo = revisionInfo;
}
void showFor(@NotNull JComponent component) {
balloon = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(prepareText(), null, BACKGROUND, createLinkListener())
.setTitle(ResBundle.message("statusBar.blame.popup.title"))
.setAnimationCycle(200)
.setShowCallout(false)
.setCloseButtonEnabled(true)
.setHideOnCloseClick(true)
.createBalloon();
balloon.addListener(new JBPopupAdapter() {
@Override
public void onClosed(@NotNull LightweightWindowEvent event) {
if (!balloon.isDisposed()) {
Disposer.dispose(balloon);
}
}
});
balloon.showInCenterOf(component);
}
private String prepareText() {
String message = RevisionService.getInstance(project).getCommitMessage(file, revisionInfo);
String details = BlamePresenter.getInstance().getPopup(revisionInfo, message);
details = details.replace("\n", "<br>");
return details
+ "<a href='" + REVEAL_IN_LOG + "'>Git Log</a>  "
+ "<a href='" + AFFECTED_FILES + "'>Affected Files</a>  "
+ "<a href='" + COPY_REVISION + "'>Copy Revision</a>";
}
private HyperlinkListener createLinkListener() {
return new HyperlinkAdapter() {
@Override
protected void hyperlinkActivated(HyperlinkEvent e) {
handleLinkClick(e.getDescription());
}
};
}
private void handleLinkClick(String action) {
if (REVEAL_IN_LOG.equalsIgnoreCase(action)) {
VcsLogContentUtil.openMainLogAndExecute(project, this::revealRevisionInLog);
} else if (AFFECTED_FILES.equalsIgnoreCase(action)) {
showAffectedFiles();
} else if (COPY_REVISION.equalsIgnoreCase(action)) {
CopyPasteManager.getInstance().setContents(new StringSelection(revisionInfo.getRevisionNumber().asString()));
}
close();
}
private void revealRevisionInLog(@NotNull AbstractVcsLogUi logUi) {
String revisionNumber = revisionInfo.getRevisionNumber().asString();
Future<Boolean> future = logUi.getVcsLog().jumpToReference(revisionNumber);
if (!future.isDone()) {
ProgressManager.getInstance().run(new Task.Backgroundable(project,
"Searching for revision " + revisionNumber, false,
PerformInBackgroundOption.ALWAYS_BACKGROUND) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
future.get();
} catch (CancellationException | InterruptedException ignored) {
//ignored
} catch (ExecutionException e) {
LOG.error(e);
}
}
});
}
}
private void showAffectedFiles() {
AbstractVcs vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file);
if (vcs != null) {
CommittedChangesProvider<?, ?> changesProvider = vcs.getCommittedChangesProvider();
if (changesProvider != null) {
Pair<? extends CommittedChangeList, FilePath> affectedFiles = findAffectedFiles(changesProvider);
if (affectedFiles != null) {
AbstractVcsHelperImpl.loadAndShowCommittedChangesDetails(project, revisionInfo.getRevisionNumber(),
affectedFiles.getSecond(), () -> affectedFiles);
}
}
}
}
@Nullable
private Pair<? extends CommittedChangeList, FilePath> findAffectedFiles(
@NotNull CommittedChangesProvider<?, ?> changesProvider) {
try {
Pair<? extends CommittedChangeList, FilePath> pair = changesProvider.getOneList(file,
revisionInfo.getRevisionNumber());
if (pair != null && pair.getFirst() != null) {
if (pair.getSecond() != null) {
pair = Pair.create(pair.getFirst(), VcsUtil.getFilePath(file));
}
return pair;
}
return null;
} catch (VcsException e) {
LOG.warn("Failed to find affected files for path " + file, e);
return null;
}
}
private void close() {
if (balloon != null) {
balloon.hide(true);
}
}
}
|
package io.github.rlee287.jrainbuck.constants;
import java.util.HashMap;
public class Constants {
//public static final int CLASSIC_SIZE=30000;
public static final String[] LIST_SWITCHES={"-file","-input","-output"};
/* 0|file MANDATORY
* 1|stdin OPTIONAL
* 2|stdout OPTIONAL
*/
public static final Character[] ALLOWED_CHAR={'[',']','+','-','<','>','.',','};
private static HashMap<Character, Byte> INIT_UVB_MAP=
new HashMap <Character,Byte>();
static {
/* JUMP_FORWARD_ZERO 0b1000 0001*/
INIT_UVB_MAP.put('[', new Byte((byte)-127));
/* JUMP_BACKWARD_NONZERO 0b1000 0000*/
INIT_UVB_MAP.put(']', new Byte((byte)-128));
/* ARRAY_INCREMENT 0b0100 0001*/
INIT_UVB_MAP.put('+', new Byte((byte)65));
/* ARRAY_DECREMENT 0b0100 0000*/
INIT_UVB_MAP.put('-', new Byte((byte)64));
/* POINTER_LEFT 0b0010 0000*/
INIT_UVB_MAP.put('<', new Byte((byte)32));
/* POINTER_RIGHT 0b0010 0001*/
INIT_UVB_MAP.put('>', new Byte((byte)33));
/* STDOUT 0b0001 0000*/
INIT_UVB_MAP.put('.', new Byte((byte)16));
/* STDIN 0b0001 0001*/
INIT_UVB_MAP.put(',', new Byte((byte)17));
}
private static HashMap<Character, Byte> INIT_UVC_MAX=
new HashMap <Character, Byte>();
static {
INIT_UVC_MAX.put('[', new Byte((byte)63));
INIT_UVC_MAX.put(']', new Byte((byte)63));
INIT_UVC_MAX.put('+', new Byte((byte)31));
INIT_UVC_MAX.put('-', new Byte((byte)31));
INIT_UVC_MAX.put('<', new Byte((byte)15));
INIT_UVC_MAX.put('>', new Byte((byte)15));
INIT_UVC_MAX.put('.', new Byte((byte)7));
INIT_UVC_MAX.put(',', new Byte((byte)7));
}
public static final HashMap<Character,Byte> UVB_MAP=INIT_UVB_MAP;
public static final HashMap<Character,Byte> UVC_MAX=INIT_UVC_MAX;
/*
* 0 |0 |0 |0 |0 |0 |0 |0
* []|+-|<>|.,|00|00|00|sign
*/
public static final int ARRAY_SIZE = 10000;
}
|
package nut.project;
import nut.artifact.Artifact;
//import nut.artifact.ArtifactUtils;
import nut.logging.Log;
import nut.model.Build;
import nut.model.Dependency;
import nut.model.Model;
import nut.model.xmlReader;
import nut.project.InvalidDependencyVersionException;
import nut.project.NutProject;
import nut.project.validation.ModelValidationException;
import nut.project.validation.ModelValidator;
import nut.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/*
Notes
* when the model is read it may not have a groupId, as it must be inherited
* the inheritance assembler must use models that are unadulterated!
*/
public class ProjectBuilder
{
private Log log;
private String packagingPath;
private String nutVersion;
public ProjectBuilder( Log log )
{
this.log = log;
// path of packaging models
this.packagingPath = System.getProperty( "nut.home", "." ) + File.separatorChar + "nut" + File.separatorChar + "packaging" ;
this.nutVersion = System.getProperty( "nut.version", "1.0" );
}
// NutProjectBuilder Implementation
public NutProject build( File projectFile )
throws ProjectBuildingException
{
String pomLocation = projectFile.getAbsolutePath();
// First read the project's nut.xml
Model model = readModel( "unknownModel", projectFile, true );
// then read the packaging model if any
Model packagingModel = null;
File packagingFile = new File( packagingPath, model.getPackaging() + "-" + nutVersion + ".xml" );
if( packagingFile.exists() )
{
packagingModel = readModel( "unknownModel", packagingFile, true );
}
else
{
log.warn( "No template for packaging '" + model.getPackaging() + "'" );
}
// at last read the parent model if any
Model parentModel = null;
if( model.getParent() != null )
{
File parentFile = new File( projectFile.getParentFile() + "/" + model.getParent(), "nut.xml" );
parentModel = readModel( "unknownModel", parentFile, true );
if( model.getGroupId() == null )
model.setGroupId( parentModel.getGroupId() );
if( model.getVersion() == null )
model.setVersion( parentModel.getVersion() );
}
//log.info( "Building " + model.getId() );
model.addProperty( "basedir", projectFile.getAbsoluteFile().getParent() );
// add properties as "nut..."
for ( Enumeration en = System.getProperties().propertyNames(); en.hasMoreElements(); )
{
String key = (String) en.nextElement();
if( key.startsWith( "nut." ) )
{
model.addProperty( key, System.getProperty(key) );
}
}
NutProject project = null;
try
{
if( packagingModel != null )
{
model.setBuild( mergedBuild( model.getBuild(), packagingModel.getBuild() ) );
model.getDependencies().addAll( packagingModel.getDependencies() );
}
if( parentModel != null )
{
model.getDependencies().addAll( parentModel.getDependencies() );
}
project = new NutProject( model );
Artifact projectArtifact = new Artifact( project.getGroupId(), project.getArtifactId(), project.getVersion(),
project.getPackaging(), null );
project.setArtifact( projectArtifact );
// Must validate before artifact construction to make sure dependencies are good
ModelValidator validator = new ModelValidator( model );
validator.validate( );
Build build = model.getBuild();
if( build != null )
{
model.addProperty( "build.directory", project.getBuild().getDirectory() );
model.addProperty( "build.outputDirectory", project.getBuild().getOutputDirectory() );
model.addProperty( "build.testOutputDirectory", project.getBuild().getTestOutputDirectory() );
model.addProperty( "build.sourceDirectory", project.getBuild().getSourceDirectory() );
model.addProperty( "build.testSourceDirectory", project.getBuild().getTestSourceDirectory() );
}
model.addProperty( "project.groupId", project.getArtifact().getGroupId() );
model.addProperty( "project.artifactId", project.getArtifact().getArtifactId() );
model.addProperty( "project.version", project.getArtifact().getVersion() );
model.addProperty( "project.packaging", project.getPackaging() );
}
catch ( ModelValidationException e )
{
throw new InvalidProjectModelException( model.getId(), pomLocation, e.getMessage(), e );
}
return project;
}
private Build mergedBuild( Build childBuild, Build parentBuild )
{
if ( childBuild == null )
return( parentBuild );
if ( parentBuild != null )
{
if( childBuild.getDirectory()==null )
childBuild.setDirectory( parentBuild.getDirectory() );
if( childBuild.getOutputDirectory()==null )
childBuild.setOutputDirectory( parentBuild.getOutputDirectory() );
if( childBuild.getTestOutputDirectory()==null )
childBuild.setTestOutputDirectory( parentBuild.getTestOutputDirectory() );
if( childBuild.getSourceDirectory()==null )
childBuild.setSourceDirectory( parentBuild.getSourceDirectory() );
if( childBuild.getTestSourceDirectory()==null )
childBuild.setTestSourceDirectory( parentBuild.getTestSourceDirectory() );
childBuild.getPlugins().addAll( parentBuild.getPlugins() );
}
return( childBuild );
}
private Model readModel( String projectId,
File file,
boolean strict )
throws ProjectBuildingException
{
Reader reader = null;
Model model = null;
//log.info( "readModel 1: " + projectId + " from file "+ file.getAbsolutePath() );
try
{
InputStream is = new FileInputStream(file);
reader = new InputStreamReader( is );
model = readModel( projectId, file.getAbsolutePath(), reader, strict );
reader.close();
}
catch ( FileNotFoundException e )
{
throw new ProjectBuildingException( projectId,
"Could not find the model file '" + file.getAbsolutePath() + "'.", e );
}
catch ( IOException e )
{
throw new ProjectBuildingException( projectId, "Failed to build model from file '" +
file.getAbsolutePath() + "'.\nError: \'" + e.getLocalizedMessage() + "\'", e );
}
return model;
}
private Model readModel( String projectId,
String pomLocation,
Reader reader,
boolean strict )
throws IOException, InvalidProjectModelException
{
//String modelSource = IOUtil.toString( reader );
StringWriter sw = new StringWriter();
final char[] buffer = new char[1024 * 4];
int n = 0;
while ( -1 != ( n = reader.read( buffer ) ) )
{
sw.write( buffer, 0, n );
}
sw.flush();
String modelSource = sw.toString();
StringReader sReader = new StringReader( modelSource );
//log.info( "readModel 2: " + projectId + " from "+ pomLocation );
try
{
xmlReader modelReader = new xmlReader();
return modelReader.read( sReader, strict );
}
catch ( XmlPullParserException e )
{
throw new InvalidProjectModelException( projectId, pomLocation,
"Parse error reading nut.xml. Reason: " + e.getMessage(), e );
}
}
}
|
package hudson;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import hudson.model.Hudson;
import hudson.model.User;
import hudson.triggers.Trigger;
import hudson.triggers.SafeTimerTask;
import hudson.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletResponse;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.URLClassLoader;
import java.net.URL;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.jvnet.localizer.LocaleProvider;
/**
* Entry point when Hudson is used as a webapp.
*
* @author Kohsuke Kawaguchi
*/
public class WebAppMain implements ServletContextListener {
private final RingBufferLogHandler handler = new RingBufferLogHandler();
private static final String APP = "app";
/**
* Creates the sole instance of {@link Hudson} and register it to the {@link ServletContext}.
*/
public void contextInitialized(ServletContextEvent event) {
try {
final ServletContext context = event.getServletContext();
// use the current request to determine the language
LocaleProvider.setProvider(new LocaleProvider() {
public Locale get() {
Locale locale=null;
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
locale = req.getLocale();
if(locale==null)
locale = Locale.getDefault();
return locale;
}
});
// quick check to see if we (seem to) have enough permissions to run. (see #719)
JVM jvm;
try {
jvm = new JVM();
new URLClassLoader(new URL[0],getClass().getClassLoader());
} catch(SecurityException e) {
context.setAttribute(APP,new InsufficientPermissionDetected(e));
return;
}
installLogger();
final File home = getHomeDir(event).getAbsoluteFile();
home.mkdirs();
System.out.println("hudson home directory: "+home);
// check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
if (! home.exists()) {
context.setAttribute(APP,new NoHomeDir(home));
return;
}
// make sure that we are using XStream in the "enhanced" (JVM-specific) mode
if(jvm.bestReflectionProvider().getClass()==PureJavaReflectionProvider.class) {
// nope
context.setAttribute(APP,new IncompatibleVMDetected());
return;
}
// make sure this is servlet 2.4 container or above
try {
ServletResponse.class.getMethod("setCharacterEncoding",String.class);
} catch (NoSuchMethodException e) {
context.setAttribute(APP,new IncompatibleServletVersionDetected(ServletResponse.class));
return;
}
// Tomcat breaks XSLT with JDK 5.0 and onward. Check if that's the case, and if so,
// try to correct it
try {
TransformerFactory.newInstance();
// if this works we are all happy
} catch (TransformerFactoryConfigurationError x) {
// no it didn't.
Logger logger = Logger.getLogger(WebAppMain.class.getName());
logger.log(Level.WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details",x);
System.setProperty(TransformerFactory.class.getName(),"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
try {
TransformerFactory.newInstance();
logger.info("XSLT is set to the JAXP RI in JRE");
} catch(TransformerFactoryConfigurationError y) {
logger.log(Level.SEVERE, "Failed to correct the problem.");
}
}
Stapler.setExpressionFactory(event, new ExpressionFactory2());
context.setAttribute(APP,new HudsonIsLoading());
new Thread("hudson initialization thread") {
public void run() {
try {
computeVersion(context);
try {
context.setAttribute(APP,new Hudson(home,context));
} catch( IOException e ) {
throw new Error(e);
}
Trigger.init(); // start running trigger
// trigger the loading of changelogs in the background,
// but give the system 10 seconds so that the first page
// can be served quickly
Trigger.timer.schedule(new SafeTimerTask() {
public void doRun() {
User.get("nobody").getBuilds();
}
}, 1000*10);
} catch (Error e) {
LOGGER.log(Level.SEVERE, "Failed to initialize Hudson",e);
throw e;
} catch (RuntimeException e) {
LOGGER.log(Level.SEVERE, "Failed to initialize Hudson",e);
throw e;
}
}
}.start();
} catch (Error e) {
LOGGER.log(Level.SEVERE, "Failed to initialize Hudson",e);
throw e;
} catch (RuntimeException e) {
LOGGER.log(Level.SEVERE, "Failed to initialize Hudson",e);
throw e;
}
}
protected void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
try {
InputStream is = getClass().getResourceAsStream("hudson-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
Hudson.VERSION = ver;
context.setAttribute("version",ver);
String verHash = Util.getDigestOf(ver).substring(0, 8);
if(ver.equals("?"))
Hudson.RESOURCE_PATH = "";
else
Hudson.RESOURCE_PATH = "/static/"+verHash;
Hudson.VIEW_RESOURCE_PATH = "/resources/"+ verHash;
}
/**
* Installs log handler to monitor all Hudson logs.
*/
private void installLogger() {
Hudson.logRecords = handler.getView();
Logger.getLogger("hudson").addHandler(handler);
}
/**
* Determines the home directory for Hudson.
*
* People makes configuration mistakes, so we are trying to be nice
* with those by doing {@link String#trim()}.
*/
private File getHomeDir(ServletContextEvent event) {
// check JNDI for the home directory first
try {
Context env = (Context) new InitialContext().lookup("java:comp/env");
String value = (String) env.lookup("HUDSON_HOME");
if(value!=null && value.trim().length()>0)
return new File(value.trim());
} catch (NamingException e) {
// ignore
}
// finally check the system property
String sysProp = System.getProperty("HUDSON_HOME");
if(sysProp!=null)
return new File(sysProp.trim());
// look at the env var next
String env = EnvVars.masterEnvVars.get("HUDSON_HOME");
if(env!=null)
return new File(env.trim()).getAbsoluteFile();
// otherwise pick a place by ourselves
String root = event.getServletContext().getRealPath("/WEB-INF/workspace");
if(root!=null) {
File ws = new File(root.trim());
if(ws.exists())
// Hudson <1.42 used to prefer this before ~/.hudson, so
// check the existence and if it's there, use it.
// otherwise if this is a new installation, prefer ~/.hudson
return ws;
}
// if for some reason we can't put it within the webapp, use home directory.
return new File(new File(System.getProperty("user.home")),".hudson");
}
public void contextDestroyed(ServletContextEvent event) {
Hudson instance = Hudson.getInstance();
if(instance!=null)
instance.cleanUp();
// Logger is in the system classloader, so if we don't do this
// the whole web app will never be undepoyed.
Logger.getLogger("hudson").removeHandler(handler);
}
private static final Logger LOGGER = Logger.getLogger(WebAppMain.class.getName());
}
|
package org.bonej.testImages;
import net.imagej.ImgPlus;
import net.imagej.axis.Axes;
import net.imagej.axis.AxisType;
import net.imagej.ops.OpEnvironment;
import net.imglib2.FinalDimensions;
import net.imglib2.img.Img;
import net.imglib2.type.logic.BitType;
/**
* A utility class to create an ImgPlus that follows the conventions of a hyperstack in ImageJ1.
* Needed so that the image display correctly (at least in the legacy ui).
*
* @author Richard Domander
*/
public class IJ1ImgPlus {
public static final int DIMENSIONS = 5;
public static final int X_DIM = 0;
public static final int Y_DIM = 1;
public static final int CHANNEL_DIM = 2;
public static final int Z_DIM = 3;
public static final int TIME_DIM = 4;
public static final AxisType[] IJ1_AXES;
static {
IJ1_AXES = new AxisType[DIMENSIONS];
IJ1_AXES[X_DIM] = Axes.X;
IJ1_AXES[Y_DIM] = Axes.Y;
IJ1_AXES[Z_DIM] = Axes.Z;
IJ1_AXES[CHANNEL_DIM] = Axes.CHANNEL;
IJ1_AXES[TIME_DIM] = Axes.TIME;
}
private IJ1ImgPlus() {}
/**
* Creates a 5-dimensional ImgPlus
*
* @param title Name of the image
* @param channels Number of colour channels
* @param frames Number of frames
* @param padding Padding added to width, height & depth (final width = width + 2 * padding)
* @param scale Scale of calibration in x, y & z
* @param unit Unit of calibration in x, y & z
* @return An empty ImgPlus
*/
public static ImgPlus<BitType> createIJ1ImgPlus(final OpEnvironment ops, String title, final long width,
final long height, final long depth, final long channels, final long frames, final long padding,
final double scale, final String unit) {
final long totalPadding = 2 * padding;
final Img<BitType> img = ops.create().img(
new FinalDimensions(width + totalPadding, height + totalPadding,
channels, depth + totalPadding, frames), new BitType());
double[] calibration = new double[]{scale, scale, 1.0, scale, 1.0};
String[] units = new String[]{unit, unit, "", unit, ""};
return new ImgPlus<>(img, title, IJ1_AXES, calibration, units);
}
}
|
package hudson.model;
import com.thoughtworks.xstream.XStream;
import hudson.FeedAdapter;
import hudson.XmlFile;
import hudson.CopyOnWrite;
import hudson.model.Descriptor.FormException;
import hudson.scm.ChangeLogSet;
import hudson.util.RunList;
import hudson.util.XStream2;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a user.
*
* @author Kohsuke Kawaguchi
*/
public class User extends AbstractModelObject {
private transient final String id;
private volatile String fullName;
private volatile String description;
/**
* List of {@link UserProperty}s configured for this project.
*/
@CopyOnWrite
private volatile List<UserProperty> properties = new ArrayList<UserProperty>();
private User(String id) {
this.id = id;
this.fullName = id; // fullName defaults to name
// load the other data from disk if it's available
XmlFile config = getConfigFile();
try {
if(config.exists())
config.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
}
// allocate default instances if needed.
// doing so after load makes sure that newly added user properties do get reflected
for (UserPropertyDescriptor d : UserProperties.LIST) {
if(getProperty(d.clazz)==null) {
UserProperty up = d.newInstance(this);
if(up!=null)
properties.add(up);
}
}
for (UserProperty p : properties)
p.setUser(this);
}
public String getId() {
return id;
}
public String getUrl() {
return "user/"+ id;
}
/**
* Gets the human readable name of this user.
* This is configurable by the user.
*
* @return
* never null.
*/
public String getFullName() {
return fullName;
}
public String getDescription() {
return description;
}
/**
* Gets the user properties configured for this user.
*/
public Map<Descriptor<UserProperty>,UserProperty> getProperties() {
return Descriptor.toMap(properties);
}
/**
* Gets the specific property, or null.
*/
public <T extends UserProperty> T getProperty(Class<T> clazz) {
for (UserProperty p : properties) {
if(clazz.isInstance(p))
return (T)p; // can't use Class.cast as that's 5.0 feature
}
return null;
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
description = req.getParameter("description");
save();
rsp.sendRedirect("."); // go to the top page
}
public static User get(String name) {
if(name==null)
return null;
synchronized(byName) {
User u = byName.get(name);
if(u==null) {
u = new User(name);
byName.put(name,u);
}
return u;
}
}
/**
* Returns the user name.
*/
public String getDisplayName() {
return getFullName();
}
/**
* Gets the list of {@link Build}s that include changes by this user,
* by the timestamp order.
*
* TODO: do we need some index for this?
*/
public List<Build> getBuilds() {
List<Build> r = new ArrayList<Build>();
for (Project p : Hudson.getInstance().getProjects()) {
for (Build b : p.getBuilds()) {
for (ChangeLogSet.Entry e : b.getChangeSet()) {
if(e.getAuthor()==this) {
r.add(b);
break;
}
}
}
}
Collections.sort(r,Run.ORDER_BY_DATE);
return r;
}
public String toString() {
return fullName;
}
/**
* The file we save our configuration.
*/
protected final XmlFile getConfigFile() {
String safeId = id.replace('\\', '_').replace('/', '_');
return new XmlFile(XSTREAM,new File(Hudson.getInstance().getRootDir(),"users/"+ safeId +"/config.xml"));
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
XmlFile config = getConfigFile();
config.mkdirs();
config.write(this);
}
/**
* Accepts submission from the configuration page.
*/
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(!Hudson.adminCheck(req,rsp))
return;
req.setCharacterEncoding("UTF-8");
try {
fullName = req.getParameter("fullName");
description = req.getParameter("description");
List<UserProperty> props = new ArrayList<UserProperty>();
for (Descriptor<UserProperty> d : UserProperties.LIST)
props.add(d.newInstance(req));
this.properties = props;
save();
rsp.sendRedirect(".");
} catch (FormException e) {
sendError(e,req,rsp);
}
}
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", RunList.fromRuns(getBuilds()));
}
public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " regression builds", RunList.fromRuns(getBuilds()).regressionOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
runs.newBuilds(), FEED_ADAPTER, req, rsp );
}
/**
* Keyed by {@link User#id}.
*/
private static final Map<String,User> byName = new HashMap<String,User>();
/**
* Used to load/save user configuration.
*/
private static final XStream XSTREAM = new XStream2();
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
static {
XSTREAM.alias("user",User.class);
}
/**
* {@link FeedAdapter} to produce build status summary in the feed.
*/
public static final FeedAdapter<Run> FEED_ADAPTER = new FeedAdapter<Run>() {
public String getEntryTitle(Run entry) {
return entry+" : "+entry.getBuildStatusSummary().message;
}
public String getEntryUrl(Run entry) {
return entry.getUrl();
}
public String getEntryID(Run entry) {
return "tag:"+entry.getParent().getName()+':'+entry.getId();
}
public Calendar getEntryTimestamp(Run entry) {
return entry.getTimestamp();
}
};
}
|
package gameOfLife.packageTracker.shipping;
import java.util.HashMap;
import java.util.Random;
import gameOfLife.packageTracker.exceptions.InvalidUserNameException;
import gameOfLife.packageTracker.exceptions.InvalidUserNameException.InvalidUserNameType;
public class User
{
private final HashMap<String , User> users = new HashMap<>();
private String name, userName;
//never return a decrypted password
private String password;
private boolean isPasswordEncrypted;
public User(String name, String userName, String password) throws InvalidUserNameException
{
this(name, userName, password, false);
}
public User(String name, String userName, String password, boolean encryptPassword) throws InvalidUserNameException
{
if(users.containsKey(name))
throw new InvalidUserNameException(InvalidUserNameType.DUPLICATE);
this.name = name;
this.userName = userName;
this.password = password;
if(encryptPassword)
encryptPassword();
isPasswordEncrypted = encryptPassword;
}
public String getUserName()
{
return userName;
}
public String getName()
{
return name;
}
public boolean validatePassword(String validate)
{
return password.equals(validate);
}
/**
* Only returns encryted passwords
*
* @return encrypted password or null if password is not encrypted
*/
public String getPassword()
{
if(isPasswordEncrypted)
return password;
else
return null;
}
public boolean isPasswordEncrypted()
{
return isPasswordEncrypted;
}
public String encryptPassword() // psuedo-random char-shift
{
if(isPasswordEncrypted)
return password;
Random random = new Random(userName.hashCode()); // for encrypting password the seed must be something unique, say the username's hashcode, that's unique
char[] password = this.password.toCharArray();
for(int i = 0; i < password.length; i++)
{
password[i] += random.nextInt() % Character.MAX_VALUE;
password[i] %= Character.MAX_VALUE;
}
this.password = new String(password);
return this.password;
}
public void decryptPassword()
{
if(!isPasswordEncrypted)
return;
Random random = new Random(userName.hashCode()); // for encrypting password the seed must be something unique, say the username's hashcode, that's unique
char[] password = this.password.toCharArray();
for(int i = 0; i < password.length; i++)
{
password[i] -= random.nextInt() % Character.MAX_VALUE;
password[i] += Character.MAX_VALUE + 1;
password[i] %= Character.MAX_VALUE;
}
this.password = new String(password);
}
@Override
public String toString()
{
return super.toString();
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof User)
{
User other = (User) obj;
return userName.equals(other.userName); // user names are unique so no need to check anything else
}
else
{
return false;
}
}
}
|
package com.junjunguo.pocketmaps.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.activities.MainActivity;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Environment;
public class IO
{
public static boolean writeToFile(String txt, File file, boolean append)
{
try(FileWriter sw = new FileWriter(file, append);
BufferedWriter bw = new BufferedWriter(sw))
{
bw.write(txt);
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static String readFromFile(File file, String lineBreak)
{
StringBuilder sb = new StringBuilder();
try(FileReader sr = new FileReader(file);
BufferedReader br = new BufferedReader(sr))
{
while (true)
{
String txt = br.readLine();
if (txt == null) { break; }
sb.append(txt).append(lineBreak);
}
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
public static void showRootfolderSelector(Activity activity, boolean cacheDir, Runnable callback)
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
builder1.setTitle(R.string.switch_maps_dir);
builder1.setCancelable(true);
addSelection(builder1, cacheDir, callback, activity);
}
else
{
builder1.setMessage(R.string.needs_vers_lollipop);
builder1.setCancelable(false);
}
AlertDialog alert11 = builder1.create();
alert11.show();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void addSelection(AlertDialog.Builder builder1, boolean cacheDir, final Runnable callback, Activity activity)
{
File files[];
if (cacheDir)
{
files = activity.getExternalCacheDirs();
}
else
{
files = activity.getExternalMediaDirs();
}
final ArrayList<String> items = new ArrayList<String>();
final ArrayList<String> itemsText = new ArrayList<String>();
itemsText.add(getStorageText(MainActivity.getDefaultBaseDirectory(activity)));
items.add(MainActivity.getDefaultBaseDirectory(activity).getPath());
for (File curFile : files)
{
if (curFile == null)
{ // Regarding to android javadoc this may be possible.
continue;
}
String mountState = Environment.getExternalStorageState(curFile);
if (mountState.equals(Environment.MEDIA_MOUNTED) ||
mountState.equals(Environment.MEDIA_SHARED))
{
itemsText.add(getStorageText(curFile));
items.add(curFile.getPath());
}
}
OnClickListener listener = new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int buttonNr)
{
String selection = items.get(buttonNr);
Variable.getVariable().setBaseFolder(selection);
File mapsFolder = Variable.getVariable().getMapsFolder();
if (!mapsFolder.exists()) { mapsFolder.mkdirs(); }
Variable.getVariable().saveVariables();
Variable.getVariable().getLocalMaps().clear();
callback.run();
}
};
builder1.setItems(itemsText.toArray(new String[0]), listener);
}
private static String getStorageText(File dir)
{
long freeSpace = dir.getFreeSpace() / (1024*1024);
long totalSpace = dir.getTotalSpace() / (1024*1024);
return "[ " + freeSpace + " MB free / " + totalSpace + " MB total]\n" + dir.getPath() + "\n";
}
}
|
package com.vk.vktestapp;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.vk.sdk.VKUIHelper;
import com.vk.sdk.api.VKApi;
import com.vk.sdk.api.VKApiConst;
import com.vk.sdk.api.VKBatchRequest;
import com.vk.sdk.api.VKBatchRequest.VKBatchRequestListener;
import com.vk.sdk.api.VKError;
import com.vk.sdk.api.VKParameters;
import com.vk.sdk.api.VKRequest;
import com.vk.sdk.api.VKRequest.VKRequestListener;
import com.vk.sdk.api.VKResponse;
import com.vk.sdk.api.methods.VKApiCaptcha;
import com.vk.sdk.api.model.VKPhoto;
import com.vk.sdk.api.model.VKPhotoArray;
import com.vk.sdk.api.model.VKWallPostResult;
import com.vk.sdk.api.photo.VKImageParameters;
import com.vk.sdk.api.photo.VKUploadImage;
import com.vk.sdk.util.VKStringJoiner;
import java.io.IOException;
public class TestActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
VKUIHelper.onResume(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
VKUIHelper.onDestroy(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
VKUIHelper.onActivityResult(requestCode, resultCode, data);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.users_get).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS,
// "id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100," +
// "photo_200_orig,photo_200,photo_400_orig,photo_max,photo_max_orig,online," +
// "online_mobile,lists,domain,has_mobile,contacts,connections,site,education," +
// "universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message," +
// "status,last_seen,common_count,relation,relatives,counters"));
VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.USER_IDS, "1,2"));
request.secure = false;
request.useSystemLanguage = false;
startApiCall(request);
}
});
view.findViewById(R.id.friends_get).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
VKRequest request = new VKRequest("friends.get", VKParameters.from(VKApiConst.FIELDS, "id,first_name,last_name,sex,bdate,city"));
startApiCall(request);
}
});
view.findViewById(R.id.captcha_force).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
VKRequest request = new VKApiCaptcha().force();
startApiCall(request);
}
});
view.findViewById(R.id.wall_post).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
VKRequest request = VKApi.wall().post(VKParameters.from(VKApiConst.OWNER_ID, "-60479154", VKApiConst.MESSAGE, "Привет, друзья!"));
request.attempts = 10;
startApiCall(request);
}
});
view.findViewById(R.id.upload_photo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Bitmap photo = getPhoto();
VKRequest request = VKApi.uploadAlbumPhotoRequest(new VKUploadImage(photo, VKImageParameters.pngImage()), 181808365, 60479154);
request.executeWithListener(new VKRequestListener() {
@Override
public void onComplete(VKResponse response) {
photo.recycle();
VKPhotoArray photoArray = (VKPhotoArray) response.parsedModel;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("https://vk.com/photo-60479154_%s", photoArray.get(0).id)));
startActivity(i);
}
@Override
public void onError(VKError error) {
showError(error);
}
});
}
});
view.findViewById(R.id.upload_photo_to_wall).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Bitmap photo = getPhoto();
VKRequest request = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.9f)), 0, 60479154);
request.executeWithListener(new VKRequestListener() {
@Override
public void onComplete(VKResponse response) {
photo.recycle();
VKPhoto photoModel = ((VKPhotoArray) response.parsedModel).get(0);
makePost(String.format("photo%s_%s", photoModel.owner_id, photoModel.id));
}
@Override
public void onError(VKError error) {
showError(error);
}
});
}
});
view.findViewById(R.id.upload_several_photos_to_wall).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Bitmap photo = getPhoto();
VKRequest request1 = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.9f)), 0, 60479154);
VKRequest request2 = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.5f)), 0, 60479154);
VKRequest request3 = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.1f)), 0, 60479154);
VKRequest request4 = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.pngImage()), 0, 60479154);
VKBatchRequest batch = new VKBatchRequest(request1, request2, request3, request4);
batch.executeWithListener(new VKBatchRequestListener() {
@Override
public void onComplete(VKResponse[] responses) {
super.onComplete(responses);
String[] photos = new String[responses.length];
for (int i = 0; i < responses.length; i++) {
VKPhoto photoModel = ((VKPhotoArray) responses[i].parsedModel).get(0);
photos[i] = String.format("photo%s_%s", photoModel.owner_id, photoModel.id);
}
makePost(VKStringJoiner.join(photos, ","));
}
@Override
public void onError(VKError error) {
showError(error);
}
});
}
});
}
private void startApiCall(VKRequest request) {
Intent i = new Intent(getActivity(), ApiCallActivity.class);
i.putExtra("request", request);
startActivity(i);
}
private void showError(VKError error) {
new AlertDialog.Builder(getActivity())
.setMessage(error.errorMessage)
.setPositiveButton("OK", null)
.show();
if (error.httpError != null) {
Log.w("Test", "Error in request or upload", error.httpError);
}
}
private Bitmap getPhoto() {
Bitmap b = null;
try {
b = BitmapFactory.decodeStream(getActivity().getAssets().open("android.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
private void makePost(String attachments) {
VKRequest post = VKApi.wall().post(VKParameters.from(VKApiConst.OWNER_ID, "-60479154", VKApiConst.ATTACHMENTS, attachments));
post.setModelClass(VKWallPostResult.class);
post.executeWithListener(new VKRequestListener() {
@Override
public void onComplete(VKResponse response) {
super.onComplete(response);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("https://vk.com/wall-60479154_%s", ((VKWallPostResult)response.parsedModel).post_id) ) );
startActivity(i);
}
@Override
public void onError(VKError error) {
showError(error);
}
});
}
}
}
|
package ragnardb.plugin;
import gw.lang.reflect.*;
import gw.lang.reflect.java.JavaTypes;
import gw.util.GosuExceptionUtil;
import ragnardb.RagnarDB;
import ragnardb.parser.ast.Expression;
import ragnardb.runtime.SQLConstraint;
import ragnardb.runtime.SQLRecord;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class SQLDdlTypeInfo extends SQLBaseTypeInfo {
public SQLDdlTypeInfo(ISQLDdlType type) {
super(type);
decorateDdlType(type);
}
/**
* ISQLDdlType will have a single getter, SqlSource : String
* @param type ISQLDdlType
*/
private void decorateDdlType( ISQLDdlType type ) {
_propertiesList = new ArrayList<>();
_propertiesMap = new HashMap<>();
IPropertyInfo sqlSource = new PropertyInfoBuilder()
.withName("SqlSource")
.withDescription("Returns the source of this ISQLDdlType")
.withStatic()
.withWritable(false)
.withType(JavaTypes.STRING())
.withAccessor(new IPropertyAccessor() {
@Override
public Object getValue( Object ctx ) {
try {
return ((ISQLDdlType) getOwnersType()).getSqlSource();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setValue( Object ctx, Object value ) {
throw new IllegalStateException("Calling setter on readonly property");
}
})
.build(this);
_propertiesMap.put( sqlSource.getName(), sqlSource );
_propertiesList.add(sqlSource);
IPropertyInfo tables = new PropertyInfoBuilder()
.withName("Tables")
.withDescription("Returns the source of this ISQLDdlType")
.withStatic()
.withWritable( false )
.withType( JavaTypes.LIST().getParameterizedType( TypeSystem.get( ISQLTableType.class ) ) )
.withAccessor( new IPropertyAccessor()
{
@Override
public Object getValue( Object ctx )
{
return ((ISQLDdlType)getOwnersType()).getTableTypes();
}
@Override
public void setValue( Object ctx, Object value )
{
throw new IllegalStateException( "Calling setter on readonly property" );
}
} )
.build( this );
_propertiesMap.put(tables.getName(), tables);
_propertiesList.add(tables);
_propertiesMap.put(tables.getName(), tables);
_propertiesList.add(tables);
_methodList = new MethodList();
_constructorList = Collections.emptyList();
_methodList.add(new MethodInfoBuilder()
.withName("transaction")
.withDescription("Runs enclosed code in a transaction")
.withParameters(new ParameterInfoBuilder().withName("condition")
.withType(TypeSystem.get(Runnable.class)))
.withReturnType(JavaTypes.VOID())
.withStatic(true)
.withCallHandler((ctx, args) -> {
Connection con = null;
Savepoint save1 = null;
try {
con = RagnarDB.getConnection();
con.setAutoCommit(false);
save1 = con.setSavepoint();
Runnable exec = (Runnable) args[0];
exec.run();
con.commit();
} catch (Exception e) {
try {
con.rollback(save1);
System.out.println("Rolling Back");
} catch (Exception ee) {
System.err.println("Error in SQLRollback");
throw GosuExceptionUtil.forceThrow(ee);
}
throw GosuExceptionUtil.forceThrow(e);
} finally {
try {
con.setAutoCommit(true);
} catch (Exception e) {
System.err.println("Error in SQLAutoCommit change");
throw GosuExceptionUtil.forceThrow(e);
}
}
return null;
})
.build(this));
}
}
|
package com.jetbrains.python.psi.types;
import com.google.common.collect.ImmutableSet;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.*;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SmartList;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.PyDynamicMember;
import com.jetbrains.python.psi.AccessDirection;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.resolve.ResolveImportUtil;
import com.jetbrains.python.psi.resolve.VariantsProcessor;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author yole
*/
public class PyModuleType implements PyType { // Modules don't descend from object
private final PyFile myModule;
protected static ImmutableSet<String> ourPossibleFields = ImmutableSet.of("__name__", "__file__", "__path__", "__doc__", "__dict__");
public PyModuleType(PyFile source) {
myModule = source;
}
public PyFile getModule() {
return myModule;
}
@Nullable
public List<? extends PsiElement> resolveMember(final String name,
PyExpression location,
AccessDirection direction,
PyResolveContext resolveContext) {
for(PyModuleMembersProvider provider: Extensions.getExtensions(PyModuleMembersProvider.EP_NAME)) {
final PsiElement element = provider.resolveMember(myModule, name);
if (element != null) {
return new SmartList<PsiElement>(element);
}
}
//return PyResolveUtil.treeWalkUp(new PyResolveUtil.ResolveProcessor(name), myModule, null, null);
final PsiElement result = ResolveImportUtil.resolveChild(myModule, name, myModule, null, false, true);
if (result != null) return new SmartList<PsiElement>(result);
return Collections.emptyList();
}
/**
* @param directory the module directory
*
* @return a list of submodules of the specified module directory, either files or dirs, for easier naming; may contain filenames
* not suitable for import.
*/
@NotNull
private static List<PsiFileSystemItem> getSubmodulesList(final PsiDirectory directory) {
List<PsiFileSystemItem> result = new ArrayList<PsiFileSystemItem>();
if (directory != null) { // just in case
// file modules
for (PsiFile f : directory.getFiles()) {
final String filename = f.getName();
// if we have a binary module, we'll most likely also have a stub for it in site-packages
if ((f instanceof PyFile && !filename.equals(PyNames.INIT_DOT_PY)) || isBinaryModule(filename)) {
result.add(f);
}
}
// dir modules
for (PsiDirectory dir : directory.getSubdirectories()) {
if (dir.findFile(PyNames.INIT_DOT_PY) instanceof PyFile) result.add(dir);
}
}
return result;
}
private static boolean isBinaryModule(String filename) {
final String ext = FileUtil.getExtension(filename);
if (SystemInfo.isWindows) {
return "pyd".equalsIgnoreCase(ext);
}
else {
return "so".equals(ext);
}
}
public Object[] getCompletionVariants(String completionPrefix, PyExpression location, ProcessingContext context) {
Set<String> names_already = context.get(CTX_NAMES);
List<Object> result = new ArrayList<Object>();
ResolveImportUtil.PointInImport point = ResolveImportUtil.getPointInImport(location);
for (PyModuleMembersProvider provider : Extensions.getExtensions(PyModuleMembersProvider.EP_NAME)) {
for (PyDynamicMember member : provider.getMembers(myModule, point)) {
final String name = member.getName();
result.add(LookupElementBuilder.create(name).setIcon(member.getIcon()).setTypeText(member.getShortType()));
}
}
if (point == ResolveImportUtil.PointInImport.NONE || point == ResolveImportUtil.PointInImport.AS_NAME) { // when not imported from, add regular attributes
final VariantsProcessor processor = new VariantsProcessor(location);
processor.setPlainNamesOnly(point == ResolveImportUtil.PointInImport.AS_NAME); // no parens after imported function names
myModule.processDeclarations(processor, ResolveState.initial(), null, location);
if (names_already != null) {
for (LookupElement le : processor.getResultList()) {
String name = le.getLookupString();
if (!names_already.contains(name)) {
result.add(le);
names_already.add(name);
}
}
}
else {
result.addAll(processor.getResultList());
}
}
if (point == ResolveImportUtil.PointInImport.AS_MODULE || point == ResolveImportUtil.PointInImport.AS_NAME) { // when imported from somehow, add submodules
if (PyNames.INIT_DOT_PY.equals(myModule.getName())) { // our module is a dir, not a single file
result.addAll(getSubmoduleVariants(myModule.getContainingDirectory(), location, names_already));
}
}
return result.toArray();
}
public static List<LookupElement> getSubmoduleVariants(final PsiDirectory directory,
PsiElement location,
Set<String> names_already) {
List<LookupElement> result = new ArrayList<LookupElement>();
for (PsiFileSystemItem pfsi : getSubmodulesList(directory)) {
if (pfsi == location.getContainingFile().getOriginalFile()) continue;
String s = pfsi.getName();
int pos = s.lastIndexOf('.'); // it may not contain a dot, except in extension; cut it off.
if (pos > 0) s = s.substring(0, pos);
if (!PyNames.isIdentifier(s)) continue;
if (names_already != null) {
if (names_already.contains(s)) continue;
else names_already.add(s);
}
result.add(LookupElementBuilder.create(pfsi, s)
.setTypeText(getPresentablePath(directory))
.setPresentableText(s)
.setIcon(pfsi.getIcon(0)));
}
return result;
}
private static String getPresentablePath(PsiDirectory directory) {
if (directory == null) {
return "";
}
final String path = directory.getVirtualFile().getPath();
if (path.contains(PythonSdkType.SKELETON_DIR_NAME)) {
return "<built-in>";
}
return FileUtil.toSystemDependentName(path);
}
public String getName() {
PsiFile mod = getModule();
if (mod != null) {
return mod.getName();
}
else {
return null;
}
}
@Override
public boolean isBuiltin() {
return true;
}
@NotNull
public static Set<String> getPossibleInstanceMembers() {
return ourPossibleFields;
}
}
|
package org.rakam.util;
import io.netty.handler.codec.http.HttpResponseStatus;
import javax.annotation.Nullable;
import java.text.Normalizer;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static java.util.Locale.ENGLISH;
public final class ValidationUtil
{
private ValidationUtil()
throws InstantiationException
{
throw new InstantiationException("The class is not created for instantiation");
}
public static String checkProject(String project)
{
checkArgument(project != null, "project is null");
if (!project.matches("^[0-9A-Za-z_]+$")) {
throw new IllegalArgumentException("Project id is not valid. It must be alphanumeric and should not include empty space.");
}
return project.toLowerCase(ENGLISH);
}
public static String checkProject(String project, char character)
{
return character + checkProject(project).replaceAll("\"", "") + character;
}
public static <T> T checkNotNull(T value, String name)
{
checkArgument(value != null, name + " is null");
return value;
}
public static String checkCollection(String collection)
{
return checkCollection(collection, '"');
}
public static String checkCollection(String collection, char character)
{
checkCollectionValid(collection);
return character + collection.replaceAll("\"", "") + character;
}
public static String checkCollectionValid(String collection)
{
checkArgument(collection != null, "collection is null");
checkArgument(!collection.isEmpty(), "collection is empty string");
if (collection.length() > 100) {
throw new IllegalArgumentException("Collection name must have maximum 250 characters.");
}
return collection;
}
public static String checkTableColumn(String column, char escape)
{
return checkTableColumn(column, column, escape);
}
public static String checkTableColumn(String column)
{
return checkTableColumn(column, column, '"');
}
public static String checkLiteral(String value)
{
return value.replaceAll("'", "''");
}
public static String checkTableColumn(String column, String type, char escape)
{
if (column == null) {
throw new IllegalArgumentException(type + " is null");
}
return escape + stripName(column, "field name") + escape;
}
public static void checkArgument(boolean expression, @Nullable String errorMessage)
{
if (!expression) {
if (errorMessage == null) {
throw new RakamException(BAD_REQUEST);
}
else {
throw new RakamException(errorMessage, BAD_REQUEST);
}
}
}
public static String stripName(String name, String type)
{
if (name.isEmpty()) {
throw new RakamException(type + " is empty", HttpResponseStatus.BAD_REQUEST);
}
StringBuilder builder = new StringBuilder(name.length());
for (int i = 0; i < name.length(); i++) {
char charAt = name.charAt(i);
if (charAt == '"' || (i == 0 && charAt == ' ')) {
continue;
}
if (Character.isUpperCase(charAt)) {
if (i > 0) {
if (Character.isLowerCase(name.charAt(i - 1))) {
builder.append("_");
}
}
charAt = Character.toLowerCase(charAt);
}
if (charAt >= 128) {
throw new IllegalArgumentException("Unicode characters are not supported. (" + name + ")");
}
else {
builder.append(charAt);
}
}
if (builder.length() == 0) {
throw new RakamException("Invalid " + type + ": " + name, HttpResponseStatus.BAD_REQUEST);
}
int lastIdx = builder.length() - 1;
if (builder.charAt(lastIdx) == ' ') {
builder.deleteCharAt(lastIdx);
}
return builder.toString();
}
}
|
package net.kencochrane.raven.dsn;
import mockit.Expectations;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.naming.Context;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class DsnTest {
@Mocked
private Context mockContext = null;
@BeforeMethod
public void setUp() throws Exception {
InitialContextFactory.context = mockContext;
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testEmptyDsnInvalid() throws Exception {
new Dsn("");
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testDsnFromInvalidUri() throws Exception {
new Dsn(URI.create(""));
}
@Test
public void testSimpleDsnValid() throws Exception {
Dsn dsn = new Dsn("http://publicKey:secretKey@host/9");
assertThat(dsn.getProtocol(), is("http"));
assertThat(dsn.getPublicKey(), is("publicKey"));
assertThat(dsn.getSecretKey(), is("secretKey"));
assertThat(dsn.getHost(), is("host"));
assertThat(dsn.getPath(), is("/"));
assertThat(dsn.getProjectId(), is("9"));
}
@Test
public void testSimpleDsnFromValidURI() throws Exception {
Dsn dsn = new Dsn(URI.create("http://publicKey:secretKey@host/9"));
assertThat(dsn.getProtocol(), is("http"));
assertThat(dsn.getPublicKey(), is("publicKey"));
assertThat(dsn.getSecretKey(), is("secretKey"));
assertThat(dsn.getHost(), is("host"));
assertThat(dsn.getPath(), is("/"));
assertThat(dsn.getProjectId(), is("9"));
}
@Test
public void testDsnLookupWithNothingSet() throws Exception {
assertThat(Dsn.dsnLookup(), is(nullValue()));
}
@Test
public void testJndiLookupFailsWithException(
@SuppressWarnings("unused") @Mocked("jndiLookup") JndiLookup mockJndiLookup) throws Exception {
new NonStrictExpectations() {{
JndiLookup.jndiLookup();
result = new ClassNotFoundException("Couldn't find the JNDI classes");
}};
assertThat(Dsn.dsnLookup(), is(nullValue()));
}
@Test
public void testJndiLookupFailsWithError(
@SuppressWarnings("unused") @Mocked("jndiLookup") JndiLookup mockJndiLookup) throws Exception {
new NonStrictExpectations() {{
JndiLookup.jndiLookup();
result = new NoClassDefFoundError("Couldn't find the JNDI classes");
}};
assertThat(Dsn.dsnLookup(), is(nullValue()));
}
@Test
public void testDsnLookupWithJndi() throws Exception {
final String dsn = "6621980c-e27b-4dc9-9130-7fc5e9ea9750";
new Expectations() {{
mockContext.lookup("java:comp/env/sentry/dsn");
result = dsn;
}};
assertThat(Dsn.dsnLookup(), is(dsn));
}
@Test
public void testDsnLookupWithSystemProperty() throws Exception {
String dsn = "aa9171a4-7e9b-4e3c-b3cc-fe537dc03527";
System.setProperty("SENTRY_DSN", dsn);
assertThat(Dsn.dsnLookup(), is(dsn));
System.clearProperty("SENTRY_DSN");
}
@Test
public void testDsnLookupWithEnvironmentVariable(@Mocked("getenv") final System system) throws Exception {
final String dsn = "759ed060-dd4f-4478-8a1a-3f23e044787c";
new NonStrictExpectations(){{
System.getenv("SENTRY_DSN");
result = dsn;
}};
assertThat(Dsn.dsnLookup(), is(dsn));
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testMissingSecretKeyInvalid() throws Exception {
new Dsn("http://publicKey:@host/9");
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testMissingHostInvalid() throws Exception {
new Dsn("http://publicKey:secretKey@/9");
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testMissingPathInvalid() throws Exception {
new Dsn("http://publicKey:secretKey@host");
}
@Test(expectedExceptions = InvalidDsnException.class)
public void testMissingProjectIdInvalid() throws Exception {
new Dsn("http://publicKey:secretKey@host/");
}
@Test
public void testAdvancedDsnValid() throws Exception {
Dsn dsn = new Dsn("naive+udp://1234567890:0987654321@complete.host.name:1234" +
"/composed/path/1029384756?option1&option2=valueOption2");
assertThat(dsn.getProtocol(), is("udp"));
assertThat(dsn.getProtocolSettings(), contains("naive"));
assertThat(dsn.getPublicKey(), is("1234567890"));
assertThat(dsn.getSecretKey(), is("0987654321"));
assertThat(dsn.getHost(), is("complete.host.name"));
assertThat(dsn.getPort(), is(1234));
assertThat(dsn.getPath(), is("/composed/path/"));
assertThat(dsn.getProjectId(), is("1029384756"));
assertThat(dsn.getOptions(), hasKey("option1"));
assertThat(dsn.getOptions(), hasKey("option2"));
assertThat(dsn.getOptions().get("option2"), is("valueOption2"));
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testOptionsImmutable() throws Exception {
Dsn dsn = new Dsn("http://publicKey:secretKey@host/9");
dsn.getOptions().put("test", "test");
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testProtocolSettingsImmutable() throws Exception {
Dsn dsn = new Dsn("http://publicKey:secretKey@host/9");
dsn.getProtocolSettings().add("test");
}
}
|
package re.notifica.reactnative;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import re.notifica.Notificare;
import re.notifica.model.NotificareAction;
import re.notifica.model.NotificareApplicationInfo;
import re.notifica.model.NotificareAsset;
import re.notifica.model.NotificareAttachment;
import re.notifica.model.NotificareBeacon;
import re.notifica.model.NotificareContent;
import re.notifica.model.NotificareCoordinates;
import re.notifica.model.NotificareDevice;
import re.notifica.model.NotificareInboxItem;
import re.notifica.model.NotificareNotification;
import re.notifica.model.NotificarePass;
import re.notifica.model.NotificarePassRedemption;
import re.notifica.model.NotificarePoint;
import re.notifica.model.NotificarePolygon;
import re.notifica.model.NotificareProduct;
import re.notifica.model.NotificareRegion;
import re.notifica.model.NotificareScannable;
import re.notifica.model.NotificareTimeOfDayRange;
import re.notifica.model.NotificareUser;
import re.notifica.model.NotificareUserPreference;
import re.notifica.model.NotificareUserPreferenceOption;
import re.notifica.model.NotificareUserSegment;
import re.notifica.util.ISODateFormatter;
import re.notifica.util.Log;
public class NotificareUtils {
public static final String TAG = NotificareUtils.class.getSimpleName();
/**
* Create a Map from ReadableMap
* @param data
* @return
*/
public static Map<String, Object> createMap(@Nullable ReadableMap data) {
if (data == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
ReadableMapKeySetIterator iterator = data.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType readableType = data.getType(key);
switch (readableType) {
case Null:
map.put(key, null);
break;
case Boolean:
map.put(key, data.getBoolean(key));
break;
case Number:
map.put(key, data.getDouble(key));
break;
case String:
map.put(key, data.getString(key));
break;
case Map:
map.put(key, createMap(data.getMap(key)));
break;
default:
break;
}
}
return map;
}
public static WritableArray mapJSON(JSONArray json) {
if (json != null) {
WritableArray writableArray = Arguments.createArray();
try {
for (int i = 0; i < json.length(); i++) {
Object value = json.get(i);
if (value instanceof Boolean) {
writableArray.pushBoolean(json.getBoolean(i));
} else if (value instanceof Float || value instanceof Double) {
writableArray.pushDouble(json.getDouble(i));
} else if (value instanceof Number) {
writableArray.pushInt(json.getInt(i));
} else if (value instanceof String) {
writableArray.pushString(json.getString(i));
} else if (value instanceof JSONObject) {
writableArray.pushMap(mapJSON(json.getJSONObject(i)));
} else if (value instanceof JSONArray) {
writableArray.pushArray(mapJSON(json.getJSONArray(i)));
} else if (value == JSONObject.NULL) {
writableArray.pushNull();
}
}
} catch (JSONException e) {
// fail silently
}
return writableArray;
} else {
return null;
}
}
public static WritableMap mapJSON(JSONObject json) {
if (json != null) {
WritableMap writableMap = Arguments.createMap();
Iterator<String> iterator = json.keys();
try {
while (iterator.hasNext()) {
String key = iterator.next();
Object value = json.get(key);
if (value instanceof Boolean) {
writableMap.putBoolean(key, json.getBoolean(key));
} else if (value instanceof Float || value instanceof Double) {
writableMap.putDouble(key, json.getDouble(key));
} else if (value instanceof Number) {
writableMap.putInt(key, json.getInt(key));
} else if (value instanceof String) {
writableMap.putString(key, json.getString(key));
} else if (value instanceof JSONObject) {
writableMap.putMap(key, mapJSON(json.getJSONObject(key)));
} else if (value instanceof JSONArray) {
writableMap.putArray(key, mapJSON(json.getJSONArray(key)));
} else if (value == JSONObject.NULL) {
writableMap.putNull(key);
}
}
} catch (JSONException e) {
// fail silently
}
return writableMap;
} else {
return null;
}
}
public static WritableMap mapApplicationInfo(NotificareApplicationInfo notificareApplicationInfo) {
WritableMap infoMap = Arguments.createMap();
infoMap.putString("id", notificareApplicationInfo.getId());
infoMap.putString("name", notificareApplicationInfo.getName());
WritableMap servicesMap = Arguments.createMap();
for (String key : notificareApplicationInfo.getServices().keySet()) {
servicesMap.putBoolean(key, notificareApplicationInfo.getServices().get(key));
}
infoMap.putMap("services", servicesMap);
if (notificareApplicationInfo.getInboxConfig() != null) {
WritableMap inboxConfigMap = Arguments.createMap();
inboxConfigMap.putBoolean("autoBadge", notificareApplicationInfo.getInboxConfig().getAutoBadge());
inboxConfigMap.putBoolean("useInbox", notificareApplicationInfo.getInboxConfig().getUseInbox());
infoMap.putMap("inboxConfig", inboxConfigMap);
}
if (notificareApplicationInfo.getRegionConfig() != null) {
WritableMap regionConfigMap = Arguments.createMap();
regionConfigMap.putString("proximityUUID", notificareApplicationInfo.getRegionConfig().getProximityUUID());
infoMap.putMap("regionConfig", regionConfigMap);
}
WritableArray userDataFieldsArray = Arguments.createArray();
for (String key : notificareApplicationInfo.getUserDataFields().keySet()){
WritableMap userDataFieldMap = Arguments.createMap();
userDataFieldMap.putString("key", key);
userDataFieldMap.putString("label", notificareApplicationInfo.getUserDataFields().get(key).getLabel());
userDataFieldsArray.pushMap(userDataFieldMap);
}
infoMap.putArray("userDataFields", userDataFieldsArray);
return infoMap;
}
public static WritableMap mapDevice(NotificareDevice device) {
WritableMap deviceMap = Arguments.createMap();
deviceMap.putString("deviceID", device.getDeviceId());
deviceMap.putString("userID", device.getUserId());
deviceMap.putString("userName", device.getUserName());
deviceMap.putDouble("timezone", device.getTimeZoneOffset());
deviceMap.putString("osVersion", device.getOsVersion());
deviceMap.putString("sdkVersion", device.getSdkVersion());
deviceMap.putString("appVersion", device.getAppVersion());
deviceMap.putString("deviceString", device.getDeviceString());
deviceMap.putString("deviceModel", device.getDeviceString());
deviceMap.putString("countryCode", device.getCountry());
deviceMap.putString("language", device.getLanguage());
deviceMap.putString("region", device.getRegion());
deviceMap.putString("transport", device.getTransport());
if (!Double.isNaN(device.getLatitude())) {
deviceMap.putDouble("latitude", device.getLatitude());
}
if (!Double.isNaN(device.getLongitude())) {
deviceMap.putDouble("longitude", device.getLongitude());
}
if (!Double.isNaN(device.getAltitude())) {
deviceMap.putDouble("altitude", device.getAltitude());
}
if (!Double.isNaN(device.getSpeed())) {
deviceMap.putDouble("speed", device.getSpeed());
}
if (!Double.isNaN(device.getCourse())) {
deviceMap.putDouble("course", device.getCourse());
}
if (!Double.isNaN(device.getAccuracy())) {
deviceMap.putDouble("accuracy", device.getAccuracy());
}
if (device.getLastActive() != null) {
deviceMap.putString("lastRegistered", ISODateFormatter.format(device.getLastActive()));
}
deviceMap.putString("locationServicesAuthStatus", device.getLocationServicesAuthStatus());
deviceMap.putBoolean("registeredForNotification", Notificare.shared().isNotificationsEnabled());
deviceMap.putBoolean("allowedLocationServices", Notificare.shared().isLocationUpdatesEnabled());
deviceMap.putBoolean("allowedUI", device.getAllowedUI());
deviceMap.putBoolean("bluetoothEnabled", device.getBluetoothEnabled());
deviceMap.putBoolean("bluetoothON", device.getBluetoothEnabled());
return deviceMap;
}
public static WritableMap mapNotification(NotificareNotification notification) {
WritableMap notificationMap = Arguments.createMap();
notificationMap.putString("id", notification.getNotificationId());
notificationMap.putString("message", notification.getMessage());
notificationMap.putString("title", notification.getTitle());
notificationMap.putString("subtitle", notification.getSubtitle());
notificationMap.putString("type", notification.getType());
notificationMap.putString("time", ISODateFormatter.format(notification.getTime()));
if (notification.getExtra() != null) {
WritableMap extraMap = Arguments.createMap();
for (HashMap.Entry<String, String> prop : notification.getExtra().entrySet()) {
extraMap.putString(prop.getKey(), prop.getValue());
}
notificationMap.putMap("extra", extraMap);
}
if (notification.getContent().size() > 0) {
WritableArray contentArray = Arguments.createArray();
for (NotificareContent c : notification.getContent()) {
WritableMap contentMap = Arguments.createMap();
contentMap.putString("type", c.getType());
contentMap.putString("data", c.getData().toString());
contentArray.pushMap(contentMap);
}
notificationMap.putArray("content", contentArray);
}
if (notification.getAttachments().size() > 0) {
WritableArray attachmentsArray = Arguments.createArray();
for (NotificareAttachment a : notification.getAttachments()) {
WritableMap attachmentsMap = Arguments.createMap();
attachmentsMap.putString("mimeType", a.getMimeType());
attachmentsMap.putString("uri", a.getUri());
attachmentsArray.pushMap(attachmentsMap);
}
notificationMap.putArray("attachments", attachmentsArray);
}
if (notification.getActions().size() > 0) {
WritableArray actionsArray = Arguments.createArray();
for (NotificareAction a : notification.getActions()) {
WritableMap actionMap = Arguments.createMap();
actionMap.putString("label", a.getLabel());
actionMap.putString("type", a.getType());
actionMap.putString("target", a.getTarget());
actionMap.putBoolean("camera", a.getCamera());
actionMap.putBoolean("keyboard", a.getKeyboard());
actionsArray.pushMap(actionMap);
}
notificationMap.putArray("actions", actionsArray);
}
notificationMap.putBoolean("partial", notification.isPartial());
return notificationMap;
}
public static NotificareNotification createNotification(ReadableMap notificationMap) {
if (notificationMap.getBoolean("partial")) {
return null;
} else {
try {
JSONObject json = new JSONObject(notificationMap.toHashMap());
if (notificationMap.hasKey("id")) {
json.put("_id", notificationMap.getString("id"));
}
// if (notificationMap.hasKey("message")) {
// json.put("message", notificationMap.getString("message"));
// if (notificationMap.hasKey("title")) {
// json.put("title", notificationMap.getString("title"));
// if (notificationMap.hasKey("subtitle")) {
// json.put("subtitle", notificationMap.getString("subtitle"));
// if (notificationMap.hasKey("type")) {
// json.put("type", notificationMap.getString("type"));
// if (notificationMap.hasKey("time")) {
// json.put("time", notificationMap.getString("time"));
// if (notificationMap.hasKey("partial")) {
// json.put("partial", notificationMap.getBoolean("partial"));
// if (notificationMap.hasKey("extra")) {
// ReadableMap extra = notificationMap.getMap("extra");
// JSONObject extraJson = new JSONObject();
// while (extra.keySetIterator().hasNextKey()) {
// String key = extra.keySetIterator().nextKey();
// extraJson.put(key, extra.getString(key));
// json.put("extra", extraJson);
// if (notificationMap.hasKey("attachments")) {
// ReadableArray attachments = notificationMap.getArray("attachments");
// if (attachments != null) {
// JSONArray attachmentsJson = new JSONArray();
// for (int i = 0; i < attachments.size(); i++) {
// ReadableMap attachment = attachments.getMap(i);
// if (attachment != null && attachment.hasKey("mimeType") && attachment.hasKey("uri")) {
// JSONObject attachmentJson = new JSONObject();
// attachmentJson.put("mimeType", attachment.getString("mimeType"));
// attachmentJson.put("uri", attachment.getString("uri"));
// attachmentsJson.put(attachmentJson);
// json.put("attachments", attachmentsJson);
// if (notificationMap.hasKey("content")) {
// ReadableArray content = notificationMap.getArray("content");
// if (content != null) {
// JSONArray contentJson = new JSONArray();
// for (int i = 0; i < content.size(); i++) {
// ReadableMap contentItem = content.getMap(i);
// if (contentItem != null && contentItem.hasKey("type") && contentItem.hasKey("data")) {
// JSONObject contentItemJson = new JSONObject();
// contentItemJson.put("type", contentItem.getString("type"));
// try {
// contentItemJson.put("data", new JSONObject(contentItem.getString("data")));
// } catch (JSONException e) {
// contentItemJson.put("data", contentItem.getString("data"));
// contentJson.put(contentItemJson);
// json.put("content", contentJson);
// if (notificationMap.hasKey("actions")) {
// ReadableArray actions = notificationMap.getArray("actions");
// if (actions != null) {
// JSONArray actionsJson = new JSONArray();
// for (int i = 0; i < actions.size(); i++) {
// ReadableMap action = actions.getMap(i);
// if (action != null && action.hasKey("label") && action.hasKey("type")) {
// JSONObject actionJson = new JSONObject();
// actionJson.put("label", action.getString("label"));
// actionJson.put("type", action.getString("type"));
// if (action.hasKey("target")) {
// actionJson.put("target", action.getString("target"));
// if (action.hasKey("camera")) {
// actionJson.put("camera", action.getBoolean("camera"));
// if (action.hasKey("keyboard")) {
// actionJson.put("keyboard", action.getBoolean("keyboard"));
// actionsJson.put(actionJson);
// json.put("actions", actionsJson);
return new NotificareNotification(json);
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return null;
}
}
}
public static WritableMap mapAsset(NotificareAsset asset) {
WritableMap assetMap = Arguments.createMap();
assetMap.putString("assetTitle", asset.getTitle());
assetMap.putString("assetDescription", asset.getDescription());
if (asset.getUrl() != null) {
assetMap.putString("assetUrl", asset.getUrl().toString());
}
assetMap.putMap("assetExtra", mapJSON(asset.getExtra()));
WritableMap theMeta = Arguments.createMap();
theMeta.putString("originalFileName", asset.getOriginalFileName());
theMeta.putString("key", asset.getKey());
theMeta.putString("contentType", asset.getContentType());
theMeta.putInt("contentLength", asset.getContentLength());
assetMap.putMap("assetMetaData", theMeta);
WritableMap theButton = Arguments.createMap();
theButton.putString("label", asset.getButtonLabel());
theButton.putString("action", asset.getButtonAction());
assetMap.putMap("assetButton", theButton);
return assetMap;
}
public static WritableMap mapTimeOfDayRange(NotificareTimeOfDayRange notificareTimeOfDayRange) {
WritableMap timeOfDayRangeMap = Arguments.createMap();
timeOfDayRangeMap.putString("start", notificareTimeOfDayRange.getStart().toString());
timeOfDayRangeMap.putString("end", notificareTimeOfDayRange.getEnd().toString());
return timeOfDayRangeMap;
}
public static WritableMap mapInboxItem(NotificareInboxItem notificareInboxItem) {
WritableMap inboxItemMap = Arguments.createMap();
inboxItemMap.putString("inboxId", notificareInboxItem.getItemId());
inboxItemMap.putString("notification", notificareInboxItem.getNotification().getNotificationId());
inboxItemMap.putString("type", notificareInboxItem.getType());
inboxItemMap.putString("message", notificareInboxItem.getNotification().getMessage());
inboxItemMap.putString("title", notificareInboxItem.getTitle());
inboxItemMap.putString("subtitle", notificareInboxItem.getSubtitle());
if (notificareInboxItem.getAttachment() != null) {
WritableMap attachmentsMap = Arguments.createMap();
attachmentsMap.putString("mimeType", notificareInboxItem.getAttachment().getMimeType());
attachmentsMap.putString("uri", notificareInboxItem.getAttachment().getUri());
inboxItemMap.putMap("attachment", attachmentsMap);
}
if (notificareInboxItem.getExtra() != null) {
WritableMap extraMap = Arguments.createMap();
for (HashMap.Entry<String, String> prop : notificareInboxItem.getExtra().entrySet()) {
extraMap.putString(prop.getKey(), prop.getValue());
}
inboxItemMap.putMap("extra", extraMap);
}
inboxItemMap.putString("time", ISODateFormatter.format(notificareInboxItem.getTimestamp()));
inboxItemMap.putBoolean("opened", notificareInboxItem.getStatus());
return inboxItemMap;
}
public static WritableMap mapBeacon(NotificareBeacon beacon) {
WritableMap map = Arguments.createMap();
map.putString("beaconId", beacon.getBeaconId());
map.putString("beaconName", beacon.getName());
map.putString("beaconRegion", beacon.getRegionId());
map.putString("beaconUUID", Notificare.shared().getApplicationInfo().getRegionConfig().getProximityUUID());
map.putInt("beaconMajor", beacon.getMajor());
map.putInt("beaconMinor", beacon.getMinor());
map.putBoolean("beaconTriggers", beacon.getTriggers());
return map;
}
public static WritableMap mapRegion(NotificareRegion region) {
WritableMap map = Arguments.createMap();
map.putString("regionId", region.getRegionId());
map.putString("regionName", region.getName());
map.putInt("regionMajor", region.getMajor());
if (region.getGeometry() != null) {
map.putMap("regionGeometry", mapPoint(region.getGeometry()));
}
if (region.getAdvancedGeometry() != null) {
map.putMap("regionAdvancedGeometry", mapPolygon(region.getAdvancedGeometry()));
}
map.putDouble("regionDistance", region.getDistance());
map.putString("regionTimezone", region.getTimezone());
return map;
}
public static WritableMap mapPoint(NotificarePoint point) {
WritableMap map = Arguments.createMap();
map.putString("type", point.getType());
WritableArray coordinates = Arguments.createArray();
coordinates.pushDouble(point.getLongitude());
coordinates.pushDouble(point.getLatitude());
map.putArray("coordinates", coordinates);
return map;
}
public static WritableMap mapPolygon(NotificarePolygon polygon) {
WritableMap map = Arguments.createMap();
map.putString("type", polygon.getType());
WritableArray ring = Arguments.createArray();
WritableArray coordinatesList = Arguments.createArray();
for (NotificareCoordinates coordinates : polygon.getCoordinates()) {
WritableArray coordinatesPair = Arguments.createArray();
coordinatesPair.pushDouble(coordinates.getLongitude());
coordinatesPair.pushDouble(coordinates.getLatitude());
coordinatesList.pushArray(coordinatesPair);
}
ring.pushArray(coordinatesList);
map.putArray("coordinates", ring);
return map;
}
public static WritableMap mapPass(NotificarePass pass) {
WritableMap map = Arguments.createMap();
map.putString("passbook", pass.getPassbook());
map.putString("serial", pass.getSerial());
if (pass.getRedeem() == NotificarePass.Redeem.ALWAYS) {
map.putString("redeem", "always");
} else if (pass.getRedeem() == NotificarePass.Redeem.LIMIT) {
map.putString("redeem", "limit");
} else if (pass.getRedeem() == NotificarePass.Redeem.ONCE) {
map.putString("redeem", "once");
}
map.putString("token", pass.getToken());
if (pass.getData() != null) {
map.putMap("data", mapJSON(pass.getData()));
}
map.putString("date", ISODateFormatter.format(pass.getDate()));
map.putInt("limit", pass.getLimit());
WritableArray redeemHistory = Arguments.createArray();
for (NotificarePassRedemption redemption : pass.getRedeemHistory()) {
WritableMap redemptionMap = Arguments.createMap();
redemptionMap.putString("comments", redemption.getComments());
redemptionMap.putString("date", ISODateFormatter.format(redemption.getDate()));
redeemHistory.pushMap(redemptionMap);
}
map.putArray("redeemHistory", redeemHistory);
return map;
}
public static WritableArray mapProducts(List<NotificareProduct> products) {
WritableArray productList = Arguments.createArray();
for (NotificareProduct product : products){
productList.pushMap(mapProduct(product));
}
return productList;
}
public static WritableMap mapProduct(NotificareProduct product) {
WritableMap productItemMap = Arguments.createMap();
productItemMap.putString("productType", product.getType());
productItemMap.putString("productIdentifier", product.getIdentifier());
productItemMap.putString("productName", product.getName());
productItemMap.putString("productDescription", product.getSkuDetails().getDescription());
productItemMap.putString("productPrice", product.getSkuDetails().getPrice());
productItemMap.putString("productCurrency", product.getSkuDetails().getPriceCurrencyCode());
productItemMap.putString("productDate", ISODateFormatter.format(product.getDate()));
productItemMap.putBoolean("productActive", true);
return productItemMap;
}
public static WritableMap mapUser(NotificareUser user) {
WritableMap userMap = Arguments.createMap();
userMap.putString("userID", user.getUserId());
userMap.putString("userName", user.getUserName());
userMap.putString("accessToken", user.getAccessToken());
WritableArray segments = Arguments.createArray();
if (user.getSegments() != null) {
for (String segmentId : user.getSegments()) {
segments.pushString(segmentId);
}
}
userMap.putArray("segments", segments);
return userMap;
}
public static WritableArray mapUserSegments(List<NotificareUserSegment> userSegments) {
WritableArray userSegmentsArray = Arguments.createArray();
for (NotificareUserSegment userSegment : userSegments) {
userSegmentsArray.pushMap(mapUserSegment(userSegment));
}
return userSegmentsArray;
}
public static WritableMap mapUserPreference(NotificareUserPreference userPreference) {
WritableMap userPreferenceMap = Arguments.createMap();
userPreferenceMap.putString("preferenceId", userPreference.getId());
userPreferenceMap.putString("preferenceLabel", userPreference.getLabel());
userPreferenceMap.putString("preferenceType", userPreference.getPreferenceType());
WritableArray options = Arguments.createArray();
for (NotificareUserPreferenceOption option : userPreference.getPreferenceOptions()) {
WritableMap optionMap = Arguments.createMap();
optionMap.putString("segmentId", option.getUserSegmentId());
optionMap.putString("segmentLabel", option.getLabel());
optionMap.putBoolean("selected", option.isSelected());
options.pushMap(optionMap);
}
userPreferenceMap.putArray("preferenceOptions", options);
return userPreferenceMap;
}
public static NotificareUserPreference createUserPreference(ReadableMap userPreferenceMap) {
try {
JSONObject json = new JSONObject();
json.put("_id", userPreferenceMap.getString("preferenceId"));
json.put("label", userPreferenceMap.getString("preferenceLabel"));
json.put("preferenceType", userPreferenceMap.getString("preferenceType"));
ReadableArray userPreferenceOptionsJson = userPreferenceMap.getArray("preferenceOptions");
JSONArray convertedUserPreferenceOptions = new JSONArray();
for (int i = 0; i < userPreferenceOptionsJson.size(); i++) {
ReadableMap optionJson = userPreferenceOptionsJson.getMap(i);
JSONObject destinationJson = new JSONObject();
destinationJson.put("label", optionJson.getString("segmentLabel"));
destinationJson.put("userSegment", optionJson.getString("segmentId"));
destinationJson.put("selected", optionJson.getBoolean("selected"));
convertedUserPreferenceOptions.put(destinationJson);
}
json.put("preferenceOptions", convertedUserPreferenceOptions);
json.put("indexPosition", -1);
return new NotificareUserPreference(json);
} catch (JSONException e) {
return null;
}
}
public static WritableMap mapUserSegment(NotificareUserSegment userSegment) {
WritableMap userSegmentMap = Arguments.createMap();
userSegmentMap.putString("segmentId", userSegment.getId());
userSegmentMap.putString("segmentLabel", userSegment.getName());
return userSegmentMap;
}
public static NotificareUserSegment createUserSegment(ReadableMap userSegmentMap) {
try {
JSONObject json = new JSONObject();
json.put("_id", userSegmentMap.getString("segmentId"));
json.put("name", userSegmentMap.getString("segmentLabel"));
return new NotificareUserSegment(json);
} catch (JSONException e) {
return null;
}
}
public static WritableMap mapScannable(NotificareScannable scannable) {
WritableMap scannableMap = Arguments.createMap();
scannableMap.putString("scannableId", scannable.getScannableId());
scannableMap.putString("name", scannable.getName());
scannableMap.putString("type", scannable.getType());
scannableMap.putString("tag", scannable.getTag());
scannableMap.putMap("data", mapJSON(scannable.getData()));
scannableMap.putMap("notification", mapNotification(scannable.getNotification()));
return scannableMap;
}
}
|
package com.creatubbles.api.service;
import com.creatubbles.api.EndPoints;
import com.creatubbles.api.model.creation.Creation;
import com.creatubbles.api.model.creation.ToybooDetails;
import com.creatubbles.api.model.image_manipulation.ImageManipulation;
import com.creatubbles.api.model.upload.Upload;
import com.creatubbles.api.request.UploadRequest;
import com.github.jasminb.jsonapi.JSONAPIDocument;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
public interface CreationService {
String PARAM_PAGE = "page";
String PARAM_PAGE_SIZE = "per_page";
String PARAM_USER_ID = "user_id";
String PARAM_ONLY_PUBLIC = "filter[public]";
String PARAM_GALLERY_ID = "gallery_id";
String PARAM_SEARCH = "search";
String PARAM_ABORTED_WITH = "aborted_with";
String PARAM_CREATION_ID = "creation_id";
String PARAM_PARTNER_APPLICATION_ID = "partner_application_id";
String PATH_USER_ID = "{" + PARAM_USER_ID + "}";
String PATH_CREATION_ID = "{" + PARAM_CREATION_ID + "}";
@GET(EndPoints.CREATIONS)
Call<JSONAPIDocument<List<Creation>>> getRecent(@Query(PARAM_PAGE) Integer page,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic,
@Query(PARAM_PAGE_SIZE) Integer pageSize);
@GET(EndPoints.CREATIONS)
Call<JSONAPIDocument<List<Creation>>> getFromGallery(@Query(PARAM_PAGE) Integer page,
@Query(PARAM_GALLERY_ID) String galleryId,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic);
@GET(EndPoints.CREATIONS)
Call<JSONAPIDocument<List<Creation>>> getByUser(@Query(PARAM_PAGE) Integer page,
@Query(PARAM_USER_ID) String userId,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic);
@GET(EndPoints.CREATIONS)
Call<JSONAPIDocument<List<Creation>>> searchByName(@Query(PARAM_PAGE) Integer page,
@Query(PARAM_SEARCH) String name,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic);
@GET(EndPoints.CREATIONS + "/" + PATH_CREATION_ID + "/recommended_creations")
Call<JSONAPIDocument<List<Creation>>> getRecommendedByCreation(@Query(PARAM_PAGE) Integer page,
@Path(PARAM_CREATION_ID) String creationId,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic);
@GET(EndPoints.USERS + "/" + PATH_USER_ID + "/recommended_creations")
Call<JSONAPIDocument<List<Creation>>> getRecommendedByUser(@Query(PARAM_PAGE) Integer page,
@Path(PARAM_USER_ID) String userId,
@Query(PARAM_ONLY_PUBLIC) Boolean onlyPublic);
@GET(EndPoints.CREATIONS + "/" + PATH_CREATION_ID)
Call<JSONAPIDocument<Creation>> getCreation(@Path(PARAM_CREATION_ID) String creationId);
@POST(EndPoints.CREATIONS)
Call<JSONAPIDocument<Creation>> createCreation(@Body Creation creation);
@PUT(EndPoints.CREATIONS + "/" + PATH_CREATION_ID)
Call<Void> updateCreation(@Path(PARAM_CREATION_ID) String creationId, @Body Creation body);
@DELETE(EndPoints.CREATIONS + "/" + PATH_CREATION_ID)
Call<Void> removeCreation(@Path(PARAM_CREATION_ID) String creationId);
@POST(EndPoints.CREATIONS + "/" + PATH_CREATION_ID + "/uploads")
Call<JSONAPIDocument<Upload>> createUpload(@Path(PARAM_CREATION_ID) String id, @Body UploadRequest body);
@PUT
@FormUrlEncoded
Call<Void> updateCreationUpload(@Url String pingUrl, @Field(PARAM_ABORTED_WITH) String abortedWith);
@PUT(EndPoints.CREATIONS + "/" + PATH_CREATION_ID + "/image_manipulation")
Call<Void> putImageManipulation(@Path(PARAM_CREATION_ID) String id, @Body ImageManipulation imageManipulation);
@GET(EndPoints.CREATIONS + "/" + PATH_CREATION_ID + "/toyboo_details")
Call<JSONAPIDocument<ToybooDetails>> getToybooDetails(@Path(PARAM_CREATION_ID) String id);
@GET(EndPoints.CREATIONS)
Call<JSONAPIDocument<List<Creation>>> getByPartnerApplication(@Query(PARAM_PAGE) Integer page,
@Query(PARAM_PARTNER_APPLICATION_ID) String partnerAppId);
@PUT(EndPoints.CREATIONS + "/" + PATH_CREATION_ID + "/view")
Call<Void> updateViewsCount(@Path(PARAM_CREATION_ID) String creationId);
}
|
package org.pmiops.workbench.db.dao;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.services.oauth2.model.Userinfoplus;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.Clock;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Provider;
import org.hibernate.exception.GenericJDBCException;
import org.javers.common.collections.Lists;
import org.pmiops.workbench.access.AccessTierService;
import org.pmiops.workbench.actionaudit.Agent;
import org.pmiops.workbench.actionaudit.auditors.UserServiceAuditor;
import org.pmiops.workbench.actionaudit.targetproperties.BypassTimeTargetProperty;
import org.pmiops.workbench.compliance.ComplianceService;
import org.pmiops.workbench.config.WorkbenchConfig;
import org.pmiops.workbench.db.model.DbAccessTier;
import org.pmiops.workbench.db.model.DbAddress;
import org.pmiops.workbench.db.model.DbAdminActionHistory;
import org.pmiops.workbench.db.model.DbDemographicSurvey;
import org.pmiops.workbench.db.model.DbUser;
import org.pmiops.workbench.db.model.DbUserDataUseAgreement;
import org.pmiops.workbench.db.model.DbUserTermsOfService;
import org.pmiops.workbench.db.model.DbVerifiedInstitutionalAffiliation;
import org.pmiops.workbench.exceptions.BadRequestException;
import org.pmiops.workbench.exceptions.ConflictException;
import org.pmiops.workbench.exceptions.NotFoundException;
import org.pmiops.workbench.firecloud.ApiClient;
import org.pmiops.workbench.firecloud.FireCloudService;
import org.pmiops.workbench.firecloud.api.NihApi;
import org.pmiops.workbench.firecloud.model.FirecloudNihStatus;
import org.pmiops.workbench.google.DirectoryService;
import org.pmiops.workbench.model.AccessBypassRequest;
import org.pmiops.workbench.model.Authority;
import org.pmiops.workbench.model.Degree;
import org.pmiops.workbench.model.EmailVerificationStatus;
import org.pmiops.workbench.model.RenewableAccessModuleStatus;
import org.pmiops.workbench.model.RenewableAccessModuleStatus.ModuleNameEnum;
import org.pmiops.workbench.monitoring.GaugeDataCollector;
import org.pmiops.workbench.monitoring.MeasurementBundle;
import org.pmiops.workbench.monitoring.labels.MetricLabel;
import org.pmiops.workbench.monitoring.views.GaugeMetric;
import org.pmiops.workbench.moodle.model.BadgeDetailsV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* A higher-level service class containing user manipulation and business logic which can't be
* represented by automatic query generation in UserDao.
*
* <p>A large portion of this class is dedicated to:
*
* <p>(1) making it easy to consistently modify a subset of fields in a User entry, with retries (2)
* ensuring we call a single updateUserAccessTiers method whenever a User entry is saved.
*/
@Service
public class UserServiceImpl implements UserService, GaugeDataCollector {
private static final int MAX_RETRIES = 3;
private static final int CURRENT_TERMS_OF_SERVICE_VERSION = 1;
private final Provider<WorkbenchConfig> configProvider;
private final Provider<DbUser> userProvider;
private final Clock clock;
private final Random random;
private final UserServiceAuditor userServiceAuditor;
private final UserDao userDao;
private final AdminActionHistoryDao adminActionHistoryDao;
private final UserDataUseAgreementDao userDataUseAgreementDao;
private final UserTermsOfServiceDao userTermsOfServiceDao;
private final VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao;
private final FireCloudService fireCloudService;
private final ComplianceService complianceService;
private final DirectoryService directoryService;
private final AccessTierService accessTierService;
private static final Logger log = Logger.getLogger(UserServiceImpl.class.getName());
@Autowired
public UserServiceImpl(
Provider<WorkbenchConfig> configProvider,
Provider<DbUser> userProvider,
Clock clock,
Random random,
UserServiceAuditor userServiceAuditor,
UserDao userDao,
AdminActionHistoryDao adminActionHistoryDao,
UserDataUseAgreementDao userDataUseAgreementDao,
UserTermsOfServiceDao userTermsOfServiceDao,
VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao,
FireCloudService fireCloudService,
ComplianceService complianceService,
DirectoryService directoryService,
AccessTierService accessTierService) {
this.configProvider = configProvider;
this.userProvider = userProvider;
this.clock = clock;
this.random = random;
this.userServiceAuditor = userServiceAuditor;
this.userDao = userDao;
this.adminActionHistoryDao = adminActionHistoryDao;
this.userDataUseAgreementDao = userDataUseAgreementDao;
this.userTermsOfServiceDao = userTermsOfServiceDao;
this.verifiedInstitutionalAffiliationDao = verifiedInstitutionalAffiliationDao;
this.fireCloudService = fireCloudService;
this.complianceService = complianceService;
this.directoryService = directoryService;
this.accessTierService = accessTierService;
}
@VisibleForTesting
@Override
public int getCurrentDuccVersion() {
return configProvider.get().featureFlags.enableV3DataUserCodeOfConduct ? 3 : 2;
}
/**
* Updates a user record with a modifier function.
*
* <p>Ensures that the data access tiers for the user reflect the state of other fields on the
* user; handles conflicts with concurrent updates by retrying.
*/
@Override
public DbUser updateUserWithRetries(
Function<DbUser, DbUser> userModifier, DbUser dbUser, Agent agent) {
int objectLockingFailureCount = 0;
int statementClosedCount = 0;
while (true) {
dbUser = userModifier.apply(dbUser);
updateUserAccessTiers(dbUser, agent);
try {
return userDao.save(dbUser);
} catch (ObjectOptimisticLockingFailureException e) {
if (objectLockingFailureCount < MAX_RETRIES) {
long userId = dbUser.getUserId();
dbUser =
userDao
.findById(userId)
.orElseThrow(
() ->
new BadRequestException(
String.format("User with ID %s not found", userId)));
objectLockingFailureCount++;
} else {
throw new ConflictException(
String.format(
"Could not update user %s after %d object locking failures",
dbUser.getUserId(), objectLockingFailureCount));
}
} catch (JpaSystemException e) {
// We don't know why this happens instead of the object locking failure.
if (((GenericJDBCException) e.getCause())
.getSQLException()
.getMessage()
.equals("Statement closed.")) {
if (statementClosedCount < MAX_RETRIES) {
long userId = dbUser.getUserId();
dbUser =
userDao
.findById(userId)
.orElseThrow(
() ->
new BadRequestException(
String.format("User with ID %s not found", userId)));
statementClosedCount++;
} else {
throw new ConflictException(
String.format(
"Could not update user %s after %d statement closes",
dbUser.getUserId(), statementClosedCount));
}
} else {
throw e;
}
}
}
}
private void updateUserAccessTiers(DbUser dbUser, Agent agent) {
final List<DbAccessTier> previousAccessTiers = accessTierService.getAccessTiersForUser(dbUser);
// TODO for Controlled Tier Beta: different access module evaluation criteria
// For Controlled Tier Alpha, we simply evaluate whether the user is qualified for
// Registered Tier and set RT+CT or RT only based on the feature flag
final List<DbAccessTier> newAccessTiers =
shouldUserBeRegistered(dbUser)
? accessTierService.getTiersForRegisteredUsers()
: Collections.emptyList();
if (!newAccessTiers.equals(previousAccessTiers)) {
userServiceAuditor.fireUpdateAccessTiersAction(
dbUser, previousAccessTiers, newAccessTiers, agent);
}
// add user to each Access Tier DB table and the tiers' Terra Auth Domains
newAccessTiers.forEach(tier -> accessTierService.addUserToTier(dbUser, tier));
// remove user from all other Access Tier DB tables and the tiers' Terra Auth Domains
final List<DbAccessTier> tiersForRemoval =
Lists.difference(accessTierService.getAllTiers(), newAccessTiers);
tiersForRemoval.forEach(tier -> accessTierService.removeUserFromTier(dbUser, tier));
}
private class ModuleTimes {
public Optional<Timestamp> completion;
public Optional<Timestamp> bypass;
public ModuleTimes(Timestamp nullableCompletion, Timestamp nullableBypass) {
completion = Optional.ofNullable(nullableCompletion);
bypass = Optional.ofNullable(nullableBypass);
}
public boolean isBypassed() {
return bypass.isPresent();
}
public boolean isComplete() {
return completion.isPresent();
}
public Optional<Timestamp> getExpiration() {
if (isBypassed() || !configProvider.get().access.enableAccessRenewal) {
return Optional.empty();
}
Long expiryDays = configProvider.get().accessRenewal.expiryDays;
Preconditions.checkNotNull(
expiryDays, "expected value for config key accessRenewal.expiryDays.expiryDays");
long expiryDaysInMs = TimeUnit.MILLISECONDS.convert(expiryDays, TimeUnit.DAYS);
return completion.map(c -> new Timestamp(c.getTime() + expiryDaysInMs));
}
public boolean hasExpired() {
final Timestamp now = new Timestamp(clock.millis());
return getExpiration().map(x -> x.before(now)).orElse(false);
}
}
private RenewableAccessModuleStatus mkStatus(ModuleNameEnum name, ModuleTimes times) {
return new RenewableAccessModuleStatus()
.moduleName(name)
.expirationEpochMillis(times.getExpiration().map(Timestamp::getTime).orElse(null))
.hasExpired(times.hasExpired());
}
public List<RenewableAccessModuleStatus> getRenewableAccessModuleStatus(DbUser user) {
return ImmutableList.of(
mkStatus(
ModuleNameEnum.COMPLIANCETRAINING,
new ModuleTimes(
user.getComplianceTrainingCompletionTime(),
user.getComplianceTrainingBypassTime())),
mkStatus(
ModuleNameEnum.DATAUSEAGREEMENT,
new ModuleTimes(
user.getDataUseAgreementCompletionTime(), user.getDataUseAgreementBypassTime())),
mkStatus(
ModuleNameEnum.PROFILECONFIRMATION,
new ModuleTimes(user.getProfileLastConfirmedTime(), null)),
mkStatus(
ModuleNameEnum.PUBLICATIONCONFIRMATION,
new ModuleTimes(user.getPublicationsLastConfirmedTime(), null)));
}
private boolean isDataUseAgreementCompliant(DbUser user) {
final ModuleTimes duaTimes =
new ModuleTimes(
user.getDataUseAgreementCompletionTime(), user.getDataUseAgreementBypassTime());
if (!configProvider.get().access.enableDataUseAgreement) {
return true;
}
if (duaTimes.isBypassed()) {
return true;
}
final Integer signedVersion = user.getDataUseAgreementSignedVersion();
if (signedVersion == null || signedVersion != getCurrentDuccVersion()) {
return false;
}
return duaTimes.isComplete() && !duaTimes.hasExpired();
}
// Checking for annual completion time is not a part of this module
private boolean isEraCommonsCompliant(DbUser user) {
return user.getEraCommonsBypassTime() != null
|| !configProvider.get().access.enableEraCommons
|| user.getEraCommonsCompletionTime() != null;
}
private boolean isComplianceTrainingCompliant(DbUser user) {
if (!configProvider.get().access.enableComplianceTraining) {
return true;
}
final ModuleTimes ctTimes =
new ModuleTimes(
user.getComplianceTrainingCompletionTime(), user.getComplianceTrainingBypassTime());
return ctTimes.isBypassed() || (ctTimes.isComplete() && !ctTimes.hasExpired());
}
private boolean shouldUserBeRegistered(DbUser user) {
// beta access bypass and 2FA do not need to be checked for annual renewal
boolean betaAccessGranted =
user.getBetaAccessBypassTime() != null || !configProvider.get().access.enableBetaAccess;
boolean twoFactorAuthComplete =
user.getTwoFactorAuthCompletionTime() != null || user.getTwoFactorAuthBypassTime() != null;
// TODO: can take out other checks once we're entirely moved over to the 'module' columns
return !user.getDisabled()
&& isComplianceTrainingCompliant(user)
&& isEraCommonsCompliant(user)
&& betaAccessGranted
&& twoFactorAuthComplete
&& isDataUseAgreementCompliant(user)
&& EmailVerificationStatus.SUBSCRIBED.equals(user.getEmailVerificationStatusEnum());
}
private boolean isServiceAccount(DbUser user) {
return configProvider.get().auth.serviceAccountApiUsers.contains(user.getUsername());
}
@Override
public DbUser createServiceAccountUser(String username) {
DbUser user = new DbUser();
user.setUsername(username);
user.setDisabled(false);
user.setEmailVerificationStatusEnum(EmailVerificationStatus.UNVERIFIED);
try {
user = userDao.save(user);
} catch (DataIntegrityViolationException e) {
// For certain test workflows, it's possible to have concurrent user creation.
// We attempt to handle that gracefully here.
final DbUser userByUserName = userDao.findUserByUsername(username);
if (userByUserName == null) {
log.log(
Level.WARNING,
String.format(
"While creating new user with email %s due to "
+ "DataIntegrityViolationException. No user matching this username was found "
+ "and none exists in the database",
username),
e);
throw e;
} else {
log.log(
Level.WARNING,
String.format(
"While creating new user with email %s due to "
+ "DataIntegrityViolationException. User %d is present however, "
+ "indicating possible concurrent creation.",
username, userByUserName.getUserId()),
e);
user = userByUserName;
}
}
// record the Service Account's access level as belonging to all tiers in user_access_tier
// which will eventually serve as the source of truth (TODO)
// this needs to occur after the user has been saved to the DB
accessTierService.addUserToAllTiers(user);
return user;
}
@Override
public DbUser createUser(
final Userinfoplus userInfo,
final String contactEmail,
DbVerifiedInstitutionalAffiliation dbVerifiedAffiliation) {
return createUser(
userInfo.getGivenName(),
userInfo.getFamilyName(),
// This GSuite primary email address is what RW refers to as `username`.
userInfo.getEmail(),
contactEmail,
null,
null,
null,
null,
null,
null,
null,
dbVerifiedAffiliation);
}
// TODO: move this and the one above to UserMapper
@Override
public DbUser createUser(
String givenName,
String familyName,
String username,
String contactEmail,
String currentPosition,
String organization,
String areaOfResearch,
String professionalUrl,
List<Degree> degrees,
DbAddress dbAddress,
DbDemographicSurvey dbDemographicSurvey,
DbVerifiedInstitutionalAffiliation dbVerifiedAffiliation) {
DbUser dbUser = new DbUser();
dbUser.setCreationNonce(Math.abs(random.nextLong()));
dbUser.setUsername(username);
dbUser.setContactEmail(contactEmail);
dbUser.setCurrentPosition(currentPosition);
dbUser.setOrganization(organization);
dbUser.setAreaOfResearch(areaOfResearch);
dbUser.setFamilyName(familyName);
dbUser.setGivenName(givenName);
dbUser.setProfessionalUrl(professionalUrl);
dbUser.setDisabled(false);
dbUser.setAboutYou(null);
dbUser.setEmailVerificationStatusEnum(EmailVerificationStatus.UNVERIFIED);
dbUser.setAddress(dbAddress);
if (degrees != null) {
dbUser.setDegreesEnum(degrees);
}
dbUser.setDemographicSurvey(dbDemographicSurvey);
// For existing user that do not have address
if (dbAddress != null) {
dbAddress.setUser(dbUser);
}
if (dbDemographicSurvey != null) {
dbDemographicSurvey.setUser(dbUser);
}
try {
dbUser = userDao.save(dbUser);
dbVerifiedAffiliation.setUser(dbUser);
verifiedInstitutionalAffiliationDao.save(dbVerifiedAffiliation);
} catch (DataIntegrityViolationException e) {
dbUser = userDao.findUserByUsername(username);
if (dbUser == null) {
throw e;
}
// If a user already existed (due to multiple requests trying to create a user simultaneously)
// just return it.
}
return dbUser;
}
/**
* Save updated dbUser object and transform ObjectOptimisticLockingFailureException into
* ConflictException
*
* @param dbUser
* @return
*/
@Override
public DbUser updateUserWithConflictHandling(DbUser dbUser) {
try {
dbUser = userDao.save(dbUser);
} catch (ObjectOptimisticLockingFailureException e) {
log.log(Level.WARNING, "version conflict for user update", e);
throw new ConflictException("Failed due to concurrent modification");
}
return dbUser;
}
@Override
public DbUser submitDataUseAgreement(
DbUser dbUser, Integer dataUseAgreementSignedVersion, String initials) {
// FIXME: this should not be hardcoded
if (dataUseAgreementSignedVersion != getCurrentDuccVersion()) {
throw new BadRequestException("Data Use Agreement Version is not up to date");
}
final Timestamp timestamp = new Timestamp(clock.instant().toEpochMilli());
DbUserDataUseAgreement dataUseAgreement = new DbUserDataUseAgreement();
dataUseAgreement.setDataUseAgreementSignedVersion(dataUseAgreementSignedVersion);
dataUseAgreement.setUserId(dbUser.getUserId());
dataUseAgreement.setUserFamilyName(dbUser.getFamilyName());
dataUseAgreement.setUserGivenName(dbUser.getGivenName());
dataUseAgreement.setUserInitials(initials);
dataUseAgreement.setCompletionTime(timestamp);
userDataUseAgreementDao.save(dataUseAgreement);
return updateUserWithRetries(
(user) -> {
// TODO: Teardown/reconcile duplicated state between the user profile and DUA.
user.setDataUseAgreementCompletionTime(timestamp);
user.setDataUseAgreementSignedVersion(dataUseAgreementSignedVersion);
return user;
},
dbUser,
Agent.asUser(dbUser));
}
@Override
@Transactional
public void setDataUseAgreementNameOutOfDate(String newGivenName, String newFamilyName) {
List<DbUserDataUseAgreement> dataUseAgreements =
userDataUseAgreementDao.findByUserIdOrderByCompletionTimeDesc(
userProvider.get().getUserId());
dataUseAgreements.forEach(
dua ->
dua.setUserNameOutOfDate(
!dua.getUserGivenName().equalsIgnoreCase(newGivenName)
|| !dua.getUserFamilyName().equalsIgnoreCase(newFamilyName)));
userDataUseAgreementDao.saveAll(dataUseAgreements);
}
@Override
@Transactional
public void submitTermsOfService(DbUser dbUser, Integer tosVersion) {
if (tosVersion != CURRENT_TERMS_OF_SERVICE_VERSION) {
throw new BadRequestException("Terms of Service version is not up to date");
}
DbUserTermsOfService userTermsOfService = new DbUserTermsOfService();
userTermsOfService.setTosVersion(tosVersion);
userTermsOfService.setUserId(dbUser.getUserId());
userTermsOfServiceDao.save(userTermsOfService);
userServiceAuditor.fireAcknowledgeTermsOfService(dbUser, tosVersion);
}
@Override
public void setDataUseAgreementBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setDataUseAgreementBypassTime,
BypassTimeTargetProperty.DATA_USE_AGREEMENT_BYPASS_TIME);
}
@Override
public void setComplianceTrainingBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setComplianceTrainingBypassTime,
BypassTimeTargetProperty.COMPLIANCE_TRAINING_BYPASS_TIME);
}
@Override
public void setBetaAccessBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setBetaAccessBypassTime,
BypassTimeTargetProperty.BETA_ACCESS_BYPASS_TIME);
}
@Override
public void setEraCommonsBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setEraCommonsBypassTime,
BypassTimeTargetProperty.ERA_COMMONS_BYPASS_TIME);
}
@Override
public void setTwoFactorAuthBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setTwoFactorAuthBypassTime,
BypassTimeTargetProperty.TWO_FACTOR_AUTH_BYPASS_TIME);
}
@Override
public void setRasLinkLoginGovBypassTime(
Long userId, Timestamp previousBypassTime, Timestamp newBypassTime) {
setBypassTimeWithRetries(
userId,
previousBypassTime,
newBypassTime,
DbUser::setRasLinkLoginGovBypassTime,
BypassTimeTargetProperty.RAS_LINK_LOGIN_GOV);
}
/**
* Functional bypass time column setter, using retry logic.
*
* @param userId id of user getting bypassed
* @param previousBypassTime time of bypass, before update
* @param newBypassTime time of bypass
* @param setter void-returning method to call to set the particular bypass field. Should
* typically be a method reference on DbUser, e.g.
* @param targetProperty BypassTimeTargetProperty enum value, for auditing
*/
private void setBypassTimeWithRetries(
long userId,
Timestamp previousBypassTime,
Timestamp newBypassTime,
BiConsumer<DbUser, Timestamp> setter,
BypassTimeTargetProperty targetProperty) {
setBypassTimeWithRetries(
userDao.findUserByUserId(userId),
previousBypassTime,
newBypassTime,
targetProperty,
setter);
}
private void setBypassTimeWithRetries(
DbUser dbUser,
Timestamp previousBypassTime,
Timestamp newBypassTime,
BypassTimeTargetProperty targetProperty,
BiConsumer<DbUser, Timestamp> setter) {
updateUserWithRetries(
(u) -> {
setter.accept(u, newBypassTime);
return u;
},
dbUser,
Agent.asAdmin(userProvider.get()));
userServiceAuditor.fireAdministrativeBypassTime(
dbUser.getUserId(),
targetProperty,
Optional.ofNullable(previousBypassTime).map(Timestamp::toInstant),
Optional.ofNullable(newBypassTime).map(Timestamp::toInstant));
}
@Override
public DbUser setDisabledStatus(Long userId, boolean disabled) {
DbUser user = userDao.findUserByUserId(userId);
return updateUserWithRetries(
(u) -> {
u.setDisabled(disabled);
return u;
},
user,
Agent.asAdmin(userProvider.get()));
}
@Override
public List<DbUser> getAllUsers() {
return userDao.findUsers();
}
@Override
public List<DbUser> getAllUsersExcludingDisabled() {
return userDao.findUsersExcludingDisabled();
}
@Override
public void logAdminUserAction(
long targetUserId, String targetAction, Object oldValue, Object newValue) {
logAdminAction(targetUserId, null, targetAction, oldValue, newValue);
}
@Override
public void logAdminWorkspaceAction(
long targetWorkspaceId, String targetAction, Object oldValue, Object newValue) {
logAdminAction(null, targetWorkspaceId, targetAction, oldValue, newValue);
}
private void logAdminAction(
Long targetUserId,
Long targetWorkspaceId,
String targetAction,
Object oldValue,
Object newValue) {
DbAdminActionHistory adminActionHistory = new DbAdminActionHistory();
adminActionHistory.setTargetUserId(targetUserId);
adminActionHistory.setTargetWorkspaceId(targetWorkspaceId);
adminActionHistory.setTargetAction(targetAction);
adminActionHistory.setOldValue(oldValue == null ? "null" : oldValue.toString());
adminActionHistory.setNewValue(newValue == null ? "null" : newValue.toString());
adminActionHistory.setAdminUserId(userProvider.get().getUserId());
adminActionHistory.setTimestamp();
adminActionHistoryDao.save(adminActionHistory);
}
/**
* Find users with Registered Tier access whose name or username match the supplied search terms.
*
* @param term User-supplied search term
* @param sort Option(s) for ordering query results
* @return the List of DbUsers which meet the search and access requirements
* @deprecated use {@link UserService#findUsersBySearchString(String, Sort, String)} instead.
*/
@Deprecated
@Override
public List<DbUser> findUsersBySearchString(String term, Sort sort) {
return findUsersBySearchString(term, sort, accessTierService.REGISTERED_TIER_SHORT_NAME);
}
/**
* Find users whose name or username match the supplied search terms and who have the appropriate
* access tier.
*
* @param term User-supplied search term
* @param sort Option(s) for ordering query results
* @param accessTierShortName the shortName of the access tier to check
* @return the List of DbUsers which meet the search and access requirements
*/
@Override
public List<DbUser> findUsersBySearchString(String term, Sort sort, String accessTierShortName) {
return userDao.findUsersBySearchStringAndTier(term, sort, accessTierShortName);
}
/** Syncs the current user's training status from Moodle. */
@Override
public DbUser syncComplianceTrainingStatusV2()
throws org.pmiops.workbench.moodle.ApiException, NotFoundException {
DbUser user = userProvider.get();
return syncComplianceTrainingStatusV2(user, Agent.asUser(user));
}
/**
* Updates the given user's training status from Moodle.
*
* <p>We can fetch Moodle data for arbitrary users since we use an API key to access Moodle,
* rather than user-specific OAuth tokens.
*
* <p>Using the user's email, we can get their badges from Moodle's APIs. If the badges are marked
* valid, we store their completion/expiration dates in the database. If they are marked invalid,
* we clear the completion/expiration dates from the database as the user will need to complete a
* new training.
*/
@Override
public DbUser syncComplianceTrainingStatusV2(DbUser dbUser, Agent agent)
throws org.pmiops.workbench.moodle.ApiException, NotFoundException {
// Skip sync for service account user rows.
if (isServiceAccount(dbUser)) {
return dbUser;
}
try {
Timestamp now = new Timestamp(clock.instant().toEpochMilli());
final Timestamp newComplianceTrainingCompletionTime;
final Timestamp newComplianceTrainingExpirationTime;
Map<String, BadgeDetailsV2> userBadgesByName =
complianceService.getUserBadgesByBadgeName(dbUser.getUsername());
if (userBadgesByName.containsKey(complianceService.getResearchEthicsTrainingField())) {
BadgeDetailsV2 complianceBadge =
userBadgesByName.get(complianceService.getResearchEthicsTrainingField());
if (complianceBadge.getValid()) {
if (dbUser.getComplianceTrainingCompletionTime() == null) {
// The badge was previously invalid and is now valid.
newComplianceTrainingCompletionTime = now;
} else if (!dbUser
.getComplianceTrainingExpirationTime()
.equals(Timestamp.from(Instant.ofEpochSecond(complianceBadge.getDateexpire())))) {
// The badge was previously valid, but has a new expiration date (and so is a new
// training)
newComplianceTrainingCompletionTime = now;
} else {
// The badge status has not changed since the last time the status was synced.
newComplianceTrainingCompletionTime = dbUser.getComplianceTrainingCompletionTime();
}
// Always update the expiration time if the training badge is valid
newComplianceTrainingExpirationTime =
Timestamp.from(Instant.ofEpochSecond(complianceBadge.getDateexpire()));
} else {
// The current badge is invalid or expired, the training must be completed or retaken.
newComplianceTrainingCompletionTime = null;
newComplianceTrainingExpirationTime = null;
}
} else {
// There is no record of this person having taken the training.
newComplianceTrainingCompletionTime = null;
newComplianceTrainingExpirationTime = null;
}
return updateUserWithRetries(
u -> {
u.setComplianceTrainingCompletionTime(newComplianceTrainingCompletionTime);
u.setComplianceTrainingExpirationTime(newComplianceTrainingExpirationTime);
return u;
},
dbUser,
agent);
} catch (NumberFormatException e) {
log.severe("Incorrect date expire format from Moodle");
throw e;
} catch (org.pmiops.workbench.moodle.ApiException ex) {
if (ex.getCode() == HttpStatus.NOT_FOUND.value()) {
log.severe(
String.format(
"Error while querying Moodle for badges for %s: %s ",
dbUser.getUsername(), ex.getMessage()));
throw new NotFoundException(ex.getMessage());
} else {
log.severe(String.format("Error while syncing compliance training: %s", ex.getMessage()));
}
throw ex;
}
}
/**
* Updates the given user's eraCommons-related fields with the NihStatus object returned from FC.
*
* <p>This method saves the updated user object to the database and returns it.
*/
private DbUser setEraCommonsStatus(DbUser targetUser, FirecloudNihStatus nihStatus, Agent agent) {
Timestamp now = new Timestamp(clock.instant().toEpochMilli());
return updateUserWithRetries(
user -> {
if (nihStatus != null) {
Timestamp eraCommonsCompletionTime = user.getEraCommonsCompletionTime();
Timestamp nihLinkExpireTime =
Timestamp.from(Instant.ofEpochSecond(nihStatus.getLinkExpireTime()));
// NihStatus should never come back from firecloud with an empty linked username.
// If that is the case, there is an error with FC, because we should get a 404
// in that case. Leaving the null checking in for code safety reasons
if (nihStatus.getLinkedNihUsername() == null) {
// If FireCloud says we have no NIH link, always clear the completion time.
eraCommonsCompletionTime = null;
} else if (!nihLinkExpireTime.equals(user.getEraCommonsLinkExpireTime())) {
// If the link expiration time has changed, we treat this as a "new" completion of the
// access requirement.
eraCommonsCompletionTime = now;
} else if (nihStatus.getLinkedNihUsername() != null
&& !nihStatus
.getLinkedNihUsername()
.equals(user.getEraCommonsLinkedNihUsername())) {
// If the linked username has changed, we treat this as a new completion time.
eraCommonsCompletionTime = now;
} else if (eraCommonsCompletionTime == null) {
// If the user hasn't yet completed this access requirement, set the time to now.
eraCommonsCompletionTime = now;
}
user.setEraCommonsLinkedNihUsername(nihStatus.getLinkedNihUsername());
user.setEraCommonsLinkExpireTime(nihLinkExpireTime);
user.setEraCommonsCompletionTime(eraCommonsCompletionTime);
} else {
user.setEraCommonsLinkedNihUsername(null);
user.setEraCommonsLinkExpireTime(null);
user.setEraCommonsCompletionTime(null);
}
return user;
},
targetUser,
agent);
}
/** Syncs the eraCommons access module status for the current user. */
@Override
public DbUser syncEraCommonsStatus() {
DbUser user = userProvider.get();
FirecloudNihStatus nihStatus = fireCloudService.getNihStatus();
return setEraCommonsStatus(user, nihStatus, Agent.asUser(user));
}
/**
* Syncs the eraCommons access module status for an arbitrary user.
*
* <p>This uses impersonated credentials and should only be called in the context of a cron job or
* a request from a user with elevated privileges.
*
* <p>Returns the updated User object.
*/
@Override
public DbUser syncEraCommonsStatusUsingImpersonation(DbUser user, Agent agent)
throws IOException, org.pmiops.workbench.firecloud.ApiException {
if (isServiceAccount(user)) {
// Skip sync for service account user rows.
return user;
}
ApiClient apiClient = fireCloudService.getApiClientWithImpersonation(user.getUsername());
NihApi api = new NihApi(apiClient);
try {
FirecloudNihStatus nihStatus = api.nihStatus();
return setEraCommonsStatus(user, nihStatus, agent);
} catch (org.pmiops.workbench.firecloud.ApiException e) {
if (e.getCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
// We'll catch the NOT_FOUND ApiException here, since we expect many users to have an empty
// eRA Commons linkage.
log.info(String.format("NIH Status not found for user %s", user.getUsername()));
return user;
} else {
throw e;
}
}
}
@Override
public void syncTwoFactorAuthStatus() {
DbUser user = userProvider.get();
syncTwoFactorAuthStatus(user, Agent.asUser(user));
}
@Override
public DbUser syncTwoFactorAuthStatus(DbUser targetUser, Agent agent) {
return syncTwoFactorAuthStatus(
targetUser, agent, directoryService.getUser(targetUser.getUsername()).getIsEnrolledIn2Sv());
}
@Override
public DbUser syncTwoFactorAuthStatus(DbUser targetUser, Agent agent, boolean isEnrolledIn2FA) {
if (isServiceAccount(targetUser)) {
// Skip sync for service account user rows.
return targetUser;
}
return updateUserWithRetries(
user -> {
if (isEnrolledIn2FA) {
if (user.getTwoFactorAuthCompletionTime() == null) {
user.setTwoFactorAuthCompletionTime(new Timestamp(clock.instant().toEpochMilli()));
}
} else {
user.setTwoFactorAuthCompletionTime(null);
}
return user;
},
targetUser,
agent);
}
@Override
public Collection<MeasurementBundle> getGaugeData() {
return userDao.getUserCountGaugeData().stream()
.map(
row ->
MeasurementBundle.builder()
.addMeasurement(GaugeMetric.USER_COUNT, row.getUserCount())
.addTag(MetricLabel.USER_DISABLED, row.getDisabled().toString())
.addTag(MetricLabel.ACCESS_TIER_SHORT_NAMES, row.getAccessTierShortNames())
.build())
.collect(ImmutableList.toImmutableList());
}
@Override
public Optional<DbUser> getByUsername(String username) {
return Optional.ofNullable(userDao.findUserByUsername(username));
}
@Override
public DbUser getByUsernameOrThrow(String username) {
return getByUsername(username)
.orElseThrow(() -> new NotFoundException("User '" + username + "' not found"));
}
@Override
public Optional<DbUser> getByDatabaseId(long databaseId) {
return Optional.ofNullable(userDao.findUserByUserId(databaseId));
}
@Override
public void updateBypassTime(long userDatabaseId, AccessBypassRequest accessBypassRequest) {
final DbUser user =
getByDatabaseId(userDatabaseId)
.orElseThrow(
() ->
new NotFoundException(
String.format("User with database ID %d not found", userDatabaseId)));
final Timestamp previousBypassTime;
final Timestamp newBypassTime;
final Boolean isBypassed = accessBypassRequest.getIsBypassed();
if (isBypassed) {
newBypassTime = new Timestamp(clock.instant().toEpochMilli());
} else {
newBypassTime = null;
}
switch (accessBypassRequest.getModuleName()) {
case DATA_USE_AGREEMENT:
previousBypassTime = user.getDataUseAgreementBypassTime();
setDataUseAgreementBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
case COMPLIANCE_TRAINING:
previousBypassTime = user.getComplianceTrainingBypassTime();
setComplianceTrainingBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
case BETA_ACCESS:
previousBypassTime = user.getBetaAccessBypassTime();
setBetaAccessBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
case ERA_COMMONS:
previousBypassTime = user.getEraCommonsBypassTime();
setEraCommonsBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
case TWO_FACTOR_AUTH:
previousBypassTime = user.getTwoFactorAuthBypassTime();
setTwoFactorAuthBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
case RAS_LINK_LOGIN_GOV:
previousBypassTime = user.getRasLinkLoginGovBypassTime();
setRasLinkLoginGovBypassTime(userDatabaseId, previousBypassTime, newBypassTime);
break;
default:
throw new BadRequestException(
"There is no access module named: " + accessBypassRequest.getModuleName().toString());
}
}
@Override
public boolean hasAuthority(long userId, Authority required) {
final Set<Authority> userAuthorities =
userDao.findUserWithAuthorities(userId).getAuthoritiesEnum();
// DEVELOPER is the super-authority which subsumes all others
return userAuthorities.contains(Authority.DEVELOPER) || userAuthorities.contains(required);
}
@Override
public Optional<DbUser> findUserWithAuthoritiesAndPageVisits(long userId) {
return Optional.ofNullable(userDao.findUserWithAuthoritiesAndPageVisits(userId));
}
@Override
public DbUser updateRasLinkLoginGovStatus(String loginGovUserName) {
DbUser dbUser = userProvider.get();
return updateUserWithRetries(
user -> {
user.setRasLinkLoginGovUsername(loginGovUserName);
user.setRasLinkLoginGovCompletionTime(new Timestamp(clock.instant().toEpochMilli()));
// TODO(RW-6480): Determine if need to set link expiration time.
return user;
},
dbUser,
Agent.asUser(dbUser));
}
/** Confirm that a user's profile is up to date, for annual renewal compliance purposes. */
@Override
public DbUser confirmProfile() {
final DbUser dbUser = userProvider.get();
return updateUserWithRetries(
user -> {
user.setProfileLastConfirmedTime(new Timestamp(clock.instant().toEpochMilli()));
return user;
},
dbUser,
Agent.asUser(dbUser));
}
/** Confirm that a user has either reported any AoU-related publications, or has none. */
@Override
public DbUser confirmPublications() {
final DbUser dbUser = userProvider.get();
return updateUserWithRetries(
user -> {
user.setPublicationsLastConfirmedTime(new Timestamp(clock.instant().toEpochMilli()));
return user;
},
dbUser,
Agent.asUser(dbUser));
}
}
|
package org.whattf.datatype;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;
import org.relaxng.datatype.DatatypeException;
import org.whattf.datatype.data.LanguageData;
/**
*
* @version $Id$
* @author hsivonen
*/
public final class Language extends AbstractDatatype {
/**
* The singleton instance.
*/
public static final Language THE_INSTANCE = new Language();
private static final Pattern HYPHEN = Pattern.compile("-");
private static String[] languages = null;
private static String[] scripts = null;
private static String[] regions = null;
private static String[] variants = null;
private static String[] grandfathered = null;
private static String[] deprecated = null;
private static int[] suppressedScriptByLanguage = null;
private static String[][][] prefixesByVariant = null;
static {
try {
LanguageData data = new LanguageData();
languages = data.getLanguages();
scripts = data.getScripts();
regions = data.getRegions();
variants = data.getScripts();
grandfathered = data.getGrandfathered();
deprecated = data.getDeprecated();
suppressedScriptByLanguage = data.getSuppressedScriptByLanguage();
prefixesByVariant = data.getPrefixesByVariant();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Package-private constructor
*/
private Language() {
super();
}
public void checkValid(CharSequence lit)
throws DatatypeException {
String literal = lit.toString();
if (literal.length() == 0) {
throw new DatatypeException(
"The empty string is not a valid language tag.");
}
literal = toAsciiLowerCase(literal);
if (isGrandfathered(literal)) {
if (isDeprecated(literal)) {
throw new DatatypeException(
"The grandfathered language tag \u201C" + literal + "\u201D is deprecated.");
}
return;
}
if (literal.startsWith("-")) {
throw new DatatypeException(
"Language tag must not start with HYPHEN-MINUS.");
}
if (literal.endsWith("-")) {
throw new DatatypeException(
"Language tag must not end with HYPHEN-MINUS.");
}
String[] subtags = HYPHEN.split(literal);
for (int j = 0; j < subtags.length; j++) {
int len = subtags[j].length();
if (len == 0) {
throw new DatatypeException(
"Zero-length subtag.");
} else if (len > 8) {
throw new DatatypeException(
"Subtags must next exceed 8 characters in length.");
}
}
// Language
int i = 0;
String subtag = subtags[i];
int len = subtag.length();
if ("x".equals(subtag)) {
checkPrivateUse(i, subtags);
return;
}
if ((len == 2 || len == 3) && isLowerCaseAlpha(subtag)) {
if (!isLanguage(subtag)) {
throw new DatatypeException(
"Bad ISO language part in language tag");
}
if (isDeprecated(subtag)) {
throw new DatatypeException(
"The language subtag \u201C" + subtag + "\u201D is deprecated.");
}
i++;
if (i == subtags.length) {
return;
}
subtag = subtags[i];
len = subtag.length();
if (len == 3) {
throw new DatatypeException(
"Found reserved language extension subtag.");
}
} else if (len == 4 && isLowerCaseAlpha(subtag)) {
throw new DatatypeException("Found reserved language tag.");
} else if (len == 5 && isLowerCaseAlpha(subtag)) {
if (!isLanguage(subtag)) {
throw new DatatypeException(
"Bad IANA language part in language tag");
}
if (isDeprecated(subtag)) {
throw new DatatypeException(
"The language subtag \u201C" + subtag + "\u201D is deprecated.");
}
i++;
if (i == subtags.length) {
return;
}
subtag = subtags[i];
len = subtag.length();
}
// Script?
if ("x".equals(subtag)) {
checkPrivateUse(i, subtags);
return;
}
if (subtag.length() == 4) {
if (!isScript(subtag)) {
throw new DatatypeException("Bad script subtag");
}
if (isDeprecated(subtag)) {
throw new DatatypeException(
"The script subtag \u201C" + subtag + "\u201D is deprecated.");
}
if (shouldSuppressScript(subtags[0], subtag)) {
throw new DatatypeException("Language tag should omit the default script for the language.");
}
i++;
if (i == subtags.length) {
return;
}
subtag = subtags[i];
len = subtag.length();
}
// Region
if ((len == 3 && isDigit(subtag))
|| (len == 2 && isLowerCaseAlpha(subtag))) {
if (!isRegion(subtag)) {
throw new DatatypeException("Bad region subtag");
}
if (isDeprecated(subtag)) {
throw new DatatypeException(
"The region subtag \u201C" + subtag + "\u201D is deprecated.");
}
i++;
if (i == subtags.length) {
return;
}
subtag = subtags[i];
len = subtag.length();
}
// Variant
for (;;) {
if ("x".equals(subtag)) {
checkPrivateUse(i, subtags);
return;
}
// cutting corners here a bit since there are no extensions at this time
if (len == 1) {
throw new DatatypeException("Unknown extension.");
} else {
if (!isVariant(subtag)) {
throw new DatatypeException("Bad variant subtag");
}
if (isDeprecated(subtag)) {
throw new DatatypeException(
"The variant subtag \u201C" + subtag + "\u201D is deprecated.");
}
if (!hasGoodPrefix(subtags, i)) {
throw new DatatypeException("Variant lacks required prefix.");
}
}
i++;
if (i == subtags.length) {
return;
}
subtag = subtags[i];
len = subtag.length();
}
}
private boolean hasGoodPrefix(String[] subtags, int i) {
String variant = subtags[i];
int index = Arrays.binarySearch(variants, variant);
assert index >= 0;
String[][] prefixes = prefixesByVariant[index];
if (prefixes.length == 0) {
return true;
}
for (int j = 0; j < prefixes.length; j++) {
String[] prefix = prefixes[j];
if (prefixMatches(prefix, subtags, i)) {
return true;
}
}
return false;
}
private boolean prefixMatches(String[] prefix, String[] subtags, int limit) {
for (int i = 0; i < prefix.length; i++) {
String prefixComponent = prefix[i];
if (!subtagsContainPrefixComponent(prefixComponent, subtags, limit)) {
return false;
}
}
return true;
}
private boolean subtagsContainPrefixComponent(String prefixComponent, String[] subtags, int limit) {
for (int i = 0; i < limit; i++) {
String subtag = subtags[i];
if (subtag.equals(prefixComponent)) {
return true;
}
}
return false;
}
private boolean shouldSuppressScript(String language, String script) {
int langIndex = Arrays.binarySearch(languages, language);
assert langIndex > -1;
int scriptIndex = suppressedScriptByLanguage[langIndex];
if (scriptIndex < 0) {
return false;
} else {
return scripts[scriptIndex].equals(script);
}
}
private boolean isVariant(String subtag) {
return (Arrays.binarySearch(variants, subtag) > -1);
}
private boolean isRegion(String subtag) {
return (Arrays.binarySearch(regions, subtag) > -1) || "aa".equals(subtag)
|| ("qm".compareTo(subtag) <= 0 && "qz".compareTo(subtag) >= 0)
|| ("xa".compareTo(subtag) <= 0 && "xz".compareTo(subtag) >= 0)
|| "zz".equals(subtag);
}
private boolean isScript(String subtag) {
return (Arrays.binarySearch(scripts, subtag) > -1)
|| ("qaaa".compareTo(subtag) <= 0 && "qabx".compareTo(subtag) >= 0);
}
private boolean isLanguage(String subtag) {
return (Arrays.binarySearch(languages, subtag) > -1)
|| ("qaa".compareTo(subtag) <= 0 && "qtz".compareTo(subtag) >= 0);
}
private void checkPrivateUse(int i, String[] subtags)
throws DatatypeException {
int len = subtags.length;
i++;
if (i == len) {
throw new DatatypeException("No subtags in private use sequence.");
}
while (i < len) {
String subtag = subtags[i];
if (!isLowerCaseAlphaNumeric(subtag)) {
throw new DatatypeException(
"Bad character in private use subtag.");
}
i++;
}
}
private final boolean isLowerCaseAlphaNumeric(char c) {
return isLowerCaseAlpha(c) || isDigit(c);
}
private final boolean isLowerCaseAlphaNumeric(String str) {
for (int i = 0; i < str.length(); i++) {
if (!isLowerCaseAlphaNumeric(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* @param c
* @return
*/
private final boolean isDigit(char c) {
return (c >= '0' && c <= '9');
}
private final boolean isDigit(String str) {
for (int i = 0; i < str.length(); i++) {
if (!isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* @param c
* @return
*/
private final boolean isLowerCaseAlpha(char c) {
return (c >= 'a' && c <= 'z');
}
private final boolean isLowerCaseAlpha(String str) {
for (int i = 0; i < str.length(); i++) {
if (!isLowerCaseAlpha(str.charAt(i))) {
return false;
}
}
return true;
}
private boolean isGrandfathered(String literal) {
return Arrays.binarySearch(grandfathered, literal) > -1;
}
private boolean isDeprecated(String subtag) {
return Arrays.binarySearch(deprecated, subtag) > -1;
}
}
|
package com.example.saurabhkumar.downz;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.downzlibrary.DataTypes.BitMap;
import com.example.downzlibrary.DataTypes.Type;
import com.example.downzlibrary.DownZ;
import com.example.downzlibrary.ListnerInterface.HttpListener;
import com.example.downzlibrary.Utilities.CacheManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import static android.R.attr.bitmap;
public class UserActivity extends AppCompatActivity {
Toolbar mToolbar;
String UrlforUpload;
String UrlforProfilepic;
String NameofUser;
String UserName;
String Categories;
String NumberOfLikes;
ImageView UploadedImage;
de.hdodenhof.circleimageview.CircleImageView ProfilePic;
TextView NumberofLikesTextView;
TextView Tags;
TextView NameofUserTextView;
TextView UserNameTextView;
int ImageLoadflag;
Type<Bitmap> Upload;
BitMap bitmaptosend;
BitMap ProfilePicBitmap;
CacheManager<Bitmap> bitmapCacheManager;
ProgressBar progressBar;
int fabFlag;
LinearLayout FabLayout;
FloatingActionButton MainButton;
RelativeLayout Overlay;
Animation animforoverlay;
Animation animforoverlayGone;
Animation animforVisible;
Animation animforFabRotate;
Animation animforInvisible;
Boolean canSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
mToolbar = findViewById(R.id.toolbar);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
/* To get all the values from previous activity */
Bundle extras = getIntent().getExtras();
UrlforUpload = extras.getString("Upload_Url");
UrlforProfilepic = extras.getString("Profile_Pic");
NameofUser = "by " + extras.getString("Name_Of_User");
UserName = extras.getString("User_Name");
Categories = extras.getString("Categories");
NumberOfLikes = extras.getString("No_Of_Likes");
bitmapCacheManager = new CacheManager<>(40 * 1024 * 1024);
/* Setting Up Layout */
UploadedImage = findViewById(R.id.Upload);
UploadedImage.setDrawingCacheEnabled(true);
UploadedImage.buildDrawingCache();
ProfilePic = findViewById(R.id.profile_image);
Tags = findViewById(R.id.Tags);
NumberofLikesTextView = findViewById(R.id.NumOfLikes);
UserNameTextView = findViewById(R.id.UserNameinNew);
NameofUserTextView = findViewById(R.id.NameOfUserinNew);
progressBar = (ProgressBar) findViewById(R.id.progress);
canSend = false;
// layout containing all FAB buttons
FabLayout = findViewById(R.id.OptionsLayout);
MainButton = findViewById(R.id.editImage);
Overlay = findViewById(R.id.overlay);
FloatingActionButton Loadimage = findViewById(R.id.LoadImage);
FloatingActionButton CancelLoad = findViewById(R.id.cancelLoad);
FloatingActionButton RemoveImage = findViewById(R.id.clearImage);
//Setting Visiblity
FabLayout.setVisibility(View.GONE);
MainButton.setImageResource(R.drawable.ic_edit);
Overlay.setVisibility(View.GONE);
//Setting up animation
animforoverlay = AnimationUtils.loadAnimation(UserActivity.this,
R.anim.fade_in);
animforoverlayGone = AnimationUtils.loadAnimation(UserActivity.this,
R.anim.fade_out);
animforVisible = AnimationUtils.loadAnimation(UserActivity.this,
R.anim.slide_in_right);
animforInvisible = AnimationUtils.loadAnimation(UserActivity.this,
R.anim.slide_out_left);
animforFabRotate = AnimationUtils.loadAnimation(UserActivity.this,
R.anim.rotate);
//Setting Up Content
Tags.setText(Categories);
NameofUserTextView.setText(NameofUser);
UserNameTextView.setText(UserName);
NumberofLikesTextView.setText(NumberOfLikes);
//Loading Uploaded Image
ImageLoadFunction();
//Loading Profile Picture
ProfilePicBitmap = DownZ
.from(UserActivity.this)
.load(DownZ.Method.GET, UrlforProfilepic)
.asBitmap()
.setCacheManager(bitmapCacheManager)
.setCallback(new HttpListener<Bitmap>() {
@Override
public void onRequest() {
}
@Override
public void onResponse(Bitmap data) {
ProfilePic.setImageBitmap(data);
}
@Override
public void onError() {
}
@Override
public void onCancel() {
}
});
MainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (fabFlag == 0) {
DisplayFab();
} else {
RemoveFab();
}
}
});
Loadimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ImageLoadflag != 1) {
ImageLoadFunction();
} else {
Snackbar.make(findViewById(android.R.id.content), "Image Already Exists", Snackbar.LENGTH_SHORT).show();
}
}
});
CancelLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Upload != null) {
Upload.cancel();
Snackbar.make(findViewById(android.R.id.content), "Cancelled", Snackbar.LENGTH_SHORT).show();
}
}
});
RemoveImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImageLoadflag = 0;
UploadedImage.setImageResource(0);
}
});
}
public void ImageLoadFunction() {
ImageLoadflag = 1;
Upload = DownZ
.from(UserActivity.this)
.load(DownZ.Method.GET, UrlforUpload)
.asBitmap()
.setCacheManager(bitmapCacheManager)
.setCallback(new HttpListener<Bitmap>() {
@Override
public void onRequest() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onResponse(Bitmap data) {
progressBar.setVisibility(View.GONE);
UploadedImage.setImageBitmap(data);
}
@Override
public void onError() {
}
@Override
public void onCancel() {
}
});
}
public void DisplayFab() {
/*function to show Fab Buttons*/
fabFlag = 1;
FabLayout.setVisibility(View.VISIBLE);
FabLayout.startAnimation(animforVisible);
Overlay.setVisibility(View.VISIBLE);
Overlay.startAnimation(animforoverlay);
MainButton.startAnimation(animforFabRotate);
MainButton.setImageResource(R.drawable.ic_close);
}
public void RemoveFab() {
/*function to remove Fab Buttons*/
fabFlag = 0;
FabLayout.setVisibility(View.GONE);
FabLayout.startAnimation(animforInvisible);
Overlay.setVisibility(View.GONE);
Overlay.startAnimation(animforoverlayGone);
MainButton.startAnimation(animforFabRotate);
MainButton.setImageResource(R.drawable.ic_edit);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Performs function associated with a menu items
switch (item.getItemId()) {
case R.id.action_send:
if (ImageLoadflag == 1) {
Bitmap sendbitmap = UploadedImage.getDrawingCache();
int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
if (!checkIfAlreadyhavePermission()) {
requestForSpecificPermission();
}
}
if (canSend) {
// Stores the file so that it can be shared on various apps
String bitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(), sendbitmap, "title", null);
Uri bitmapUri = Uri.parse(bitmapPath);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
startActivity(Intent.createChooser(intent, "Share"));
}
}
break;
case R.id.action_download:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(UrlforUpload));
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
canSend = true;
return true;
} else {
canSend = false;
return false;
}
}
private void requestForSpecificPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//granted
canSend = true;
} else {
canSend = false;
//not granted
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
|
package com.instamojo.androidsdksample;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatSpinner;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;
import com.instamojo.android.Instamojo;
import com.instamojo.android.activities.PaymentDetailsActivity;
import com.instamojo.android.callbacks.OrderRequestCallBack;
import com.instamojo.android.helpers.Constants;
import com.instamojo.android.models.Errors;
import com.instamojo.android.models.Order;
import com.instamojo.android.network.Request;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static class DefaultHeadersInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request()
.newBuilder()
.header("User-Agent", getUserAgent())
.header("Referer", getReferer())
.build());
}
private static String getUserAgent() {
return "instamojo-android-sdk-sample/" + BuildConfig.VERSION_NAME
+ " android/" + Build.VERSION.RELEASE
+ " " + Build.BRAND + "/" + Build.MODEL;
}
private static String getReferer() {
return "android-app://" + BuildConfig.APPLICATION_ID;
}
}
private static final HashMap<String, String> env_options = new HashMap<>();
static {
env_options.put("Test", "https://test.instamojo.com/");
env_options.put("Production", "https://api.instamojo.com/");
}
private ProgressDialog dialog;
private AppCompatEditText nameBox, emailBox, phoneBox, amountBox, descriptionBox;
private String currentEnv = null;
private String accessToken = null;
private static OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new DefaultHeadersInterceptor())
.build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.pay);
nameBox = (AppCompatEditText) findViewById(R.id.name);
nameBox.setSelection(nameBox.getText().toString().trim().length());
emailBox = (AppCompatEditText) findViewById(R.id.email);
emailBox.setSelection(emailBox.getText().toString().trim().length());
phoneBox = (AppCompatEditText) findViewById(R.id.phone);
phoneBox.setSelection(phoneBox.getText().toString().trim().length());
amountBox = (AppCompatEditText) findViewById(R.id.amount);
amountBox.setSelection(amountBox.getText().toString().trim().length());
descriptionBox = (AppCompatEditText) findViewById(R.id.description);
descriptionBox.setSelection(descriptionBox.getText().toString().trim().length());
AppCompatSpinner envSpinner = (AppCompatSpinner) findViewById(R.id.env_spinner);
final ArrayList<String> envs = new ArrayList<>(env_options.keySet());
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, envs);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
envSpinner.setAdapter(adapter);
envSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
currentEnv = envs.get(position);
Instamojo.setBaseUrl(env_options.get(currentEnv));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchTokenAndTransactionID();
}
});
//let's set the log level to debug
Instamojo.setLogLevel(Log.DEBUG);
}
// this is for the market place
// you should have created the order from your backend and pass back the order id to app for the payment
private void fetchOrder(String accessToken, String orderID) {
// Good time to show dialog
Request request = new Request(accessToken, orderID, new OrderRequestCallBack() {
@Override
public void onFinish(final Order order, final Exception error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
if (error != null) {
if (error instanceof Errors.ConnectionError) {
showToast("No internet connection");
} else if (error instanceof Errors.ServerError) {
showToast("Server error. Try again");
} else if (error instanceof Errors.AuthenticationError) {
showToast("Access token is invalid or expired. Please update the token");
} else {
showToast(error.toString());
}
return;
}
startPreCreatedUI(order);
}
});
}
});
request.execute();
}
private void createOrder(String accessToken, String transactionID) {
String name = nameBox.getText().toString();
final String email = emailBox.getText().toString();
String phone = phoneBox.getText().toString();
String amount = amountBox.getText().toString();
String description = descriptionBox.getText().toString();
//Create the Order
Order order = new Order(accessToken, transactionID, name, email, phone, amount, description);
//set webhook
//Validate the Order
if (!order.isValid()) {
//oops order validation failed. Pinpoint the issue(s).
if (!order.isValidName()) {
nameBox.setError("Buyer name is invalid");
}
if (!order.isValidEmail()) {
emailBox.setError("Buyer email is invalid");
}
if (!order.isValidPhone()) {
phoneBox.setError("Buyer phone is invalid");
}
if (!order.isValidAmount()) {
amountBox.setError("Amount is invalid or has more than two decimal places");
}
if (!order.isValidDescription()) {
descriptionBox.setError("Description is invalid");
}
if (!order.isValidTransactionID()) {
showToast("Transaction is Invalid");
}
if (!order.isValidRedirectURL()) {
showToast("Redirection URL is invalid");
}
if (!order.isValidWebhook()) {
showToast("Webhook URL is invalid");
}
return;
}
//Validation is successful. Proceed
dialog.show();
Request request = new Request(order, new OrderRequestCallBack() {
@Override
public void onFinish(final Order order, final Exception error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
if (error != null) {
if (error instanceof Errors.ConnectionError) {
showToast("No internet connection");
} else if (error instanceof Errors.ServerError) {
showToast("Server error. Try again");
} else if (error instanceof Errors.AuthenticationError) {
showToast("Access token is invalid or expired. Please Update the token.");
} else if (error instanceof Errors.ValidationError) {
// Cast object to validation to pinpoint the issue
Errors.ValidationError validationError = (Errors.ValidationError) error;
if (!validationError.isValidTransactionID()) {
showToast("Transaction ID is not Unique");
return;
}
if (!validationError.isValidRedirectURL()) {
showToast("Redirect url is invalid");
return;
}
if (!validationError.isValidWebhook()) {
showToast("Webhook url is invalid");
return;
}
if (!validationError.isValidPhone()) {
phoneBox.setError("Buyer's Phone Number is invalid/empty");
return;
}
if (!validationError.isValidEmail()) {
emailBox.setError("Buyer's Email is invalid/empty");
return;
}
if (!validationError.isValidAmount()) {
amountBox.setError("Amount is either less than Rs.9 or has more than two decimal places");
return;
}
if (!validationError.isValidName()) {
nameBox.setError("Buyer's Name is required");
return;
}
} else {
showToast(error.getMessage());
}
return;
}
startPreCreatedUI(order);
}
});
}
});
request.execute();
}
private void startPreCreatedUI(Order order) {
//Using Pre created UI
Intent intent = new Intent(getBaseContext(), PaymentDetailsActivity.class);
intent.putExtra(Constants.ORDER, order);
startActivityForResult(intent, Constants.REQUEST_CODE);
}
private void startCustomUI(Order order) {
//Custom UI Implementation
Intent intent = new Intent(getBaseContext(), CustomUIActivity.class);
intent.putExtra(Constants.ORDER, order);
startActivityForResult(intent, Constants.REQUEST_CODE);
}
private void showToast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
}
});
}
/**
* Fetch Access token and unique transactionID from developers server
*/
private void fetchTokenAndTransactionID() {
if (!dialog.isShowing()) {
dialog.show();
}
HttpUrl url = getHttpURLBuilder()
.addPathSegment("create")
.build();
RequestBody body = new FormBody.Builder()
.add("env", currentEnv.toLowerCase(Locale.US))
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
showToast("Failed to fetch the Order Tokens");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString;
String errorMessage = null;
String transactionID = null;
responseString = response.body().string();
response.body().close();
try {
JSONObject responseObject = new JSONObject(responseString);
if (responseObject.has("error")) {
errorMessage = responseObject.getString("error");
} else {
accessToken = responseObject.getString("access_token");
transactionID = responseObject.getString("transaction_id");
}
} catch (JSONException e) {
errorMessage = "Failed to fetch order tokens";
}
final String finalErrorMessage = errorMessage;
final String finalTransactionID = transactionID;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
if (finalErrorMessage != null) {
showToast(finalErrorMessage);
return;
}
createOrder(accessToken, finalTransactionID);
}
});
}
});
}
/**
* Will check for the transaction status of a particular Transaction
*
* @param transactionID Unique identifier of a transaction ID
*/
private void checkPaymentStatus(final String transactionID, final String orderID) {
if (accessToken == null || (transactionID == null && orderID == null)) {
return;
}
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
showToast("Checking transaction status");
HttpUrl.Builder builder = getHttpURLBuilder();
builder.addPathSegment("status");
if (transactionID != null) {
builder.addQueryParameter("transaction_id", transactionID);
} else {
builder.addQueryParameter("id", orderID);
}
builder.addQueryParameter("env", currentEnv.toLowerCase(Locale.US));
HttpUrl url = builder.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + accessToken)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
showToast("Failed to fetch the transaction status");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
response.body().close();
String status = null;
String paymentID = null;
String amount = null;
String errorMessage = null;
try {
JSONObject responseObject = new JSONObject(responseString);
JSONObject payment = responseObject.getJSONArray("payments").getJSONObject(0);
status = payment.getString("status");
paymentID = payment.getString("id");
amount = responseObject.getString("amount");
} catch (JSONException e) {
errorMessage = "Failed to fetch the transaction status";
}
final String finalStatus = status;
final String finalErrorMessage = errorMessage;
final String finalPaymentID = paymentID;
final String finalAmount = amount;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
if (finalStatus == null) {
showToast(finalErrorMessage);
return;
}
if (!finalStatus.equalsIgnoreCase("successful")) {
showToast("Transaction still pending");
return;
}
showToast("Transaction successful for id - " + finalPaymentID);
refundTheAmount(transactionID, finalAmount);
}
});
}
});
}
/**
* Will initiate a refund for a given transaction with given amount
*
* @param transactionID Unique identifier for the transaction
* @param amount amount to be refunded
*/
private void refundTheAmount(String transactionID, String amount) {
if (accessToken == null || transactionID == null || amount == null) {
return;
}
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
showToast("Initiating a refund for - " + amount);
HttpUrl url = getHttpURLBuilder()
.addPathSegment("refund")
.addPathSegment("")
.build();
RequestBody body = new FormBody.Builder()
.add("env", currentEnv.toLowerCase(Locale.US))
.add("transaction_id", transactionID)
.add("amount", amount)
.add("type", "PTH")
.add("body", "Refund the Amount")
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + accessToken)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
showToast("Failed to Initiate a refund");
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
String message;
if (response.isSuccessful()) {
message = "Refund initiated successfully";
} else {
message = "Failed to initiate a refund";
}
showToast(message);
}
});
}
});
}
private HttpUrl.Builder getHttpURLBuilder() {
return new HttpUrl.Builder()
.scheme("https")
.host("sample-sdk-server.instamojo.com");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE && data != null) {
String orderID = data.getStringExtra(Constants.ORDER_ID);
String transactionID = data.getStringExtra(Constants.TRANSACTION_ID);
String paymentID = data.getStringExtra(Constants.PAYMENT_ID);
// Check transactionID, orderID, and orderID for null before using them to check the Payment status.
if (transactionID != null || paymentID != null) {
checkPaymentStatus(transactionID, orderID);
} else {
showToast("Oops!! Payment was cancelled");
}
}
}
}
|
package com.nikita.recipiesapp.common.models;
import java.util.List;
public final class Recipe {
public final int id;
public final String name;
public final List<Ingredient> ingredients;
public final List<Step> steps;
public final int servings;
private final String image;
public Recipe(int id,
String name,
List<Ingredient> ingredients,
List<Step> steps,
int servings,
String image) {
this.id = id;
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
this.servings = servings;
this.image = image;
}
public String getImageUri() {
if (image != null && !image.isEmpty()) return image;
String url;
switch (id) {
case 1:
url = "https://i0.wp.com/bakingamoment.com/wp-content/uploads/2015/03/4255featured2.jpg?w=720";
break;
case 2:
url = "https://d2gk7xgygi98cy.cloudfront.net/4-3-large.jpg";
break;
case 3:
url = "https://dessertswithbenefits.com/wp-content/uploads/2014/01/33.jpg";
break;
case 4:
url = "http://img.taste.com.au/3kqM4rqu/w720-h480-cfill-q80/taste/2016/11/classic-baked-vanilla-cheesecake-53202-1.jpeg";
break;
default:
url = "http://img.taste.com.au/BcemwIdD/taste/2016/11/chocolate-celebration-cake-85607-1.jpeg";
}
return url;
}
@Override
public String toString() {
return "{" +
"id:" + id +
"name:" + name +
"ingredients:" + ingredients +
"steps:" + steps +
"servings:" + servings +
"image:" + image +
"}";
}
}
|
package com.platypii.baseline.altimeter;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.firebase.crash.FirebaseCrash;
import com.platypii.baseline.Services;
import com.platypii.baseline.util.Convert;
import com.platypii.baseline.util.Stat;
import com.platypii.baseline.data.measurements.MAltitude;
import com.platypii.baseline.data.measurements.MLocation;
import com.platypii.baseline.location.MyLocationListener;
import org.greenrobot.eventbus.EventBus;
/**
* The main Altimeter class.
* This class integrates sensor readings from barometer and GPS to model the altitude of the phone.
* Altitude is measured both AGL and AMSL. Ground level is set to zero on initialization.
* Kalman filter is used to smooth barometer data.
*/
public class MyAltimeter {
private static final String TAG = "MyAltimeter";
private static SensorManager sensorManager;
private static SharedPreferences prefs;
// Pressure data
public static float pressure = Float.NaN; // hPa (millibars)
public static double pressure_altitude_raw = Double.NaN; // pressure converted to altitude under standard conditions (unfiltered)
public static double pressure_altitude_filtered = Double.NaN; // kalman filtered pressure altitude
// official altitude AMSL = pressure_altitude - altitude_offset
// altitude_offset uses GPS to get absolute altitude right
private static double altitude_offset = 0.0;
// Pressure altitude kalman filter
private static final Filter filter = new FilterKalman(); // Unfiltered(), AlphaBeta(), MovingAverage(), etc
// Official altitude data
public static double altitude = Double.NaN; // Meters AMSL
public static double climb = Double.NaN; // Rate of climb m/s
// public static double verticalAcceleration = Double.NaN;
// Ground level
// Save ground level for 12 hours (in milliseconds)
private static final double GROUND_LEVEL_TTL = 12 * 60 * 60 * 1000;
private static boolean ground_level_initialized = false;
private static double ground_level = Double.NaN;
private static long lastFixNano; // nanoseconds
private static long lastFixMillis; // milliseconds
// Stats
// Model error is the difference between our filtered output and the raw pressure altitude
// Model error should approximate the sensor variance, even when in motion
public static final Stat model_error = new Stat();
public static float refreshRate = 0; // Moving average of refresh rate in Hz
private static long n = 0; // number of samples
/**
* Initializes altimeter services, if not already running
* @param appContext The Application context
*/
public static synchronized void start(@NonNull Context appContext) {
// Get a new preference manager
prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
if(sensorManager == null) {
// Load ground level from preferences
loadGroundLevel();
// Add sensor listener
sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
final Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (sensor != null) {
// Start sensor updates
sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
}
// Start GPS updates
if(Services.location != null) {
Services.location.addListener(locationListener);
} else {
Log.e(TAG, "Location services should be initialized before altimeter");
}
} else {
Log.w(TAG, "MyAltimeter already started");
}
}
public static double altitudeAGL() {
return pressure_altitude_filtered - ground_level;
}
public static double groundLevel() {
return ground_level;
}
/**
* Load ground level from preferences
*/
private static void loadGroundLevel() {
final long groundLevelTime = prefs.getLong("altimeter_ground_level_time", -1L);
if(groundLevelTime != -1 && System.currentTimeMillis() - groundLevelTime < GROUND_LEVEL_TTL) {
ground_level = prefs.getFloat("altimeter_ground_level", 0);
ground_level_initialized = true;
Log.i(TAG, "Restoring ground level from preferences: " + Convert.distance(ground_level, 2, true));
}
}
/**
* Set ground level, based on pressure altitude.
* @param groundLevel the pressure altitude at ground level (0m AGL)
*/
public static void setGroundLevel(double groundLevel) {
ground_level = groundLevel;
ground_level_initialized = true;
// Save to preferences
final SharedPreferences.Editor edit = prefs.edit();
edit.putFloat("altimeter_ground_level", (float) ground_level);
edit.putLong("altimeter_ground_level_time", System.currentTimeMillis());
edit.apply();
}
// Sensor Event Listener
private static final SensorEventListener sensorEventListener = new AltimeterSensorEventListener();
private static class AltimeterSensorEventListener implements SensorEventListener {
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(@NonNull SensorEvent event) {
long millis = System.currentTimeMillis(); // Record time as soon as possible
// assert event.sensor.getType() == Sensor.TYPE_PRESSURE;
// Log.w(TAG, "values[] = " + event.values[0] + ", " + event.values[1] + ", " + event.values[2]);
MyAltimeter.updateBarometer(millis, event);
}
}
// Location Listener
private static final MyLocationListener locationListener = new AltimeterLocationListener();
private static class AltimeterLocationListener implements MyLocationListener {
public void onLocationChanged(@NonNull MLocation loc) {
MyAltimeter.updateGPS(loc);
}
public void onLocationChangedPostExecute() {}
}
/**
* Process new barometer reading
*/
private static void updateBarometer(long millis, SensorEvent event) {
if(event == null || event.values.length == 0 || Double.isNaN(event.values[0]))
return;
if(lastFixNano == event.timestamp) {
Log.e(TAG, "Double update: " + lastFixNano);
}
double prevAltitude = altitude;
// double prevClimb = climb;
long prevLastFixNano = lastFixNano;
pressure = event.values[0];
lastFixNano = event.timestamp;
lastFixMillis = millis - Services.location.phoneOffsetMillis; // Convert to GPS time
// Barometer refresh rate
final long deltaTime = lastFixNano - prevLastFixNano; // time since last refresh
if(deltaTime > 0 && prevLastFixNano > 0) {
final float newRefreshRate = 1E9f / (float) (deltaTime); // Refresh rate based on last 2 samples
if(refreshRate == 0) {
refreshRate = newRefreshRate;
} else {
refreshRate += (newRefreshRate - refreshRate) * 0.5f; // Moving average
}
if (Double.isNaN(refreshRate)) {
Log.e(TAG, "Refresh rate is NaN, deltaTime = " + deltaTime + " refreshTime = " + newRefreshRate);
FirebaseCrash.report(new Exception("Refresh rate is NaN, deltaTime = " + deltaTime + " newRefreshRate = " + newRefreshRate));
refreshRate = 0;
}
}
// Convert pressure to altitude
pressure_altitude_raw = pressureToAltitude(pressure);
// Apply kalman filter to pressure altitude, to produce smooth barometric pressure altitude.
final double dt = Double.isNaN(prevAltitude)? 0 : (lastFixNano - prevLastFixNano) * 1E-9;
filter.update(pressure_altitude_raw, dt);
pressure_altitude_filtered = filter.x;
climb = filter.v;
// Compute model error
model_error.addSample(pressure_altitude_filtered - pressure_altitude_raw);
// Compute GPS corrected altitude AMSL
altitude = pressure_altitude_filtered - altitude_offset;
if(Double.isNaN(altitude)) {
Log.w(TAG, "Altitude should not be NaN: altitude = " + altitude);
}
// Adjust for ground level
if(!ground_level_initialized) {
if (n == 0) {
// First pressure reading. Calibrate ground level.
ground_level = pressure_altitude_raw;
} else if (n < 30) {
// Average the first N raw samples
ground_level += (pressure_altitude_raw - ground_level) / (n + 1);
} else {
setGroundLevel(ground_level);
}
}
n++;
updateAltitude();
}
private static long gps_sample_count = 0;
/**
* Process new GPS reading
*/
private static void updateGPS(MLocation loc) {
// Log.d(TAG, "GPS Update Time: " + System.currentTimeMillis() + " " + System.nanoTime() + " " + loc.millis);
if(!Double.isNaN(loc.altitude_gps)) {
if(n > 0) {
// Log.d(TAG, "alt = " + altitude + ", alt_gps = " + altitude_gps + ", offset = " + altitude_offset);
// GPS correction for altitude AMSL
if(gps_sample_count == 0) {
// First altitude reading. Calibrate ground level.
altitude_offset = pressure_altitude_filtered - loc.altitude_gps;
} else {
// Average the first N samples, then use moving average with lag 20
final double altitude_error = altitude - loc.altitude_gps;
final long correction_factor = Math.min(gps_sample_count, 20);
final double altitude_correction = altitude_error / correction_factor;
altitude_offset += altitude_correction;
}
} else {
// No barometer use gps
final double prevAltitude = altitude;
final long prevLastFix = lastFixMillis;
lastFixMillis = loc.millis;
// Update the official altitude
altitude = loc.altitude_gps;
if(Double.isNaN(prevAltitude)) {
climb = 0;
} else {
final double dt = (lastFixMillis - prevLastFix) * 1E-3;
climb = (altitude - prevAltitude) / dt;
}
// Only update official altitude if we are relying solely on GPS for altitude
updateAltitude();
}
gps_sample_count++;
}
}
/**
* Saves an official altitude measurement
*/
private static void updateAltitude() {
// Log.d(TAG, "Altimeter Update Time: " + System.currentTimeMillis() + " " + System.nanoTime() + " " + lastFixMillis + " " + lastFixNano);
// Create the measurement
final MAltitude myAltitude = new MAltitude(lastFixMillis, lastFixNano, altitude, climb, pressure);
EventBus.getDefault().post(myAltitude);
}
// ISA pressure and temperature
private static final double altitude0 = 0; // ISA height 0 meters
private static final double pressure0 = SensorManager.PRESSURE_STANDARD_ATMOSPHERE; // ISA pressure 1013.25 hPa
private static final double temp0 = 288.15; // ISA temperature 15 degrees celcius
// Physical constants
// private static final double G = 9.80665; // Gravity (m/s^2)
// private static final double R = 8.31432; // Universal Gas Constant ((N m)/(mol K))
// private static final double M = 0.0289644; // Molar Mass of air (kg/mol)
private static final double L = -0.0065; // Temperature Lapse Rate (K/m)
private static final double EXP = 0.190263237; // -L * R / (G * M);
/**
* Convert air pressure to altitude
* @param pressure Pressure in hPa
* @return The pressure altitude in meters
*/
private static double pressureToAltitude(double pressure) {
// Barometric formula
return altitude0 - temp0 * (1 - Math.pow(pressure / pressure0, EXP)) / L;
}
public static void stop() {
Services.location.removeListener(locationListener);
sensorManager.unregisterListener(sensorEventListener);
sensorManager = null;
prefs = null;
}
}
|
package com.seandbeach.stockticker;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
public class SettingsActivity extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_mobile_data_key)));
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getBoolean(preference.getKey(), false));
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
// Exclude SwitchPreferences, since those values are obvious
if (!(preference instanceof SwitchPreference)) {
preference.setSummary(stringValue);
}
}
return true;
}
}
|
package com.tamic.retrofitclient.net;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.tamic.retrofitclient.IpResult;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class RetrofitClient {
private static final int DEFAULT_TIMEOUT = 20;
private BaseApiService apiService;
private static OkHttpClient okHttpClient;
public static String baseUrl = BaseApiService.Base_URL;
private static Context mContext;
private static RetrofitClient sNewInstance;
private static Retrofit retrofit;
private Cache cache = null;
private File httpCacheDirectory;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(baseUrl);
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder()
.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
private static class SingletonHolder {
private static RetrofitClient INSTANCE = new RetrofitClient(
mContext);
}
public static RetrofitClient getInstance(Context context) {
if (context != null) {
mContext = context;
}
return SingletonHolder.INSTANCE;
}
public static RetrofitClient getInstance(Context context, String url) {
if (context != null) {
mContext = context;
}
return new RetrofitClient(context, url);
}
public static RetrofitClient getInstance(Context context, String url, Map<String, String> headers) {
if (context != null) {
mContext = context;
}
return new RetrofitClient(context, url, headers);
}
private RetrofitClient() {
}
private RetrofitClient(Context context) {
this(context, baseUrl, null);
}
private RetrofitClient(Context context, String url) {
this(context, url, null);
}
private RetrofitClient(Context context, String url, Map<String, String> headers) {
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
if ( httpCacheDirectory == null) {
httpCacheDirectory = new File(mContext.getCacheDir(), "tamic_cache");
}
try {
if (cache == null) {
cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
}
} catch (Exception e) {
Log.e("OKHttp", "Could not create http cache", e);
}
okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.cookieJar(new NovateCookieManger(context))
.cache(cache)
.addInterceptor(new BaseInterceptor(headers))
.addInterceptor(new CaheInterceptor(context))
.addNetworkInterceptor(new CaheInterceptor(context))
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
// 810s
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(url)
.build();
}
/**
* ApiBaseUrl
*
* @param newApiBaseUrl
*/
public static void changeApiBaseUrl(String newApiBaseUrl) {
baseUrl = newApiBaseUrl;
builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl);
}
/**
*addcookieJar
*/
public static void addCookie() {
okHttpClient.newBuilder().cookieJar(new NovateCookieManger(mContext)).build();
retrofit = builder.client(okHttpClient).build();
}
/**
* ApiBaseUrl
*
* @param newApiHeaders
*/
public static void changeApiHeader(Map<String, String> newApiHeaders) {
okHttpClient.newBuilder().addInterceptor(new BaseInterceptor(newApiHeaders)).build();
builder.client(httpClient.build()).build();
}
/**
* create BaseApi defalte ApiManager
* @return ApiManager
*/
public RetrofitClient createBaseApi() {
apiService = create(BaseApiService.class);
return this;
}
/**
* create you ApiService
* Create an implementation of the API endpoints defined by the {@code service} interface.
*/
public <T> T create(final Class<T> service) {
if (service == null) {
throw new RuntimeException("Api service is null!");
}
return retrofit.create(service);
}
public Subscription getData(Subscriber<IpResult> subscriber, String ip) {
return apiService.getData(ip)
.compose(schedulersTransformer())
.compose(transformer())
.subscribe(subscriber);
}
public Subscription get(String url, Map parameters, Subscriber<IpResult> subscriber) {
return apiService.executeGet(url, parameters)
.compose(schedulersTransformer())
.compose(transformer())
.subscribe(subscriber);
}
public void post(String url, Map<String, String> parameters, Subscriber<ResponseBody> subscriber) {
apiService.executePost(url, parameters)
.compose(schedulersTransformer())
.compose(transformer())
.subscribe(subscriber);
}
public void upload(String url, RequestBody requestBody,Subscriber<ResponseBody> subscriber) {
apiService.upLoadFile(url, requestBody)
.compose(schedulersTransformer())
.compose(transformer())
.subscribe(subscriber);
}
public void download(String url, final CallBack callBack) {
apiService.downloadFile(url)
.compose(schedulersTransformer())
.compose(transformer())
.subscribe(new DownSubscriber<ResponseBody>(callBack));
}
Observable.Transformer schedulersTransformer() {
return new Observable.Transformer() {
@Override
public Object call(Object observable) {
return ((Observable) observable).subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
/* @Override
public Observable call(Observable observable) {
return observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}*/
};
}
<T> Observable.Transformer<T, T> applySchedulers() {
return (Observable.Transformer<T, T>) schedulersTransformer();
}
public <T> Observable.Transformer<BaseResponse<T>, T> transformer() {
return new Observable.Transformer() {
@Override
public Object call(Object observable) {
return ((Observable) observable).map(new HandleFuc<T>()).onErrorResumeNext(new HttpResponseFunc<T>());
}
};
}
public <T> Observable<T> switchSchedulers(Observable<T> observable) {
return observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
private static class HttpResponseFunc<T> implements Func1<Throwable, Observable<T>> {
@Override public Observable<T> call(Throwable t) {
return Observable.error(ExceptionHandle.handleException(t));
}
}
private class HandleFuc<T> implements Func1<BaseResponse<T>, T> {
@Override
public T call(BaseResponse<T> response) {
if (!response.isOk()) throw new RuntimeException(response.getCode() + "" + response.getMsg() != null ? response.getMsg(): "");
return response.getData();
}
}
* /**
* execute your customer API
* For example:
* MyApiService service =
* RetrofitClient.getInstance(MainActivity.this).create(MyApiService.class);
*
* RetrofitClient.getInstance(MainActivity.this)
* .execute(service.lgon("name", "password"), subscriber)
* * @param subscriber
*/
public static <T> T execute(Observable<T> observable ,Subscriber<T> subscriber) {
observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
return null;
}
/**
* DownSubscriber
* @param <ResponseBody>
*/
class DownSubscriber<ResponseBody> extends Subscriber<ResponseBody> {
CallBack callBack;
public DownSubscriber(CallBack callBack) {
this.callBack = callBack;
}
@Override
public void onStart() {
super.onStart();
if (callBack != null) {
callBack.onStart();
}
}
@Override
public void onCompleted() {
if (callBack != null) {
callBack.onCompleted();
}
}
@Override
public void onError(Throwable e) {
if (callBack != null) {
callBack.onError(e);
}
}
@Override
public void onNext(ResponseBody responseBody) {
DownLoadManager.getInstance(callBack).writeResponseBodyToDisk(mContext, (okhttp3.ResponseBody) responseBody);
}
}
}
|
package fm.jiecao.jiecaovideoplayer;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.AbsoluteLayout;
import com.squareup.picasso.Picasso;
import fm.jiecao.jcvideoplayer_lib.JCUtils;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
public class WebViewActivity extends AppCompatActivity {
WebView mWebView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setTitle("AboutWebView");
setContentView(R.layout.activity_webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JCCallBack(), "jcvd");
mWebView.loadUrl("file:///android_asset/jcvd.html");
}
public class JCCallBack {
@JavascriptInterface
public void adViewJieCaoVideoPlayer(final int width, final int height, final int top, final int left) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JCVideoPlayerStandard webVieo = new JCVideoPlayerStandard(WebViewActivity.this);
webVieo.setUp("http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4",
JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
Picasso.with(WebViewActivity.this)
.load("http://cos.myqcloud.com/1000264/qcloud_video_attachment/842646334/vod_cover/cover1458036374.jpg")
.into(webVieo.thumbImageView);
ViewGroup.LayoutParams ll = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(ll);
layoutParams.y = JCUtils.dip2px(WebViewActivity.this, top);
layoutParams.x = JCUtils.dip2px(WebViewActivity.this, left);
layoutParams.height = JCUtils.dip2px(WebViewActivity.this, height);
layoutParams.width = JCUtils.dip2px(WebViewActivity.this, width);
mWebView.addView(webVieo, layoutParams);
}
});
}
}
@Override
public void onBackPressed() {
if (JCVideoPlayer.backPress()) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
JCVideoPlayer.releaseAllVideos();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package me.devsaki.hentoid.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceScreen;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.abstracts.BaseActivity;
import me.devsaki.hentoid.fragments.LibRefreshLauncher;
import me.devsaki.hentoid.services.ImportService;
import me.devsaki.hentoid.services.UpdateCheckService;
import me.devsaki.hentoid.services.UpdateDownloadService;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.Helper;
import me.devsaki.hentoid.util.Preferences;
public class PrefsActivity extends BaseActivity {
public static final String TARGET_SETTING_PAGE = "target";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment())
.commit();
}
public static class MyPreferenceFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
if(getArguments() != null){
String key = getArguments().getString(TARGET_SETTING_PAGE);
setPreferencesFromResource(R.xml.preferences, key);
findPreference(Preferences.Key.PREF_DL_THREADS_QUANTITY_LISTS)
.setOnPreferenceChangeListener((preference, newValue) -> onPrefRequiringRestartChanged());
} else {
setPreferencesFromResource(R.xml.preferences, rootKey);
findPreference(Preferences.Key.PREF_HIDE_RECENT)
.setOnPreferenceChangeListener((preference, newValue) -> onPrefRequiringRestartChanged());
findPreference(Preferences.Key.PREF_ANALYTICS_TRACKING)
.setOnPreferenceChangeListener((preference, newValue) -> onPrefRequiringRestartChanged());
findPreference(Preferences.Key.PREF_USE_SFW)
.setOnPreferenceChangeListener((preference, newValue) -> onPrefRequiringRestartChanged());
findPreference(Preferences.Key.PREF_APP_LOCK)
.setOnPreferenceChangeListener((preference, newValue) -> onAppLockPinChanged(newValue));
}
}
@Override
public boolean onPreferenceTreeClick(Preference preference) {
String key = preference.getKey();
if (key == null) return super.onPreferenceTreeClick(preference);
switch (key) {
case Preferences.Key.PREF_ADD_NO_MEDIA_FILE:
return FileHelper.createNoMedia();
case Preferences.Key.PREF_CHECK_UPDATE_MANUAL:
return onCheckUpdatePrefClick();
case Preferences.Key.PREF_REFRESH_LIBRARY:
if (ImportService.isRunning()) {
Helper.toast("Import is already running");
} else {
LibRefreshLauncher.invoke(requireFragmentManager());
}
return true;
default:
return super.onPreferenceTreeClick(preference);
}
}
@Override
public void onNavigateToScreen(PreferenceScreen preferenceScreen)
{
MyPreferenceFragment applicationPreferencesFragment = new MyPreferenceFragment();
Bundle args = new Bundle();
args.putString(TARGET_SETTING_PAGE, preferenceScreen.getKey());
applicationPreferencesFragment.setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(getId(), applicationPreferencesFragment)
.addToBackStack(null)
.commit();
}
private boolean onCheckUpdatePrefClick() {
if (!UpdateDownloadService.isRunning()) {
Intent intent = UpdateCheckService.makeIntent(requireContext(), true);
requireContext().startService(intent);
}
return true;
}
private boolean onPrefRequiringRestartChanged() {
Helper.toast(R.string.restart_needed);
return true;
}
private boolean onAppLockPinChanged(Object newValue) {
String pin = (String) newValue;
if (pin.isEmpty()) {
Helper.toast(getActivity(), R.string.app_lock_disabled);
} else {
Helper.toast(getActivity(), R.string.app_lock_enable);
}
return true;
}
}
}
|
package net.squanchy.support.debug;
import android.content.Context;
import android.content.SharedPreferences;
import net.squanchy.BuildConfig;
public class DebugPreferences {
private static final String PREFERENCES_NAME_DEBUG = "debug";
private static final String KEY_CONTEST_TESTING_ENABLED = "contest.testing_enabled";
private static final boolean IS_DEBUG = BuildConfig.DEBUG;
private final SharedPreferences preferences;
public DebugPreferences(Context context) {
this.preferences = context.getSharedPreferences(DebugPreferences.PREFERENCES_NAME_DEBUG, Context.MODE_PRIVATE);
}
public boolean contestTestingEnabled() {
return IS_DEBUG && preferences.getBoolean(KEY_CONTEST_TESTING_ENABLED, false);
}
public void enableContestTesting() {
storeDebugPreference(KEY_CONTEST_TESTING_ENABLED, true);
}
public void disableContestTesting() {
storeDebugPreference(KEY_CONTEST_TESTING_ENABLED, false);
}
private void storeDebugPreference(String key, boolean value) {
if (!IS_DEBUG) {
return;
}
preferences.edit()
.putBoolean(key, value)
.apply();
}
}
|
package org.stepic.droid.ui.fragments;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.squareup.otto.Subscribe;
import org.stepic.droid.R;
import org.stepic.droid.base.FragmentBase;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.core.StepModule;
import org.stepic.droid.core.presenters.StepsPresenter;
import org.stepic.droid.core.presenters.contracts.StepsView;
import org.stepic.droid.events.steps.UpdateStepEvent;
import org.stepic.droid.events.video.VideoQualityEvent;
import org.stepic.droid.model.CachedVideo;
import org.stepic.droid.model.Lesson;
import org.stepic.droid.model.Step;
import org.stepic.droid.model.Unit;
import org.stepic.droid.model.VideoUrl;
import org.stepic.droid.ui.adapters.StepFragmentAdapter;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.util.ProgressHelper;
import org.stepic.droid.web.ViewAssignment;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
public class StepsFragment extends FragmentBase implements StepsView {
private static final String FROM_PREVIOUS_KEY = "fromPrevKey";
private static final String SIMPLE_UNIT_ID_KEY = "simpleUnitId";
private static final String SIMPLE_LESSON_ID_KEY = "simpleLessonId";
private static final String SIMPLE_STEP_POSITION_KEY = "simpleStepPosition";
public static StepsFragment newInstance(@org.jetbrains.annotations.Nullable Unit unit, Lesson lesson, boolean fromPreviousLesson) {
Bundle args = new Bundle();
args.putParcelable(AppConstants.KEY_UNIT_BUNDLE, unit);
args.putParcelable(AppConstants.KEY_LESSON_BUNDLE, lesson);
args.putBoolean(FROM_PREVIOUS_KEY, fromPreviousLesson);
StepsFragment fragment = new StepsFragment();
fragment.setArguments(args);
return fragment;
}
public static StepsFragment newInstance(long simpleUnitId, long simpleLessonId, long simpleStepPosition) {
Bundle args = new Bundle();
args.putLong(SIMPLE_UNIT_ID_KEY, simpleUnitId);
args.putLong(SIMPLE_LESSON_ID_KEY, simpleLessonId);
args.putLong(SIMPLE_STEP_POSITION_KEY, simpleStepPosition);
StepsFragment fragment = new StepsFragment();
fragment.setArguments(args);
return fragment;
}
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.viewpager)
ViewPager viewPager;
@BindView(R.id.tabs)
TabLayout tabLayout;
@BindView(R.id.load_progressbar)
ProgressBar progressBar;
@BindString(R.string.not_available_lesson)
String notAvailableLessonString;
StepFragmentAdapter stepAdapter;
private List<Step> stepList;
private String qualityForView;
private boolean fromPreviousLesson = false;
@Inject
StepsPresenter stepsPresenter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
MainApplication
.component()
.plus(new StepModule())
.inject(this);
fromPreviousLesson = getArguments().getBoolean(FROM_PREVIOUS_KEY);
stepList = new ArrayList<>();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_steps, container, false);
setHasOptionsMenu(true);
unbinder = ButterKnife.bind(this, v);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initIndependentUI();
stepsPresenter.attachView(this);
if (stepsPresenter.getLesson() == null) {
Lesson lesson = getArguments().getParcelable(AppConstants.KEY_LESSON_BUNDLE);
Unit unit = getArguments().getParcelable(AppConstants.KEY_UNIT_BUNDLE);
long unitId = getArguments().getLong(SIMPLE_UNIT_ID_KEY);
long defaultStepPos = getArguments().getLong(SIMPLE_STEP_POSITION_KEY);
long lessonId = getArguments().getLong(SIMPLE_LESSON_ID_KEY);
stepsPresenter.init(lesson, unit, lessonId, unitId, defaultStepPos);
}
bus.register(this);
}
private void initIndependentUI() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
hideSoftKeypad();
pushState(position);
checkOptionsMenu(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void init(Lesson lesson, Unit unit) {
stepAdapter = new StepFragmentAdapter(getActivity().getSupportFragmentManager(), stepList, lesson, unit);
viewPager.setAdapter(stepAdapter);
getActivity().setTitle(lesson.getTitle());
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onDestroyView() {
bus.unregister(this);
stepsPresenter.detachView(this);
super.onDestroyView();
}
private void checkOptionsMenu(int position) {
if (stepList.size() <= position) return;
final Step step = stepList.get(position);
if (step.getBlock() == null || step.getBlock().getVideo() == null) {
bus.post(new VideoQualityEvent(null, step.getId()));
} else {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
CachedVideo video = mDatabaseFacade.getCachedVideoById(step.getBlock().getVideo().getId());
String quality;
if (video == null) {
String resultQuality = mUserPreferences.getQualityVideo();
try {
int weWant = Integer.parseInt(mUserPreferences.getQualityVideo());
final List<VideoUrl> urls = step.getBlock().getVideo().getUrls();
int bestDelta = Integer.MAX_VALUE;
int bestIndex = 0;
for (int i = 0; i < urls.size(); i++) {
int current = Integer.parseInt(urls.get(i).getQuality());
int delta = Math.abs(current - weWant);
if (delta < bestDelta) {
bestDelta = delta;
bestIndex = i;
}
}
resultQuality = urls.get(bestIndex).getQuality();
} catch (NumberFormatException e) {
resultQuality = mUserPreferences.getQualityVideo();
}
quality = resultQuality;
} else {
quality = video.getQuality();
}
return quality;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null) {
bus.post(new VideoQualityEvent(s, step.getId()));
} else {
bus.post(new VideoQualityEvent(s + "p", step.getId()));
}
}
};
task.executeOnExecutor(mThreadPoolExecutor);
}
}
private void pushState(int position) {
if (stepList.size() <= position) return;
final Step step = stepList.get(position);
if (mStepResolver.isViewedStatePost(step) && !step.is_custom_passed()) {
//try to push viewed state to the server
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
long stepId = step.getId();
protected Void doInBackground(Void... params) {
long assignmentID = mDatabaseFacade.getAssignmentIdByStepId(stepId);
mShell.getScreenProvider().pushToViewedQueue(new ViewAssignment(assignmentID, stepId));
return null;
}
};
task.execute();
}
}
@Subscribe
public void onUpdateOneStep(UpdateStepEvent e) {
long stepId = e.getStepId();
Step step = null;
if (stepList != null) {
for (Step item : stepList) {
if (item.getId() == stepId) {
step = item;
break;
}
}
}
if (step != null) {
step.set_custom_passed(true);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setIcon(stepAdapter.getTabDrawable(i));
}
}
}
@Override
public void onEmptySteps() {
Toast.makeText(getContext(), "Empty steps", Toast.LENGTH_SHORT).show();
}
private void scrollTabLayoutToEnd(ViewTreeObserver.OnPreDrawListener listener) {
int tabWidth = tabLayout.getMeasuredWidth();
if (tabWidth > 0) {
tabLayout.getViewTreeObserver().removeOnPreDrawListener(listener);
int tabCount = tabLayout.getTabCount();
int right = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(tabCount - 1).getRight(); //workaround to get really last element
if (right >= tabWidth) {
tabLayout.setScrollX(right);
}
}
}
private void updateTabs() {
if (tabLayout.getTabCount() == 0) {
tabLayout.setupWithViewPager(viewPager);
}
for (int i = 0; i < stepAdapter.getCount(); i++) {
if (i < tabLayout.getTabCount() && i >= 0 && stepAdapter != null) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
tab.setIcon(stepAdapter.getTabDrawable(i));
}
}
}
}
@Subscribe
public void onQualityDetermined(VideoQualityEvent e) {
int currentPosition = viewPager.getCurrentItem();
if (currentPosition < 0 || currentPosition >= stepList.size()) return;
long stepId = stepList.get(currentPosition).getId();
if (e.getStepId() != stepId) return;
qualityForView = e.getQuality();
getActivity().invalidateOptionsMenu();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.video_step_menu, menu);
MenuItem quality = menu.findItem(R.id.action_quality);
if (qualityForView != null) {
quality.setTitle(qualityForView);
} else {
quality.setVisible(false);
}
MenuItem comments = menu.findItem(R.id.action_comments);
if (stepList.isEmpty()) {
comments.setVisible(false);
} else {
comments.setVisible(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_comments:
int position = viewPager.getCurrentItem();
if (position < 0 || position >= stepList.size()) {
return super.onOptionsItemSelected(item);
}
Step step = stepList.get(position);
mShell.getScreenProvider().openComments(getContext(), step.getDiscussion_proxy(), step.getId());
break;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onLessonCorrupted() {
// FIXME: 05.09.16 show placeholder
Toast.makeText(getContext(), "Sorry, link was broken", Toast.LENGTH_SHORT).show();
}
@Override
public void onLessonUnitPrepared(Lesson lesson, @NonNull Unit unit) {
init(lesson, unit);
}
@Override
public void onConnectionProblem() {
Toast.makeText(getActivity(), notAvailableLessonString, Toast.LENGTH_LONG).show();
ProgressHelper.dismiss(progressBar);
}
@Override
public void updateTabState(List<Step> stepList) {
showSteps(stepList);
}
@Override
public void showSteps(List<Step> steps) {
boolean isNumEquals = stepList.isEmpty() || steps.size() == stepList.size(); // hack for need updating view?
stepList.clear();
stepList.addAll(steps);
stepAdapter.notifyDataSetChanged();
updateTabs();
if (fromPreviousLesson) {
viewPager.setCurrentItem(stepList.size() - 1, false);
tabLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
scrollTabLayoutToEnd(this);
return true;
}
});
fromPreviousLesson = false;
}
tabLayout.setVisibility(View.VISIBLE);
ProgressHelper.dismiss(progressBar);
pushState(viewPager.getCurrentItem());
checkOptionsMenu(viewPager.getCurrentItem());
if (!isNumEquals) {
//it is working only if teacher add steps in lesson and user has not cached new steps, but cached old.
stepAdapter.notifyDataSetChanged();
updateTabs();
}
}
}
|
package se.chalmers.dat255.sleepfighter;
import se.chalmers.dat255.sleepfighter.model.AlarmList;
import se.chalmers.dat255.sleepfighter.persist.PersistenceManager;
import se.chalmers.dat255.sleepfighter.utils.message.Message;
import se.chalmers.dat255.sleepfighter.utils.message.MessageBus;
import android.app.Application;
/**
* A custom implementation of Application for SleepFighter.
*/
public class SFApplication extends Application {
private static final boolean CLEAN_START = false;
private AlarmList alarmList;
private MessageBus<Message> bus;
private PersistenceManager persistenceManager;
@Override
public void onCreate() {
super.onCreate();
this.persistenceManager = new PersistenceManager( this );
}
/**
* Returns the AlarmList for the application.<br/>
* It is lazy loaded.
*
* @return the AlarmList for the application
*/
public AlarmList getAlarms() {
if ( this.alarmList == null ) {
if ( CLEAN_START ) {
this.persistenceManager.cleanStart();
}
this.alarmList = this.getPersister().fetchAlarms();
this.alarmList.setMessageBus(this.getBus());
this.bus.subscribe( this.persistenceManager );
}
return alarmList;
}
/**
* Returns the default MessageBus for the application.
*
* @return the default MessageBus for the application
*/
public MessageBus<Message> getBus() {
if ( this.bus == null ) {
this.bus = new MessageBus<Message>();
}
return bus;
}
/**
* Returns the PersistenceManager for the application.
*
* @return the periste
*/
public PersistenceManager getPersister() {
return this.persistenceManager;
}
}
|
package uk.ac.ebi.gxa.statistics;
import java.io.Serializable;
import java.util.*;
import it.uniroma3.mat.extendedset.ConciseSet;
public class Statistics implements Serializable {
private static final long serialVersionUID = -164439988781254870L;
private Map<Integer, Map<Integer, ConciseSet>> statistics =
new HashMap<Integer, Map<Integer, ConciseSet>>();
synchronized
public void addStatistics(final Integer attributeIndex,
final Integer experimentIndex,
final Collection<Integer> geneIndexes) {
Map<Integer, ConciseSet> stats;
if (statistics.containsKey(attributeIndex)) {
stats = statistics.get(attributeIndex);
} else {
stats = new HashMap<Integer, ConciseSet>();
statistics.put(attributeIndex, stats);
}
if (stats.containsKey(experimentIndex))
stats.get(experimentIndex).addAll(geneIndexes);
else
stats.put(experimentIndex, new ConciseSet(geneIndexes));
}
synchronized
public int getNumStatistics(final Integer attributeIndex,
final Integer experimentIndex) {
if (statistics.containsKey(attributeIndex) &&
statistics.get(attributeIndex).containsKey(experimentIndex)) {
return statistics.get(attributeIndex).get(experimentIndex).size();
}
return 0;
}
public Map<Integer, ConciseSet> getStatisticsForAttribute(Integer attributeIndex) {
return statistics.get(attributeIndex);
}
public Set<Integer> getAttributeIndexes() {
return statistics.keySet();
}
}
|
package org.chromium.base;
import android.app.Notification;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
/**
* Utility class to use new APIs that were added after ICS (API level 14).
*/
public class ApiCompatibilityUtils {
private ApiCompatibilityUtils() {
}
/**
* Returns true if view's layout direction is right-to-left.
*
* @param view the View whose layout is being considered
*/
public static boolean isLayoutRtl(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
} else {
// All layouts are LTR before JB MR1.
return false;
}
}
/**
* @see android.view.View#setLayoutDirection(int)
*/
public static void setLayoutDirection(View view, int layoutDirection) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
view.setLayoutDirection(layoutDirection);
} else {
// Do nothing. RTL layouts aren't supported before JB MR1.
}
}
/**
* @see android.view.ViewGroup.MarginLayoutParams#setMarginEnd(int)
*/
public static void setMarginEnd(MarginLayoutParams layoutParams, int end) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.setMarginEnd(end);
} else {
layoutParams.rightMargin = end;
}
}
/**
* @see android.view.ViewGroup.MarginLayoutParams#setMarginStart(int)
*/
public static void setMarginStart(MarginLayoutParams layoutParams, int start) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.setMarginStart(start);
} else {
layoutParams.leftMargin = start;
}
}
/**
* @see android.view.ViewGroup.MarginLayoutParams#getMarginStart()
*/
public static int getMarginStart(MarginLayoutParams layoutParams) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return layoutParams.getMarginStart();
} else {
return layoutParams.leftMargin;
}
}
/**
* @see android.view.View#postInvalidateOnAnimation()
*/
public static void postInvalidateOnAnimation(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.postInvalidateOnAnimation();
} else {
view.postInvalidate();
}
}
// These methods have a new name, and the old name is deprecated.
/**
* @see android.view.View#setBackground(Drawable)
*/
@SuppressWarnings("deprecation")
public static void setBackgroundForView(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
}
/**
* @see android.view.ViewTreeObserver#removeOnGlobalLayoutListener()
*/
@SuppressWarnings("deprecation")
public static void removeOnGlobalLayoutListener(
View view, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
} else {
view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
}
}
/**
* @see android.app.Notification.Builder#build()
*/
@SuppressWarnings("deprecation")
public static Notification buildNotification(Notification.Builder builder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return builder.build();
} else {
return builder.getNotification();
}
}
}
|
package org.basex.query.func.admin;
import static org.basex.core.users.UserText.*;
import static org.basex.query.QueryError.*;
import java.io.*;
import java.math.*;
import java.util.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.server.*;
import org.basex.server.Log.*;
import org.basex.util.*;
public final class AdminLogs extends AdminFn {
@Override
public Iter iter(final QueryContext qc) throws QueryException {
checkAdmin(qc);
return exprs.length == 0 ? list(qc).iter() : logs(qc);
}
@Override
public Value value(final QueryContext qc) throws QueryException {
checkAdmin(qc);
return exprs.length == 0 ? list(qc) : logs(qc).value(qc, this);
}
/**
* Returns a list of all log files.
* @param qc query context
* @return list
*/
private static Value list(final QueryContext qc) {
final ValueBuilder vb = new ValueBuilder(qc);
for(final IOFile file : qc.context.log.files()) {
final String date = file.name().replace(IO.LOGSUFFIX, "");
vb.add(new FElem(FILE).add(date).add(SIZE, Token.token(file.length())));
}
return vb.value();
}
/**
* Returns the logs from the specified log file.
* @param qc query context
* @return list
* @throws QueryException query exception
*/
private Iter logs(final QueryContext qc) throws QueryException {
// return content of single log file
final String name = Token.string(toToken(exprs[0], qc));
final boolean merge = exprs.length > 1 && toBoolean(exprs[1], qc);
final LinkedList<LogEntry> list = logs(name, qc);
final HashMap<String, LinkedList<LogEntry>> map = new HashMap<>();
if(merge) {
// group entries by address
for(final LogEntry entry : list) {
map.computeIfAbsent(entry.address, address -> new LinkedList<>()).add(entry);
}
}
return new Iter() {
@Override
public Item next() throws QueryException {
// scan and merge entries
for(LogEntry entry; (entry = list.pollFirst()) != null;) {
// REQUEST entries: find concluding entries (status code, OK, error)
if(merge) {
// skip entries that have already been consumed
final LinkedList<LogEntry> entries = map.get(entry.address);
if(entries.peekFirst() != entry) continue;
entries.removeFirst();
if(entry.type.equals(LogType.REQUEST.name())) {
final Iterator<LogEntry> iter = entries.iterator();
while(iter.hasNext()) {
final LogEntry next = iter.next();
final String t = next.type;
// REQUEST entry with identical address: no concluding entry exists
if(t.equals(LogType.REQUEST.name())) break;
if(t.matches("^\\d+$") || Strings.eq(t, LogType.OK.name(), LogType.ERROR.name())) {
entry.type = t;
entry.user = next.user;
entry.ms = entry.ms.add(next.ms);
if(!next.message.isEmpty()) entry.message += "; " + next.message;
iter.remove();
break;
}
}
}
}
// add new element
final FElem elem = new FElem(ENTRY);
if(entry.message != null) elem.add(entry.message);
if(entry.address != null) {
elem.add(TIME, entry.time).add(ADDRESS, entry.address).add(USER, entry.user);
if(entry.type != null) elem.add(TYPE, entry.type);
if(entry.ms != BigDecimal.ZERO) elem.add(MS, entry.ms.toString());
}
return elem;
}
return null;
}
};
}
/**
* Returns all log entries.
* @param name name of log file
* @param qc query context
* @return list
* @throws QueryException query exception
*/
private LinkedList<LogEntry> logs(final String name, final QueryContext qc)
throws QueryException {
final Log log = qc.context.log;
final LogFile file = log.file(name);
if(file == null) throw WHICHRES_X.get(info, name);
try {
final LinkedList<LogEntry> logs = new LinkedList<>();
for(final String line : file.read()) {
qc.checkStop();
final LogEntry entry = new LogEntry();
final String[] cols = line.split("\t");
if(cols.length > 2) {
entry.time = cols[0];
entry.address = cols[1];
entry.user = cols[2];
entry.type = cols.length > 3 ? cols[3] : "";
entry.message = cols.length > 4 ? cols[4] : "";
entry.ms = cols.length > 5 ? new BigDecimal(cols[5].replace(" ms", "")) : BigDecimal.ZERO;
} else {
// legacy format
entry.message = line;
}
logs.add(entry);
}
return logs;
} catch(final IOException ex) {
throw IOERR_X.get(info, ex);
}
}
}
|
package io.bootique.meta.module;
import io.bootique.meta.MetadataNode;
import io.bootique.meta.config.ConfigListMetadata;
import io.bootique.meta.config.ConfigMapMetadata;
import io.bootique.meta.config.ConfigMetadataNode;
import io.bootique.meta.config.ConfigMetadataVisitor;
import io.bootique.meta.config.ConfigObjectMetadata;
import io.bootique.meta.config.ConfigValueMetadata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
/**
* Metadata descriptor of a DI module.
*
* @since 0.21
*/
public class ModuleMetadata implements MetadataNode {
// unwraps ConfigObjectMetadata decorated with ConfigMetadataNodeProxy
private static final ConfigMetadataVisitor<Optional<ConfigObjectMetadata>> OBJECT_CONFIG_RESOLVER =
new ConfigMetadataVisitor<Optional<ConfigObjectMetadata>>() {
@Override
public Optional<ConfigObjectMetadata> visitObjectMetadata(ConfigObjectMetadata metadata) {
return Optional.of(metadata);
}
@Override
public Optional<ConfigObjectMetadata> visitValueMetadata(ConfigValueMetadata metadata) {
return Optional.empty();
}
@Override
public Optional<ConfigObjectMetadata> visitListMetadata(ConfigListMetadata metadata) {
return Optional.empty();
}
@Override
public Optional<ConfigObjectMetadata> visitMapMetadata(ConfigMapMetadata metadata) {
return Optional.empty();
}
};
private String name;
private String providerName;
private String description;
private Collection<ConfigMetadataNode> configs;
private ModuleMetadata() {
this.configs = new ArrayList<>();
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(String name) {
return builder().name(name);
}
@Override
public String getName() {
return name;
}
public String getProviderName() {
return providerName;
}
@Override
public String getDescription() {
return description;
}
public Collection<ConfigMetadataNode> getConfigs() {
return configs;
}
/**
* Locates configuration node for the specified dot-separated path.
*
* @param configPath a dot-separated path that presumably corresponds to a configuration node.
* @return an optional result of a search for the node matching config path.
* @since 0.22
*/
public Optional<ConfigMetadataNode> findConfig(String configPath) {
String[] split = splitFirstComponent(configPath);
return configs
.stream()
.filter(c -> c.getName().equals(split[0]))
.map(c -> findConfig(c, split[1]))
.findFirst().orElse(Optional.empty());
}
protected Optional<ConfigMetadataNode> findConfig(ConfigMetadataNode root, String configPath) {
Objects.requireNonNull(root);
if (configPath.length() == 0) {
return Optional.of(root);
}
String[] split = splitFirstComponent(configPath);
return root.accept(new ConfigMetadataVisitor<Optional<ConfigMetadataNode>>() {
@Override
public Optional<ConfigMetadataNode> visitObjectMetadata(ConfigObjectMetadata metadata) {
return metadata.getAllSubConfigs()
.map(c -> c.accept(OBJECT_CONFIG_RESOLVER))
.filter(Optional::isPresent)
.map(c -> c.get().getProperties())
.flatMap(Collection::stream)
.filter(c -> c.getName().equals(split[0]))
.map(c -> findConfig(c, split[1]))
.findFirst().orElse(Optional.empty());
}
@Override
public Optional<ConfigMetadataNode> visitMapMetadata(ConfigMapMetadata metadata) {
// map can have arbitrary keys, so any name is valid
return findConfig(metadata.getValuesType(), split[1]);
}
@Override
public Optional<ConfigMetadataNode> visitValueMetadata(ConfigValueMetadata metadata) {
return Optional.empty();
}
@Override
public Optional<ConfigMetadataNode> visitListMetadata(ConfigListMetadata metadata) {
return Optional.empty();
}
});
}
private String[] splitFirstComponent(String configPath) {
int dot = configPath.indexOf('.');
return dot < 0 ? new String[]{configPath, ""} : new String[]{
configPath.substring(0, dot),
configPath.substring(dot + 1)
};
}
public static class Builder {
private ModuleMetadata moduleMetadata;
private Builder() {
this.moduleMetadata = new ModuleMetadata();
}
public ModuleMetadata build() {
return moduleMetadata;
}
public Builder name(String name) {
moduleMetadata.name = name;
return this;
}
public Builder providerName(String name) {
moduleMetadata.providerName = name;
return this;
}
public Builder description(String description) {
moduleMetadata.description = description;
return this;
}
public Builder addConfig(ConfigObjectMetadata config) {
moduleMetadata.configs.add(config);
return this;
}
public Builder addConfigs(Collection<ConfigMetadataNode> configs) {
moduleMetadata.configs.addAll(configs);
return this;
}
}
}
|
package de.hpi.bpmn2execpn.converter;
import java.util.ArrayList;
import java.util.List;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import de.hpi.bpmn.BPMNDiagram;
import de.hpi.bpmn.IntermediateEvent;
import de.hpi.bpmn.SubProcess;
import de.hpi.bpmn.Task;
import de.hpi.bpmn2execpn.model.ExecTask;
import de.hpi.bpmn2pn.converter.Converter;
import de.hpi.bpmn2pn.model.ConversionContext;
import de.hpi.bpmn2pn.model.SubProcessPlaces;
import de.hpi.execpn.ExecPetriNet;
import de.hpi.execpn.impl.ExecPNFactoryImpl;
import de.hpi.petrinet.PetriNet;
import de.hpi.petrinet.Place;
import de.hpi.petrinet.Transition;
public class ExecConverter extends Converter {
private static final boolean abortWhenFinalize = true;
protected String modelURL;
private List<ExecTask> taskMap;
public ExecConverter(BPMNDiagram diagram, String modelURL) {
super(diagram, new ExecPNFactoryImpl(modelURL));
this.modelURL = modelURL;
this.taskMap = new ArrayList<ExecTask>();
}
@Override
protected void handleDiagram(PetriNet net, ConversionContext c) {
((ExecPetriNet) net).setName(diagram.getTitle());
}
@Override
protected void createStartPlaces(PetriNet net, ConversionContext c) {
// do nothing...: we want start transitions instead of start places
}
// TODO this is a dirty hack...
@Override
protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
exTask.startT = addLabeledTransition(net, "start_" + task.getId(), "start_"
+ task.getId());
exTask.running = addPlace(net, "running_" + task.getId());
exTask.endT = addLabeledTransition(net, "end_" + task.getId(), "end_"
+ task.getId());
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)),
exTask.startT);
addFlowRelationship(net, exTask.endT, c.map
.get(getOutgoingSequenceFlow(task)));
addFlowRelationship(net, exTask.startT, exTask.running);
addFlowRelationship(net, exTask.running, exTask.endT);
//construct for suspend/resume
exTask.suspend = addLabeledTransition(net, "suspend_" + task.getId(),
"suspend_" + task.getId());
exTask.resume = addLabeledTransition(net, "resume_" + task.getId(),
"resume_" + task.getId());
exTask.suspended = addPlace(net, "suspended_" + task.getId());
addFlowRelationship(net, exTask.running, exTask.suspend);
addFlowRelationship(net, exTask.suspend, exTask.suspended);
addFlowRelationship(net, exTask.suspended, exTask.resume);
addFlowRelationship(net, exTask.resume, exTask.running);
taskMap.add(exTask);
handleMessageFlow(net, task, exTask.startT, exTask.endT, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.endT, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
@Override
protected void handleSubProcess(PetriNet net, SubProcess process,
ConversionContext c) {
super.handleSubProcess(net, process, c);
if (process.isAdhoc()) {
handleSubProcessAdHoc(net, process, c);
}
}
// TODO: Data dependencies
protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_"
+ process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_"
+ process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_"
+ process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_"
+ process.getId(), "ad-hoc_ccCheck");
Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_"
+ process.getId(), "ad-hoc_finalize");
Transition resume = addLabeledTransition(net, "ad-hoc_resume_"
+ process.getId(), "ad-hoc_resume");
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskMap) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, enableStarting, exTask.startT);
addFlowRelationship(net, enableFinishing, exTask.endT);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net,
"ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_"
+ exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_"
+ exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_"
+ exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
throw new NotImplementedException();
}else {
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskMap) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, synch, exTask.startT);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net,
"ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_"
+ exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_"
+ exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_"
+ exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
}
|
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Couleur extends JPanel implements ChangeListener{
private JLabel imageLabel;
private ImageIcon image;
private JSlider couleurSLider;
private JSlider grisSlider;
private Color couleur;
private Color gris;
private JLabel couleurLabel;
private JLabel grisLabel;
private double grisValeur;
private int couleurValeur;
public Couleur () {
image = new ImageIcon(Couleur.class.getResource("SpectrumBar.jpg"));
imageLabel = new JLabel(image);
imageLabel.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
Border border = new LineBorder(Color.BLACK, 3);
couleurSLider = new JSlider(0, 16777215, 50);
grisSlider = new JSlider(0, 100, 50);
couleurSLider.setPreferredSize(new Dimension(150 ,20));
grisSlider.setPreferredSize(new Dimension(150 ,20));
gris = new Color(128, 128, 128);
couleur = new Color(255, 255, 255);
couleurLabel = new JLabel();
couleurLabel.setBackground(couleur);
couleurLabel.setOpaque(true);
couleurLabel.setPreferredSize(new Dimension(64, 64));
couleurLabel.setBorder(border);
grisLabel = new JLabel();
grisLabel.setBackground(gris);
grisLabel.setOpaque(true);
grisLabel.setPreferredSize(new Dimension(64, 64));
grisLabel.setBorder(border);
couleurValeur = couleurSLider.getValue();
grisValeur = grisSlider.getValue();
couleurSLider.addChangeListener(this);
grisSlider.addChangeListener(this);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(imageLabel);
add(couleurLabel);
add(grisLabel);
add(grisSlider);
add(couleurSLider);
setSize(new Dimension(800, 70));
}
@Override
public void stateChanged(ChangeEvent e) {
if (e.getSource().equals(couleurSLider)) {
couleurValeur = couleurSLider.getValue();
couleurLabel.setBackground(Color.decode("0x" + Integer.toHexString(couleurValeur)));
} else {
grisValeur = grisSlider.getValue();
grisValeur = grisValeur / 100;
// a recopier la formule a partir de la vraie couleur et non diretement de nuances de gris
gris = new Color((int) (grisValeur * 255), (int) (grisValeur * 255), (int) (grisValeur * 255));
grisLabel.setBackground(gris);
}
repaint();
}
}
|
package org.opencms.ade.galleries.client.preview.ui;
import org.opencms.ade.galleries.client.preview.CmsImagePreviewHandler;
import org.opencms.ade.galleries.client.preview.I_CmsPreviewHandler;
import org.opencms.ade.galleries.client.ui.Messages;
import org.opencms.ade.galleries.client.ui.css.I_CmsLayoutBundle;
import org.opencms.ade.galleries.shared.CmsImageInfoBean;
import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.GalleryMode;
import org.opencms.gwt.client.CmsCoreProvider;
import java.util.Map;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
/**
* Provides a widget for the image preview dialog .<p>
*
* @author Polina Smagina
*
* @version $Revision: 1.6 $
*
* @since 8.0.
*/
public class CmsImagePreviewDialog extends A_CmsPreviewDialog<CmsImageInfoBean> {
/** The default min height of the image. */
public static final int IMAGE_HEIGHT_MAX = 361;
/** The default min width of the image. */
public static final int IMAGE_WIDTH_MAX = 640;
/** The preview handler. */
private CmsImagePreviewHandler m_handler;
/** The format tab. */
private CmsImageFormatsTab m_imageFormatTab;
/** The infos tab. */
private CmsImageInfoTab m_imageInfosTab;
private CmsImageAdvancedTab m_imageAdvancedTab;
/** The formats tab. */
private CmsImageEditorTab m_imageEditorFormatsTab;
/** The initial fill flag. */
private boolean m_initialFill = true;
private Image m_previewImage;
/** The properties tab. */
private CmsPropertiesTab m_propertiesTab;
/**
* The constructor.<p>
*
* @param dialogMode the dialog mode
* @param dialogHeight the dialog height to set
* @param dialogWidth the dialog width to set
*/
public CmsImagePreviewDialog(GalleryMode dialogMode, int dialogHeight, int dialogWidth) {
super(dialogMode, dialogHeight, dialogWidth);
}
/**
* Fills the content of the tabs panel.<p>
*
* @param infoBean the bean containing the parameter
*/
@Override
public void fillContent(CmsImageInfoBean infoBean) {
// properties tab
m_propertiesTab.fillProperties(infoBean.getProperties());
m_imageInfosTab.fillContent(infoBean);
if (m_initialFill) {
if (getGalleryMode() == GalleryMode.widget) {
m_imageFormatTab.fillContent(infoBean);
}
if (getGalleryMode() == GalleryMode.editor) {
m_imageFormatTab.fillContent(infoBean);
m_imageEditorFormatsTab.fillContent(infoBean);
m_imageAdvancedTab.fillContent(infoBean);
}
m_initialFill = false;
}
fillPreviewPanel(infoBean);
}
/**
* Fills the preview panel.<p>
*
* @param infoBean the image info
*/
public void fillPreviewPanel(CmsImageInfoBean infoBean) {
FlowPanel panel = new FlowPanel();
panel.addStyleName(I_CmsLayoutBundle.INSTANCE.previewDialogCss().imagePanel());
m_previewImage = new Image();
StringBuffer urlScaled = new StringBuffer(128);
urlScaled.append(CmsCoreProvider.get().link(infoBean.getResourcePath())).append("?").append(
m_handler.getPreviewScaleParam());
m_previewImage.setUrl(urlScaled.toString());
panel.add(m_previewImage);
m_previewPanel.setWidget(panel);
}
/**
* @see org.opencms.ade.galleries.client.preview.ui.A_CmsPreviewDialog#hasChanges()
*/
@Override
public boolean hasChanges() {
return false;
}
/**
* Initializes the preview.<p>
*
* @param handler the preview handler
*/
public void init(CmsImagePreviewHandler handler) {
m_handler = handler;
m_propertiesTab = new CmsPropertiesTab(m_galleryMode, m_dialogHeight, m_dialogWidth, m_handler);
m_tabbedPanel.add(m_propertiesTab, m_propertiesTab.getTabName());
m_imageFormatTab = new CmsImageFormatsTab(m_galleryMode, m_dialogHeight, m_dialogWidth, handler, null);
m_tabbedPanel.add(m_imageFormatTab, Messages.get().key(Messages.GUI_PREVIEW_TAB_IMAGEFORMAT_0));
m_imageInfosTab = new CmsImageInfoTab(m_galleryMode, m_dialogHeight, m_dialogWidth, handler);
m_tabbedPanel.add(m_imageInfosTab, Messages.get().key(Messages.GUI_PREVIEW_TAB_IMAGEINFOS_0));
if (getGalleryMode() == GalleryMode.editor) {
m_imageEditorFormatsTab = new CmsImageEditorTab(m_galleryMode, m_dialogHeight, m_dialogWidth, handler);
m_tabbedPanel.add(m_imageEditorFormatsTab, "Editor Formats");
m_imageAdvancedTab = new CmsImageAdvancedTab(m_galleryMode, m_dialogHeight, m_dialogWidth, handler);
m_tabbedPanel.add(m_imageAdvancedTab, "Advanced");
}
}
/**
* Resets the image displayed in the preview.<p>
*
* @param path the image path including scale parameter
*/
public void resetPreviewImage(String path) {
m_previewImage.setUrl(path);
}
/**
* @see org.opencms.ade.galleries.client.preview.ui.A_CmsPreviewDialog#getHandler()
*/
@Override
protected I_CmsPreviewHandler<CmsImageInfoBean> getHandler() {
return m_handler;
}
/**
* Adds necessary attributes to the map.<p>
*
* @param attributes the attribute map
* @return the attribute map
*/
public Map<String, String> getImageAttributes(Map<String, String> attributes) {
if (getGalleryMode() == GalleryMode.editor) {
m_imageEditorFormatsTab.getImageAttributes(attributes);
m_imageAdvancedTab.getImageAttributes(attributes);
}
return attributes;
}
}
|
/*
* Chat server
*/
package freeleserver;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
/**
*
* @author Vetle, Mirza, Kjetil
*/
public class FreeleServer {
/**
* @param args the command line arguments
*/
ArrayList userOutputStream;
HashMap<String, InetAddress> onlineUsers = new HashMap();
//ArrayList<String> onlineUsers = new ArrayList();
/*
This class is gonna handle our clients, with socket and with connections from diffrent users.
*/
public class UserServer implements Runnable {
BufferedReader bufferedReader;
Socket socket;
PrintWriter client;
InetAddress clientAddress;
/*
Connection socket
*/
public UserServer(Socket clientSocket, PrintWriter user) {
client = user;
try {
socket = clientSocket;
clientAddress = socket.getInetAddress();
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(isReader);
}
catch (Exception ex) {
System.out.println("Error beginning StreamReader. \n");
}
}
/*
Message runner, here the program will handel the message resived.
*/
public void run() {
String message;
String connect = "Connect";
String chat = "Chat";
String disconnect = "Disconnect";
String[] data;
try {
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Message: " + message);
data = message.split("β");
for (String i : data) {
System.out.println(i + "\n");
}
if (data[2].equals(connect)) {
messageAll((data[0] + "β" + data[1] + "β" + chat));
addUser(data[0], clientAddress);
} else if (data[2].equals(disconnect)) {
messageAll((data[0] + "βhas disconnected." + "β" + chat));
removeUser(data[0]);
} else if (data[2].equals(chat)) {
messageAll(message);
} else {
System.out.println("something gone wrong");
}
}
} catch (Exception e) {
System.out.println("connection lost");
userOutputStream.remove(client);
}
}
}
/*
Main function to start the program
*/
public static void main(String[] args) {
new FreeleServer().start();
}
/*
This method establish connection to the clients and creats a new thread to the client.
*/
public void start() {
userOutputStream = new ArrayList ();
try {
ServerSocket serverSocket = new ServerSocket(4000);
while (true) {
Socket clientSock = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
userOutputStream.add(writer);
Thread listener = new Thread(new UserServer(clientSock, writer));
listener.start();
System.out.println("connection complete");
}
}
catch (Exception e) {
System.out.println("connection failed");
}
}
/**
*This method add users into the system and sends a signal to print out users on the client side
* @param data
*/
public void addUser(String data, InetAddress ip) {
String message;
String add = "β βConnect";
String done = "Serverβ βDone";
onlineUsers.put(data, ip);
//String[] l = new String[(onlineUsers.size())];
//onlineUsers.toArray(l);
for(Entry<String, InetAddress> s : onlineUsers.entrySet()) {
String k = s.getKey();
message = (k + add);
messageAll(message);
}
messageAll(done);
}
/**
* This method removes users into the system and sends a signal to print out users on the client side
* @param data
*/
public void removeUser(String data) {
String message;
String add = "β βConnect";
String done = "Serverβ βDone";
onlineUsers.remove(data);
//String[] l = new String[(onlineUsers.size())];
//onlineUsers.toArray(l);
for(Entry<String, InetAddress> s : onlineUsers.entrySet()) {
String k = s.getKey();
message = (k + add);
messageAll(message);
}
messageAll(done);
}
/**
* This method is used to send messages to all clients connected to the server
* @param m
*/
public void messageAll(String m) {
Iterator i = userOutputStream.iterator();
while(i.hasNext()){
try{
PrintWriter w = (PrintWriter) i.next();
w.println(m);
System.out.println("Send " + m);
w.flush();
}catch(Exception e){
System.out.println("message all failed");
}
}
}
}
|
package nl.b3p.viewer.util;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.app.ConfiguredAttribute;
import nl.b3p.viewer.config.services.AttributeDescriptor;
import nl.b3p.viewer.config.services.FeatureTypeRelation;
import nl.b3p.viewer.config.services.FeatureTypeRelationKey;
import nl.b3p.viewer.config.services.SimpleFeatureType;
import static nl.b3p.viewer.stripes.FeatureInfoActionBean.FID;
import nl.b3p.viewer.stripes.FileUploadActionBean;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.filter.visitor.SimplifyingFilterVisitor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author Roy Braam
*/
public class FeatureToJson {
public static final int MAX_FEATURES = 1000;
private boolean arrays = false;
private boolean edit = false;
private boolean graph = false;
private boolean aliases = true;
/**
* Set to {@code true} to return an JSONArray with attributes per feature instead of JSONObject to maintain order of attributes
*/
private boolean ordered = false;
/**
* set to {@code true} to return empty string for null value.
*/
private boolean returnNullval = false;
private List<Long> attributesToInclude = new ArrayList();
private static final int TIMEOUT = 5000;
private FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
public FeatureToJson(boolean arrays,boolean edit){
this.arrays=arrays;
this.edit=edit;
}
public FeatureToJson(boolean arrays, boolean edit, boolean graph, List<Long> attributesToInclude) {
this.arrays=arrays;
this.edit=edit;
this.graph = graph;
this.attributesToInclude=attributesToInclude;
}
public FeatureToJson(boolean arrays, boolean edit, boolean graph, boolean aliases, List<Long> attributesToInclude) {
this.arrays = arrays;
this.edit = edit;
this.graph = graph;
this.attributesToInclude = attributesToInclude;
this.aliases = aliases;
}
public FeatureToJson(boolean arrays, boolean edit, boolean graph, boolean aliases, boolean returnNullval, List<Long> attributesToInclude) {
this.arrays = arrays;
this.edit = edit;
this.graph = graph;
this.attributesToInclude = attributesToInclude;
this.aliases = aliases;
this.returnNullval = returnNullval;
}
/**
*
* @param arrays {@code true} when???
* @param edit {@code true} to return editable data
* @param graph {@code true} when??
* @param aliases {@code true} to return aliases in the response
* @param returnNullval {@code true} to return empty string for null value
* @param attributesToInclude List of attributes to return in the response
* @param ordered {@code true} to return an JSONArray with attributes per
* feature instead of JSONObject to maintain order of attributes
*/
public FeatureToJson(boolean arrays, boolean edit, boolean graph, boolean aliases, boolean returnNullval, List<Long> attributesToInclude, boolean ordered) {
this.arrays = arrays;
this.edit = edit;
this.graph = graph;
this.attributesToInclude = attributesToInclude;
this.aliases = aliases;
this.returnNullval = returnNullval;
this.ordered = ordered;
}
/**
* Get the features, unsorted, as JSONArray with the given params.
*
* @param al The application layer(if there is a application layer)
* @param ft The featuretype that must be used to get the features
* @param fs The featureSource
* @param q The query
* @param em The entitymanager of the session, for retrieving uploads
* @param application The application from which this request originates
* @param request The current request to look if the user has rights to view the uploads
* @return JSONArray with features.
* @throws IOException if any
* @throws JSONException if transforming to json fails
* @throws Exception if any
*
* @see #getJSONFeatures(nl.b3p.viewer.config.app.ApplicationLayer,
* nl.b3p.viewer.config.services.SimpleFeatureType,
* org.geotools.data.FeatureSource, org.geotools.data.Query,
* java.lang.String, java.lang.String, javax.persistence.EntityManager, Application, HttpServletRequest)
*/
public JSONArray getJSONFeatures(ApplicationLayer al, SimpleFeatureType ft, FeatureSource fs, Query q, EntityManager em, Application application, HttpServletRequest request) throws IOException, JSONException, Exception {
return this.getJSONFeatures(al, ft, fs, q, null, null, em, application,request);
}
/**
* Get the features, optionally sorted, as JSONArray with the given params.
* <strong>Note</strong> that the FeatureSource fs will be closed and
* disposed.
*
* @param al The application layer(if there is a application layer)
* @param ft The featuretype that must be used to get the features
* @param fs The featureSource
* @param q The query
* @param sort The attribute name that is used to sort
* @param dir Sort direction (DESC or ASC)
* @return JSONArray with features.
* @throws IOException if any
* @throws JSONException if transforming to json fails
* @throws Exception if any
*/
public JSONArray getJSONFeatures(ApplicationLayer al, SimpleFeatureType ft, FeatureSource fs, Query q, String sort, String dir, EntityManager em, Application application, HttpServletRequest request) throws IOException, JSONException, Exception{
Map<String,String> attributeAliases = new HashMap<String,String>();
if(!edit) {
for(AttributeDescriptor ad: ft.getAttributes()) {
if(ad.getAlias() != null) {
attributeAliases.put(ad.getName(), ad.getAlias());
}
}
}
List<String> propertyNames;
if(al != null) {
propertyNames = this.setPropertyNames(al, q, ft,edit);
} else {
propertyNames = new ArrayList<String>();
for(AttributeDescriptor ad: ft.getAttributes()) {
propertyNames.add(ad.getName());
}
}
if (sort!=null){
setSortBy(q, propertyNames, sort, dir);
}
/* Use the first property as sort field, otherwise geotools while give a error when quering
* a JDBC featureType without a primary key.
*/
else if ( (fs instanceof org.geotools.jdbc.JDBCFeatureSource || fs.getDataStore() instanceof WFSDataStore ) && !propertyNames.isEmpty()){
int index = 0;
if (fs.getSchema().getGeometryDescriptor() != null && fs.getSchema().getGeometryDescriptor().getLocalName().equals(propertyNames.get(0))) {
if(propertyNames.size() > 1){
index = 1;
}else {
index = -1;
}
}
if(index != -1){
setSortBy(q, propertyNames.get(index),dir);
}
}
Integer start = q.getStartIndex();
if (start==null){
start=0;
}
boolean offsetSupported = fs.getQueryCapabilities().isOffsetSupported();
//if offSet is not supported, get more features (start + the wanted features)
if (!offsetSupported && q.getMaxFeatures() < MAX_FEATURES || fs.getDataStore() instanceof WFSDataStore){
q.setMaxFeatures(q.getMaxFeatures()+start);
}
FeatureIterator<SimpleFeature> it = null;
JSONArray features = new JSONArray();
try{
it=fs.getFeatures(q).features();
int featureIndex=0;
while(it.hasNext()){
SimpleFeature feature = it.next();
/* if offset not supported and there are more features returned then
* only get the features after index >= start*/
if (offsetSupported || featureIndex >= start){
JSONObject uploads = null;
if (al != null
&& al.getDetails().containsKey("summary.retrieveUploads")
&& Boolean.parseBoolean(al.getDetails().get("summary.retrieveUploads").getValue())
&& application != null && request != null) {
// 'al' can be null when this method is called from DirectSearch
uploads = FileUploadActionBean.retrieveUploads(feature.getID(), al,em, application, request);
}
JSONObject jsonFeature = new JSONObject();
jsonFeature.put("__UPLOADS__", uploads);
if(this.ordered) {
JSONArray j = this.toJSONFeatureOrdered(jsonFeature,feature,ft,al,propertyNames,attributeAliases,0);
features.put(j);
} else {
JSONObject j = this.toJSONFeature(jsonFeature,feature,ft,al,propertyNames,attributeAliases,0);
features.put(j);
}
}
featureIndex++;
}
}finally{
if (it!=null){
it.close();
}
fs.getDataStore().dispose();
}
return features;
}
private JSONObject toJSONFeature(JSONObject j,SimpleFeature f, SimpleFeatureType ft, ApplicationLayer al, List<String> propertyNames,Map<String,String> attributeAliases, int index) throws JSONException, Exception{
if(arrays) {
for(String name: propertyNames) {
Object value = f.getAttribute(name);
j.put("c" + index++, formatValue(value));
}
} else {
for (String name : propertyNames) {
this.addKeyValue(j, f, name, attributeAliases);
}
}
//if edit and not yet set
// removed check for edit variable here because we need to compare features in edit component and feature info attributes
// was if(edit && j.optString(FID,null)==null) {
if(j.optString(FID,null)==null) {
String id = f.getID();
j.put(FID, id);
}
if (ft.hasRelations()){
j = populateWithRelatedFeatures(j,f,ft,al,index, null);
}
return j;
}
private JSONArray toJSONFeatureOrdered(JSONObject j,SimpleFeature f, SimpleFeatureType ft, ApplicationLayer al, List<String> propertyNames,Map<String,String> attributeAliases, int index) throws JSONException, Exception{
JSONArray ordered = new JSONArray();
ordered.put(j);
for (String name : propertyNames) {
ordered.put(this.addKeyValue(new JSONObject(), f, name, attributeAliases));
}
if(!FeaturePropertiesArrayHelper.containsKey(ordered, FID)) {
JSONObject fidObject = new JSONObject();
String id = f.getID();
fidObject.put(FID, id);
ordered.put(fidObject);
}
if (ft.hasRelations()){
populateWithRelatedFeatures(j,f,ft,al,index, ordered);
}
return ordered;
}
private JSONObject addKeyValue(JSONObject j, SimpleFeature f, String name, Map<String,String> attributeAliases) {
String alias = name;
if (aliases && attributeAliases != null && attributeAliases.get(name)!=null) {
alias = attributeAliases.get(name);
}
j.put(alias, formatValue(f.getAttribute(name)));
return j;
}
/**
* Populate the json object with related featues
*/
private JSONObject populateWithRelatedFeatures(JSONObject j,SimpleFeature feature,SimpleFeatureType ft,ApplicationLayer al, int index, JSONArray ordered) throws Exception{
if (ft.hasRelations()){
JSONArray related_featuretypes = new JSONArray();
for (FeatureTypeRelation rel :ft.getRelations()){
boolean isJoin=rel.getType().equals(FeatureTypeRelation.JOIN);
if (isJoin){
FeatureSource foreignFs = rel.getForeignFeatureType().openGeoToolsFeatureSource(TIMEOUT);
FeatureIterator<SimpleFeature> foreignIt=null;
try{
Query foreignQ = new Query(foreignFs.getName().toString());
//create filter
Filter filter = createFilter(feature,rel);
if (filter==null){
continue;
}
//if join only get 1 feature
foreignQ.setMaxFeatures(1);
foreignQ.setFilter(filter);
//set propertynames
List<String> propertyNames;
if (al!=null){
propertyNames=setPropertyNames(al, foreignQ, rel.getForeignFeatureType(), edit);
}else{
propertyNames = new ArrayList<String>();
for(AttributeDescriptor ad: rel.getForeignFeatureType().getAttributes()) {
propertyNames.add(ad.getName());
}
}
if (propertyNames.isEmpty()) {
// if there are no properties to retrieve just get out
continue;
}
//get aliases
Map<String,String> attributeAliases = new HashMap<String,String>();
if(!edit) {
for(AttributeDescriptor ad: rel.getForeignFeatureType().getAttributes()) {
if(ad.getAlias() != null) {
attributeAliases.put(ad.getName(), ad.getAlias());
}
}
}
//Get Feature and populate JSON object with the values.
foreignIt=foreignFs.getFeatures(foreignQ).features();
while (foreignIt.hasNext()){
SimpleFeature foreignFeature = foreignIt.next();
//join it in the same json
if(ordered == null) {
j = toJSONFeature(j, foreignFeature, rel.getForeignFeatureType(), al, propertyNames, attributeAliases, index);
} else {
this.concatArray(ordered, toJSONFeatureOrdered(j, foreignFeature, rel.getForeignFeatureType(), al, propertyNames, attributeAliases, index));
}
}
}finally{
if (foreignIt!=null){
foreignIt.close();
}
foreignFs.getDataStore().dispose();
}
}else{
Filter filter = createFilter(feature,rel);
if (filter==null){
continue;
}
JSONObject related_ft = new JSONObject();
related_ft.put("filter", CQL.toCQL(filter));
related_ft.put("id",rel.getForeignFeatureType().getId());
related_ft.put("foreignFeatureTypeName",rel.getForeignFeatureType().getTypeName());
related_featuretypes.put(related_ft);
}
}
if (related_featuretypes.length()>0){
if(ordered == null) {
j.put("related_featuretypes",related_featuretypes);
} else {
JSONObject relatedFeatures = new JSONObject();
relatedFeatures.put("related_featuretypes", related_featuretypes);
ordered.put(relatedFeatures);
}
}
}
return j;
}
private void concatArray(JSONArray arr1, JSONArray arr2) throws JSONException {
for (int i = 0; i < arr2.length(); i++) {
arr1.put(arr2.get(i));
}
}
HashMap<Long,List<String>> propertyNamesQueryCache = new HashMap<Long,List<String>>();
HashMap<Long,Boolean> haveInvisiblePropertiesCache = new HashMap<Long,Boolean>();
HashMap<Long,List<String>> propertyNamesReturnCache = new HashMap<Long,List<String>>();
/**
* Get the propertynames and add the needed propertynames to the query.
*/
private List<String> setPropertyNames(ApplicationLayer appLayer, Query q, SimpleFeatureType sft,boolean edit) {
List<String> propertyNames = new ArrayList<String>();
boolean haveInvisibleProperties = false;
if (propertyNamesQueryCache.containsKey(sft.getId())){
haveInvisibleProperties= haveInvisiblePropertiesCache.get(sft.getId());
if(haveInvisibleProperties){
q.setPropertyNames(propertyNamesQueryCache.get(sft.getId()));
}
return propertyNamesReturnCache.get(sft.getId());
}else{
for(ConfiguredAttribute ca: appLayer.getAttributes(sft)) {
if((!edit && !graph && ca.isVisible()) || (edit && ca.isEditable()) || (graph && attributesToInclude.contains(ca.getId()))) {
propertyNames.add(ca.getAttributeName());
} else {
haveInvisibleProperties = true;
}
}
haveInvisiblePropertiesCache.put(sft.getId(),haveInvisibleProperties);
propertyNamesReturnCache.put(sft.getId(),propertyNames);
propertyNamesQueryCache.put(sft.getId(),propertyNames);
if(haveInvisibleProperties) {
// By default Query retrieves Query.ALL_NAMES
// Query.NO_NAMES is an empty String array
q.setPropertyNames(propertyNames);
// If any related featuretypes are set, add the leftside names in the query
// don't add them to propertynames, maybe they are not visible
if (sft.getRelations()!=null){
List<String> withRelations= new ArrayList<String>();
withRelations.addAll(propertyNames);
for (FeatureTypeRelation ftr : sft.getRelations()){
if (ftr.getRelationKeys()!=null){
for (FeatureTypeRelationKey key : ftr.getRelationKeys()){
if (!withRelations.contains(key.getLeftSide().getName())){
withRelations.add(key.getLeftSide().getName());
}
}
}
}
propertyNamesQueryCache.put(sft.getId(), withRelations);
q.setPropertyNames(withRelations);
}
}
propertyNamesReturnCache.put(sft.getId(),propertyNames);
return propertyNames;
}
}
/**
* Set sort in query based on the index of the propertynames list.
* @param q the query on which the sort is added
* @param propertyNames a list of propertynames for this featuretype
* @param sort a Stringified integer. The index of the propertyname
* @param dir sorting direction DESC or ASC
*/
private void setSortBy(Query q, List<String> propertyNames, String sort, String dir) {
if(sort != null) {
String sortAttribute = null;
if(arrays) {
int i = Integer.parseInt(sort.substring(1));
int j = 0;
for(String name: propertyNames) {
if(j == i) {
sortAttribute = name;
break;
}
j++;
}
} else {
sortAttribute = sort;
}
this.setSortBy(q,sortAttribute,dir);
}
}
/**
* Set sort on query
* @param q the query on which the sort is added
* @param sort the name of the sort column
* @param dir sorting direction DESC or ASC
*/
private void setSortBy(Query q,String sort, String dir){
if(sort != null) {
q.setSortBy(new SortBy[] {
ff2.sort(sort, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING)
});
}
}
private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private Object formatValue(Object value) {
if (this.returnNullval && value == null) {
return "";
}
if(value instanceof Date) {
// JSON has no date type so format the date as it is used for
// display, not calculation
return dateFormat.format((Date)value);
} else {
return value;
}
}
private Filter createFilter(SimpleFeature feature,FeatureTypeRelation rel) {
List<Filter> filters = new ArrayList<Filter>();
for (FeatureTypeRelationKey key : rel.getRelationKeys()){
AttributeDescriptor rightSide = key.getRightSide();
AttributeDescriptor leftSide = key.getLeftSide();
Object value= feature.getAttribute(leftSide.getName());
if (value==null){
continue;
}
if (AttributeDescriptor.GEOMETRY_TYPES.contains(rightSide.getType()) &&
AttributeDescriptor.GEOMETRY_TYPES.contains(leftSide.getType())){
filters.add(ff2.not(ff2.isNull(ff2.property(rightSide.getName()))));
filters.add(ff2.intersects(ff2.property(rightSide.getName()),ff2.literal(value)));
}else{
filters.add(ff2.equals(ff2.property(rightSide.getName()),ff2.literal(value)));
}
}
if (filters.size()>1){
return ff2.and(filters);
}else if (filters.size()==1){
return filters.get(0);
}else{
return null;
}
}
/**
*
* Optimze and reformat filter. Delegates to
* {@link #reformatFilter(org.opengis.filter.Filter, nl.b3p.viewer.config.services.SimpleFeatureType, boolean)}
* with the {@code includeRelations} set to {@code true}.
*
* @param filter the filter to process
* @param ft featuretype to apply filter
* @return reformatted / optimised filter
* @throws Exception if any
* @see #reformatFilter(org.opengis.filter.Filter,
* nl.b3p.viewer.config.services.SimpleFeatureType, boolean)
*/
public static Filter reformatFilter(Filter filter, SimpleFeatureType ft) throws Exception {
return reformatFilter(filter, ft, true);
}
/**
* Optimze and reformat filter.
*
* @param filter the filter to process
* @param ft featuretype to apply filter
* @param includeRelations whether to include related (joined) data
* @return reformatted / optimised filter
* @throws Exception if any
*/
public static Filter reformatFilter(Filter filter, SimpleFeatureType ft, boolean includeRelations) throws Exception {
if (Filter.INCLUDE.equals(filter) || Filter.EXCLUDE.equals(filter)) {
return filter;
}
if (includeRelations) {
for (FeatureTypeRelation rel : ft.getRelations()) {
if (FeatureTypeRelation.JOIN.equals(rel.getType())) {
filter = reformatFilter(filter, rel.getForeignFeatureType(), includeRelations);
filter = (Filter) filter.accept(new ValidFilterExtractor(rel), filter);
}
}
}
filter = (Filter) filter.accept(new SimplifyingFilterVisitor(), null);
return filter;
}
}
|
package com.oldterns.vilebot.handlers.user;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import net.engio.mbassy.listener.Handler;
import org.jsoup.Jsoup;
import twitter4j.JSONArray;
import twitter4j.JSONObject;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@HandlerContainer
public class Trivia {
private static final Pattern questionPattern = Pattern.compile( "^!jeopardy" );
private static final Pattern answerPattern = Pattern.compile( "^!(whatis|whois) (.*)" );
private static TriviaGame currentGame = null;
private static final String JEOPARDY_CHANNEL = "jeopardyChannel";
private static final int TIMEOUT = 30000;
private static ExecutorService timer = Executors.newScheduledThreadPool(1);
@Handler
public void doTrivia(ReceivePrivmsg event) {
String text = event.getText();
Matcher questionMatcher = questionPattern.matcher(text);
Matcher answerMatcher = answerPattern.matcher(text);
try {
if (questionMatcher.matches() && shouldStartGame(event.getChannel())) {
startGame(event);
} else if (answerMatcher.matches() && shouldStartGame(event.getChannel())) {
String answer = answerMatcher.group(2);
finishGame(event, answer);
}
} catch(Exception e) {
event.reply("I don't feel like playing.");
e.printStackTrace();
}
}
private boolean shouldStartGame(String channel) {
String limitingChannel = Vilebot.getConfig().get(JEOPARDY_CHANNEL);
return limitingChannel == null || limitingChannel.equals(channel);
}
private synchronized void startGame(ReceivePrivmsg event) throws Exception {
if (currentGame != null) {
event.reply(currentGame.getAlreadyPlayingString());
}
else {
currentGame = new TriviaGame();
event.reply(currentGame.getIntroString());
startTimer(event);
}
}
private void startTimer(final ReceivePrivmsg event) {
timer.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(TIMEOUT);
timeoutTimer(event);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void timeoutTimer(ReceivePrivmsg event) {
String message = currentGame.getTimeoutString();
event.reply(message);
currentGame = null;
}
private void stopTimer() {
timer.shutdownNow();
timer = Executors.newFixedThreadPool(1);
}
private synchronized void finishGame(ReceivePrivmsg event, String answer) {
if (currentGame != null) {
String answerer = event.getSender();
if (currentGame.isCorrect(answer)) {
stopTimer();
event.reply(String.format("Congrats %s, you win %d karma!", event.getSender(), currentGame.getStakes()));
KarmaDB.modNounKarma(answerer, currentGame.getStakes());
currentGame = null;
}
else {
event.reply(String.format("Sorry %s! That is incorrect, you lose %d karma.",
event.getSender(), currentGame.getStakes()));
KarmaDB.modNounKarma(answerer, -1 * currentGame.getStakes());
}
}
else {
event.reply("No active game. Start a new one with !jeopardy");
}
}
private static class TriviaGame {
private int stakes;
private String question;
private String answer;
private String category;
private static final String API_URL = "http://jservice.io/api/random";
public TriviaGame() throws Exception {
String jsonContent = getQuestionJson();
JSONObject triviaJSON = new JSONArray(jsonContent).getJSONObject(0);
question = triviaJSON.getString("question");
category= triviaJSON.getJSONObject("category").getString("title");
answer = Jsoup.parse(triviaJSON.getString("answer")).text();
stakes = getRandomKarma();
}
private int getRandomKarma() {
return new Random().nextInt(10) + 1;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public int getStakes() {
return stakes;
}
private boolean isCorrect(String answer) {
String formattedUserAnswer = formatAnswer(answer);
String formattedActualAnswer = formatAnswer(this.answer);
return formattedActualAnswer.equals(formattedUserAnswer);
}
private String formatAnswer(String answer) {
return answer.toLowerCase()
.replaceAll("[^A-Za-z\\s\\d]", "")
.replaceAll("^the ", "")
.replaceAll("^a ", "")
.replaceAll("^an ", "");
}
private String getQuestionBlurb() {
return String.format(
"Your category is: %s\nFor %d karma:\n%s",
category, stakes, question);
}
public String getIntroString() {
return "Welcome to VileBot trivia!\n" + getQuestionBlurb() + "\nYou have 30 seconds!";
}
public String getAlreadyPlayingString() {
return "A game is already in session!\n" + getQuestionBlurb();
}
public String getTimeoutString() {
return String.format("Your 30 seconds is up! The answer we were looking for was:\n%s", answer);
}
private String getQuestionJson() throws Exception {
String content;
URLConnection connection;
connection = new URL(API_URL).openConnection();
connection.addRequestProperty(
"User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
);
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
return content;
}
}
}
|
package org.jgrapes.http;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.WeakHashMap;
import org.jdrupes.httpcodec.HttpRequest;
import org.jdrupes.httpcodec.HttpRequestDecoder;
import org.jdrupes.httpcodec.HttpResponse;
import org.jdrupes.httpcodec.HttpResponseEncoder;
import org.jdrupes.httpcodec.ProtocolException;
import org.jdrupes.httpcodec.HttpCodec.HttpStatus;
import org.jgrapes.core.AbstractComponent;
import org.jgrapes.core.Channel;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.http.events.ConnectRequest;
import org.jgrapes.http.events.DeleteRequest;
import org.jgrapes.http.events.GetRequest;
import org.jgrapes.http.events.HeadRequest;
import org.jgrapes.http.events.OptionsRequest;
import org.jgrapes.http.events.PostRequest;
import org.jgrapes.http.events.PutRequest;
import org.jgrapes.http.events.Request;
import org.jgrapes.http.events.Response;
import org.jgrapes.http.events.TraceRequest;
import org.jgrapes.http.events.Request.HandlingResult;
import org.jgrapes.io.Connection;
import org.jgrapes.io.DataConnection;
import org.jgrapes.io.events.Read;
import org.jgrapes.io.events.Write;
import org.jgrapes.net.Server;
import org.jgrapes.net.events.Accepted;
/**
* @author Michael N. Lipp
*
*/
public class HttpServer extends AbstractComponent {
private Channel networkChannel;
private Map<Connection, HttpRequestDecoder> decoders = new WeakHashMap<>();
private Map<Connection, HttpResponseEncoder> encoders = new WeakHashMap<>();
/**
* Create a new server that uses the {@code serverChannel} for
* network level I/O.
*
* @param componentChannel this component's channel
* @param networkChannel the channel for network level I/O
*/
public HttpServer(Channel componentChannel, Channel networkChannel) {
super(componentChannel);
this.networkChannel = networkChannel;
addHandler(Accepted.class, networkChannel.getMatchKey(), "onAccepted");
addHandler(Read.class, networkChannel.getMatchKey(), "onRead");
}
/**
* Create a new server that creates its own {@link Server} with
* the given address and uses it for network level I/O.
*
* @param componentChannel
*/
public HttpServer(Channel componentChannel, SocketAddress serverAddress) {
super(componentChannel);
Server server = new Server(Channel.SELF, serverAddress);
networkChannel = server;
attach(server);
addHandler(Accepted.class, networkChannel.getMatchKey(), "onAccepted");
addHandler(Read.class, networkChannel.getMatchKey(), "onRead");
}
// @Handler
public void onAccepted(Accepted<ByteBuffer> event) {
decoders.put(event.getConnection(), new HttpRequestDecoder());
encoders.put(event.getConnection(), new HttpResponseEncoder());
}
// @Handler
public void onRead(Read<ByteBuffer> event) {
try {
HttpRequestDecoder httpDecoder
= decoders.get(event.getConnection());
if (httpDecoder == null) {
System.out.println("");
}
httpDecoder.decode(event.getBuffer());
HttpRequest request = httpDecoder.decodedRequest();
if (request != null) {
Request req;
switch(request.getMethod()) {
case "OPTIONS":
req = new OptionsRequest(event.getConnection(), request);
break;
case "GET":
req = new GetRequest(event.getConnection(), request);
break;
case "HEAD":
req = new HeadRequest(event.getConnection(), request);
break;
case "POST":
req = new PostRequest(event.getConnection(), request);
break;
case "PUT":
req = new PutRequest(event.getConnection(), request);
break;
case "DELETE":
req = new DeleteRequest(event.getConnection(), request);
break;
case "TRACE":
req = new TraceRequest(event.getConnection(), request);
break;
case "CONNECT":
req = new ConnectRequest(event.getConnection(), request);
break;
default:
req = new Request(event.getConnection(), request);
break;
}
fire(req);
}
} catch (ProtocolException e) {
HttpResponse response = new HttpResponse(e.getHttpVersion());
response.setResponseCode(HttpStatus.BAD_REQUEST.getCode());
response.setResponseMessage(e.getMessage());
fire (new Response(event.getConnection(), response));
}
}
@Handler
public void onRequestCompleted(Request.Completed event)
throws InterruptedException {
Request requestEvent = event.getCompleted();
DataConnection<ByteBuffer> connection = requestEvent.getConnection();
HttpResponse response = null;
switch (requestEvent.get()) {
case UNHANDLED:
response = new HttpResponse
(requestEvent.getRequest().getProtocol());
response.setResponseStatus(HttpStatus.NOT_IMPLEMENTED);
break;
case RESOURCE_NOT_FOUND:
response = new HttpResponse
(requestEvent.getRequest().getProtocol());
response.setResponseStatus(HttpStatus.NOT_FOUND);
break;
case RESPONDED:
return;
}
fire (new Response(connection, response));
}
@Handler
public void onResponse(Response event) throws InterruptedException {
DataConnection<ByteBuffer> connection = event.getConnection();
HttpResponse response = event.getResponse();
HttpResponseEncoder encoder = encoders.get(connection);
EventPipeline pipeline = newEventPipeline();
while (true) {
ByteBuffer buffer = connection.acquireWriteBuffer();
boolean more = encoder.encode(response, buffer);
pipeline.add(new Write<>(connection, buffer), networkChannel);
if (!more) {
break;
}
}
}
public void onOptions(OptionsRequest event) {
if (event.getRequestUri() == HttpRequest.ASTERISK_REQUEST) {
event.setResult(HandlingResult.RESPONDED);
}
}
}
|
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import components.simplereader.SimpleReader;
import components.simplereader.SimpleReader1L;
/**
* This class retrieves the saved data from the /data folder and uses it to
* create a visual graph
*
* @author Thomas Clark
*/
public final class NFGraph {
class DataPoint {
String newsSource;
double ranking;
}
class DataForDate {
String date;
long xValueLong;
int xValue;
ArrayList<DataPoint> dataPoints;
DataForDate() {
this.dataPoints = new ArrayList<DataPoint>();
}
}
/**
* Array of news sources
*/
ArrayList<DataForDate> allDatesData;
/**
* Constructor for NFNewsSource
*/
public NFGraph() {
this.allDatesData = new ArrayList<DataForDate>();
File data = new File("data");
long lowestXValue = 0l;
File[] listOfFiles = data.listFiles();
if (listOfFiles.length != 0) {
long fileArray[] = new long[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
fileArray[i] = Long.parseLong(file.getName()
.replace(".txt", ""));
}
Arrays.sort(fileArray);
for (int i = 0; i < fileArray.length; i++) {
DataForDate date = new DataForDate();
SimpleReader fileIn = new SimpleReader1L("data/" + fileArray[i]
+ ".txt");
date.xValueLong = Long.parseLong(fileIn.nextLine());
if (i == 0) {
lowestXValue = date.xValueLong;
} else if (date.xValue < lowestXValue) {
lowestXValue = date.xValueLong;
}
date.date = fileIn.nextLine();
while (!fileIn.atEOS()) {
DataPoint point = new DataPoint();
String line = fileIn.nextLine();
int index = line.indexOf("*");
point.newsSource = line.substring(0, index);
point.ranking = Double.parseDouble(line
.substring(index + 1));
date.dataPoints.add(point);
}
this.allDatesData.add(date);
}
for (int i = 0; i < this.allDatesData.size(); i++) {
long xValueLong = this.allDatesData.get(i).xValueLong;
Long newXValueLong = xValueLong - lowestXValue;
this.allDatesData.get(i).xValue = newXValueLong.intValue();
}
}
}
}
|
package org.locationtech.geogig.plumbing.diff;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Maps.uniqueIndex;
import static com.google.common.collect.Sets.newTreeSet;
import static com.google.common.collect.Sets.union;
import static org.locationtech.geogig.storage.BulkOpListener.NOOP_LISTENER;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.model.Bounded;
import org.locationtech.geogig.model.Bucket;
import org.locationtech.geogig.model.CanonicalNodeOrder;
import org.locationtech.geogig.model.Node;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevObject.TYPE;
import org.locationtech.geogig.model.RevObjects;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.repository.NodeRef;
import org.locationtech.geogig.repository.impl.SpatialOps;
import org.locationtech.geogig.storage.ObjectStore;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.vividsolutions.jts.geom.Envelope;
/**
* Provides a means to "walk" the differences between two {@link RevTree trees} in in-order order
* and emit diff events to a {@link Consumer}, which can choose to skip parts of the walk when it
* had collected enough information for its purpose and don't need to go further down a given pair
* of trees (either named or bucket).
*/
@NonNullByDefault
public class PreOrderDiffWalk {
public static final CanonicalNodeOrder ORDER = CanonicalNodeOrder.INSTANCE;
// this is the same as the defaultForkJoinWorkerThreadFactory but gives the threads a
// different name (easier to see in debugger)
static ForkJoinPool.ForkJoinWorkerThreadFactory threadFactoryPrivate = pool -> {
final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
worker.setName("PreOrderDiffWalk-private-" + worker.getPoolIndex());
return worker;
};
// this is the same as the defaultForkJoinWorkerThreadFactory but gives the threads a
// different name (easier to see in debugger)
static ForkJoinPool.ForkJoinWorkerThreadFactory threadFactoryShared = pool -> {
final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
worker.setName("PreOrderDiffWalk-shared-" + worker.getPoolIndex());
return worker;
};
private static final ForkJoinPool SHARED_FORK_JOIN_POOL;
static {
final int parallelism = Math.max(2, Runtime.getRuntime().availableProcessors());
// establishes local first-in-first-out scheduling mode for forked
// more appropriate than default locally stack-based mode when
// worker threads only process event-style asynchronous tasks
final boolean asyncMode = true;
SHARED_FORK_JOIN_POOL = new ForkJoinPool(parallelism,
threadFactoryShared, null, asyncMode);
}
/**
* Contains the full path to the bucket as an array of integers where the array length
* determines the bucket depth and each array element its index at the depth defined by the
* element index.
*
*/
public static final class BucketIndex implements Comparable<BucketIndex> {
private final int[] indexPath;
/**
* "Null object" for the root tree.
*/
static final BucketIndex ROOT = new BucketIndex();
/**
* Creates a root bucket index
*/
private BucketIndex() {
this.indexPath = new int[0];
}
public BucketIndex(final int[] parentPath, final int index) {
int[] path = new int[parentPath.length + 1];
System.arraycopy(parentPath, 0, path, 0, parentPath.length);
path[parentPath.length] = index;
this.indexPath = path;
}
public BucketIndex append(final Integer index) {
return append(index.intValue());
}
public BucketIndex append(final int index) {
return new BucketIndex(this.indexPath, index);
}
/**
* @return the zero-based depth index for the bucket addressed by this bucket index
*/
public int depthIndex() {
return indexPath.length - 1;
}
/**
* @return the bucket index at the last depth level
*/
public Integer lastIndex() {
return Integer.valueOf(indexPath[indexPath.length - 1]);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BucketIndex)) {
return false;
}
return Arrays.equals(indexPath, ((BucketIndex) o).indexPath);
}
@Override
public int hashCode() {
return Arrays.hashCode(indexPath);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indexPath.length - 1; i++) {
sb.append(indexPath[i]).append('/');
}
if (indexPath.length > 0) {
sb.append(indexPath[indexPath.length - 1]);
}
return sb.toString();
}
@Override
public int compareTo(BucketIndex o) {
return Ints.lexicographicalComparator().compare(indexPath, o.indexPath);
}
}
private final RevTree left;
private final RevTree right;
private final ObjectStore leftSource;
private final ObjectStore rightSource;
private ObjectId metadataId;
private ForkJoinPool forkJoinPool;
private CancellableConsumer walkConsumer = null;
private AtomicBoolean finished = new AtomicBoolean(false);
public PreOrderDiffWalk(RevTree left, RevTree right, ObjectStore leftSource,
ObjectStore rightSource) {
this(left, right, leftSource, rightSource, false);
}
public PreOrderDiffWalk(RevTree left, RevTree right, ObjectStore leftSource,
ObjectStore rightSource, boolean preserveIterationOrder) {
checkNotNull(left, "left");
checkNotNull(right, "right");
checkNotNull(leftSource, "leftSource");
checkNotNull(rightSource, "rightSource");
this.left = left;
this.right = right;
this.leftSource = leftSource;
this.rightSource = rightSource;
if (preserveIterationOrder) {
forkJoinPool = new ForkJoinPool(1, threadFactoryPrivate, null, false);
} else {
forkJoinPool = SHARED_FORK_JOIN_POOL;
}
}
public void setDefaultMetadataId(ObjectId metadataId) {
this.metadataId = metadataId;
}
private static final class SideInfo {
final ObjectStore source;
@Nullable
final NodeRef parentRef;
SideInfo(ObjectStore source, NodeRef parentRef) {
this.source = source;
this.parentRef = parentRef;
}
}
private static final class WalkInfo {
final CancellableConsumer consumer;
final SideInfo left;
final SideInfo right;
WalkInfo(CancellableConsumer consumer, SideInfo left, SideInfo right) {
this.consumer = consumer;
this.left = left;
this.right = right;
}
public WalkInfo child(NodeRef leftChild, NodeRef rightChild) {
SideInfo leftInfo = new SideInfo(left.source, leftChild);
SideInfo rightInfo = new SideInfo(right.source, rightChild);
return new WalkInfo(consumer, leftInfo, rightInfo);
}
}
/**
* Walk up the differences between the two trees and emit events to the {@code consumer}.
* <p>
* NOTE: the {@link Consumer} must be thread safe.
* <p>
* If the two root trees are not equal, an initial call to {@link Consumer#tree(Node, Node)}
* will be made where the nodes will have {@link NodeRef#ROOT the root name} (i.e. empty
* string), and provided the consumer indicates to continue with the traversal, further calls to
* {@link Consumer#feature}, {@link Consumer#tree}, and/or {@link Consumer#bucket} will be made
* as changes between the two trees are found.
* <p>
* At any time, if {@link Consumer#tree} or {@link Consumer#bucket} returns {@code false}, that
* pair of trees won't be further evaluated and the traversal continues with their siblings or
* parents if there are no more siblings.
* <p>
* Note the {@code consumer} is only notified of nodes or buckets that differ, using
* {@code null} of either the left of right argument to indicate there's no matching object at
* the left or right side of the comparison. Left side nulls indicate a new object, right side
* nulls a deleted one. None of the {@code Consumer} method is ever called with equal left and
* right arguments.
*
* @param consumer the callback object that gets notified of changes between the two trees and
* can abort the walk for whole subtrees.
*/
public final void walk(Consumer consumer) {
if (left.equals(right)) {
return;
}
// start by asking the consumer if go on with the walk at all with the
// root nodes
final RevTree left = this.left;
final RevTree right = this.right;
Envelope lbounds = SpatialOps.boundsOf(left);
final ObjectId metadataId = this.metadataId == null ? ObjectId.NULL : this.metadataId;
Node lnode = Node.create(NodeRef.ROOT, left.getId(), metadataId, TYPE.TREE, lbounds);
Envelope rbounds = SpatialOps.boundsOf(right);
Node rnode = Node.create(NodeRef.ROOT, right.getId(), metadataId, TYPE.TREE, rbounds);
NodeRef leftRef = NodeRef.createRoot(lnode);
NodeRef rightRef = NodeRef.createRoot(rnode);
this.walkConsumer = new CancellableConsumer(consumer);
SideInfo leftInfo = new SideInfo(leftSource, leftRef);
SideInfo rightInfo = new SideInfo(rightSource, rightRef);
WalkInfo walkInfo = new WalkInfo(walkConsumer, leftInfo, rightInfo);
TraverseTree task = new TraverseTree(walkInfo);
try {
forkJoinPool.invoke(task);
} catch (Exception e) {
if (!(leftSource.isOpen() && rightSource.isOpen())) {
// someone closed the repo, we're ok.
} else {
System.err.println("Excaption caught executing task: ");
e.printStackTrace();
Throwables.propagate(e);
}
} finally {
finished.set(true);
cleanupForkJoinPool();
}
}
private void cleanupForkJoinPool() {
if (forkJoinPool == SHARED_FORK_JOIN_POOL)
return; //no need to clean up
else
forkJoinPool.shutdown(); //private pool needs cleaning
}
/**
* Abort the traversal in the consumer.
*/
public void abortTraversal() {
if (walkConsumer != null) {
walkConsumer.abortTraversal();
}
}
public void awaitTermination() {
while (!finished.get()) {
// wait.
}
}
@SuppressWarnings("serial")
private static abstract class WalkAction extends RecursiveAction {
protected final WalkInfo info;
protected final BucketIndex bucketIndex;
WalkAction(WalkInfo walkInfo) {
this(walkInfo, BucketIndex.ROOT);
}
WalkAction(WalkInfo info, final BucketIndex bucketIndex) {
checkArgument(info.left.parentRef != null || info.right.parentRef != null,
"leftParent and rightParent can't be null at the same time");
checkNotNull(bucketIndex);
this.info = info;
this.bucketIndex = bucketIndex;
}
TraverseTree traverseTree(@Nullable NodeRef left, @Nullable NodeRef right) {
checkArgument(left != null || right != null);
WalkInfo treeInfo = info.child(left, right);
return new TraverseTree(treeInfo);
}
TraverseTreeContents traverseTreeContents(RevTree left, RevTree right) {
return new TraverseTreeContents(info, left, right, bucketIndex);
}
TraverseLeafLeaf leafLeaf(Iterator<Node> leftChildren, Iterator<Node> rightChildren) {
return new TraverseLeafLeaf(info, leftChildren, rightChildren);
}
List<WalkAction> bucketBucket(RevTree left, RevTree right) {
checkArgument(!left.buckets().isEmpty());
checkArgument(!right.buckets().isEmpty());
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
final ImmutableSortedMap<Integer, Bucket> lb = left.buckets();
final ImmutableSortedMap<Integer, Bucket> rb = right.buckets();
final TreeSet<BucketIndex> childBucketIndexes;
{
Iterable<BucketIndex> indexes = Iterables.transform(
union(lb.keySet(), rb.keySet()),
(i) -> this.bucketIndex.append(i));
childBucketIndexes = newTreeSet(indexes);
}
final Map<ObjectId, RevTree> trees;
try {
trees = loadTrees(lb, rb);
} catch (RuntimeException e) {
info.consumer.abortTraversal();
return Collections.emptyList();
}
@Nullable
Bucket lbucket, rbucket;
RevTree ltree, rtree;
final List<WalkAction> tasks = new ArrayList<>();
for (BucketIndex index : childBucketIndexes) {
lbucket = lb.get(index.lastIndex());
rbucket = rb.get(index.lastIndex());
Preconditions.checkState(lbucket != null || rbucket != null);
if (!Objects.equal(lbucket, rbucket)) {
ltree = lbucket == null ? RevTree.EMPTY : trees.get(lbucket.getObjectId());
rtree = rbucket == null ? RevTree.EMPTY : trees.get(rbucket.getObjectId());
WalkAction task;
task = new TraverseBucketBucket(info, ltree, rtree, lbucket, rbucket, index);
tasks.add(task);
}
}
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
return tasks;
}
private Map<ObjectId, RevTree> loadTrees(final ImmutableSortedMap<Integer, Bucket> lb,
final ImmutableSortedMap<Integer, Bucket> rb) {
final Map<ObjectId, RevTree> trees;
final Set<ObjectId> lbucketIds = Sets
.newHashSet(transform(lb.values(), (b) -> b.getObjectId()));
final Set<ObjectId> rbucketIds = Sets
.newHashSet(transform(rb.values(), (b) -> b.getObjectId()));
// get all buckets at once, to leverage ObjectStore optimizations
if (info.left.source == info.right.source) {
Set<ObjectId> ids = Sets.union(lbucketIds, rbucketIds);
Iterator<RevTree> titer = info.left.source.getAll(ids, NOOP_LISTENER,
RevTree.class);
trees = uniqueIndex(titer, (t) -> t.getId());
} else {
trees = new HashMap<>();
trees.putAll(uniqueIndex(
info.left.source.getAll(transform(lb.values(), (b) -> b.getObjectId()),
NOOP_LISTENER, RevTree.class),
(t) -> t.getId()));
trees.putAll(uniqueIndex(
info.right.source.getAll(transform(rb.values(), (b) -> b.getObjectId()),
NOOP_LISTENER, RevTree.class),
(t) -> t.getId()));
}
return trees;
}
/**
* Compares a bucket tree at the right side of the comparison, and a the
* {@link RevObjects#children() children} nodes of a leaf tree at the left side of the
* comparison.
* <p>
* This happens when the right tree is much larger than the left tree
* <p>
* This traversal is symmetric to {@link #bucketLeaf} so be careful that any change made to
* this method shall have a matching change at {@link #bucketLeaf}
*
* @precondition {@code !right.buckets().isEmpty()}
*/
protected List<WalkAction> leafBucket(Iterator<Node> leftc, RevTree right) {
checkArgument(!right.buckets().isEmpty());
final SortedMap<Integer, Bucket> rightBuckets = right.buckets();
final ListMultimap<Integer, Node> nodesByBucket = splitNodesToBucketsAtDepth(leftc,
bucketIndex);
final SortedSet<BucketIndex> bucketIndexes = getChildBucketIndexes(rightBuckets,
nodesByBucket);
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
// get all buckets at once, to leverage ObjectStore optimizations
final ObjectStore source = info.right.source;
final Map<ObjectId, RevTree> bucketTrees = loadBucketTrees(source, rightBuckets);
List<WalkAction> tasks = new ArrayList<>();
for (BucketIndex childIndex : bucketIndexes) {
Bucket rightBucket = rightBuckets.get(childIndex.lastIndex());
// never returns null, but empty
List<Node> leftNodes = nodesByBucket.get(childIndex.lastIndex());
if (null == rightBucket) {
tasks.add(leafLeaf(leftNodes.iterator(), Collections.emptyIterator()));
} else {
RevTree rightTree = bucketTrees.get(rightBucket.getObjectId());
TraverseLeafBucket task;
task = new TraverseLeafBucket(info, leftNodes.iterator(), rightBucket,
rightTree, childIndex);
tasks.add(task);
}
}
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
return tasks;
}
/**
* Compares a bucket tree at the left side of the comparison, and a the
* {@link RevObjects#children() children} nodes of a leaf tree at the right side of the
* comparison.
* <p>
* This happens when the left tree is much larger than the right tree
* <p>
* This traversal is symmetric to {@link #leafBucket} so be careful that any change made to
* this method shall have a matching change at {@link #leafBucket}
*
* @precondition {@code !left.buckets().isEmpty()}
*/
protected List<WalkAction> bucketLeaf(RevTree left, Iterator<Node> rightc) {
checkArgument(!left.buckets().isEmpty());
final SortedMap<Integer, Bucket> leftBuckets = left.buckets();
final ListMultimap<Integer, Node> nodesByBucket = splitNodesToBucketsAtDepth(rightc,
bucketIndex);
final SortedSet<BucketIndex> bucketIndexes = getChildBucketIndexes(leftBuckets,
nodesByBucket);
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
// get all buckets at once, to leverage ObjectStore optimizations
final ObjectStore source = info.left.source;
final Map<ObjectId, RevTree> bucketTrees = loadBucketTrees(source, leftBuckets);
List<WalkAction> tasks = new ArrayList<>();
for (BucketIndex childIndex : bucketIndexes) {
Bucket leftBucket = leftBuckets.get(childIndex.lastIndex());
// never returns null, but empty
List<Node> rightNodes = nodesByBucket.get(childIndex.lastIndex());
if (null == leftBucket) {
tasks.add(leafLeaf(Collections.emptyIterator(), rightNodes.iterator()));
} else {
RevTree leftTree = bucketTrees.get(leftBucket.getObjectId());
TraverseBucketLeaf task = new TraverseBucketLeaf(info, leftBucket, leftTree,
rightNodes.iterator(), childIndex);
tasks.add(task);
}
}
if (info.consumer.isCancelled()) {
return Collections.emptyList();
}
return tasks;
}
private Map<ObjectId, RevTree> loadBucketTrees(final ObjectStore source,
final SortedMap<Integer, Bucket> buckets) {
final Map<ObjectId, RevTree> bucketTrees;
{
Iterable<ObjectId> ids = transform(buckets.values(), (b) -> b.getObjectId());
bucketTrees = uniqueIndex(source.getAll(ids, NOOP_LISTENER, RevTree.class),
(t) -> t.getId());
}
return bucketTrees;
}
private SortedSet<BucketIndex> getChildBucketIndexes(
final SortedMap<Integer, Bucket> treeBuckets,
final ListMultimap<Integer, Node> leafTreeNodesByBucket) {
final SortedSet<BucketIndex> bucketIndexes;
Set<Integer> childIndexes = Sets.union(treeBuckets.keySet(),
leafTreeNodesByBucket.keySet());
Iterable<BucketIndex> childPaths = Iterables.transform(childIndexes,
(i) -> this.bucketIndex.append(i));
bucketIndexes = Sets.newTreeSet(childPaths);
return bucketIndexes;
}
/**
* Called when found a difference between two nodes. It can be a removal ({@code right} is
* null), an added node ({@code left} is null}, or a modified feature/tree (neither is
* null); but {@code left} and {@code right} can never be equal.
* <p>
* Depending on the type of node, this method will call {@link Consumer#tree} or
* {@link Consumer#feature}, and continue the traversal down the trees in case it was a tree
* and {@link Consumer#tree} returned null.
*/
@Nullable
protected final WalkAction node(@Nullable final NodeRef left,
@Nullable final NodeRef right) {
if (info.consumer.isCancelled()) {
return null;
}
checkState(left != null || right != null, "both nodes can't be null");
checkArgument(!Objects.equal(left, right));
final TYPE type = left == null ? right.getType() : left.getType();
if (TYPE.FEATURE.equals(type)) {
info.consumer.feature(left, right);
return null;
}
checkState(TYPE.TREE.equals(type));
return traverseTree(left, right);
}
/**
* Split the given nodes into lists keyed by the bucket indes they would belong if they were
* part of a tree bucket at the given {@code bucketDepth}
*/
protected final ListMultimap<Integer, Node> splitNodesToBucketsAtDepth(Iterator<Node> nodes,
final BucketIndex parentIndex) {
Function<Node, Integer> keyFunction = (node) -> ORDER.bucket(node,
parentIndex.depthIndex() + 1);
ListMultimap<Integer, Node> nodesByBucket = Multimaps.index(nodes, keyFunction);
return nodesByBucket;
}
}
/**
* When this action is called its guaranteed that either {@link Consumer#tree} returned
* {@code true} (i.e. its a pair of trees pointed out by a Node), or {@link Consumer#bucket}
* returned {@code true} (i.e. they are trees pointed out by buckets).
*
* @param consumer the callback object
* @param leftBucketTree the tree at the left side of the comparison
* @param rightBucketTree the tree at the right side of the comparison
* @param bucketDepth the depth of bucket traversal (only non zero if comparing two bucket
* trees, as when called from {@link #handleBucketBucket})
* @precondition {@code left != null && right != null}
*/
@SuppressWarnings("serial")
private static class TraverseTree extends WalkAction {
public TraverseTree(WalkInfo walkInfo) {
super(walkInfo);
}
@Override
protected void compute() {
final @Nullable NodeRef leftNode = info.left.parentRef;
final @Nullable NodeRef rightNode = info.right.parentRef;
if (Objects.equal(leftNode, rightNode)) {
return;
}
if (info.consumer.isCancelled()) {
return;
}
if (info.consumer.tree(leftNode, rightNode)) {
RevTree left;
RevTree right;
left = leftNode == null || RevTree.EMPTY_TREE_ID.equals(leftNode.getObjectId())
? RevTree.EMPTY : info.left.source.getTree(leftNode.getObjectId());
right = rightNode == null || RevTree.EMPTY_TREE_ID.equals(rightNode.getObjectId())
? RevTree.EMPTY : info.right.source.getTree(rightNode.getObjectId());
TraverseTreeContents traverseTreeContents = new TraverseTreeContents(info, left,
right, BucketIndex.ROOT);
traverseTreeContents.compute();
}
info.consumer.endTree(leftNode, rightNode);
}
}
@SuppressWarnings("serial")
private static class TraverseTreeContents extends WalkAction {
private final RevTree left, right;
public TraverseTreeContents(WalkInfo info, RevTree left, RevTree right,
BucketIndex bucketIndex) {
super(info, bucketIndex);
checkNotNull(left);
checkNotNull(right);
this.left = left;
this.right = right;
}
@Override
protected void compute() {
if (Objects.equal(left, right)) {
return;
}
if (info.consumer.isCancelled()) {
return;
}
// Possible cases:
// 1- left and right are leaf trees
// 2- left and right are bucket trees
// 3- left is leaf and right is bucketed
// 4- left is bucketed and right is leaf
final boolean leftIsLeaf = left.buckets().isEmpty();
final boolean rightIsLeaf = right.buckets().isEmpty();
Iterator<Node> leftc = leftIsLeaf
? RevObjects.children(left, CanonicalNodeOrder.INSTANCE) : null;
Iterator<Node> rightc = rightIsLeaf
? RevObjects.children(right, CanonicalNodeOrder.INSTANCE) : null;
List<WalkAction> tasks = new ArrayList<>();
if (leftIsLeaf && rightIsLeaf) {
leafLeaf(leftc, rightc).compute();
} else if (!(leftIsLeaf || rightIsLeaf)) {
tasks.addAll(bucketBucket(left, right));
} else if (leftIsLeaf) {
tasks.addAll(leafBucket(leftc, right));
} else {
tasks.addAll(bucketLeaf(left, rightc));
}
if (!info.consumer.isCancelled()) {
invokeAll(tasks);
}
}
}
@SuppressWarnings("serial")
private static class TraverseLeafLeaf extends WalkAction {
private Iterator<Node> left;
private Iterator<Node> right;
TraverseLeafLeaf(WalkInfo info, Iterator<Node> leftChildren, Iterator<Node> rightChildren) {
super(info);
this.left = leftChildren;
this.right = rightChildren;
}
/**
* Traverse and compare the {@link RevObjects#children() children} nodes of two leaf trees,
* calling {@link #node(Consumer, Node, Node)} for each diff.
*/
@Override
protected void compute() {
if (info.consumer.isCancelled()) {
return;
}
PeekingIterator<Node> li = Iterators.peekingIterator(left);
PeekingIterator<Node> ri = Iterators.peekingIterator(right);
List<WalkAction> tasks = new ArrayList<>();
final NodeRef leftParent = info.left.parentRef;
final NodeRef rightParent = info.right.parentRef;
while (li.hasNext() && ri.hasNext() && !info.consumer.isCancelled()) {
final Node lpeek = li.peek();
final Node rpeek = ri.peek();
final int order = ORDER.compare(lpeek, rpeek);
@Nullable
WalkAction action = null;
if (order < 0) {
NodeRef lref = newRef(leftParent, li.next());
action = node(lref, null);// removal
} else if (order == 0) {// change
// same feature at both sides of the traversal, consume them and check if its
// changed it or not
Node l = li.next();
Node r = ri.next();
if (!Objects.equal(l, r)) {
NodeRef lref = newRef(leftParent, l);
NodeRef rref = newRef(rightParent, r);
if (!l.equals(r)) {
action = node(lref, rref);
}
}
} else {
NodeRef rref = newRef(rightParent, ri.next());
action = node(null, rref);// addition
}
if (action != null) {
tasks.add(action);
}
}
checkState(info.consumer.isCancelled() || !li.hasNext() || !ri.hasNext(),
"either the left or the right iterator should have been fully consumed");
// right fully consumed, any remaining node in left is a removal
while (!info.consumer.isCancelled() && li.hasNext()) {
WalkAction action = node(newRef(leftParent, li.next()), null);
if (action != null) {
tasks.add(action);
}
}
// left fully consumed, any remaining node in right is an add
while (!info.consumer.isCancelled() && ri.hasNext()) {
WalkAction action = node(null, newRef(rightParent, ri.next()));
if (action != null) {
tasks.add(action);
}
}
if (!info.consumer.isCancelled()) {
invokeAll(tasks);
}
}
private NodeRef newRef(NodeRef parent, Node lnode) {
return NodeRef.create(parent.path(), lnode, parent.getMetadataId());
}
}
@SuppressWarnings("serial")
private static class TraverseBucketBucket extends TraverseTreeContents {
private final Bucket leftBucket, rightBucket;
/**
* @param info
* @param leftTree
* @param rightTree
* @param bucketIndex if {@code null}, the trees are top level, otherwise they're the inner
* trees at the specified bucket index
*/
TraverseBucketBucket(WalkInfo info, RevTree leftTree, RevTree rightTree,
@Nullable Bucket leftBucket, @Nullable Bucket rightBucket,
final BucketIndex bucketIndex) {
super(info, leftTree, rightTree, bucketIndex);
checkArgument(leftBucket != null || rightBucket != null);
checkArgument(!Objects.equal(leftBucket, rightBucket));
this.leftBucket = leftBucket;
this.rightBucket = rightBucket;
}
/**
* Traverse two bucket trees and notify their differences to the {@code consumer}.
* <p>
* If this method is called than its guaranteed that the two bucket trees are note equal
* (one of them may be empty though), and that {@link Consumer#bucket} returned {@code true}
* <p>
* For each bucket index present in the joint set of the two trees buckets,
* {@link #traverseTree(Consumer, RevTree, RevTree, int)} will be called for the bucket
* trees that are not equal with {@code bucketDepth} incremented by one.
*
* @param consumer the callback object to receive diff events from the comparison of the two
* trees
* @param leftBucketTree the bucket tree at the left side of the comparison
* @param rightBucketTree the bucket tree at the right side of the comparison
* @param bucketDepth the current depth at which the comparison is evaluating these two
* bucket trees
* @see #traverseTree(Consumer, RevTree, RevTree, int)
* @precondition {@code !left.equals(right)}
* @precondition {@code left.isEmpty() || left.buckets().isPresent()}
* @precondition {@code right.isEmpty() || right.buckets().isPresent()}
*/
@Override
protected void compute() {
if (info.consumer.isCancelled()) {
return;
}
final NodeRef leftParent = info.left.parentRef;
final NodeRef rightParent = info.right.parentRef;
final BucketIndex index = super.bucketIndex;
if (info.consumer.bucket(leftParent, rightParent, index, leftBucket, rightBucket)) {
super.compute();
}
info.consumer.endBucket(leftParent, rightParent, index, leftBucket, rightBucket);
}
}
@SuppressWarnings("serial")
private static class TraverseBucketLeaf extends WalkAction {
private RevTree leftTree;
private Bucket leftBucket;
private Iterator<Node> rightNodes;
TraverseBucketLeaf(WalkInfo info, Bucket leftBucket, RevTree bucketTree,
Iterator<Node> rightcChildren, BucketIndex bucketIndex) {
super(info, bucketIndex);
this.leftBucket = leftBucket;
this.leftTree = bucketTree;
this.rightNodes = rightcChildren;
}
/**
* Compares a bucket tree at the left side of the comparison, and a the
* {@link RevObjects#children() children} nodes of a leaf tree at the right side of the
* comparison.
* <p>
* This happens when the left tree is much larger than the right tree
* <p>
* This traversal is symmetric to {@link #traverseLeafBucket} so be careful that any change
* made to this method shall have a matching change at {@link #traverseLeafBucket}
*
* @precondition {@code left.buckets().isPresent()}
*/
@Override
protected void compute() {
final CancellableConsumer consumer = info.consumer;
if (consumer.isCancelled()) {
return;
}
final NodeRef leftParent = info.left.parentRef;
final NodeRef rightParent = info.right.parentRef;
final BucketIndex index = super.bucketIndex;
if (rightNodes.hasNext()) {
if (leftTree.buckets().isEmpty()) {
Iterator<Node> children;
children = RevObjects.children(leftTree, CanonicalNodeOrder.INSTANCE);
TraverseLeafLeaf task = leafLeaf(children, rightNodes);
task.compute();
} else {
List<WalkAction> tasks = bucketLeaf(leftTree, rightNodes);
invokeAll(tasks);
}
} else {
if (consumer.bucket(leftParent, rightParent, index, leftBucket, null)) {
TraverseTreeContents task = traverseTreeContents(leftTree, RevTree.EMPTY);
task.compute();
}
consumer.endBucket(leftParent, rightParent, index, leftBucket, null);
}
}
}
@SuppressWarnings("serial")
private static class TraverseLeafBucket extends WalkAction {
private Iterator<Node> leftNodes;
private RevTree rightTree;
private Bucket rightBucket;
TraverseLeafBucket(WalkInfo info, Iterator<Node> leftcChildren, Bucket rightBucket,
RevTree rightTree, BucketIndex bucketIndex) {
super(info, bucketIndex);
this.leftNodes = leftcChildren;
this.rightBucket = rightBucket;
this.rightTree = rightTree;
}
/**
* Compares a bucket tree at the right side of the comparison, and a the
* {@link RevObjects#children() children} nodes of a leaf tree at the left side of the
* comparison.
* <p>
* This happens when the right tree is much larger than the left tree
* <p>
* This traversal is symmetric to {@link #traverseBucketLeaf} so be careful that any change
* made to this method shall have a matching change at {@link #traverseBucketLeaf}
*
* @precondition {@code right.buckets().isPresent()}
*/
@Override
protected void compute() {
final CancellableConsumer consumer = info.consumer;
if (consumer.isCancelled()) {
return;
}
final NodeRef leftParent = info.left.parentRef;
final NodeRef rightParent = info.right.parentRef;
final BucketIndex index = super.bucketIndex;
if (leftNodes.hasNext()) {
if (rightTree.buckets().isEmpty()) {
Iterator<Node> children;
children = RevObjects.children(rightTree, CanonicalNodeOrder.INSTANCE);
TraverseLeafLeaf task = leafLeaf(leftNodes, children);
task.compute();
} else {
List<WalkAction> tasks = leafBucket(leftNodes, rightTree);
invokeAll(tasks);
}
} else {
if (consumer.bucket(leftParent, rightParent, index, null, rightBucket)) {
TraverseTreeContents task = traverseTreeContents(RevTree.EMPTY, rightTree);
task.compute();
}
consumer.endBucket(leftParent, rightParent, index, null, rightBucket);
}
}
}
/**
* Defines an interface to consume the events emitted by a diff-tree "depth first" traversal,
* with the ability to be notified of changes to feature and tree nodes, as well as to buckets,
* and to skip the further traversal of whole trees (either as pointed out by "name tree" nodes,
* or internal tree buckets).
* <p>
* NOTE implementations are mandated to be thread safe.
* <p>
* This is especially useful when there's no need to traverse the whole diff to compute the
* desired result, as it can be the case of counting changes between two trees where one side of
* the comparison does not have such tree, or the spatial bounds of the difference between two
* trees on the same case.
* <p>
* The first call will always be to {@link #tree(Node, Node)} with the root tree nodes, or there
* may be no call to any method at all if the two tree nodes are equal.
* <p>
* This also allows to parallelize some computations where there's no need to have the output of
* the tree comparison in "prescribed storage order" as defined by {@link CanonicalNodeOrder}.
*/
public static interface Consumer {
/**
* Called when either two leaf trees are being compared and a feature node have changed (i.e
* neither {@code left} nor {@code right} is null, or a feature has been deleted (
* {@code left} is null), or added ({@code right} is null).
*
* @param left the feature node at the left side of the traversal; may be {@code null) in
* which case {@code right} has been added.
* @param right the feature node at the right side of the traversal; may be {@code null} in
* which case {@code left} has been removed.
* @return {@code false} if the WHOLE traversal shall be aborted, {@true} to continue
* traversing other features and trees. Note this differs from the return value of
* {@link #tree()} and {@link #bucket()} in that they only avoid the traversal of
* the indicated tree or bucket, not the whole traversal.
* @precondition {@code left != null || right != null}
* @precondition {@code if(left != null && right != null) then left.name() == right.name()}
*/
public abstract boolean feature(@Nullable final NodeRef left,
@Nullable final NodeRef right);
/**
* Called when the traversal finds a tree node at both sides of the traversal with the same
* name and pointing to different trees (i.e. a changed tree), or just one node tree at
* either side of the traversal with no corresponding tree node at the other side (i.e.
* either an added tree - {@code left} is null -, or a deleted tree - {@code right} is null
* -).
* <p>
* If this method returns {@code true} then the traversal will continue down the tree(s)
* contents, calling {@link #bucket}, {@link #feature}, or {@link #tree} as appropriate. If
* this method returns {@code false} the traversal of the tree(s) contents will be skipped
* and continue with the siblings or parents' siblings if there are no more nodes to
* evaluate at the current depth.
*
* @param left the left tree of the traversal
* @param right the right tree of the traversal
* @return {@code true} if the traversal of the contents of this pair of trees should come
* right after this method returns, {@code false} if this consumer does not want to
* continue traversing the trees pointed out by these nodes. Note this differs from
* the return value of {@link #feature()} in that {@code false} only avoids going
* deeper into this tree, instead of aborting the whole traversal
* @precondition {@code left != null || right != null}
*/
public abstract boolean tree(@Nullable final NodeRef left, @Nullable final NodeRef right);
/**
* Called once done with a {@link #tree}, regardless of the returned value
*/
public abstract void endTree(@Nullable final NodeRef left, @Nullable final NodeRef right);
/**
* Called when the traversal finds either a bucket at both sides of the traversal with same
* depth an index that have changed, or just one at either side of the comparison with no
* node at the other side that would fall into that bucket if it existed.
* <p>
* When comparing the contents of two trees, it could be that both are bucket trees and then
* this method will be called for each bucket index/depth, resulting in calls to this method
* with wither both buckets or one depending on the existence of buckets at the given index
* at both sides.
* <p>
* Or it can also be that only one of the trees is be a bucket tree and the other a leaf
* tree, in which case this method can be called only if the leaf tree has no node that
* would fall on the same bucket index at the current bucket depth; otherwise
* {@link #feature}, {@link #tree}, or this same method will be called recursively while
* evaluating the leaf tree nodes that would fall on this bucket index and depth, as
* compared with the nodes of the tree pointed out by the bucket that exists at the other
* side of the traversal, or any of its children bucket trees at a more deep bucket, until
* there's no ambiguity.
* <p>
* If this method returns {@code true}, then the traversal will continue down to the
* contents of the trees pointed out but the bucket(s), otherwise the bucket(s) contents
* will be skipped and the traversal continues with the next bucket index, or the parents
* trees siblings.
*
* @param bucketIndex the index of the bucket inside the bucket trees being evaluated, its
* the same for both buckets in case buckets for the same index are present in both
* trees
* @param bucketDepth the depth of the bucket(s)
* @param left the bucket at the given index on the left-tree of the traversal, or
* {@code null} if no bucket exists on the left tree for that index
* @param right the bucket at the given index on the right-tree of the traversal, or
* {@code null} if no bucket exists on the left tree for that index
* @return {@code true} if a call to {@link #tree(Node, Node)} should come right after this
* method is called, {@code false} if this consumer does not want to continue the
* traversal deeper for the trees pointed out by these buckets.
* @precondition {@code left != null || right != null}
*/
public abstract boolean bucket(final NodeRef leftParent, final NodeRef rightParent,
final BucketIndex bucketIndex, @Nullable final Bucket left,
@Nullable final Bucket right);
/**
* Called once done with a {@link #bucket}, regardless of the returned value
*/
public abstract void endBucket(NodeRef leftParent, NodeRef rightParent,
final BucketIndex bucketIndex, @Nullable final Bucket left,
@Nullable final Bucket right);
}
public static abstract class AbstractConsumer implements Consumer {
@Override
public boolean feature(@Nullable NodeRef left, @Nullable NodeRef right) {
return true;
}
@Override
public boolean tree(@Nullable NodeRef left, @Nullable NodeRef right) {
return true;
}
@Override
public void endTree(@Nullable NodeRef left, @Nullable NodeRef right) {
}
@Override
public boolean bucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
@Nullable Bucket left, @Nullable Bucket right) {
return true;
}
@Override
public void endBucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
@Nullable Bucket left, @Nullable Bucket right) {
}
}
/**
* Template class for consumer decorators, forwards all event calls to the provided consumer;
* concrete subclasses shall override the event methods of their interest.
*/
public static abstract class ForwardingConsumer implements Consumer {
protected final Consumer delegate;
public ForwardingConsumer(final Consumer delegate) {
this.delegate = delegate;
}
@Override
public boolean feature(NodeRef left, NodeRef right) {
return delegate.feature(left, right);
}
@Override
public boolean tree(NodeRef left, NodeRef right) {
return delegate.tree(left, right);
}
@Override
public void endTree(NodeRef left, NodeRef right) {
delegate.endTree(left, right);
}
@Override
public boolean bucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
Bucket left, Bucket right) {
return delegate.bucket(leftParent, rightParent, bucketIndex, left, right);
}
@Override
public void endBucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
Bucket left, Bucket right) {
delegate.endBucket(leftParent, rightParent, bucketIndex, left, right);
}
}
public static class MaxFeatureDiffsLimiter extends ForwardingConsumer {
private final AtomicLong count;
private final long limit;
public MaxFeatureDiffsLimiter(final Consumer delegate, final long limit) {
super(delegate);
this.limit = limit;
this.count = new AtomicLong();
}
@Override
public boolean feature(NodeRef left, NodeRef right) {
if (count.incrementAndGet() > limit) {
return false;
}
return super.feature(left, right);
}
}
public static class FilteringConsumer extends ForwardingConsumer {
private final Predicate<Bounded> predicate;
public FilteringConsumer(final Consumer delegate, final Predicate<Bounded> predicate) {
super(delegate);
this.predicate = predicate;
}
@Override
public boolean feature(NodeRef left, NodeRef right) {
if (predicate.apply(left) || predicate.apply(right)) {
super.feature(left, right);
}
return true;
}
@Override
public boolean tree(NodeRef left, NodeRef right) {
if (predicate.apply(left) || predicate.apply(right)) {
return super.tree(left, right);
}
return false;
}
@Override
public void endTree(NodeRef left, NodeRef right) {
if (predicate.apply(left) || predicate.apply(right)) {
super.endTree(left, right);
}
}
@Override
public boolean bucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
Bucket left, Bucket right) {
if (predicate.apply(left) || predicate.apply(right)) {
return super.bucket(leftParent, rightParent, bucketIndex, left, right);
}
return false;
}
@Override
public void endBucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
Bucket left, Bucket right) {
if (predicate.apply(left) || predicate.apply(right)) {
super.endBucket(leftParent, rightParent, bucketIndex, left, right);
}
}
}
private static final class CancellableConsumer extends ForwardingConsumer {
private final AtomicBoolean cancel = new AtomicBoolean();
public CancellableConsumer(Consumer delegate) {
super(delegate);
}
private void abortTraversal() {
this.cancel.set(true);
}
public boolean isCancelled() {
return this.cancel.get();
}
@Override
public boolean feature(NodeRef left, NodeRef right) {
boolean continuteTraversal = !isCancelled() && delegate.feature(left, right);
if (!continuteTraversal) {
abortTraversal();
}
return continuteTraversal;
}
@Override
public boolean tree(NodeRef left, NodeRef right) {
return !isCancelled() && delegate.tree(left, right);
}
@Override
public boolean bucket(NodeRef leftParent, NodeRef rightParent, BucketIndex bucketIndex,
Bucket left, Bucket right) {
return !isCancelled()
&& delegate.bucket(leftParent, rightParent, bucketIndex, left, right);
}
}
}
|
import java.util.*;
/* Computes Ext_A^{s,t} (M, Z/2) through a minimal resolution of M. */
/* This seems to work effectively through about t=75, and then becomes prohibitively slow. */
public class ResMain
{
/* upper bound on total degree to compute */
static final int T_CAP = 100;
static final boolean DEBUG = false;
static final boolean MATRIX_DEBUG = false;
static final boolean MICHAEL_MODE = true;
static final Sq P1 = new Sq(new int[] {2});
static final Sq P1B = new Sq(new int[] {2,1});
static final Sq P2 = new Sq(new int[] {4});
static final Sq P3 = new Sq(new int[] {6});
static HashMap<String,CellData> output = new HashMap<String,CellData>();
static String keystr(int s, int t) {
return s+","+t;
}
/* convenience methods for cell data lookup */
static int ngens(int s, int t) {
CellData dat = output.get(keystr(s,t));
if(dat == null) return -1;
return dat.gimg.length;
}
static int nhidden(int s, int t) {
CellData dat = output.get(keystr(s,t));
if(dat == null) return -1;
return dat.hidden;
}
static int[] extra_grading(int s, int t) {
CellData dat = output.get(keystr(s,t));
if(dat == null) return null;
return dat.extra_grading;
}
static boolean[] hiddens(int s, int t) {
CellData dat = output.get(keystr(s,t));
die_if(dat == null, "Data null in ("+s+","+t+")");
return dat.hiddens;
}
static DModSet[] kbasis(int s, int t) {
CellData dat = output.get(keystr(s,t));
die_if(dat == null, "Data null in ("+s+","+t+")");
return dat.kbasis;
}
static DModSet[] gimg(int s, int t) {
CellData dat = output.get(keystr(s,t));
die_if(dat == null, "Data null in ("+s+","+t+")");
return dat.gimg;
}
/* Main minimal-resolution procedure. */
static void resolve(AMod a)
{
for(int t = 0; t <= T_CAP; t++) {
/* first handle the s=0 case: process the input */
/* XXX TMP just using the sphere as input */
CellData dat0 = new CellData();
dat0.gimg = new DModSet[] {};
dat0.hiddens = new boolean[] { false };
dat0.extra_grading = new int[] { 0 };
if(t == 0) {
dat0.kbasis = new DModSet[] {};
} else {
List<DModSet> kbasis0 = new ArrayList<DModSet>();
for(Sq q : Sq.steenrod(t)) {
DModSet ms = new DModSet();
ms.add(new Dot(q,0,0), 1);
kbasis0.add(ms);
}
dat0.kbasis = kbasis0.toArray(new DModSet[] {});
}
System.out.printf("(%2d,%2d): %2d gen, %2d ker\n", 0, t, 0, dat0.kbasis.length);
output.put(keystr(0,t), dat0);
/* now the typical s>0 case */
for(int s = 1; s <= t; s++) {
/* compute the basis for this resolution bidegree */
ArrayList<Dot> basis_l = new ArrayList<Dot>();
for(int gt = s; gt < t; gt++) {
for(int i = 0; i < ngens(s,gt); i++) {
for(Sq q : Sq.steenrod(t - gt)) {
Dot dot = new Dot(q,gt,i,s);
basis_l.add(dot);
}
}
}
DModSet[] okbasis = kbasis(s-1,t);
/* compute what the map does in this basis. this takes maybe 10% of the running time */
DotMatrix mat = new DotMatrix();
if(DEBUG) System.out.printf("(%d,%d) Map:\n",s,t);
Collection<DModSet> easy_ker = new ArrayList<DModSet>();
for(Dot dot : basis_l) {
/* compute the image of this basis vector */
DModSet image = new DModSet();
for(Map.Entry<Dot,Integer> d : gimg(s, dot.t)[dot.idx].entrySet()) {
ModSet<Sq> c = dot.sq.times(d.getKey().sq);
for(Map.Entry<Sq,Integer> q : c.entrySet())
image.add(new Dot(q.getKey(), d.getKey().t, d.getKey().idx, s-1), d.getValue() * q.getValue());
}
if(DEBUG) System.out.println("Image of "+dot+" is "+image);
if(image.isEmpty()) {
easy_ker.add(new DModSet(dot));
} else { /* have to do actual linear algebra ... */
mat.put(dot, image);
}
}
/* OK, do all the heavy lifting = linear algebra. timesuck */
CellData dat = calc_gimg(mat, okbasis, s);
output.put(keystr(s,t), dat);
/* add in the "easy" elements */
DModSet[] newkbasis = Arrays.copyOf(dat.kbasis, dat.kbasis.length + easy_ker.size());
int i = 0;
for(DModSet k : easy_ker)
newkbasis[dat.kbasis.length + (i++)] = k;
dat.kbasis = newkbasis;
/* list generators */
if(dat.gimg.length > 0) {
System.out.println("Generators:");
for(DModSet g : dat.gimg) System.out.println(g);
}
/* compute the novikov filtration */
if(MICHAEL_MODE) {
dat.extra_grading = new int[dat.gimg.length];
for(i = 0; i < dat.gimg.length; i++) {
DModSet g = dat.gimg[i];
int val = -1;
for(Dot d : g.keySet()) {
int oval = d.get_n(s-1);
if(val == -1 || val > oval)
val = oval;
}
if(STDOUT) System.out.println("generator has extra grading "+val);
dat.extra_grading[i] = val;
}
}
/* figure out how many gimg elements are to be "hidden" */
/* XXX TMP */
dat.hiddens = new boolean[dat.gimg.length];
if(MICHAEL_MODE) {
for(int l = 0; l < dat.gimg.length; l++) {
DModSet g = dat.gimg[l];
boolean nonfunky_occured = false;
for(Dot d : g.keySet()) {
System.out.println(d.sq);
if(d.sq.equals(P1) || hiddens(s-1,d.t)[d.idx]) {
} else {
System.out.println("nonfunky occured: "+d.sq);
nonfunky_occured = true;
break;
}
}
if(! nonfunky_occured) {
dat.hiddens[l] = true;
dat.hidden++;
System.out.println("funky element");
}
}
}
print_result(t);
System.out.printf("(%2d,%2d): %2d gen, %2d ker\n", s, t, dat.gimg.length, dat.kbasis.length);
System.out.println();
}
}
}
static Comparator<Dot> buildNovikovComparator(final int s)
{
return new Comparator<Dot>() {
@Override public int compare(Dot a, Dot b) {
return a.get_n(s) - b.get_n(s);
}
};
}
/* Computes a basis complement to the image of mat inside the span of okbasis */
static CellData calc_gimg(DotMatrix mat, DModSet[] okbasis, int s)
{
/* sketch idea:
* do RREF on okbasis.
* apply the same row ops (matrix mult) to mat.
* (should find that the zero lines of okbasis are zero in mat)
* finish RREFing mat from this form
* find the overall complement of mat, excluding these zero lines
* transform back
*
* To do this more efficiently, we basically rref a huge augmentation: bokbasis | mat | id.
*
* The code for computing the kernel of mat was merged into this function (since
* it was basically doing all the same computations), so this function now does
* all of the interesting linear algebra.
*
* Probably the last step of inverting a matrix via RREF could be sped up by keeping better
* track of row operations used in earlier steps...
*/
CellData ret = new CellData();
/* choose an ordering on all keys and values */
Dot[] keys = mat.keySet().toArray(new Dot[] {});
if(s >= 1) Arrays.sort(keys, buildNovikovComparator(s));
DModSet val_set = new DModSet();
for(DModSet ms : okbasis)
val_set.union(ms);
if(DEBUG) System.out.println("val_set: "+val_set);
Dot[] values = val_set.toArray();
if(s >= 2) Arrays.sort(values, buildNovikovComparator(s-1));
System.out.printf("o:%d k:%d v:%d\n", okbasis.length, keys.length, values.length);
/* construct our huge augmented behemoth */
int[][] aug = new int[values.length][okbasis.length + keys.length + values.length];
for(int i = 0; i < values.length; i++) {
for(int j = 0; j < okbasis.length; j++)
aug[i][j] = Math.dmod(okbasis[j].getsafe(values[i]));
for(int j = 0; j < keys.length; j++)
aug[i][j + okbasis.length] = Math.dmod(mat.get(keys[j]).getsafe(values[i]));
for(int j = 0; j < values.length; j++)
aug[i][j + okbasis.length + keys.length] = (i == j ? 1 : 0);
}
Matrices.printMatrix("aug", aug);
/* rref it */
int l1 = Matrices.rref(aug, keys.length + values.length).length;
Matrices.printMatrix("rref(aug)", aug);
/* extract mat | id */
int[][] bmatrr = new int[values.length][keys.length + values.length];
for(int i = 0; i < values.length; i++)
for(int j = 0; j < keys.length + values.length; j++)
bmatrr[i][j] = aug[i][j + okbasis.length];
Matrices.printMatrix("bmatrr", bmatrr);
/* rref it some more */
int[] bmatrr_leads = Matrices.rref(bmatrr, values.length);
int l2 = bmatrr_leads.length;
Matrices.printMatrix("rref(bmatrr)", bmatrr);
if(DEBUG) System.out.printf("l1: %2d l2: %2d\n", l1, l2);
/* read out the kernel */
List<DModSet> ker = new ArrayList<DModSet>();
int idx = 0;
for(int j = 0; j < keys.length; j++) {
/* keep an eye out for leading ones and skip them */
if(idx < bmatrr_leads.length && bmatrr_leads[idx] == j) {
idx++;
continue;
}
/* not a leading column, so we obtain a kernel element */
DModSet ms = new DModSet();
ms.add(keys[j], 1);
for(int i = 0; i < values.length; i++) {
if(bmatrr[i][j] != 0) {
ResMain.die_if(i >= bmatrr_leads.length, "bad rref: no leading one");
ms.add(keys[bmatrr_leads[i]], -bmatrr[i][j]);
}
}
ker.add(ms);
}
ret.kbasis = ker.toArray(new DModSet[]{});
if(ResMain.DEBUG && ker.size() != 0) {
System.out.println("Kernel:");
for(DModSet dm : ret.kbasis)
System.out.println(dm);
}
/* extract and invert (via rref, tracking only the relevant part) the row transform matrix */
int[][] transf = new int[values.length][2 * values.length];
for(int i = 0; i < values.length; i++) {
for(int j = 0; j < values.length; j++)
transf[i][j] = bmatrr[i][j + keys.length];
for(int j = 0; j < l1 - l2; j++)
transf[i][j + values.length] = (i == j + l2 ? 1 : 0);
}
Matrices.printMatrix("transf", transf);
Matrices.rref(transf, values.length);
Matrices.printMatrix("rref(transf)", transf);
/* read off the output */
ret.gimg = new DModSet[l1 - l2];
for(int j = 0; j < l1 - l2; j++) {
DModSet out = new DModSet();
for(int i = 0; i < values.length; i++)
out.add(values[i], transf[i][j + values.length]);
ret.gimg[j] = out;
}
return ret;
}
static void print_result(int s_max)
{
for(int s = s_max; s >= 0; s
for(int t = s; ; t++) {
int ng = ngens(s,t);
if(ng < 0) break;
int n = ng - nhidden(s,t); /* TMP XXX */
if(n > 0)
System.out.printf("%2d ", n);
else if(ng > 0)
System.out.print(" ` ");
else
System.out.print(" ");
}
System.out.println("
}
}
static void die_if(boolean test, String fail)
{
if(test) {
System.err.println(fail);
Thread.dumpStack();
System.err.println("Failing.");
System.exit(1);
}
}
public static void main(String[] args)
{
/* tests */
/* init */
/* make the sphere A-module */
/* resolve */
resolve(null); /* TMP */
/* print */
System.out.println("Conclusion:");
print_result(T_CAP);
}
}
class CellData
{
DModSet[] gimg; /* images of generators as dot-sums in bidegree s-1,t*/
DModSet[] kbasis; /* kernel basis dot-sums in bidegree s,t */
boolean[] hiddens;
int hidden = 0;
int[] extra_grading;
CellData() { }
CellData(DModSet[] g, DModSet[] k) {
gimg = g;
kbasis = k;
}
}
class Dot
{
/* kernel basis vector */
Sq sq;
int t;
int idx;
int s_hint = -1;
String id_cache = null;
int n_cache = -1;
Dot(Sq _sq, int _t, int _idx) {
sq = _sq; t = _t; idx = _idx;
}
Dot(Sq _sq, int _t, int _idx, int _s) {
this(_sq,_t,_idx);
s_hint = _s;
}
public int get_n(int s)
{
if(n_cache != -1)
return n_cache;
int n = ResMain.extra_grading(s,t)[idx];
boolean found_beta = false;
for(int pow : sq.q)
if((pow % ResMath.P) != 0)
found_beta = true;
if(ResMain.DEBUG) System.out.printf("nov-grading %d, square %s, beta %s\n", n, sq.toString(), found_beta ? "true" : "false");
if(! found_beta)
n++;
n_cache = n;
return n;
}
public int hashCode()
{
int hash = sq.hashCode();
hash *= 27863521;
hash ^= t;
hash *= 27863521;
hash ^= idx;
return hash;
}
public String toString()
{
if(id_cache == null) {
id_cache = sq.toString() + "(" + t + ";" + idx + ")";
if(s_hint != -1)
id_cache += "(n=" + get_n(s_hint) + ")";
}
return id_cache;
}
public boolean equals(Object o)
{
return o.hashCode() == hashCode();
}
}
class Math
{
// static final int P = 3;
static final int P = 2;
// static final int[] inverse = { 0, 1, 3, 2, 4 }; /* multiplicative inverses mod P */
static final int[] inverse = { 0, 1, 2 }; /* multiplicative inverses mod P */
static boolean binom_2(int a, int b)
{
return ((~a) & b) == 0;
}
static Map<String,Integer> binom_cache = new HashMap<String,Integer>();
static String binom_cache_str(int a, int b) { return a+"/"+b; }
static int binom_p(int a, int b)
{
String s = binom_cache_str(a,b);
Integer i = binom_cache.get(s);
if(i != null) return i;
int ret;
if(a < 0 || b < 0 || b > a)
ret = 0;
else if(a == 0)
ret = 1;
else ret = dmod(binom_p(a-1,b) + binom_p(a-1,b-1));
binom_cache.put(s,ret);
return ret;
}
static int dmod(int n)
{
return (n + (P << 8)) % P;
}
}
class Sq
{
int[] q; /* Indices of the power operations.
Mod 2, i indicates Sq^i.
Mod p>2, 2k(p-1) indicates P^i, 2k(p-1)+1 indicates B P^i. */
public Sq(int[] qq) { q = qq; }
public ModSet<Sq> times(Sq o)
{
int[] ret = new int[q.length + o.q.length];
for(int i = 0; i < q.length; i++)
ret[i] = q[i];
for(int i = 0; i < o.q.length; i++)
ret[q.length + i] = o.q[i];
if(Math.P == 2 && !ResMain.MICHAEL_MODE)
return new Sq(ret).resolve_2();
else
return new Sq(ret).resolve_p();
}
// private static Map<String,ModSet<Sq>> resolve_cache = new HashMap<String,ModSet<Sq>>();
private ModSet<Sq> resolve_2()
{
ModSet<Sq> ret;
// String key = toString();
// ret = resolve_cache.get(key);
// if(ret != null)
// return ret;
ret = new ModSet<Sq>();
for(int i = q.length - 2; i >= 0; i
int a = q[i];
int b = q[i+1];
if(a >= 2 * b)
continue;
/* apply Adem relation */
for(int c = 0; c <= a/2; c++) {
if(! Math.binom_2(b - c - 1, a - 2*c))
continue;
int[] t;
if(c == 0) {
t = Arrays.copyOf(q, q.length - 1);
for(int k = i+2; k < q.length; k++)
t[k-1] = q[k];
t[i] = a+b-c;
} else {
t = Arrays.copyOf(q, q.length);
t[i] = a+b-c;
t[i+1] = c;
}
/* recurse */
for(Map.Entry<Sq,Integer> sub : new Sq(t).resolve_2().entrySet())
ret.add(sub.getKey(), sub.getValue());
}
// resolve_cache.put(key, ret);
return ret;
}
/* all clear */
ret.add(this, 1);
// resolve_cache.put(key, ret);
return ret;
}
private ModSet<Sq> resolve_p()
{
ModSet<Sq> ret;
// String key = toString();
// ModSet<Sq> ret = resolve_cache.get(key);
// if(ret != null)
// return ret;
ret = new ModSet<Sq>();
int Q = 2 * (Math.P - 1); /* convenience */
for(int i = q.length - 2; i >= 0; i
int x = q[i];
int y = q[i+1];
if(x >= Math.P * y)
continue;
/* apply Adem relation */
int a = x / Q;
int b = y / Q;
int rx = x % Q;
int ry = y % Q;
for(int c = 0; c <= a/Math.P; c++) {
int sign = 1 - 2 * ((a+c) % 2);
// System.out.printf("adem: x=%d y=%d a=%d b=%d sign=%d\n", x, y, a, b, sign);
if(rx == 0 && ry == 0)
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P), (a+b-c)*Q, c*Q, i, ret);
else if(rx == 1 && ry == 0)
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P), (a+b-c)*Q+1, c*Q, i, ret);
else if(rx == 0 && ry == 1) {
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c),a-c*Math.P), (a+b-c)*Q+1, c*Q, i, ret);
resolve_p_add_term(-sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P-1), (a+b-c)*Q, c*Q+1, i, ret);
}
else if(rx == 1 && ry == 1)
resolve_p_add_term(-sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P-1), (a+b-c)*Q+1, c*Q+1, i, ret);
else ResMain.die_if(true, "Bad Adem case.");
}
// resolve_cache.put(key, ret);
return ret;
}
/* all clear */
ret.add(this, 1);
// resolve_cache.put(key, ret);
return ret;
}
private void resolve_p_add_term(int coeff, int a, int b, int i, ModSet<Sq> ret)
{
// System.out.printf("adem_term: coeff=%d a=%d b=%d\n", coeff, a, b);
coeff = Math.dmod(coeff);
if(coeff == 0) return; /* save some work... */
int[] t;
if(b == 0) {
t = Arrays.copyOf(q, q.length - 1);
for(int k = i+2; k < q.length; k++)
t[k-1] = q[k];
t[i] = a;
} else {
t = Arrays.copyOf(q, q.length);
t[i] = a;
t[i+1] = b;
}
/* recurse */
for(Map.Entry<Sq,Integer> sub : new Sq(t).resolve_p().entrySet())
ret.add(sub.getKey(), sub.getValue() * coeff);
}
public String toString()
{
if(q.length == 0) return "1";
String s = "";
for(int i : q) s += "Sq"+i;
return s;
}
public int hashCode()
{
int hash = 0;
for(int i : q)
hash = hash * 27863521 + i;
return hash;
}
public boolean equals(Object o)
{
return toString().equals(o.toString());
}
/* The Steenrod algebra. */
public static Iterable<Sq> steenrod(int n)
{
Iterable<int[]> p;
if(Math.P == 2) p = part_2(n,n);
else p = part_p(n,n);
Collection<Sq> ret = new ArrayList<Sq>();
for(int[] q : p)
ret.add(new Sq(q));
return ret;
}
private static Map<String,Iterable<int[]>> part_cache = new HashMap<String,Iterable<int[]>>();
private static String part_cache_keystr(int n, int max) {
return "("+n+"/"+max+"/"+Math.P+")";
}
private static Iterable<int[]> part_2(int n, int max)
{
if(n == 0) { /* the trivial solution */
Collection<int[]> ret = new ArrayList<int[]>();
ret.add(new int[] {});
return ret;
}
if(max == 0) return new ArrayList<int[]>(); /* no solutions */
Iterable<int[]> ret0 = part_cache.get(part_cache_keystr(n,max));
if(ret0 != null) return ret0;
Collection<int[]> ret = new ArrayList<int[]>();
for(int i = (n+1)/2; i <= max; i++) {
for(int[] q0 : part_2(n-i, i/2)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
}
part_cache.put(part_cache_keystr(n,max), ret);
return ret;
}
private static Iterable<int[]> part_p(int n, int max)
{
if(n == 0) { /* the trivial solution */
Collection<int[]> ret = new ArrayList<int[]>();
ret.add(new int[] {});
return ret;
}
if(max == 0) return new ArrayList<int[]>(); /* no solutions */
Iterable<int[]> ret0 = part_cache.get(part_cache_keystr(n,max));
if(ret0 != null) return ret0;
Collection<int[]> ret = new ArrayList<int[]>();
for(int i = 0; i <= max; i += 2 * (Math.P - 1)) { /* XXX i could start higher? */
/* try P^i */
for(int[] q0 : part_p(n-i, i/Math.P)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
/* try BP^i */
if(i+1 > max) break;
for(int[] q0 : part_p(n-(i+1), (i+1)/Math.P)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i+1;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
}
part_cache.put(part_cache_keystr(n,max), ret);
return ret;
}
}
/* A formal F_p-linear combination of things of type T. */
class ModSet<T> extends HashMap<T,Integer>
{
public void add(T d, int mult)
{
int c;
if(containsKey(d)) c = get(d);
else c = 0;
c = Math.dmod(c + mult);
if(c == 0)
remove(d);
else
put(d, c);
}
public int getsafe(T d)
{
Integer i = get(d);
if(i == null)
return 0;
return i;
}
public boolean contains(T d)
{
return (getsafe(d) % Math.P != 0);
}
public void union(ModSet<T> s)
{
for(T d : s.keySet()) {
if(!containsKey(d))
put(d,1);
}
}
public String toString()
{
return toStringDelim(" + ");
}
public String toStringDelim(String delim)
{
if(isEmpty())
return "0";
String s = "";
for(Map.Entry<T,Integer> e : entrySet()) {
if(s.length() != 0)
s += delim;
if(e.getValue() != 1)
s += e.getValue();
s += e.getKey().toString();
}
return s;
}
}
class DModSet extends ModSet<Dot> { /* to work around generic array restrictions */
DModSet() {}
DModSet(Dot d) {
add(d,1);
}
public Dot[] toArray() {
return keySet().toArray(new Dot[] {});
}
}
class Matrices
{
/* row-reduces a matrix (in place).
* Returns an array giving the column position of the leading 1 in each row.
* It should be noted that matrices are assumed to be reduced to lowest
* non-negative residues (mod p), and this operation respects that. */
static int[] rref(int[][] mat, int preserve_right)
{
if(mat.length == 0)
return new int[] {};
int h = mat.length;
int w = mat[0].length;
int good_rows = 0;
int[] leading_cols = new int[h];
for(int j = 0; j < w - preserve_right; j++) {
/* find the first nonzero entry in this column */
int i;
for(i = good_rows; i < h && mat[i][j] == 0; i++);
if(i == h) continue;
/* swap the rows */
int[] row = mat[good_rows];
mat[good_rows] = mat[i];
mat[i] = row;
i = good_rows++;
leading_cols[i] = j;
/* normalize the row */
int inv = Math.inverse[mat[i][j]];
for(int k = h; k < w; k++)
mat[i][k] = (mat[i][k] * inv) % Math.P;
/* clear the rest of the column. this part is cubic-time so we optimize P=2 */
if(Math.P == 2) {
for(int k = 0; k < h; k++) {
if(mat[k][j] == 0) continue;
if(k == i) continue;
for(int l = 0; l < w; l++)
mat[k][l] ^= mat[i][l];
}
} else {
for(int k = 0; k < h; k++) {
if(mat[k][j] == 0) continue;
if(k == i) continue;
int mul = Math.P - mat[k][j];
for(int l = 0; l < w; l++)
mat[k][l] = (mat[k][l] + mat[i][l] * mul) % Math.P;
}
}
}
return Arrays.copyOf(leading_cols, good_rows);
}
static void printMatrix(String name, int[][] mat)
{
if(!ResMain.MATRIX_DEBUG) return;
System.out.print(name + ":");
if(mat.length == 0) {
System.out.println(" <zero lines>");
return;
}
for(int i = 0; i < mat.length; i++) {
System.out.println();
for(int j = 0; j < mat[0].length; j++)
System.out.printf("%2d ", mat[i][j]);
}
System.out.println();
}
}
class DotMatrix extends HashMap<Dot,DModSet>
{
}
class AMod
{
/* TODO encode a general A-module and be able to resolve it */
}
|
package com.sapienter.jbilling.server.user.balance;
import com.sapienter.jbilling.common.Constants;
import com.sapienter.jbilling.server.item.CurrencyBL;
import com.sapienter.jbilling.server.order.db.OrderDAS;
import com.sapienter.jbilling.server.order.event.NewOrderEvent;
import com.sapienter.jbilling.server.order.event.NewQuantityEvent;
import com.sapienter.jbilling.server.order.event.OrderDeletedEvent;
import com.sapienter.jbilling.server.order.event.OrderAddedOnInvoiceEvent;
import com.sapienter.jbilling.server.payment.event.PaymentDeletedEvent;
import com.sapienter.jbilling.server.payment.event.PaymentSuccessfulEvent;
import com.sapienter.jbilling.server.pluggableTask.PluggableTask;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
import com.sapienter.jbilling.server.system.event.Event;
import com.sapienter.jbilling.server.system.event.EventManager;
import com.sapienter.jbilling.server.system.event.task.IInternalEventsTask;
import com.sapienter.jbilling.server.user.db.CustomerDTO;
import com.sapienter.jbilling.server.user.db.UserDAS;
import com.sapienter.jbilling.server.user.db.UserDTO;
import com.sapienter.jbilling.server.user.event.DynamicBalanceChangeEvent;
import com.sapienter.jbilling.server.util.audit.EventLogger;
import java.math.BigDecimal;
import com.sapienter.jbilling.server.util.db.CurrencyDTO;
import org.apache.log4j.Logger;
/**
*
* @author emilc
*/
public class DynamicBalanceManagerTask extends PluggableTask implements IInternalEventsTask {
private static final Logger LOG = Logger.getLogger(DynamicBalanceManagerTask.class);
@SuppressWarnings("unchecked")
private static final Class<Event> events[] = new Class[] {
PaymentSuccessfulEvent.class,
OrderDeletedEvent.class,
NewOrderEvent.class,
PaymentDeletedEvent.class,
OrderAddedOnInvoiceEvent.class,
NewQuantityEvent.class
};
public Class<Event>[] getSubscribedEvents() {
return events;
}
public void process(Event event) throws PluggableTaskException {
updateDynamicBalance(event.getEntityId(), determineUserId(event), determineAmount(event));
}
private BigDecimal determineAmount(Event event) {
if (event instanceof PaymentSuccessfulEvent) {
PaymentSuccessfulEvent payment = (PaymentSuccessfulEvent) event;
// get the amount
BigDecimal amount = payment.getPayment().getAmount();
// check if amount is ZERO
if(amount.equals(BigDecimal.ZERO)) {
LOG.debug("Amount is ZERO "+amount);
return BigDecimal.ZERO;
}
else {
// get currency in which payment was made
CurrencyDTO paymentCurrency = payment.getPayment().getCurrency();
LOG.debug("Payment was made in currency "+paymentCurrency.getSymbol());
// get the user currency
CurrencyDTO userDefaultCurrency = new UserDAS().find(payment.getPayment().getUserId()).getCurrency();
LOG.debug("User's default currency is "+userDefaultCurrency.getSymbol());
// determine currency of user
if(paymentCurrency.getId()!=userDefaultCurrency.getId()) {
// currency is different so convert the amount
return new CurrencyBL().convert(paymentCurrency.getId(), userDefaultCurrency.getId(), amount, payment.getEntityId());
}
else {
LOG.debug("Currencies are same");
return payment.getPayment().getAmount();
}
}
} else if (event instanceof OrderDeletedEvent) {
OrderDeletedEvent order = (OrderDeletedEvent) event;
// get the amount
BigDecimal amount = order.getOrder().getTotal();
if(amount.equals(BigDecimal.ZERO)) {
LOG.debug("Amount is ZERO "+amount);
return BigDecimal.ZERO;
}
CurrencyDTO orderCurrency = order.getOrder().getCurrency();
CurrencyDTO userDefaultCurrency = new UserDAS().find(order.getOrder().getUserId()).getCurrency();
if (order.getOrder().getOrderPeriod().getId() == com.sapienter.jbilling.server.util.Constants.ORDER_PERIOD_ONCE) {
if(orderCurrency.getId() != userDefaultCurrency.getId()) {
// currency is different so convert the amount
return new CurrencyBL().convert(orderCurrency.getId(), userDefaultCurrency.getId(), amount, order.getEntityId());
}
else {
LOG.debug("Currency is same in order");
return order.getOrder().getTotal();
}
} else {
return BigDecimal.ZERO;
}
} else if (event instanceof NewOrderEvent) {
NewOrderEvent order = (NewOrderEvent) event;
// get the amount
BigDecimal amount = order.getOrder().getTotal();
if(amount.equals(BigDecimal.ZERO)) {
LOG.debug("Amount is ZERO in order "+order.getOrder().getId());
return BigDecimal.ZERO;
}
if (order.getOrder().getOrderPeriod().getId() == com.sapienter.jbilling.server.util.Constants.ORDER_PERIOD_ONCE) {
CurrencyDTO orderCurrency = order.getOrder().getCurrency();
CurrencyDTO userDefaultCurrency = new UserDAS().find(order.getOrder().getUserId()).getCurrency();
if(orderCurrency.getId()!=userDefaultCurrency.getId()) {
// currency is different so convert the amount
return new CurrencyBL().convert(orderCurrency.getId(), userDefaultCurrency.getId(), amount, order.getEntityId()).multiply(new BigDecimal(-1));
}
else {
LOG.debug("Currency is same in order");
return order.getOrder().getTotal().multiply(new BigDecimal(-1));
}
} else {
return BigDecimal.ZERO;
}
} else if (event instanceof PaymentDeletedEvent) {
PaymentDeletedEvent payment = (PaymentDeletedEvent) event;
// get the amount
BigDecimal amount = payment.getPayment().getAmount();
// check if amount is ZERO
if(amount.equals(BigDecimal.ZERO)) {
LOG.debug("Amount is ZERO "+amount);
return BigDecimal.ZERO;
}
// get currency in which payment was made
CurrencyDTO paymentCurrency = payment.getPayment().getCurrency();
LOG.debug("Payment was made in currency "+paymentCurrency.getSymbol());
// get the user currency
CurrencyDTO userDefaultCurrency = new UserDAS().find(payment.getPayment().getBaseUser().getUserId()).getCurrency();
LOG.debug("User's default currency is "+userDefaultCurrency.getSymbol());
// determine currency of user
if(paymentCurrency.getId()!= userDefaultCurrency.getId()) {
// currency is different so convert the amount
return new CurrencyBL().convert(paymentCurrency.getId(), userDefaultCurrency.getId(), amount, payment.getEntityId()).multiply(new BigDecimal(-1));
}
else {
LOG.debug("Currencies are same");
return payment.getPayment().getAmount().multiply(new BigDecimal(-1));
}
} else if (event instanceof OrderAddedOnInvoiceEvent) {
LOG.debug("Instance of OrderAddedOnInvoiceEvent");
OrderAddedOnInvoiceEvent orderOnInvoiceEvent = (OrderAddedOnInvoiceEvent) event;
OrderAddedOnInvoiceEvent order = (OrderAddedOnInvoiceEvent) event;
// get the amount
BigDecimal amount = order.getOrder().getTotal();
if(amount.equals(BigDecimal.ZERO)) {
LOG.debug("Amount is ZERO in order "+order.getOrder().getId());
return BigDecimal.ZERO;
}
if (order.getOrder().getOrderPeriod().getId() != com.sapienter.jbilling.server.util.Constants.ORDER_PERIOD_ONCE) {
CurrencyDTO orderCurrency = order.getOrder().getCurrency();
CurrencyDTO userDefaultCurrency = new UserDAS().find(order.getOrder().getUserId()).getCurrency();
if(orderCurrency.getId()!=userDefaultCurrency.getId()) {
// currency is different so convert the amount
return new CurrencyBL().convert(orderCurrency.getId(), userDefaultCurrency.getId(), amount, order.getEntityId()).multiply(new BigDecimal(-1));
}
else {
LOG.debug("Currency is same in order");
return order.getOrder().getTotal().multiply(new BigDecimal(-1));
}
} else {
return BigDecimal.ZERO;
}
} else if (event instanceof NewQuantityEvent) {
NewQuantityEvent nq = (NewQuantityEvent) event;
LOG.debug("Instance of NewQuantityEvent Event");
if (new OrderDAS().find(nq.getOrderId()).getOrderPeriod().getId() ==
com.sapienter.jbilling.server.util.Constants.ORDER_PERIOD_ONCE) {
BigDecimal newTotal, oldTotal;
// new order line, or old one updated?
if (nq.getNewOrderLine() == null) {
// new
oldTotal = BigDecimal.ZERO;
newTotal = nq.getOrderLine().getAmount();
if (nq.getNewQuantity().compareTo(BigDecimal.ZERO) == 0) {
// it is a delete
newTotal = newTotal.multiply(new BigDecimal(-1));
}
} else {
// old
oldTotal = nq.getOrderLine().getAmount();
newTotal = nq.getNewOrderLine().getAmount();
}
LOG.debug("Old order line's item is "+nq.getOrderLine().getItem());
// convert before returning
int oldOrderLineCurrencyId = nq.getOrderLine().getItem().getDefaultPrice().getCurrency().getId();
int newOrderLineCurrencyId = nq.getNewOrderLine().getItem().getDefaultPrice().getCurrency().getId();
LOG.debug("OLD order line currency is "+nq.getOrderLine().getItem().getDefaultPrice().getCurrency().getDescription());
LOG.debug("NEW order line currency is "+nq.getNewOrderLine().getItem().getDefaultPrice().getCurrency().getDescription());
// finding the current user's default currency id from the order
int currentUserCurrencyId = new OrderDAS().find(nq.getOrderId()).getCurrencyId();
// convert oldOrderLineCurrency and newOrderLineCurrency to userDefaultCurrency and then return
oldTotal = new CurrencyBL().convert(oldOrderLineCurrencyId, currentUserCurrencyId, oldTotal, nq.getEntityId());
newTotal = new CurrencyBL().convert(newOrderLineCurrencyId, currentUserCurrencyId, newTotal, nq.getEntityId());
// now return after converting operations
return newTotal.subtract(oldTotal).multiply(new BigDecimal(-1));
} else {
return BigDecimal.ZERO;
}
} else {
LOG.error("Can not determine amount for event " + event);
return null;
}
}
private int determineUserId(Event event) {
if (event instanceof PaymentSuccessfulEvent) {
PaymentSuccessfulEvent payment = (PaymentSuccessfulEvent) event;
return payment.getPayment().getUserId();
} else if (event instanceof OrderDeletedEvent) {
OrderDeletedEvent order = (OrderDeletedEvent) event;
return order.getOrder().getBaseUserByUserId().getId();
} else if (event instanceof NewOrderEvent) {
NewOrderEvent order = (NewOrderEvent) event;
return order.getOrder().getBaseUserByUserId().getId();
} else if (event instanceof PaymentDeletedEvent) {
PaymentDeletedEvent payment = (PaymentDeletedEvent) event;
return payment.getPayment().getBaseUser().getId();
} else if (event instanceof OrderAddedOnInvoiceEvent) {
OrderAddedOnInvoiceEvent order = (OrderAddedOnInvoiceEvent) event;
return order.getOrder().getBaseUserByUserId().getId();
} else if (event instanceof NewQuantityEvent) {
NewQuantityEvent nq = (NewQuantityEvent) event;
return new OrderDAS().find(nq.getOrderId()).getBaseUserByUserId().getId();
} else {
LOG.error("Can not determine user for event " + event);
return 0;
}
}
private void updateDynamicBalance(Integer entityId, Integer userId, BigDecimal amount) {
UserDTO user = new UserDAS().find(userId);
CustomerDTO customer = user.getCustomer();
// get the parent customer that pays, if it exists
if (customer != null) {
while (customer.getParent() != null
&& (customer.getInvoiceChild() == null || customer.getInvoiceChild() == 0)) {
customer = customer.getParent(); // go up one level
}
}
// fail fast condition, no dynamic balance or ammount is zero
if (customer == null
|| customer.getBalanceType() == Constants.BALANCE_NO_DYNAMIC
|| amount.compareTo(BigDecimal.ZERO) == 0) {
LOG.debug("Nothing to update");
return;
}
LOG.debug("Updating dynamic balance for " + amount);
BigDecimal balance = (customer.getDynamicBalance() == null ? BigDecimal.ZERO : customer.getDynamicBalance());
// register the event, before the balance is changed
new EventLogger().auditBySystem(entityId,
customer.getBaseUser().getId(),
com.sapienter.jbilling.server.util.Constants.TABLE_CUSTOMER,
user.getCustomer().getId(),
EventLogger.MODULE_USER_MAINTENANCE,
EventLogger.DYNAMIC_BALANCE_CHANGE,
null,
balance.toString(),
null);
if (customer.getBalanceType() == Constants.BALANCE_CREDIT_LIMIT) {
customer.setDynamicBalance(balance.subtract(amount));
} else if (customer.getBalanceType() == Constants.BALANCE_PRE_PAID) {
customer.setDynamicBalance(balance.add(amount));
} else {
customer.setDynamicBalance(balance);
}
if (!balance.equals(customer.getDynamicBalance())) {
DynamicBalanceChangeEvent event = new DynamicBalanceChangeEvent(user.getEntity().getId(),
user.getUserId(),
customer.getDynamicBalance(), // new
balance); // old
EventManager.process(event);
}
}
}
|
package bisq.desktop.util;
import bisq.desktop.components.AddressTextField;
import bisq.desktop.components.AutoTooltipButton;
import bisq.desktop.components.AutoTooltipCheckBox;
import bisq.desktop.components.AutoTooltipLabel;
import bisq.desktop.components.AutoTooltipRadioButton;
import bisq.desktop.components.AutoTooltipSlideToggleButton;
import bisq.desktop.components.AutocompleteComboBox;
import bisq.desktop.components.BalanceTextField;
import bisq.desktop.components.BisqTextArea;
import bisq.desktop.components.BisqTextField;
import bisq.desktop.components.BsqAddressTextField;
import bisq.desktop.components.BusyAnimation;
import bisq.desktop.components.ExplorerAddressTextField;
import bisq.desktop.components.ExternalHyperlink;
import bisq.desktop.components.FundsTextField;
import bisq.desktop.components.HyperlinkWithIcon;
import bisq.desktop.components.InfoInputTextField;
import bisq.desktop.components.InfoTextField;
import bisq.desktop.components.InputTextField;
import bisq.desktop.components.PasswordTextField;
import bisq.desktop.components.TextFieldWithCopyIcon;
import bisq.desktop.components.TextFieldWithIcon;
import bisq.desktop.components.TitledGroupBg;
import bisq.desktop.components.TxIdTextField;
import bisq.core.locale.Res;
import bisq.common.util.Tuple2;
import bisq.common.util.Tuple3;
import bisq.common.util.Tuple4;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import de.jensd.fx.glyphs.GlyphIcons;
import de.jensd.fx.glyphs.materialdesignicons.utils.MaterialDesignIconFactory;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXTextArea;
import com.jfoenix.controls.JFXToggleButton;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import org.jetbrains.annotations.NotNull;
import static bisq.desktop.util.GUIUtil.getComboBoxButtonCell;
public class FormBuilder {
private static final String MATERIAL_DESIGN_ICONS = "'Material Design Icons'";
// TitledGroupBg
public static TitledGroupBg addTitledGroupBg(GridPane gridPane, int rowIndex, int rowSpan, String title) {
return addTitledGroupBg(gridPane, rowIndex, rowSpan, title, 0);
}
public static TitledGroupBg addTitledGroupBg(GridPane gridPane,
int rowIndex,
int columnIndex,
int rowSpan,
String title) {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, rowSpan, title, 0);
GridPane.setColumnIndex(titledGroupBg, columnIndex);
return titledGroupBg;
}
public static TitledGroupBg addTitledGroupBg(GridPane gridPane,
int rowIndex,
int columnIndex,
int rowSpan,
String title,
double top) {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, rowSpan, title, top);
GridPane.setColumnIndex(titledGroupBg, columnIndex);
return titledGroupBg;
}
public static TitledGroupBg addTitledGroupBg(GridPane gridPane,
int rowIndex,
int rowSpan,
String title,
double top) {
TitledGroupBg titledGroupBg = new TitledGroupBg();
titledGroupBg.setText(title);
titledGroupBg.prefWidthProperty().bind(gridPane.widthProperty());
GridPane.setRowIndex(titledGroupBg, rowIndex);
GridPane.setRowSpan(titledGroupBg, rowSpan);
GridPane.setMargin(titledGroupBg, new Insets(top + 8, -10, -12, -10));
gridPane.getChildren().add(titledGroupBg);
return titledGroupBg;
}
// Label
public static Label addLabel(GridPane gridPane, int rowIndex, String title) {
return addLabel(gridPane, rowIndex, title, 0);
}
public static Label addLabel(GridPane gridPane, int rowIndex, String title, double top) {
Label label = new AutoTooltipLabel(title);
GridPane.setRowIndex(label, rowIndex);
GridPane.setMargin(label, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(label);
return label;
}
// Label + Subtext
public static Tuple3<Label, Label, VBox> addLabelWithSubText(GridPane gridPane,
int rowIndex,
String title,
String description) {
return addLabelWithSubText(gridPane, rowIndex, title, description, 0);
}
public static Tuple3<Label, Label, VBox> addLabelWithSubText(GridPane gridPane,
int rowIndex,
String title,
String description,
double top) {
Label label = new AutoTooltipLabel(title);
Label subText = new AutoTooltipLabel(description);
VBox vBox = new VBox();
vBox.getChildren().setAll(label, subText);
GridPane.setRowIndex(vBox, rowIndex);
GridPane.setMargin(vBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(vBox);
return new Tuple3<>(label, subText, vBox);
}
// Multiline Label
public static Label addMultilineLabel(GridPane gridPane, int rowIndex) {
return addMultilineLabel(gridPane, rowIndex, 0);
}
public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text) {
return addMultilineLabel(gridPane, rowIndex, text, 0);
}
public static Label addMultilineLabel(GridPane gridPane, int rowIndex, double top) {
return addMultilineLabel(gridPane, rowIndex, "", top);
}
public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text, double top) {
return addMultilineLabel(gridPane, rowIndex, text, top, 600);
}
public static Label addMultilineLabel(GridPane gridPane, int rowIndex, String text, double top, double maxWidth) {
Label label = new AutoTooltipLabel(text);
label.setWrapText(true);
label.setMaxWidth(maxWidth);
GridPane.setHalignment(label, HPos.LEFT);
GridPane.setHgrow(label, Priority.ALWAYS);
GridPane.setRowIndex(label, rowIndex);
GridPane.setMargin(label, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(label);
return label;
}
// Label + TextField
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
String title) {
return addTopLabelTextField(gridPane, rowIndex, title, "", -15);
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
int columnIndex,
String title) {
Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, "", -15);
GridPane.setColumnIndex(tuple.third, columnIndex);
return tuple;
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
return addTopLabelTextField(gridPane, rowIndex, title, "", top - 15);
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addTopLabelReadOnlyTextField(gridPane, rowIndex, title, value, 0);
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
String value,
double top) {
Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, value, top - 15);
GridPane.setColumnIndex(tuple.third, columnIndex);
return tuple;
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
double top) {
Tuple3<Label, TextField, VBox> tuple = addTopLabelTextField(gridPane, rowIndex, title, "", top - 15);
GridPane.setColumnIndex(tuple.third, columnIndex);
return tuple;
}
public static Tuple3<Label, TextField, VBox> addTopLabelReadOnlyTextField(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
return addTopLabelTextField(gridPane, rowIndex, title, value, top - 15);
}
public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane, int rowIndex, String title) {
return addTopLabelTextField(gridPane, rowIndex, title, "", 0);
}
public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addTopLabelTextField(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value) {
final Tuple3<Label, TextField, VBox> labelTextFieldVBoxTuple3 = addTopLabelTextField(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE);
GridPane.setColumnIndex(labelTextFieldVBoxTuple3.third, colIndex);
return labelTextFieldVBoxTuple3;
}
public static Tuple3<Label, TextField, VBox> addCompactTopLabelTextField(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
return addTopLabelTextField(gridPane, rowIndex, title, value, top - Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addTopLabelTextField(gridPane, rowIndex, title, value, 0);
}
public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
return addTopLabelTextField(gridPane, rowIndex, title, "", top);
}
public static Tuple3<Label, TextField, VBox> addTopLabelTextField(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
TextField textField = new BisqTextField(value);
textField.setEditable(false);
textField.setFocusTraversable(false);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textField, top);
// TODO not 100% sure if that is a good idea....
//topLabelWithVBox.first.getStyleClass().add("jfx-text-field-top-label");
return new Tuple3<>(topLabelWithVBox.first, textField, topLabelWithVBox.second);
}
public static Tuple2<TextField, Button> addTextFieldWithEditButton(GridPane gridPane, int rowIndex, String title) {
TextField textField = new BisqTextField();
textField.setPromptText(title);
textField.setEditable(false);
textField.setFocusTraversable(false);
textField.setPrefWidth(Layout.INITIAL_WINDOW_WIDTH);
Button button = new AutoTooltipButton("...");
button.setStyle("-fx-min-width: 35px; -fx-pref-height: 20; -fx-padding: 3 3 3 3; -fx-border-insets: 5px;");
button.managedProperty().bind(button.visibleProperty());
VBox vBoxButton = new VBox(button);
vBoxButton.setAlignment(Pos.CENTER);
HBox hBox2 = new HBox(textField, vBoxButton);
Label label = getTopLabel(title);
VBox textFieldVbox = getTopLabelVBox(0);
textFieldVbox.getChildren().addAll(label, hBox2);
gridPane.getChildren().add(textFieldVbox);
GridPane.setRowIndex(textFieldVbox, rowIndex);
GridPane.setMargin(textFieldVbox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
return new Tuple2<>(textField, button);
}
// Confirmation Fields
public static Tuple2<Label, Label> addConfirmationLabelLabel(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
return addConfirmationLabelLabel(gridPane, rowIndex, title1, title2, 0);
}
public static Tuple2<Label, Label> addConfirmationLabelLabel(GridPane gridPane,
int rowIndex,
String title1,
String title2,
double top) {
Label label1 = addLabel(gridPane, rowIndex, title1);
label1.getStyleClass().add("confirmation-label");
Label label2 = addLabel(gridPane, rowIndex, title2);
label2.getStyleClass().add("confirmation-value");
GridPane.setColumnIndex(label2, 1);
GridPane.setMargin(label1, new Insets(top, 0, 0, 0));
GridPane.setHalignment(label1, HPos.LEFT);
GridPane.setMargin(label2, new Insets(top, 0, 0, 0));
return new Tuple2<>(label1, label2);
}
public static Tuple2<Label, TextField> addConfirmationLabelTextField(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
return addConfirmationLabelTextField(gridPane, rowIndex, title1, title2, 0);
}
public static Tuple2<Label, TextField> addConfirmationLabelTextField(GridPane gridPane,
int rowIndex,
String title1,
String title2,
double top) {
Label label1 = addLabel(gridPane, rowIndex, title1);
label1.getStyleClass().add("confirmation-label");
TextField label2 = new BisqTextField(title2);
gridPane.getChildren().add(label2);
label2.getStyleClass().add("confirmation-text-field-as-label");
label2.setEditable(false);
label2.setFocusTraversable(false);
GridPane.setRowIndex(label2, rowIndex);
GridPane.setColumnIndex(label2, 1);
GridPane.setMargin(label1, new Insets(top, 0, 0, 0));
GridPane.setHalignment(label1, HPos.LEFT);
GridPane.setMargin(label2, new Insets(top, 0, 0, 0));
return new Tuple2<>(label1, label2);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addConfirmationLabelLabelWithCopyIcon(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
Label label1 = addLabel(gridPane, rowIndex, title1);
label1.getStyleClass().add("confirmation-label");
TextFieldWithCopyIcon label2 = new TextFieldWithCopyIcon("confirmation-value");
label2.setText(title2);
GridPane.setRowIndex(label2, rowIndex);
gridPane.getChildren().add(label2);
GridPane.setColumnIndex(label2, 1);
GridPane.setHalignment(label1, HPos.LEFT);
return new Tuple2<>(label1, label2);
}
public static Tuple2<Label, TextArea> addConfirmationLabelTextArea(GridPane gridPane,
int rowIndex,
String title1,
String title2,
double top) {
Label label = addLabel(gridPane, rowIndex, title1);
label.getStyleClass().add("confirmation-label");
TextArea textArea = addTextArea(gridPane, rowIndex, title2);
((JFXTextArea) textArea).setLabelFloat(false);
GridPane.setColumnIndex(textArea, 1);
GridPane.setMargin(label, new Insets(top, 0, 0, 0));
GridPane.setHalignment(label, HPos.LEFT);
GridPane.setMargin(textArea, new Insets(top, 0, 0, 0));
return new Tuple2<>(label, textArea);
}
// Label + TextFieldWithIcon
public static Tuple2<Label, TextFieldWithIcon> addTopLabelTextFieldWithIcon(GridPane gridPane,
int rowIndex,
String title,
double top) {
return addTopLabelTextFieldWithIcon(gridPane, rowIndex, 0, title, top);
}
public static Tuple2<Label, TextFieldWithIcon> addTopLabelTextFieldWithIcon(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
double top) {
TextFieldWithIcon textFieldWithIcon = new TextFieldWithIcon();
textFieldWithIcon.setFocusTraversable(false);
return new Tuple2<>(addTopLabelWithVBox(gridPane, rowIndex, columnIndex, title, textFieldWithIcon, top).first, textFieldWithIcon);
}
// HyperlinkWithIcon
public static HyperlinkWithIcon addHyperlinkWithIcon(GridPane gridPane, int rowIndex, String title, String url) {
return addHyperlinkWithIcon(gridPane, rowIndex, title, url, 0);
}
public static HyperlinkWithIcon addHyperlinkWithIcon(GridPane gridPane,
int rowIndex,
String title,
String url,
double top) {
HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(title);
hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url));
GridPane.setRowIndex(hyperlinkWithIcon, rowIndex);
GridPane.setColumnIndex(hyperlinkWithIcon, 0);
GridPane.setMargin(hyperlinkWithIcon, new Insets(top, 0, 0, 0));
GridPane.setHalignment(hyperlinkWithIcon, HPos.LEFT);
gridPane.getChildren().add(hyperlinkWithIcon);
return hyperlinkWithIcon;
}
// Label + HyperlinkWithIcon
public static Tuple2<Label, HyperlinkWithIcon> addLabelHyperlinkWithIcon(GridPane gridPane,
int rowIndex,
String labelTitle,
String title,
String url) {
return addLabelHyperlinkWithIcon(gridPane, rowIndex, labelTitle, title, url, 0);
}
public static Tuple2<Label, HyperlinkWithIcon> addLabelHyperlinkWithIcon(GridPane gridPane,
int rowIndex,
String labelTitle,
String title,
String url,
double top) {
Label label = addLabel(gridPane, rowIndex, labelTitle, top);
HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(title);
hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url));
GridPane.setRowIndex(hyperlinkWithIcon, rowIndex);
GridPane.setMargin(hyperlinkWithIcon, new Insets(top, 0, 0, -4));
gridPane.getChildren().add(hyperlinkWithIcon);
return new Tuple2<>(label, hyperlinkWithIcon);
}
public static Tuple3<Label, HyperlinkWithIcon, VBox> addTopLabelHyperlinkWithIcon(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
String value,
String url,
double top) {
Tuple3<Label, HyperlinkWithIcon, VBox> tuple = addTopLabelHyperlinkWithIcon(gridPane,
rowIndex,
title,
value,
url,
top);
GridPane.setColumnIndex(tuple.third, columnIndex);
return tuple;
}
public static Tuple3<Label, HyperlinkWithIcon, VBox> addTopLabelHyperlinkWithIcon(GridPane gridPane,
int rowIndex,
String title,
String value,
String url,
double top) {
HyperlinkWithIcon hyperlinkWithIcon = new ExternalHyperlink(value);
hyperlinkWithIcon.setOnAction(e -> GUIUtil.openWebPage(url));
hyperlinkWithIcon.getStyleClass().add("hyperlink-with-icon");
GridPane.setRowIndex(hyperlinkWithIcon, rowIndex);
Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hyperlinkWithIcon, top - 15);
return new Tuple3<>(topLabelWithVBox.first, hyperlinkWithIcon, topLabelWithVBox.second);
}
// TextArea
public static TextArea addTextArea(GridPane gridPane, int rowIndex, String prompt) {
return addTextArea(gridPane, rowIndex, prompt, 0);
}
public static TextArea addTextArea(GridPane gridPane, int rowIndex, String prompt, double top) {
JFXTextArea textArea = new BisqTextArea();
textArea.setPromptText(prompt);
textArea.setLabelFloat(true);
textArea.setWrapText(true);
GridPane.setRowIndex(textArea, rowIndex);
GridPane.setColumnIndex(textArea, 0);
GridPane.setMargin(textArea, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(textArea);
return textArea;
}
// Label + TextArea
public static Tuple2<Label, TextArea> addCompactTopLabelTextArea(GridPane gridPane,
int rowIndex,
String title,
String prompt) {
return addTopLabelTextArea(gridPane, rowIndex, title, prompt, -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextArea> addCompactTopLabelTextArea(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String prompt) {
return addTopLabelTextArea(gridPane, rowIndex, colIndex, title, prompt, -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane,
int rowIndex,
String title,
String prompt) {
return addTopLabelTextArea(gridPane, rowIndex, title, prompt, 0);
}
public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String prompt) {
return addTopLabelTextArea(gridPane, rowIndex, colIndex, title, prompt, 0);
}
public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane,
int rowIndex,
String title,
String prompt,
double top) {
return addTopLabelTextArea(gridPane, rowIndex, 0, title, prompt, top);
}
public static Tuple2<Label, TextArea> addTopLabelTextArea(GridPane gridPane, int rowIndex, int colIndex,
String title, String prompt, double top) {
TextArea textArea = new BisqTextArea();
textArea.setPromptText(prompt);
textArea.setWrapText(true);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textArea, top);
GridPane.setColumnIndex(topLabelWithVBox.second, colIndex);
return new Tuple2<>(topLabelWithVBox.first, textArea);
}
// Label + DatePicker
public static Tuple2<Label, DatePicker> addTopLabelDatePicker(GridPane gridPane,
int rowIndex,
String title,
double top) {
return addTopLabelDatePicker(gridPane, rowIndex, 0, title, top);
}
public static Tuple2<Label, DatePicker> addTopLabelDatePicker(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
double top) {
DatePicker datePicker = new JFXDatePicker();
Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, columnIndex, title, datePicker, top);
return new Tuple2<>(topLabelWithVBox.first, datePicker);
}
// 2 DatePickers
public static Tuple2<DatePicker, DatePicker> add2TopLabelDatePicker(GridPane gridPane,
int rowIndex,
int columnIndex,
String title1,
String title2,
double top) {
DatePicker datePicker1 = new JFXDatePicker();
Tuple2<Label, VBox> topLabelWithVBox1 = getTopLabelWithVBox(title1, datePicker1);
VBox vBox1 = topLabelWithVBox1.second;
DatePicker datePicker2 = new JFXDatePicker();
Tuple2<Label, VBox> topLabelWithVBox2 = getTopLabelWithVBox(title2, datePicker2);
VBox vBox2 = topLabelWithVBox2.second;
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(spacer, vBox1, vBox2);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, columnIndex);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple2<>(datePicker1, datePicker2);
}
// Label + TxIdTextField
@SuppressWarnings("UnusedReturnValue")
public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addLabelTxIdTextField(gridPane, rowIndex, title, value, 0);
}
public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
Label label = addLabel(gridPane, rowIndex, title, top);
label.getStyleClass().add("confirmation-label");
GridPane.setHalignment(label, HPos.LEFT);
TxIdTextField txTextField = new TxIdTextField();
txTextField.setup(value);
GridPane.setRowIndex(txTextField, rowIndex);
GridPane.setColumnIndex(txTextField, 1);
gridPane.getChildren().add(txTextField);
return new Tuple2<>(label, txTextField);
}
// Label + ExplorerAddressTextField
public static void addLabelExplorerAddressTextField(GridPane gridPane,
int rowIndex,
String title,
String address) {
Label label = addLabel(gridPane, rowIndex, title, 0);
label.getStyleClass().add("confirmation-label");
GridPane.setHalignment(label, HPos.LEFT);
ExplorerAddressTextField addressTextField = new ExplorerAddressTextField();
addressTextField.setup(address);
GridPane.setRowIndex(addressTextField, rowIndex);
GridPane.setColumnIndex(addressTextField, 1);
gridPane.getChildren().add(addressTextField);
}
// Label + InputTextField
public static InputTextField addInputTextField(GridPane gridPane, int rowIndex, String title) {
return addInputTextField(gridPane, rowIndex, title, 0);
}
public static InputTextField addInputTextField(GridPane gridPane, int rowIndex, String title, double top) {
InputTextField inputTextField = new InputTextField();
inputTextField.setLabelFloat(true);
inputTextField.setPromptText(title);
GridPane.setRowIndex(inputTextField, rowIndex);
GridPane.setColumnIndex(inputTextField, 0);
GridPane.setMargin(inputTextField, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(inputTextField);
return inputTextField;
}
// Label + InputTextField
public static Tuple2<Label, InputTextField> addTopLabelInputTextField(GridPane gridPane,
int rowIndex,
String title) {
return addTopLabelInputTextField(gridPane, rowIndex, title, 0);
}
public static Tuple2<Label, InputTextField> addTopLabelInputTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
final Tuple3<Label, InputTextField, VBox> topLabelWithVBox = addTopLabelInputTextFieldWithVBox(gridPane, rowIndex, title, top);
return new Tuple2<>(topLabelWithVBox.first, topLabelWithVBox.second);
}
public static Tuple3<Label, InputTextField, VBox> addTopLabelInputTextFieldWithVBox(GridPane gridPane,
int rowIndex,
String title,
double top) {
InputTextField inputTextField = new InputTextField();
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, top);
return new Tuple3<>(topLabelWithVBox.first, inputTextField, topLabelWithVBox.second);
}
// Label + InfoInputTextField
public static Tuple2<Label, InfoInputTextField> addTopLabelInfoInputTextField(GridPane gridPane,
int rowIndex,
String title) {
return addTopLabelInfoInputTextField(gridPane, rowIndex, title, 0);
}
public static Tuple2<Label, InfoInputTextField> addTopLabelInfoInputTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
InfoInputTextField inputTextField = new InfoInputTextField();
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, top);
return new Tuple2<>(topLabelWithVBox.first, inputTextField);
}
// PasswordField
public static PasswordTextField addPasswordTextField(GridPane gridPane, int rowIndex, String title) {
return addPasswordTextField(gridPane, rowIndex, title, 0);
}
public static PasswordTextField addPasswordTextField(GridPane gridPane, int rowIndex, String title, double top) {
PasswordTextField passwordField = new PasswordTextField();
passwordField.setPromptText(title);
GridPane.setRowIndex(passwordField, rowIndex);
GridPane.setColumnIndex(passwordField, 0);
GridPane.setColumnSpan(passwordField, 2);
GridPane.setMargin(passwordField, new Insets(top + 10, 0, 20, 0));
gridPane.getChildren().add(passwordField);
return passwordField;
}
// Label + InputTextField + CheckBox
public static Tuple3<Label, InputTextField, ToggleButton> addTopLabelInputTextFieldSlideToggleButton(GridPane gridPane,
int rowIndex,
String title,
String toggleButtonTitle) {
InputTextField inputTextField = new InputTextField();
ToggleButton toggleButton = new JFXToggleButton();
toggleButton.setText(toggleButtonTitle);
VBox.setMargin(toggleButton, new Insets(4, 0, 0, 0));
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, 0);
topLabelWithVBox.second.getChildren().add(toggleButton);
return new Tuple3<>(topLabelWithVBox.first, inputTextField, toggleButton);
}
public static Tuple3<Label, InputTextField, ToggleButton> addTopLabelInputTextFieldSlideToggleButtonRight(GridPane gridPane,
int rowIndex,
String title,
String toggleButtonTitle) {
InputTextField inputTextField = new InputTextField();
Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, inputTextField, 0);
ToggleButton toggleButton = new JFXToggleButton();
toggleButton.setText(toggleButtonTitle);
HBox hBox = new HBox();
hBox.getChildren().addAll(topLabelWithVBox.second, toggleButton);
HBox.setMargin(toggleButton, new Insets(9, 0, 0, 0));
gridPane.add(hBox, 0, rowIndex);
GridPane.setMargin(hBox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
return new Tuple3<>(topLabelWithVBox.first, inputTextField, toggleButton);
}
// Label + InputTextField + Button
public static Tuple3<Label, InputTextField, Button> addTopLabelInputTextFieldButton(GridPane gridPane,
int rowIndex,
String title,
String buttonTitle) {
InputTextField inputTextField = new InputTextField();
Button button = new AutoTooltipButton(buttonTitle);
button.setDefaultButton(true);
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(inputTextField, button);
HBox.setHgrow(inputTextField, Priority.ALWAYS);
final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, 0);
return new Tuple3<>(labelVBoxTuple2.first, inputTextField, button);
}
// Label + TextField + Button
public static Tuple3<Label, TextField, Button> addTopLabelTextFieldButton(GridPane gridPane,
int rowIndex,
String title,
String buttonTitle) {
return addTopLabelTextFieldButton(gridPane, rowIndex, title, buttonTitle, 0);
}
public static Tuple3<Label, TextField, Button> addTopLabelTextFieldButton(GridPane gridPane,
int rowIndex,
String title,
String buttonTitle,
double top) {
TextField textField = new BisqTextField();
textField.setEditable(false);
textField.setMouseTransparent(true);
textField.setFocusTraversable(false);
Button button = new AutoTooltipButton(buttonTitle);
button.setDefaultButton(true);
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(textField, button);
HBox.setHgrow(textField, Priority.ALWAYS);
final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top);
return new Tuple3<>(labelVBoxTuple2.first, textField, button);
}
// Label + InputTextField + Label + InputTextField
public static Tuple2<InputTextField, InputTextField> addInputTextFieldInputTextField(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
InputTextField inputTextField1 = new InputTextField();
inputTextField1.setPromptText(title1);
inputTextField1.setLabelFloat(true);
InputTextField inputTextField2 = new InputTextField();
inputTextField2.setLabelFloat(true);
inputTextField2.setPromptText(title2);
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(inputTextField1, inputTextField2);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, 0);
GridPane.setMargin(hBox, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple2<>(inputTextField1, inputTextField2);
}
// Label + TextField + Label + TextField
public static Tuple4<Label, TextField, Label, TextField> addCompactTopLabelTextFieldTopLabelTextField(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
TextField textField1 = new BisqTextField();
textField1.setEditable(false);
textField1.setMouseTransparent(true);
textField1.setFocusTraversable(false);
final Tuple2<Label, VBox> topLabelWithVBox1 = getTopLabelWithVBox(title1, textField1);
TextField textField2 = new BisqTextField();
textField2.setEditable(false);
textField2.setMouseTransparent(true);
textField2.setFocusTraversable(false);
final Tuple2<Label, VBox> topLabelWithVBox2 = getTopLabelWithVBox(title2, textField2);
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(topLabelWithVBox1.second, topLabelWithVBox2.second);
GridPane.setRowIndex(hBox, rowIndex);
gridPane.getChildren().add(hBox);
return new Tuple4<>(topLabelWithVBox1.first, textField1, topLabelWithVBox2.first, textField2);
}
// Button + CheckBox
public static Tuple2<Button, CheckBox> addButtonCheckBox(GridPane gridPane,
int rowIndex,
String buttonTitle,
String checkBoxTitle) {
return addButtonCheckBox(gridPane, rowIndex, buttonTitle, checkBoxTitle, 0);
}
public static Tuple2<Button, CheckBox> addButtonCheckBox(GridPane gridPane,
int rowIndex,
String buttonTitle,
String checkBoxTitle,
double top) {
final Tuple3<Button, CheckBox, HBox> tuple = addButtonCheckBoxWithBox(gridPane, rowIndex, buttonTitle, checkBoxTitle, top);
return new Tuple2<>(tuple.first, tuple.second);
}
public static Tuple3<Button, CheckBox, HBox> addButtonCheckBoxWithBox(GridPane gridPane,
int rowIndex,
String buttonTitle,
String checkBoxTitle,
double top) {
Button button = new AutoTooltipButton(buttonTitle);
CheckBox checkBox = new AutoTooltipCheckBox(checkBoxTitle);
HBox hBox = new HBox(20);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(button, checkBox);
GridPane.setRowIndex(hBox, rowIndex);
hBox.setPadding(new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(button, checkBox, hBox);
}
// CheckBox
public static CheckBox addCheckBox(GridPane gridPane, int rowIndex, String checkBoxTitle) {
return addCheckBox(gridPane, rowIndex, checkBoxTitle, 0);
}
public static CheckBox addCheckBox(GridPane gridPane, int rowIndex, String checkBoxTitle, double top) {
return addCheckBox(gridPane, rowIndex, 0, checkBoxTitle, top);
}
public static CheckBox addCheckBox(GridPane gridPane,
int rowIndex,
int colIndex,
String checkBoxTitle,
double top) {
CheckBox checkBox = new AutoTooltipCheckBox(checkBoxTitle);
GridPane.setMargin(checkBox, new Insets(top, 0, 0, 0));
GridPane.setRowIndex(checkBox, rowIndex);
GridPane.setColumnIndex(checkBox, colIndex);
gridPane.getChildren().add(checkBox);
return checkBox;
}
// RadioButton
public static RadioButton addRadioButton(GridPane gridPane, int rowIndex, ToggleGroup toggleGroup, String title) {
RadioButton radioButton = new AutoTooltipRadioButton(title);
radioButton.setToggleGroup(toggleGroup);
GridPane.setRowIndex(radioButton, rowIndex);
gridPane.getChildren().add(radioButton);
return radioButton;
}
// Label + RadioButton + RadioButton
public static Tuple3<Label, RadioButton, RadioButton> addTopLabelRadioButtonRadioButton(GridPane gridPane,
int rowIndex,
ToggleGroup toggleGroup,
String title,
String radioButtonTitle1,
String radioButtonTitle2,
double top) {
RadioButton radioButton1 = new AutoTooltipRadioButton(radioButtonTitle1);
radioButton1.setToggleGroup(toggleGroup);
radioButton1.setPadding(new Insets(6, 0, 0, 0));
RadioButton radioButton2 = new AutoTooltipRadioButton(radioButtonTitle2);
radioButton2.setToggleGroup(toggleGroup);
radioButton2.setPadding(new Insets(6, 0, 0, 0));
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(radioButton1, radioButton2);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top);
return new Tuple3<>(topLabelWithVBox.first, radioButton1, radioButton2);
}
// Label + TextField + RadioButton + RadioButton
public static Tuple4<Label, TextField, RadioButton, RadioButton> addTopLabelTextFieldRadioButtonRadioButton(GridPane gridPane,
int rowIndex,
ToggleGroup toggleGroup,
String title,
String textFieldTitle,
String radioButtonTitle1,
String radioButtonTitle2,
double top) {
TextField textField = new BisqTextField();
textField.setPromptText(textFieldTitle);
RadioButton radioButton1 = new AutoTooltipRadioButton(radioButtonTitle1);
radioButton1.setToggleGroup(toggleGroup);
radioButton1.setPadding(new Insets(6, 0, 0, 0));
RadioButton radioButton2 = new AutoTooltipRadioButton(radioButtonTitle2);
radioButton2.setToggleGroup(toggleGroup);
radioButton2.setPadding(new Insets(6, 0, 0, 0));
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.getChildren().addAll(textField, radioButton1, radioButton2);
final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top);
return new Tuple4<>(labelVBoxTuple2.first, textField, radioButton1, radioButton2);
}
// Label + CheckBox
public static CheckBox addLabelCheckBox(GridPane gridPane, int rowIndex, String title) {
return addLabelCheckBox(gridPane, rowIndex, title, 0);
}
public static CheckBox addLabelCheckBox(GridPane gridPane, int rowIndex, String title, double top) {
CheckBox checkBox = new AutoTooltipCheckBox(title);
GridPane.setRowIndex(checkBox, rowIndex);
GridPane.setColumnIndex(checkBox, 0);
GridPane.setMargin(checkBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(checkBox);
return checkBox;
}
// SlideToggleButton
public static ToggleButton addSlideToggleButton(GridPane gridPane, int rowIndex, String title) {
return addSlideToggleButton(gridPane, rowIndex, title, 0);
}
public static ToggleButton addSlideToggleButton(GridPane gridPane, int rowIndex, String title, double top) {
ToggleButton toggleButton = new AutoTooltipSlideToggleButton();
toggleButton.setText(title);
GridPane.setRowIndex(toggleButton, rowIndex);
GridPane.setColumnIndex(toggleButton, 0);
GridPane.setMargin(toggleButton, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(toggleButton);
return toggleButton;
}
// ComboBox
public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, int top) {
final JFXComboBox<T> comboBox = new JFXComboBox<>();
GridPane.setRowIndex(comboBox, rowIndex);
GridPane.setMargin(comboBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(comboBox);
return comboBox;
}
// Label + ComboBox
public static <T> Tuple2<Label, ComboBox<T>> addTopLabelComboBox(GridPane gridPane,
int rowIndex,
String title,
String prompt,
int top) {
final Tuple3<VBox, Label, ComboBox<T>> tuple3 = addTopLabelComboBox(title, prompt, 0);
final VBox vBox = tuple3.first;
GridPane.setRowIndex(vBox, rowIndex);
GridPane.setMargin(vBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(vBox);
return new Tuple2<>(tuple3.second, tuple3.third);
}
public static <T> Tuple3<VBox, Label, ComboBox<T>> addTopLabelComboBox(String title, String prompt) {
return addTopLabelComboBox(title, prompt, 0);
}
public static <T> Tuple3<VBox, Label, ComboBox<T>> addTopLabelComboBox(String title, String prompt, int top) {
Label label = getTopLabel(title);
VBox vBox = getTopLabelVBox(top);
final JFXComboBox<T> comboBox = new JFXComboBox<>();
comboBox.setPromptText(prompt);
vBox.getChildren().addAll(label, comboBox);
return new Tuple3<>(vBox, label, comboBox);
}
public static <T> Tuple3<VBox, Label, AutocompleteComboBox<T>> addTopLabelAutocompleteComboBox(String title) {
return addTopLabelAutocompleteComboBox(title, 0);
}
public static <T> Tuple3<VBox, Label, AutocompleteComboBox<T>> addTopLabelAutocompleteComboBox(String title,
int top) {
Label label = getTopLabel(title);
VBox vBox = getTopLabelVBox(top);
final AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>();
vBox.getChildren().addAll(label, comboBox);
return new Tuple3<>(vBox, label, comboBox);
}
@NotNull
private static VBox getTopLabelVBox(int top) {
VBox vBox = new VBox();
vBox.setSpacing(0);
vBox.setPadding(new Insets(top, 0, 0, 0));
vBox.setAlignment(Pos.CENTER_LEFT);
return vBox;
}
@NotNull
private static Label getTopLabel(String title) {
Label label = new AutoTooltipLabel(title);
label.getStyleClass().add("small-text");
return label;
}
public static Tuple2<Label, VBox> addTopLabelWithVBox(GridPane gridPane,
int rowIndex,
String title,
Node node,
double top) {
return addTopLabelWithVBox(gridPane, rowIndex, 0, title, node, top);
}
@NotNull
public static Tuple2<Label, VBox> addTopLabelWithVBox(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
Node node,
double top) {
final Tuple2<Label, VBox> topLabelWithVBox = getTopLabelWithVBox(title, node);
VBox vBox = topLabelWithVBox.second;
GridPane.setRowIndex(vBox, rowIndex);
GridPane.setColumnIndex(vBox, columnIndex);
GridPane.setMargin(vBox, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(vBox);
return new Tuple2<>(topLabelWithVBox.first, vBox);
}
@NotNull
public static Tuple2<Label, VBox> getTopLabelWithVBox(String title, Node node) {
Label label = getTopLabel(title);
VBox vBox = getTopLabelVBox(0);
vBox.getChildren().addAll(label, node);
return new Tuple2<>(label, vBox);
}
public static Tuple3<Label, TextField, HBox> addTopLabelTextFieldWithHbox(GridPane gridPane,
int rowIndex,
String titleTextfield,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
TextField textField = new BisqTextField();
final VBox topLabelVBox = getTopLabelVBox(5);
final Label topLabel = getTopLabel(titleTextfield);
topLabelVBox.getChildren().addAll(topLabel, textField);
hBox.getChildren().addAll(topLabelVBox);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(topLabel, textField, hBox);
}
// Label + ComboBox
public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex) {
return addComboBox(gridPane, rowIndex, null, 0);
}
public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, String title) {
return addComboBox(gridPane, rowIndex, title, 0);
}
public static <T> ComboBox<T> addComboBox(GridPane gridPane, int rowIndex, String title, double top) {
JFXComboBox<T> comboBox = new JFXComboBox<>();
comboBox.setLabelFloat(true);
comboBox.setPromptText(title);
comboBox.setMaxWidth(Double.MAX_VALUE);
// Default ComboBox does not show promptText after clear selection.
comboBox.setButtonCell(getComboBoxButtonCell(title, comboBox));
GridPane.setRowIndex(comboBox, rowIndex);
GridPane.setColumnIndex(comboBox, 0);
GridPane.setMargin(comboBox, new Insets(top + Layout.FLOATING_LABEL_DISTANCE, 0, 0, 0));
gridPane.getChildren().add(comboBox);
return comboBox;
}
// Label + AutocompleteComboBox
public static <T> Tuple2<Label, ComboBox<T>> addLabelAutocompleteComboBox(GridPane gridPane,
int rowIndex,
String title,
double top) {
AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>();
final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, title, comboBox, top);
return new Tuple2<>(labelVBoxTuple2.first, comboBox);
}
// Label + TextField + AutocompleteComboBox
public static <T> Tuple4<Label, TextField, Label, ComboBox<T>> addTopLabelTextFieldAutocompleteComboBox(
GridPane gridPane,
int rowIndex,
String titleTextfield,
String titleCombobox
) {
return addTopLabelTextFieldAutocompleteComboBox(gridPane, rowIndex, titleTextfield, titleCombobox, 0);
}
public static <T> Tuple4<Label, TextField, Label, ComboBox<T>> addTopLabelTextFieldAutocompleteComboBox(
GridPane gridPane,
int rowIndex,
String titleTextfield,
String titleCombobox,
double top
) {
HBox hBox = new HBox();
hBox.setSpacing(10);
final VBox topLabelVBox1 = getTopLabelVBox(5);
final Label topLabel1 = getTopLabel(titleTextfield);
final TextField textField = new BisqTextField();
topLabelVBox1.getChildren().addAll(topLabel1, textField);
final VBox topLabelVBox2 = getTopLabelVBox(5);
final Label topLabel2 = getTopLabel(titleCombobox);
AutocompleteComboBox<T> comboBox = new AutocompleteComboBox<>();
comboBox.setPromptText(titleCombobox);
comboBox.setLabelFloat(true);
topLabelVBox2.getChildren().addAll(topLabel2, comboBox);
hBox.getChildren().addAll(topLabelVBox1, topLabelVBox2);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple4<>(topLabel1, textField, topLabel2, comboBox);
}
// Label + ComboBox + ComboBox
public static <T, R> Tuple3<Label, ComboBox<R>, ComboBox<T>> addTopLabelComboBoxComboBox(GridPane gridPane,
int rowIndex,
String title) {
return addTopLabelComboBoxComboBox(gridPane, rowIndex, title, 0);
}
public static <T, R> Tuple3<Label, ComboBox<T>, ComboBox<R>> addTopLabelComboBoxComboBox(GridPane gridPane,
int rowIndex,
String title,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
ComboBox<T> comboBox1 = new JFXComboBox<>();
ComboBox<R> comboBox2 = new JFXComboBox<>();
hBox.getChildren().addAll(comboBox1, comboBox2);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, hBox, top);
return new Tuple3<>(topLabelWithVBox.first, comboBox1, comboBox2);
}
// Label + ComboBox + TextField
public static <T> Tuple4<ComboBox<T>, Label, TextField, HBox> addComboBoxTopLabelTextField(GridPane gridPane,
int rowIndex,
String titleCombobox,
String titleTextfield) {
return addComboBoxTopLabelTextField(gridPane, rowIndex, titleCombobox, titleTextfield, 0);
}
public static <T> Tuple4<ComboBox<T>, Label, TextField, HBox> addComboBoxTopLabelTextField(GridPane gridPane,
int rowIndex,
String titleCombobox,
String titleTextfield,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
JFXComboBox<T> comboBox = new JFXComboBox<>();
comboBox.setPromptText(titleCombobox);
comboBox.setLabelFloat(true);
TextField textField = new BisqTextField();
final VBox topLabelVBox = getTopLabelVBox(5);
final Label topLabel = getTopLabel(titleTextfield);
topLabelVBox.getChildren().addAll(topLabel, textField);
hBox.getChildren().addAll(comboBox, topLabelVBox);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple4<>(comboBox, topLabel, textField, hBox);
}
// Label + ComboBox + Button
public static <T> Tuple3<Label, ComboBox<T>, Button> addLabelComboBoxButton(GridPane gridPane,
int rowIndex,
String title,
String buttonTitle) {
return addLabelComboBoxButton(gridPane, rowIndex, title, buttonTitle, 0);
}
public static <T> Tuple3<Label, ComboBox<T>, Button> addLabelComboBoxButton(GridPane gridPane,
int rowIndex,
String title,
String buttonTitle,
double top) {
Label label = addLabel(gridPane, rowIndex, title, top);
HBox hBox = new HBox();
hBox.setSpacing(10);
Button button = new AutoTooltipButton(buttonTitle);
button.setDefaultButton(true);
ComboBox<T> comboBox = new JFXComboBox<>();
hBox.getChildren().addAll(comboBox, button);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(label, comboBox, button);
}
// Label + ComboBox + Label
public static <T> Tuple3<Label, ComboBox<T>, TextField> addLabelComboBoxLabel(GridPane gridPane,
int rowIndex,
String title,
String textFieldText) {
return addLabelComboBoxLabel(gridPane, rowIndex, title, textFieldText, 0);
}
public static <T> Tuple3<Label, ComboBox<T>, TextField> addLabelComboBoxLabel(GridPane gridPane,
int rowIndex,
String title,
String textFieldText,
double top) {
Label label = addLabel(gridPane, rowIndex, title, top);
HBox hBox = new HBox();
hBox.setSpacing(10);
ComboBox<T> comboBox = new JFXComboBox<>();
TextField textField = new TextField(textFieldText);
textField.setEditable(false);
textField.setMouseTransparent(true);
textField.setFocusTraversable(false);
hBox.getChildren().addAll(comboBox, textField);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(label, comboBox, textField);
}
// Label + TxIdTextField
public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane,
int rowIndex,
int columnIndex,
String title) {
return addLabelTxIdTextField(gridPane, rowIndex, columnIndex, title, 0);
}
public static Tuple2<Label, TxIdTextField> addLabelTxIdTextField(GridPane gridPane,
int rowIndex,
int columnIndex,
String title,
double top) {
Label label = addLabel(gridPane, rowIndex, title, top);
TxIdTextField txIdTextField = new TxIdTextField();
GridPane.setRowIndex(txIdTextField, rowIndex);
GridPane.setColumnIndex(txIdTextField, columnIndex);
GridPane.setMargin(txIdTextField, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(txIdTextField);
return new Tuple2<>(label, txIdTextField);
}
public static Tuple3<Label, TxIdTextField, VBox> addTopLabelTxIdTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
TxIdTextField textField = new TxIdTextField();
textField.setFocusTraversable(false);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textField, top);
// TODO not 100% sure if that is a good idea....
//topLabelWithVBox.first.getStyleClass().add("jfx-text-field-top-label");
return new Tuple3<>(topLabelWithVBox.first, textField, topLabelWithVBox.second);
}
// Label + TextFieldWithCopyIcon
public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value,
double top) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, value, top - Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, "", -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addCompactTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value,
boolean onlyCopyTextAfterDelimiter) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, colIndex, title, value, -Layout.FLOATING_LABEL_DISTANCE, onlyCopyTextAfterDelimiter);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, 0);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
return addTopLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, top, null);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value,
double top,
String styleClass) {
TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon(styleClass);
textFieldWithCopyIcon.setText(value);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textFieldWithCopyIcon, top);
return new Tuple2<>(topLabelWithVBox.first, textFieldWithCopyIcon);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value,
double top,
boolean onlyCopyTextAfterDelimiter) {
TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon();
textFieldWithCopyIcon.setText(value);
textFieldWithCopyIcon.setCopyTextAfterDelimiter(true);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textFieldWithCopyIcon, top);
topLabelWithVBox.second.setAlignment(Pos.TOP_LEFT);
GridPane.setColumnIndex(topLabelWithVBox.second, colIndex);
return new Tuple2<>(topLabelWithVBox.first, textFieldWithCopyIcon);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addTopLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
int colIndex,
String title,
String value,
double top) {
TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon();
textFieldWithCopyIcon.setText(value);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, textFieldWithCopyIcon, top);
topLabelWithVBox.second.setAlignment(Pos.TOP_LEFT);
GridPane.setColumnIndex(topLabelWithVBox.second, colIndex);
return new Tuple2<>(topLabelWithVBox.first, textFieldWithCopyIcon);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addConfirmationLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value) {
return addConfirmationLabelTextFieldWithCopyIcon(gridPane, rowIndex, title, value, 0);
}
public static Tuple2<Label, TextFieldWithCopyIcon> addConfirmationLabelTextFieldWithCopyIcon(GridPane gridPane,
int rowIndex,
String title,
String value,
double top) {
Label label = addLabel(gridPane, rowIndex, title, top);
label.getStyleClass().add("confirmation-label");
GridPane.setHalignment(label, HPos.LEFT);
TextFieldWithCopyIcon textFieldWithCopyIcon = new TextFieldWithCopyIcon("confirmation-text-field-as-label");
textFieldWithCopyIcon.setText(value);
GridPane.setRowIndex(textFieldWithCopyIcon, rowIndex);
GridPane.setColumnIndex(textFieldWithCopyIcon, 1);
GridPane.setMargin(textFieldWithCopyIcon, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(textFieldWithCopyIcon);
return new Tuple2<>(label, textFieldWithCopyIcon);
}
// Label + AddressTextField
public static AddressTextField addAddressTextField(GridPane gridPane, int rowIndex, String title) {
return addAddressTextField(gridPane, rowIndex, title, 0);
}
public static AddressTextField addAddressTextField(GridPane gridPane, int rowIndex, String title, double top) {
AddressTextField addressTextField = new AddressTextField(title);
GridPane.setRowIndex(addressTextField, rowIndex);
GridPane.setColumnIndex(addressTextField, 0);
GridPane.setMargin(addressTextField, new Insets(top + 20, 0, 0, 0));
gridPane.getChildren().add(addressTextField);
return addressTextField;
}
// Label + FundsTextField
public static FundsTextField addFundsTextfield(GridPane gridPane, int rowIndex, String text) {
return addFundsTextfield(gridPane, rowIndex, text, 0);
}
public static FundsTextField addFundsTextfield(GridPane gridPane, int rowIndex, String text, double top) {
FundsTextField fundsTextField = new FundsTextField();
fundsTextField.getTextField().setPromptText(text);
GridPane.setRowIndex(fundsTextField, rowIndex);
GridPane.setColumnIndex(fundsTextField, 0);
GridPane.setMargin(fundsTextField, new Insets(top + 20, 0, 0, 0));
gridPane.getChildren().add(fundsTextField);
return fundsTextField;
}
// Label + InfoTextField
public static Tuple3<Label, InfoTextField, VBox> addCompactTopLabelInfoTextField(GridPane gridPane,
int rowIndex,
String labelText,
String fieldText) {
return addTopLabelInfoTextField(gridPane, rowIndex, labelText, fieldText,
-Layout.FLOATING_LABEL_DISTANCE);
}
public static Tuple3<Label, InfoTextField, VBox> addTopLabelInfoTextField(GridPane gridPane,
int rowIndex,
String labelText,
String fieldText,
double top) {
InfoTextField infoTextField = new InfoTextField();
infoTextField.setText(fieldText);
final Tuple2<Label, VBox> labelVBoxTuple2 = addTopLabelWithVBox(gridPane, rowIndex, labelText, infoTextField, top);
return new Tuple3<>(labelVBoxTuple2.first, infoTextField, labelVBoxTuple2.second);
}
// Label + BsqAddressTextField
public static Tuple3<Label, BsqAddressTextField, VBox> addLabelBsqAddressTextField(GridPane gridPane,
int rowIndex,
String title) {
return addLabelBsqAddressTextField(gridPane, rowIndex, title, 0);
}
public static Tuple3<Label, BsqAddressTextField, VBox> addLabelBsqAddressTextField(GridPane gridPane,
int rowIndex,
String title,
double top) {
BsqAddressTextField addressTextField = new BsqAddressTextField();
addressTextField.setFocusTraversable(false);
Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, addressTextField, top - 15);
return new Tuple3<>(topLabelWithVBox.first, addressTextField, topLabelWithVBox.second);
}
// Label + BalanceTextField
public static BalanceTextField addBalanceTextField(GridPane gridPane, int rowIndex, String title) {
return addBalanceTextField(gridPane, rowIndex, title, 20);
}
public static BalanceTextField addBalanceTextField(GridPane gridPane, int rowIndex, String title, double top) {
BalanceTextField balanceTextField = new BalanceTextField(title);
GridPane.setRowIndex(balanceTextField, rowIndex);
GridPane.setColumnIndex(balanceTextField, 0);
GridPane.setMargin(balanceTextField, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(balanceTextField);
return balanceTextField;
}
// Label + Button
public static Tuple2<Label, Button> addTopLabelButton(GridPane gridPane,
int rowIndex,
String labelText,
String buttonTitle) {
return addTopLabelButton(gridPane, rowIndex, labelText, buttonTitle, 0);
}
public static Tuple2<Label, Button> addTopLabelButton(GridPane gridPane,
int rowIndex,
String labelText,
String buttonTitle,
double top) {
Button button = new AutoTooltipButton(buttonTitle);
button.setDefaultButton(true);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, labelText, button, top);
return new Tuple2<>(topLabelWithVBox.first, button);
}
public static Tuple2<Label, Button> addConfirmationLabelButton(GridPane gridPane,
int rowIndex,
String labelText,
String buttonTitle,
double top) {
Label label = addLabel(gridPane, rowIndex, labelText);
label.getStyleClass().add("confirmation-label");
Button button = new AutoTooltipButton(buttonTitle);
button.getStyleClass().add("confirmation-value");
button.setDefaultButton(true);
GridPane.setColumnIndex(button, 1);
GridPane.setRowIndex(button, rowIndex);
GridPane.setMargin(label, new Insets(top, 0, 0, 0));
GridPane.setHalignment(label, HPos.LEFT);
GridPane.setMargin(button, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(button);
return new Tuple2<>(label, button);
}
// Label + Button + Button
public static Tuple3<Label, Button, Button> addTopLabel2Buttons(GridPane gridPane,
int rowIndex,
String labelText,
String title1,
String title2,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
Button button1 = new AutoTooltipButton(title1);
button1.setDefaultButton(true);
button1.getStyleClass().add("action-button");
button1.setDefaultButton(true);
button1.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button1, Priority.ALWAYS);
Button button2 = new AutoTooltipButton(title2);
button2.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button2, Priority.ALWAYS);
hBox.getChildren().addAll(button1, button2);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, labelText, hBox, top);
return new Tuple3<>(topLabelWithVBox.first, button1, button2);
}
// Button
public static Button addButton(GridPane gridPane, int rowIndex, String title) {
return addButton(gridPane, rowIndex, title, 0);
}
public static Button addButtonAfterGroup(GridPane gridPane, int rowIndex, String title) {
return addButton(gridPane, rowIndex, title, 15);
}
public static Button addPrimaryActionButton(GridPane gridPane, int rowIndex, String title, double top) {
return addButton(gridPane, rowIndex, title, top, true);
}
public static Button addPrimaryActionButtonAFterGroup(GridPane gridPane, int rowIndex, String title) {
return addPrimaryActionButton(gridPane, rowIndex, title, 15);
}
public static Button addButton(GridPane gridPane, int rowIndex, String title, double top) {
return addButton(gridPane, rowIndex, title, top, false);
}
public static Button addButton(GridPane gridPane, int rowIndex, String title, double top, boolean isPrimaryAction) {
Button button = new AutoTooltipButton(title);
if (isPrimaryAction) {
button.setDefaultButton(true);
button.getStyleClass().add("action-button");
}
GridPane.setRowIndex(button, rowIndex);
GridPane.setColumnIndex(button, 0);
gridPane.getChildren().add(button);
GridPane.setMargin(button, new Insets(top, 0, 0, 0));
return button;
}
// Button + Button
public static Tuple2<Button, Button> add2Buttons(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
return add2Buttons(gridPane, rowIndex, title1, title2, 0);
}
public static Tuple2<Button, Button> add2ButtonsAfterGroup(GridPane gridPane,
int rowIndex,
String title1,
String title2) {
return add2ButtonsAfterGroup(gridPane, rowIndex, title1, title2, true);
}
public static Tuple2<Button, Button> add2ButtonsAfterGroup(GridPane gridPane,
int rowIndex,
String title1,
String title2,
boolean hasPrimaryButton) {
return add2Buttons(gridPane, rowIndex, title1, title2, 15, hasPrimaryButton);
}
public static Tuple2<Button, Button> add2Buttons(GridPane gridPane,
int rowIndex,
String title1,
String title2,
double top) {
return add2Buttons(gridPane, rowIndex, title1, title2, top, true);
}
public static Tuple2<Button, Button> add2Buttons(GridPane gridPane, int rowIndex, String title1,
String title2, double top, boolean hasPrimaryButton) {
final Tuple3<Button, Button, HBox> buttonButtonHBoxTuple3 = add2ButtonsWithBox(gridPane, rowIndex, title1, title2, top, hasPrimaryButton);
return new Tuple2<>(buttonButtonHBoxTuple3.first, buttonButtonHBoxTuple3.second);
}
public static Tuple3<Button, Button, HBox> add2ButtonsWithBox(GridPane gridPane, int rowIndex, String title1,
String title2, double top, boolean hasPrimaryButton) {
HBox hBox = new HBox();
hBox.setSpacing(10);
Button button1 = new AutoTooltipButton(title1);
if (hasPrimaryButton) {
button1.getStyleClass().add("action-button");
button1.setDefaultButton(true);
}
button1.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button1, Priority.ALWAYS);
Button button2 = new AutoTooltipButton(title2);
button2.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button2, Priority.ALWAYS);
hBox.getChildren().addAll(button1, button2);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, 0);
GridPane.setMargin(hBox, new Insets(top, 10, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(button1, button2, hBox);
}
// Button + Button + Button
public static Tuple3<Button, Button, Button> add3Buttons(GridPane gridPane,
int rowIndex,
String title1,
String title2,
String title3) {
return add3Buttons(gridPane, rowIndex, title1, title2, title3, 0);
}
public static Tuple3<Button, Button, Button> add3ButtonsAfterGroup(GridPane gridPane,
int rowIndex,
String title1,
String title2,
String title3) {
return add3Buttons(gridPane, rowIndex, title1, title2, title3, 15);
}
public static Tuple3<Button, Button, Button> add3Buttons(GridPane gridPane,
int rowIndex,
String title1,
String title2,
String title3,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
Button button1 = new AutoTooltipButton(title1);
button1.getStyleClass().add("action-button");
button1.setDefaultButton(true);
button1.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button1, Priority.ALWAYS);
Button button2 = new AutoTooltipButton(title2);
button2.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button2, Priority.ALWAYS);
Button button3 = new AutoTooltipButton(title3);
button3.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(button3, Priority.ALWAYS);
hBox.getChildren().addAll(button1, button2, button3);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setColumnIndex(hBox, 0);
GridPane.setMargin(hBox, new Insets(top, 10, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple3<>(button1, button2, button3);
}
// Button + ProgressIndicator + Label
public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabelAfterGroup(GridPane gridPane,
int rowIndex,
int colIndex,
String buttonTitle) {
return addButtonBusyAnimationLabel(gridPane, rowIndex, colIndex, buttonTitle, 15);
}
public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabelAfterGroup(GridPane gridPane,
int rowIndex,
String buttonTitle) {
return addButtonBusyAnimationLabelAfterGroup(gridPane, rowIndex, 0, buttonTitle);
}
public static Tuple4<Button, BusyAnimation, Label, HBox> addButtonBusyAnimationLabel(GridPane gridPane,
int rowIndex,
int colIndex,
String buttonTitle,
double top) {
HBox hBox = new HBox();
hBox.setSpacing(10);
Button button = new AutoTooltipButton(buttonTitle);
button.setDefaultButton(true);
button.getStyleClass().add("action-button");
BusyAnimation busyAnimation = new BusyAnimation(false);
Label label = new AutoTooltipLabel();
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(button, busyAnimation, label);
GridPane.setRowIndex(hBox, rowIndex);
GridPane.setHalignment(hBox, HPos.LEFT);
GridPane.setColumnIndex(hBox, colIndex);
GridPane.setMargin(hBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(hBox);
return new Tuple4<>(button, busyAnimation, label, hBox);
}
// Trade: HBox, InputTextField, Label
public static Tuple3<HBox, InputTextField, Label> getEditableValueBox(String promptText) {
InputTextField input = new InputTextField(60);
input.setPromptText(promptText);
Label label = new AutoTooltipLabel(Res.getBaseCurrencyCode());
label.getStyleClass().add("input-label");
HBox box = new HBox();
HBox.setHgrow(input, Priority.ALWAYS);
input.setMaxWidth(Double.MAX_VALUE);
box.getStyleClass().add("input-with-border");
box.getChildren().addAll(input, label);
return new Tuple3<>(box, input, label);
}
public static Tuple3<HBox, InfoInputTextField, Label> getEditableValueBoxWithInfo(String promptText) {
InfoInputTextField infoInputTextField = new InfoInputTextField(60);
InputTextField input = infoInputTextField.getInputTextField();
input.setPromptText(promptText);
Label label = new AutoTooltipLabel(Res.getBaseCurrencyCode());
label.getStyleClass().add("input-label");
HBox box = new HBox();
HBox.setHgrow(infoInputTextField, Priority.ALWAYS);
infoInputTextField.setMaxWidth(Double.MAX_VALUE);
box.getStyleClass().add("input-with-border");
box.getChildren().addAll(infoInputTextField, label);
return new Tuple3<>(box, infoInputTextField, label);
}
public static Tuple3<HBox, TextField, Label> getNonEditableValueBox() {
final Tuple3<HBox, InputTextField, Label> editableValueBox = getEditableValueBox("");
final TextField textField = editableValueBox.second;
textField.setDisable(true);
return new Tuple3<>(editableValueBox.first, editableValueBox.second, editableValueBox.third);
}
public static Tuple3<HBox, InfoInputTextField, Label> getNonEditableValueBoxWithInfo() {
final Tuple3<HBox, InfoInputTextField, Label> editableValueBoxWithInfo = getEditableValueBoxWithInfo("");
TextField textField = editableValueBoxWithInfo.second.getInputTextField();
textField.setDisable(true);
return editableValueBoxWithInfo;
}
// Trade: Label, VBox
public static Tuple2<Label, VBox> getTradeInputBox(Pane amountValueBox, String descriptionText) {
Label descriptionLabel = new AutoTooltipLabel(descriptionText);
descriptionLabel.setId("input-description-label");
descriptionLabel.setPrefWidth(190);
VBox box = new VBox();
box.setPadding(new Insets(10, 0, 0, 0));
box.setSpacing(2);
box.getChildren().addAll(descriptionLabel, amountValueBox);
return new Tuple2<>(descriptionLabel, box);
}
// Label + List
public static <T> Tuple3<Label, ListView<T>, VBox> addTopLabelListView(GridPane gridPane,
int rowIndex,
String title) {
return addTopLabelListView(gridPane, rowIndex, title, 0);
}
public static <T> Tuple3<Label, ListView<T>, VBox> addTopLabelListView(GridPane gridPane,
int rowIndex,
String title,
double top) {
ListView<T> listView = new ListView<>();
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, listView, top);
return new Tuple3<>(topLabelWithVBox.first, listView, topLabelWithVBox.second);
}
// Label + FlowPane
public static Tuple2<Label, FlowPane> addTopLabelFlowPane(GridPane gridPane,
int rowIndex,
String title,
double top) {
return addTopLabelFlowPane(gridPane, rowIndex, title, top, 0);
}
public static Tuple2<Label, FlowPane> addTopLabelFlowPane(GridPane gridPane,
int rowIndex,
String title,
double top,
double bottom) {
FlowPane flowPane = new FlowPane();
flowPane.setPadding(new Insets(10, 10, 10, 10));
flowPane.setVgap(10);
flowPane.setHgap(10);
final Tuple2<Label, VBox> topLabelWithVBox = addTopLabelWithVBox(gridPane, rowIndex, title, flowPane, top);
GridPane.setMargin(topLabelWithVBox.second, new Insets(top + Layout.FLOATING_LABEL_DISTANCE,
0, bottom, 0));
return new Tuple2<>(topLabelWithVBox.first, flowPane);
}
// Remove
public static void removeRowFromGridPane(GridPane gridPane, int gridRow) {
removeRowsFromGridPane(gridPane, gridRow, gridRow);
}
public static void removeRowsFromGridPane(GridPane gridPane, int fromGridRow, int toGridRow) {
Set<Node> nodes = new CopyOnWriteArraySet<>(gridPane.getChildren());
nodes.stream()
.filter(e -> GridPane.getRowIndex(e) != null && GridPane.getRowIndex(e) >= fromGridRow && GridPane.getRowIndex(e) <= toGridRow)
.forEach(e -> gridPane.getChildren().remove(e));
}
// Icons
public static Text getIconForLabel(GlyphIcons icon, String iconSize, Label label, String style) {
if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) {
final Text textIcon = MaterialDesignIconFactory.get().createIcon(icon, iconSize);
textIcon.setOpacity(0.7);
if (style != null) {
textIcon.getStyleClass().add(style);
}
label.setContentDisplay(ContentDisplay.LEFT);
label.setGraphic(textIcon);
return textIcon;
} else {
throw new IllegalArgumentException("Not supported icon type");
}
}
public static Text getIconForLabel(GlyphIcons icon, String iconSize, Label label) {
return getIconForLabel(icon, iconSize, label, null);
}
public static Text getSmallIconForLabel(GlyphIcons icon, Label label, String style) {
return getIconForLabel(icon, "0.769em", label, style);
}
public static Text getSmallIconForLabel(GlyphIcons icon, Label label) {
return getIconForLabel(icon, "0.769em", label);
}
public static Text getRegularIconForLabel(GlyphIcons icon, Label label) {
return getIconForLabel(icon, "1.231em", label);
}
public static Text getIcon(GlyphIcons icon) {
return getIcon(icon, "1.231em");
}
public static Text getBigIcon(GlyphIcons icon) {
return getIcon(icon, "2em");
}
public static Text getMediumSizeIcon(GlyphIcons icon) {
return getIcon(icon, "1.5em");
}
public static Text getIcon(GlyphIcons icon, String iconSize) {
Text textIcon;
if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) {
textIcon = MaterialDesignIconFactory.get().createIcon(icon, iconSize);
} else {
throw new IllegalArgumentException("Not supported icon type");
}
return textIcon;
}
public static Label getIcon(AwesomeIcon icon) {
final Label label = new Label();
AwesomeDude.setIcon(label, icon);
return label;
}
public static Label getIconForLabel(AwesomeIcon icon, Label label, String fontSize) {
AwesomeDude.setIcon(label, icon, fontSize);
return label;
}
public static Button getIconButton(GlyphIcons icon) {
return getIconButton(icon, "highlight");
}
public static Button getIconButton(GlyphIcons icon, String styleClass) {
return getIconButton(icon, styleClass, "2em");
}
public static Button getRegularIconButton(GlyphIcons icon) {
return getIconButton(icon, "highlight", "1.6em");
}
public static Button getRegularIconButton(GlyphIcons icon, String styleClass) {
return getIconButton(icon, styleClass, "1.6em");
}
public static Button getIconButton(GlyphIcons icon, String styleClass, String iconSize) {
if (icon.fontFamily().equals(MATERIAL_DESIGN_ICONS)) {
Button iconButton = MaterialDesignIconFactory.get().createIconButton(icon,
"", iconSize, null, ContentDisplay.CENTER);
iconButton.setId("icon-button");
iconButton.getGraphic().getStyleClass().add(styleClass);
iconButton.setPrefWidth(20);
iconButton.setPrefHeight(20);
iconButton.setPadding(new Insets(0));
return iconButton;
} else {
throw new IllegalArgumentException("Not supported icon type");
}
}
public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText) {
return addTableViewWithHeader(gridPane, rowIndex, headerText, 0, null);
}
public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane,
int rowIndex,
String headerText,
String groupStyle) {
return addTableViewWithHeader(gridPane, rowIndex, headerText, 0, groupStyle);
}
public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane, int rowIndex, String headerText, int top) {
return addTableViewWithHeader(gridPane, rowIndex, headerText, top, null);
}
public static <T> TableView<T> addTableViewWithHeader(GridPane gridPane,
int rowIndex,
String headerText,
int top,
String groupStyle) {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, 1, headerText, top);
if (groupStyle != null) titledGroupBg.getStyleClass().add(groupStyle);
TableView<T> tableView = new TableView<>();
GridPane.setRowIndex(tableView, rowIndex);
GridPane.setMargin(tableView, new Insets(top + 30, -10, 5, -10));
gridPane.getChildren().add(tableView);
tableView.setPlaceholder(new AutoTooltipLabel(Res.get("table.placeholder.noData")));
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return tableView;
}
}
|
package net.codejva;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import com.hp.hpl.jena.rdf.model.Model;
/**
* Servlet implementation class Melih
*/
@WebServlet("/Melih")
public class Melih extends HttpServlet {
private static final long serialVersionUID = 1L;
public Melih() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer menu = 0;
PrintWriter out = response.getWriter();
String my_query = request.getParameter("my_query");
if (my_query == null){out.println("<form action='Melih' method='get'> Please enter a query:<br><input type='text' name='my_query'><br><br><input type='submit' value='Submit'></form>");}
else{out.println("<html>");
out.println("<body>");
out.println("<p>" + my_query + "</p>");
out.println("</body>");
out.println("</html>");}
}
}
|
package au.com.centrumsystems.hudson.plugin.buildpipeline;
import hudson.Util;
import hudson.model.Item;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleProject;
import hudson.model.Hudson;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import au.com.centrumsystems.hudson.plugin.util.BuildUtil;
import au.com.centrumsystems.hudson.plugin.util.HudsonResult;
import au.com.centrumsystems.hudson.plugin.util.ProjectUtil;
import hudson.plugins.parameterizedtrigger.BlockableBuildTriggerConfig;
import hudson.plugins.parameterizedtrigger.SubProjectsAction;
/**
* @author Centrum Systems
*
*/
public class PipelineBuild {
/** Represents the current build */
private AbstractBuild<?, ?> currentBuild;
/** Represents the current project */
private AbstractProject<?, ?> project;
/** Represents the upstream build */
private AbstractBuild<?, ?> upstreamBuild;
/**
* Contains the upstreamBuild result. Can be one of the following: - BUILDING - SUCCESS - FAILURE - UNSTABLE - NOT_BUILT - ABORT -
* PENDING - MANUAL
*/
private String upstreamBuildResult;
/**
* Contains the currentBuild result. Can be one of the following: - BUILDING - SUCCESS - FAILURE - UNSTABLE - NOT_BUILT - ABORT -
* PENDING - MANUAL
*/
private String currentBuildResult;
/** A Logger object is used to log messages */
private static final Logger LOGGER = Logger.getLogger(PipelineBuild.class.getName());
/**
* Default constructor
*/
public PipelineBuild() {
}
/**
* Creates a new PipelineBuild with currentBuild, project and upstreamBuild set.
*
* @param build
* - current build
* @param project
* - current project
* @param previousBuild
* - upstream build
*/
public PipelineBuild(final AbstractBuild<?, ?> build, final AbstractProject<?, ?> project, final AbstractBuild<?, ?> previousBuild) {
this.currentBuild = build;
this.project = project;
this.upstreamBuild = previousBuild;
this.currentBuildResult = ""; //$NON-NLS-1$
this.upstreamBuildResult = ""; //$NON-NLS-1$
}
/**
* Convenience method to create {@link PipelineBuild} from a build.
*
* @param build
* The object to be wrapped.
*/
public PipelineBuild(final AbstractBuild<?, ?> build) {
this(build, build.getProject(), build.getPreviousBuild());
}
/**
* @param project
* project
*/
public PipelineBuild(final FreeStyleProject project) {
this(null, project, null);
}
public AbstractBuild<?, ?> getCurrentBuild() {
return currentBuild;
}
public void setCurrentBuild(final AbstractBuild<?, ?> currentBuild) {
this.currentBuild = currentBuild;
}
public AbstractBuild<?, ?> getUpstreamBuild() {
return upstreamBuild;
}
public void setUpstreamBuild(final AbstractBuild<?, ?> upstreamBuild) {
this.upstreamBuild = upstreamBuild;
}
public void setProject(final AbstractProject<?, ?> currentProject) {
this.project = currentProject;
}
/**
* Returns the project name. If the current project is null the project name is determined using the current build.
*
* @return - Project name
*/
public AbstractProject<?, ?> getProject() {
final AbstractProject<?, ?> currentProject;
if (this.project == null && this.currentBuild != null) {
currentProject = this.currentBuild.getProject();
} else {
currentProject = this.project;
}
return currentProject;
}
/**
* Returns the current build number.
*
* @return - Current build number or empty String is the current build is null.
*/
public String getCurrentBuildNumber() {
if (this.currentBuild != null) {
return Integer.toString(currentBuild.getNumber());
} else {
return ""; //$NON-NLS-1$
}
}
/**
* Constructs a List of downstream PipelineBuild objects that make up the current pipeline.
*
* @return - List of downstream PipelineBuild objects that make up the current pipeline.
*/
public List<PipelineBuild> getDownstreamPipeline() {
final List<PipelineBuild> pbList = new ArrayList<PipelineBuild>();
final AbstractProject<?, ?> currentProject;
currentProject = getProject();
final List<AbstractProject<?, ?>> downstreamProjects = ProjectUtil.getDownstreamProjects(currentProject);
for (final AbstractProject<?, ?> proj : downstreamProjects) {
AbstractBuild<?, ?> returnedBuild = null;
if (this.currentBuild != null) {
returnedBuild = BuildUtil.getDownstreamBuild(proj, currentBuild);
}
final PipelineBuild newPB = new PipelineBuild(returnedBuild, proj, this.currentBuild);
pbList.add(newPB);
}
if (Hudson.getInstance().getPlugin("parameterized-trigger") != null) {
for (SubProjectsAction action : Util.filter(currentProject.getActions(), SubProjectsAction.class)) {
for (BlockableBuildTriggerConfig config : action.getConfigs()) {
for (final AbstractProject<?, ?> dependency : config.getProjectList(currentProject.getParent(), null)) {
AbstractBuild<?, ?> returnedBuild = null;
if (this.currentBuild != null) {
returnedBuild = BuildUtil.getDownstreamBuild(dependency, currentBuild);
}
final PipelineBuild candidate = new PipelineBuild(returnedBuild, dependency, this.currentBuild);
// if subprojects come back as downstreams someday, no duplicates wanted
if (!pbList.contains(candidate)) {
pbList.add(candidate);
}
}
}
}
}
return pbList;
}
/**
* Build a URL of the currentBuild
*
* @return URL of the currentBuild
*/
public String getBuildResultURL() {
return currentBuild != null ? currentBuild.getAbsoluteUrl() : ""; //$NON-NLS-1$
}
/**
* Builds a URL of the current project
*
* @return URL - of the project
*/
public String getProjectURL() {
return project != null ? project.getUrl() : ""; //$NON-NLS-1$
}
/**
* Determines the result of the current build.
*
* @return - String representing the build result
* @see PipelineBuild#getBuildResult(AbstractBuild)
*/
public String getCurrentBuildResult() {
this.currentBuildResult = getBuildResult(this.currentBuild);
return this.currentBuildResult;
}
/**
* Determines the result of the upstream build.
*
* @return - String representing the build result
* @see PipelineBuild#getBuildResult(AbstractBuild)
*/
public String getUpstreamBuildResult() {
if (this.upstreamBuildResult.length() == 0) {
this.upstreamBuildResult = getBuildResult(this.upstreamBuild);
}
return this.upstreamBuildResult;
}
/**
* Determines the result for a particular build. Can be one of the following: - BUILDING - SUCCESS - FAILURE - UNSTABLE - NOT_BUILT -
* ABORT - PENDING - MANUAL
*
* @param build
* - The build for which a result is requested.
* @return - String representing the build result
*/
private String getBuildResult(final AbstractBuild<?, ?> build) {
String buildResult;
// If AbstractBuild exists determine its current status
if (build != null) {
if (build.isBuilding()) {
buildResult = HudsonResult.BUILDING.toString();
} else {
buildResult = HudsonResult.values()[build.getResult().ordinal].toString();
}
} else {
// Otherwise determine its pending status
buildResult = getPendingStatus();
}
return buildResult;
}
/**
* Determines the pending currentBuild status of a currentBuild in the pipeline that has not been completed. (i.e. the currentBuild is
* null)
*
* @return - PENDING: Current currentBuild is pending the execution of upstream builds. MANUAL: Current currentBuild requires a manual
* trigger
*/
private String getPendingStatus() {
String pendingStatus = HudsonResult.PENDING.toString();
final PipelineBuild upstreamPB = getUpstreamPipelineBuild();
if (upstreamPB != null) {
if (this.getUpstreamBuild() != null) {
if (getUpstreamBuildResult().equals(HudsonResult.SUCCESS.toString())) {
if (ProjectUtil.isManualTrigger(this.upstreamBuild.getProject(), this.project)) {
pendingStatus = HudsonResult.MANUAL.toString();
}
}
}
}
return pendingStatus;
}
/**
* Returns the upstream PipelineBuild object from the current PipelineBuild object.
*
* @return - Upstream PipelineBuild object from the current PipelineBuild object
*/
public PipelineBuild getUpstreamPipelineBuild() {
@SuppressWarnings("rawtypes")
final List<AbstractProject> upstreamProjects = getProject().getUpstreamProjects();
AbstractProject<?, ?> previousProject = null;
String upstreamBuildName;
final PipelineBuild previousPB = new PipelineBuild();
if (this.upstreamBuild != null) {
upstreamBuildName = this.upstreamBuild.getProject().getName();
} else {
upstreamBuildName = "";
}
if (upstreamProjects.size() > 0) {
if (isManualTrigger()) {
for (AbstractProject upstreamProject : upstreamProjects) {
if (upstreamProject.getName().equals(upstreamBuildName)) {
previousProject = upstreamProject;
break;
}
}
}
if (previousProject == null) {
previousProject = upstreamProjects.get(0);
}
previousPB.setCurrentBuild(this.getUpstreamBuild());
previousPB.setProject(previousProject);
}
return previousPB;
}
/**
* Returns the current build duration.
*
* @return - Current build duration or an empty String if the current build is null.
*/
public String getBuildDuration() {
if (this.currentBuild != null) {
return this.currentBuild.getDurationString();
} else {
return ""; //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Project: " + getProject().getName() + " : Build: " + getCurrentBuildNumber();
}
/**
* Returns the current build description.
*
* @return - Current build description or the project name if the current build is null.
*/
public String getBuildDescription() {
if (this.currentBuild != null) {
return this.currentBuild.toString();
} else {
return Strings.getString("PipelineBuild.PendingBuildOfProject") + this.getProject().getName(); //$NON-NLS-1$
}
}
/**
* Returns the estimated percentage complete of the current build.
*
* @return - Estimated percentage complete of the current build.
*/
public long getBuildProgress() {
if (this.currentBuild != null && this.currentBuild.isBuilding()) {
final long duration = new Date().getTime() - this.currentBuild.getTimestamp().getTimeInMillis();
return calculatePercentage(duration, this.currentBuild.getEstimatedDuration());
} else {
return 0;
}
}
/**
* Calculates percentage of the current duration to the estimated duration. Caters for the possibility that current duration will be
* longer than estimated duration
*
* @param duration
* - Current running time in milliseconds
* @param estimatedDuration
* - Estimated running time in milliseconds
* @return - Percentage of current duration to estimated duration
*/
protected long calculatePercentage(final long duration, final long estimatedDuration) {
if (duration > estimatedDuration) {
return 100;
}
if (estimatedDuration > 0) {
return (long) ((float) duration / (float) estimatedDuration * 100);
}
return 100;
}
/**
* Return pipeline version which is simply the first build's number
*
* @return pipeline verison
*/
public String getPipelineVersion() {
String version;
if (currentBuild != null) {
final String displayName = currentBuild.getDisplayName();
if (displayName == null || displayName.trim().length() == 0) {
version = currentBuild.getNumber() > 0 ? String.valueOf(currentBuild.getNumber()) : Strings
.getString("PipelineBuild.RevisionNotAvailable");
} else {
version = displayName;
}
} else {
version = Strings.getString("PipelineBuild.RevisionNotAvailable");
}
return version;
}
public boolean hasBuildPermission() {
boolean buildPermission = false;
// If no security is enabled then allow builds
if (!Hudson.getInstance().isUseSecurity()) {
LOGGER.fine("Security is not enabled.");
buildPermission = true;
} else if (this.project != null) {
// If security is enabled check if BUILD is enabled
buildPermission = this.project.hasPermission(Item.BUILD);
}
LOGGER.fine("Is user allowed to build? -> " + buildPermission);
return buildPermission;
}
/**
* @return is ready to be mannlly built.
*/
public boolean isReadyToBeManuallyBuilt() {
return isManualTrigger() && this.currentBuild == null && upstreamBuildSucceeded() && hasBuildPermission();
}
public boolean isRerunnable() {
return !isReadyToBeManuallyBuilt()
&& !"PENDING".equals(getCurrentBuildResult())
&& !"BUILDING".equals(getCurrentBuildResult())
&& hasBuildPermission();
}
/**
* @return upstream build is existed and successful.
*/
private boolean upstreamBuildSucceeded() {
return this.getUpstreamBuild() != null && HudsonResult.SUCCESS.toString().equals(getBuildResult(this.upstreamBuild));
}
/**
* Determine if the project is triggered manually, regardless of the state of its upstream builds
*
* @return true if it is manual
*/
public boolean isManualTrigger() {
boolean manualTrigger = false;
if (this.upstreamBuild != null) {
manualTrigger = ProjectUtil.isManualTrigger(this.upstreamBuild.getProject(), this.project);
}
return manualTrigger;
}
/**
* Start time of build
*
* @return start time
*/
public Date getStartTime() {
return currentBuild != null ? currentBuild.getTime() : null;
}
/**
* @return Formatted start time
*/
public String getFormattedStartTime() {
String formattedStartTime = ""; //$NON-NLS-1$
if (getStartTime() != null) {
formattedStartTime = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(getStartTime());
}
return formattedStartTime;
}
/**
* @return Formatted start date
*/
public String getFormattedStartDate() {
String formattedStartTime = ""; //$NON-NLS-1$
if (getStartTime() != null) {
formattedStartTime = DateFormat.getDateInstance(DateFormat.MEDIUM).format(getStartTime());
}
return formattedStartTime;
}
/**
* @return a map including build parameters
*/
public Map<String, String> getBuildParameters() {
final Map<String, String> retval = new HashMap<String, String>();
if (currentBuild != null) {
retval.putAll(currentBuild.getBuildVariables());
}
return retval;
}
public boolean isProjectDisabled() {
return getProject().isDisabled();
}
public String getProjectHealth() {
return project.getBuildHealth().getIconUrl().replaceAll("\\.gif", "\\.png");
}
}
|
package ru.job4j;
public class Model<V> implements Versionable {
/**
* Name.
*/
String name;
V v;
final private int version;
/**
* Constructor.
*/
public Model() {
this.version = 0;
}
/**
* Constructor.
* @param v v
*/
public Model(V v) {
this.v = v;
this.version = 0;
}
/**
* Constructor.
* @param v v
* @param version version
*/
public Model(V v, int version) {
this.v = v;
this.version = version;
}
/**
* Gets version.
*/
@Override
public int getVersion() {
return version;
}
}
|
package com.github.appreciated.quickstart.base.navigation.upload;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Upload {
private File file;
private StringUploadListener stringUploadListener;
private ByteUploadListener byteUploadListener;
private FileUploadListener fileUploadListener;
public Upload(StringUploadListener stringUploadListener) {
this.stringUploadListener = stringUploadListener;
}
public Upload(ByteUploadListener byteUploadListener) {
this.byteUploadListener = byteUploadListener;
}
public Upload(File file, FileUploadListener fileUploadListener) {
this.file = file;
this.fileUploadListener = fileUploadListener;
}
public void createUploadButton(com.vaadin.ui.Upload button) {
if (file != null) {
try {
file(file, button, fileUploadListener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else if (stringUploadListener != null) {
fileAsString(button, stringUploadListener);
} else if (byteUploadListener != null) {
fileAsBytes(button, byteUploadListener);
}
}
public interface StringUploadListener {
void onUploadFinished(String string);
}
public interface FileUploadListener {
void onUploadFinished(File file);
}
public interface ByteUploadListener {
void onUploadFinished(byte[] bytes);
}
public static void file(File destination, com.vaadin.ui.Upload upload, FileUploadListener listener) throws FileNotFoundException {
FileOutputStream stream = new FileOutputStream(destination);
com.vaadin.ui.Upload.FinishedListener uploadListener = (com.vaadin.ui.Upload.FinishedListener) finishedEvent -> listener.onUploadFinished(destination);
fileAsStream(upload, stream, uploadListener);
}
public static void fileAsString(com.vaadin.ui.Upload upload, StringUploadListener listener) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
com.vaadin.ui.Upload.FinishedListener uploadListener = (com.vaadin.ui.Upload.FinishedListener) finishedEvent -> listener.onUploadFinished(new String(stream.toByteArray(), StandardCharsets.UTF_8));
fileAsStream(upload, stream, uploadListener);
}
public static void fileAsBytes(com.vaadin.ui.Upload upload, ByteUploadListener listener) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
com.vaadin.ui.Upload.FinishedListener uploadListener = (com.vaadin.ui.Upload.FinishedListener) finishedEvent -> listener.onUploadFinished(stream.toByteArray());
fileAsStream(upload, stream, uploadListener);
}
private static void fileAsStream(com.vaadin.ui.Upload upload, OutputStream stream, com.vaadin.ui.Upload.FinishedListener listener) {
upload.setReceiver((com.vaadin.ui.Upload.Receiver) (s, s1) -> stream);
upload.addFinishedListener(listener);
}
}
|
package com.wegas.core.rest;
import java.lang.management.*;
import java.util.*;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Stateless
@Path("JvmStats")
@Produces(MediaType.APPLICATION_JSON)
public class JvmStats {
private static final long serialVersionUID = 1627669174708657566L;
public static final String
HEAP_USED_INIT = "HEAP_USED_INIT_BYTES",
HEAP_USED_MAX = "HEAP_USED_MAX_BYTES",
HEAP_USED_COMMITTED = "HEAP_USED_COMMITTED_BYTES",
HEAP_USED = "HEAP_USED_BYTES",
OLDGEN_USED_INIT = "OLDGEN_USED_INIT_BYTES",
OLDGEN_USED_MAX = "OLDGEN_USED_MAX_BYTES",
OLDGEN_USED_COMMITTED = "OLDGEN_USED_COMMITTED_BYTES",
OLDGEN_USED = "OLDGEN_USED_BYTES",
OLDGEN_USAGE_THRESHOLD = "OLDGEN_USAGE_THRESHOLD",
OLDGEN_USAGE_THRESHOLD_EXCEEDED = "OLDGEN_USAGE_THRESHOLD_EXCEEDED",
OLDGEN_USAGE_THRESHOLD_CNT = "OLDGEN_USAGE_THRESHOLD_CNT",
NONHEAP_USED_INIT = "NONHEAP_USED_INIT_BYTES",
NONHEAP_USED_MAX = "NONHEAP_USED_MAX_BYTES",
NONHEAP_USED_COMMITTED = "NONHEAP_USED_COMMITTED_BYTES",
NONHEAP_USED = "NONHEAP_USED_BYTES",
THREAD_CNT = "THREAD_CNT",
THREAD_DAEMON_CNT = "THREAD_DAEMON_CNT",
THREAD_PEAK_CNT = "THREAD_PEAK_CNT",
THREAD_STARTED_CNT = "THREAD_STARTED_CNT",
LOADED_CLASS_CNT = "LOADED_CLASS_CNT",
UNLOADED_CLASS_CNT = "UNLOADED_CLASS_CNT",
TOTAL_LOADED_CLASS_CNT = "TOTAL_LOADED_CLASS_CNT",
GC = "GC_",
CNT = "_CNT",
MILLIS = "_MS",
STATS_EXEC_TIME_NANO = "STATS_EXEC_TIME_NANO";
/*
** Returns the state of the tenured/old generation of the heap, i.e. the one for which a usage threshold can be set.
** Threshold values are returned and the threshold can be set with {@link #setUsageThreshold setUsageThreshold()} to allow simple polling.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("oldGenHeap")
public Map oldGenHeap() {
long startTime = System.nanoTime();
Map map = new HashMap<String,Object>();
MemoryUsage heapUsed = findOldGenPool().getUsage();
map.put(OLDGEN_USAGE_THRESHOLD, oldGenPool.getUsageThreshold());
map.put(OLDGEN_USAGE_THRESHOLD_CNT, oldGenPool.getUsageThresholdCount());
map.put(OLDGEN_USAGE_THRESHOLD_EXCEEDED, oldGenPool.isUsageThresholdExceeded());
map.put(OLDGEN_USED, heapUsed.getUsed());
map.put(OLDGEN_USED_COMMITTED, heapUsed.getCommitted());
map.put(OLDGEN_USED_INIT, heapUsed.getInit());
map.put(OLDGEN_USED_MAX, heapUsed.getMax());
map.putAll(gc());
map.put(STATS_EXEC_TIME_NANO, System.nanoTime() - startTime); // 1 millisecond = 1E6 nanoseconds
return map;
}
/*
** Sets the old/tenured generation threshold to allow low-cost web-based polling.
** @param threshold the new collection usage threshold value in bytes.
** Must be non-negative and less than (or equal to) current max pool size.
** The usage threshold crossing checking is disabled if set to zero.
** @return resulting JSON structure from method {@link #oldGenHeap oldGenHeap}.
*/
@GET
@Path("setUsageThreshold/{threshold : [0-9]*}")
public Map setUsageThreshold (@PathParam("threshold") Long threshold) {
findOldGenPool().setUsageThreshold(threshold);
return oldGenHeap();
}
/*
** Returns the global state of the heap.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("globalHeap")
public Map globalHeap() {
Map map = new HashMap<String,Object>();
MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsed = memory.getHeapMemoryUsage();
map.put(HEAP_USED_INIT, heapUsed.getInit());
map.put(HEAP_USED_MAX, heapUsed.getMax());
map.put(HEAP_USED_COMMITTED, heapUsed.getCommitted());
map.put(HEAP_USED, heapUsed.getUsed());
map.putAll(gc());
return map;
}
/*
** Returns statistics on garbage collection activity.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("gc")
public Map gc() {
Map map = new HashMap<String,Object>();
long gcCount = 0;
long gcTime = 0;
for (GarbageCollectorMXBean gbean : ManagementFactory.getGarbageCollectorMXBeans()) {
//map.put(GC + gbean.getName() + CNT, gbean.getCollectionCount());
//map.put(GC + gbean.getName() + MILLIS, gbean.getCollectionTime());
gcCount += gbean.getCollectionCount();
gcTime += gbean.getCollectionTime();
}
map.put("GC_CNT", gcCount);
map.put("GC_MS", gcTime);
return map;
}
/*
** Returns statistics on non-heap memory.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("nonHeap")
public Map nonHeap() {
Map map = new HashMap<String,Object>();
MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
MemoryUsage nonheapUsed = memory.getNonHeapMemoryUsage();
map.put(NONHEAP_USED_INIT, nonheapUsed.getInit());
map.put(NONHEAP_USED_MAX, nonheapUsed.getMax());
map.put(NONHEAP_USED_COMMITTED, nonheapUsed.getCommitted());
map.put(NONHEAP_USED, nonheapUsed.getUsed());
return map;
}
/*
** Returns statistics on threads inside the JVM.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("threads")
public Map threads() {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
Map map = new HashMap<String,Object>();
map.put(THREAD_CNT, threads.getThreadCount());
map.put(THREAD_DAEMON_CNT, threads.getDaemonThreadCount());
map.put(THREAD_PEAK_CNT, threads.getPeakThreadCount());
map.put(THREAD_STARTED_CNT, threads.getTotalStartedThreadCount());
return map;
}
/*
** Returns statistics on class loader activity.
**
** @return JSON structure with heterogeneous values.
*/
@GET
@Path("classLoader")
public Map classLoader() {
ClassLoadingMXBean classes = ManagementFactory.getClassLoadingMXBean();
Map map = new HashMap<String,Object>();
map.put(LOADED_CLASS_CNT, classes.getLoadedClassCount());
map.put(UNLOADED_CLASS_CNT, classes.getUnloadedClassCount());
map.put(TOTAL_LOADED_CLASS_CNT, classes.getTotalLoadedClassCount());
return map;
}
/*
** In the current JVM, there is only one memory pool where usage thresholds are supported: the old/tenured pool.
** The following code identifies that pool and maintains a reference to it.
*/
private static MemoryPoolMXBean oldGenPool = null;
private static MemoryPoolMXBean findOldGenPool() {
if (oldGenPool != null) {
return oldGenPool;
} else {
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
oldGenPool = pool;
return pool;
}
}
throw new AssertionError("Could not find old space");
}
}
}
|
package plugin.google.maps;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
public class PluginUtil {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static JSONObject location2Json(Location location) throws JSONException {
JSONObject latLng = new JSONObject();
latLng.put("lat", location.getLatitude());
latLng.put("lng", location.getLongitude());
JSONObject params = new JSONObject();
params.put("latLng", latLng);
Build.VERSION version = new Build.VERSION();
if (version.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos());
} else {
params.put("elapsedRealtimeNanos", 0);
}
params.put("time", location.getTime());
if (location.hasAccuracy()) {
params.put("accuracy", location.getAccuracy());
}
if (location.hasBearing()) {
params.put("bearing", location.getBearing());
}
if (location.hasAltitude()) {
params.put("altitude", location.getAltitude());
}
if (location.hasSpeed()) {
params.put("speed", location.getSpeed());
}
params.put("provider", location.getProvider());
params.put("hashCode", location.hashCode());
return params;
}
/**
* return color integer value
* @param arrayRGBA
* @throws JSONException
*/
public static int parsePluginColor(JSONArray arrayRGBA) throws JSONException {
return Color.argb(arrayRGBA.getInt(3), arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2));
}
public static List<LatLng> JSONArray2LatLngList(JSONArray points) throws JSONException {
List<LatLng> path = new ArrayList<LatLng>();
JSONObject pointJSON;
int i = 0;
for (i = 0; i < points.length(); i++) {
pointJSON = points.getJSONObject(i);
path.add(new LatLng(pointJSON.getDouble("lat"), pointJSON.getDouble("lng")));
}
return path;
}
/*
public static Set<LatLng> JSONArray2LatLngHash(JSONArray points) throws JSONException {
Set<LatLng> path = new HashSet<LatLng>();
JSONObject pointJSON;
int i = 0;
for (i = 0; i < points.length(); i++) {
pointJSON = points.getJSONObject(i);
path.add(new LatLng(pointJSON.getDouble("lat"), pointJSON.getDouble("lng")));
}
return path;
}
*/
public static LatLngBounds JSONArray2LatLngBounds(JSONArray points) throws JSONException {
List<LatLng> path = JSONArray2LatLngList(points);
Builder builder = LatLngBounds.builder();
int i = 0;
for (i = 0; i < path.size(); i++) {
builder.include(path.get(i));
}
return builder.build();
}
public static Bundle Json2Bundle(JSONObject json) {
Bundle mBundle = new Bundle();
@SuppressWarnings("unchecked")
Iterator<String> iter = json.keys();
Object value;
while (iter.hasNext()) {
String key = iter.next();
try {
value = json.get(key);
if (Boolean.class.isInstance(value)) {
mBundle.putBoolean(key, (Boolean)value);
} else if (Double.class.isInstance(value)) {
mBundle.putDouble(key, (Double)value);
} else if (Integer.class.isInstance(value)) {
mBundle.putInt(key, (Integer)value);
} else if (Long.class.isInstance(value)) {
mBundle.putLong(key, (Long)value);
} else if (JSONObject.class.isInstance(value)) {
mBundle.putBundle(key, Json2Bundle((JSONObject)value));
} else {
mBundle.putString(key, json.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mBundle;
}
public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) {
if (bitmap == null) {
return null;
}
Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
bitmap.recycle();
return resizeBitmap;
}
public static Bitmap scaleBitmapForDevice(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
float density = Resources.getSystem().getDisplayMetrics().density;
int width = (int)(bitmap.getWidth() * density);
int height = (int)(bitmap.getHeight() * density);
Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
bitmap.recycle();
return resizeBitmap;
}
public static Bitmap getBitmapFromBase64encodedImage(String base64EncodedImage) {
byte[] byteArray= Base64.decode(base64EncodedImage, Base64.DEFAULT);
Bitmap image= null;
try {
image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
}
|
package com.google.gcs.sdrs.service.worker.impl;
import com.google.api.services.storagetransfer.v1.Storagetransfer;
import com.google.api.services.storagetransfer.v1.model.ObjectConditions;
import com.google.api.services.storagetransfer.v1.model.TimeOfDay;
import com.google.api.services.storagetransfer.v1.model.TransferJob;
import com.google.gcs.sdrs.SdrsApplication;
import com.google.gcs.sdrs.common.RetentionRuleType;
import com.google.gcs.sdrs.controller.validation.ValidationConstants;
import com.google.gcs.sdrs.dao.DmQueueDao;
import com.google.gcs.sdrs.dao.LockDao;
import com.google.gcs.sdrs.dao.SingletonDao;
import com.google.gcs.sdrs.dao.model.DistributedLock;
import com.google.gcs.sdrs.dao.model.DmRequest;
import com.google.gcs.sdrs.dao.model.RetentionJob;
import com.google.gcs.sdrs.dao.model.RetentionRule;
import com.google.gcs.sdrs.dao.util.DatabaseConstants;
import com.google.gcs.sdrs.service.worker.BaseWorker;
import com.google.gcs.sdrs.service.worker.WorkerResult.WorkerResultStatus;
import com.google.gcs.sdrs.service.worker.rule.impl.StsRuleExecutor;
import com.google.gcs.sdrs.util.CredentialsUtil;
import com.google.gcs.sdrs.util.RetentionUtil;
import com.google.gcs.sdrs.util.StsUtil;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DmBatchProcessingWorker extends BaseWorker {
private static final Logger logger = LoggerFactory.getLogger(DmBatchProcessingWorker.class);
private DmQueueDao dmQueueDao;
private LockDao lockDao;
private Storagetransfer client;
public static final int DEFAULT_DM_LOCK_TIMEOUT = 60000; // one minute by default
public static final int DEFAULT_DM_MAX_RETRY = 5;
public static final int DM_MAX_RETRY =
Integer.valueOf(
SdrsApplication.getAppConfigProperty(
"scheduler.task.dmBatchProcessing.maxRetry", String.valueOf(DEFAULT_DM_MAX_RETRY)));
public static final int DM_LOCK_TIMEOUT =
Integer.valueOf(
SdrsApplication.getAppConfigProperty(
"lock.dm.timeout", String.valueOf(DEFAULT_DM_LOCK_TIMEOUT)));
public static final String DEFAULT_DM_LOCK_ID = "dm-batch";
public static final String DM_LOCK_ID =
SdrsApplication.getAppConfigProperty("lock.dm.id", DEFAULT_DM_LOCK_ID);
public DmBatchProcessingWorker(String correlationId) {
super(correlationId);
try {
client = StsUtil.createStsClient(CredentialsUtil.getInstance().getCredentials());
} catch (IOException e) {
logger.error("Failed to create STS client.", e);
}
dmQueueDao = SingletonDao.getDmQueueDao();
lockDao = SingletonDao.getLockDao();
}
@Override
public void doWork() {
Session currentLockSession = lockDao.getLockSession();
try {
logger.info(String.format("acquiring lock at %s", Instant.now(Clock.systemUTC()).toString()));
DistributedLock distributedLock =
lockDao.obtainLock(currentLockSession, DM_LOCK_TIMEOUT, DM_LOCK_ID);
if (distributedLock != null) {
logger.info(
String.format(
"acquired lock %s at %s",
distributedLock.getLockToken(), Instant.now(Clock.systemUTC()).toString()));
// get sorted (by priority) list of all available queue for processing
List<DmRequest> allAvailableRequetsForProcessing =
dmQueueDao.getAllAvailableRequestsByPriority();
// sort the list by bucket while keeping the same order
Map<String, List<DmRequest>> dmRequestsMap =
allAvailableRequetsForProcessing.stream()
.collect(Collectors.groupingBy(DmRequest::getDataStorageRoot));
List<String> failedDmProcessingBuckets = new ArrayList<>();
for (String bucket : dmRequestsMap.keySet()) {
if (!processDmRequestByBucket(bucket, dmRequestsMap.get(bucket))) {
failedDmProcessingBuckets.add(bucket);
}
}
if (failedDmProcessingBuckets.isEmpty()) {
logger.info(
String.format(
"Successfully processed DM requests for %d buckets.", dmRequestsMap.size()));
workerResult.setStatus(WorkerResultStatus.SUCCESS);
} else {
logger.error(
String.format(
"DM requests processing failed for %d out of %d buckets.",
failedDmProcessingBuckets.size(), dmRequestsMap.size()));
workerResult.setStatus(WorkerResultStatus.FAILED);
}
lockDao.releaseLock(currentLockSession, distributedLock);
logger.info(
String.format(
"released lock %s at %s",
distributedLock.getLockToken(), Instant.now(Clock.systemUTC()).toString()));
} else {
logger.info("Can not acquire lock.");
workerResult.setStatus(WorkerResultStatus.SUCCESS);
}
} catch (Exception e) {
logger.error("Unknown error. ", e);
workerResult.setStatus(WorkerResultStatus.FAILED);
} finally {
// clean up resource
lockDao.closeLockSession(currentLockSession);
}
}
private boolean processDmRequestByBucket(String bucket, List<DmRequest> dmRequests) {
String destinationBucket = StsUtil.buildDestinationBucketName(bucket);
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(Clock.systemUTC());
String scheduleTimeOfDay = zonedDateTimeNow.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
String projectId = dmRequests.get(0).getProjectId();
TransferJob transferJob = null;
try {
transferJob =
StsRuleExecutor.getInstance()
.findPooledJob(projectId, bucket, scheduleTimeOfDay, RetentionRuleType.USER);
} catch (IOException e) {
// Can't allocate the job from the pool. Fail immediately.
return false;
}
TimeOfDay jobRunAtTimeOfDay = transferJob.getSchedule().getStartTimeOfDay();
// derived from transferJob.tomeOfDay and now
ZonedDateTime lastRunTime =
ZonedDateTime.of(
zonedDateTimeNow.getYear(),
zonedDateTimeNow.getMonthValue(),
zonedDateTimeNow.getDayOfMonth(),
jobRunAtTimeOfDay.getHours(),
jobRunAtTimeOfDay.getMinutes(),
jobRunAtTimeOfDay.getSeconds(),
jobRunAtTimeOfDay.getNanos() != null ? jobRunAtTimeOfDay.getNanos() : 0,
ZoneId.of("UTC")).minusHours(24);
ZonedDateTime lastModifiedTime = ZonedDateTime.parse(transferJob.getLastModificationTime());
List<String> existingIncludePrefixList = new ArrayList<>();
if (transferJob.getStatus().equals(StsUtil.STS_ENABLED_STRING)) {
ObjectConditions objectConditions = transferJob.getTransferSpec().getObjectConditions();
if (objectConditions != null && objectConditions.getIncludePrefixes() != null) {
existingIncludePrefixList = objectConditions.getIncludePrefixes();
}
}
int initPrefxiNumber = 0;
Set<String> newIncludePrefixSet = new HashSet<>();
// Replace the existing prefix list if last modified time is older than the last job run time,
// meaning the daily STS job has already run and the existing prefix list has been processed.
if (lastModifiedTime.isBefore(lastRunTime)) {
initPrefxiNumber = StsUtil.MAX_PREFIX_COUNT;
} else {
initPrefxiNumber = StsUtil.MAX_PREFIX_COUNT - existingIncludePrefixList.size();
newIncludePrefixSet.addAll(existingIncludePrefixList);
}
int maxCount = Math.min(initPrefxiNumber, dmRequests.size());
int total = 0;
int start = 0;
List<String> newIncludePrefixList = null;
while (total < StsUtil.MAX_PREFIX_COUNT && start < dmRequests.size()) {
for (int i = 0; i < maxCount; i++) {
String prefix =
RetentionUtil.getDatasetPath(dmRequests.get(i + start).getDataStorageName());
if (prefix != null && !prefix.isEmpty()) {
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
newIncludePrefixSet.add(prefix);
}
}
newIncludePrefixList =
RetentionUtil.consolidateDmPrefixes(new ArrayList<>(newIncludePrefixSet));
total = newIncludePrefixList.size();
start = maxCount + start;
maxCount = Math.min(StsUtil.MAX_PREFIX_COUNT - total, dmRequests.size() - start);
newIncludePrefixSet = new HashSet<>(newIncludePrefixList);
}
// update STS job
TransferJob jobToUpdate =
new TransferJob()
.setDescription(
StsRuleExecutor.buildDescription(
RetentionRuleType.USER.toString(), null, scheduleTimeOfDay))
.setTransferSpec(
StsUtil.buildTransferSpec(
bucket, destinationBucket, newIncludePrefixList, false, null))
.setStatus(StsUtil.STS_ENABLED_STRING);
try {
transferJob =
StsUtil.updateExistingJob(client, jobToUpdate, transferJob.getName(), projectId);
} catch (IOException e) {
// Update STS job failed. Fail the process immediately.
logger.error("Failed to update STS job.", e);
return false;
}
RetentionRule retentionRule = new RetentionRule();
retentionRule.setProjectId(projectId);
retentionRule.setDataStorageName(ValidationConstants.STORAGE_PREFIX + bucket);
retentionRule.setType(RetentionRuleType.USER);
RetentionJob retentionJob =
StsRuleExecutor.buildRetentionJobEntity(
transferJob.getName(),
retentionRule,
StsUtil.convertPrefixToString(newIncludePrefixList),
new Timestamp(Instant.parse(transferJob.getLastModificationTime()).toEpochMilli()));
retentionJob.setBatchId(getUuid());
// update retention_job and dm_queue tables
List<DmRequest> processedDmRequests = dmRequests.subList(0, start);
dmRequests.stream()
.forEach(
request -> {
if (request.getStatus().equals(DatabaseConstants.DM_REQUEST_STATIUS_RETRY)) {
request.setNumberOfRetry(request.getNumberOfRetry() + 1);
request.setPriority(
RetentionUtil.generatePriority(
request.getNumberOfRetry(),
request.getCreatedAt().toInstant().toEpochMilli()));
}
request.setStatus(DatabaseConstants.DM_REQUEST_STATUS_SCHEDULED);
});
try {
dmQueueDao.createRetentionJobUdpateDmStatus(retentionJob, processedDmRequests);
} catch (IOException e) {
// Database transaction failed. However the process is still considered success as STS job has
// been updated successfully.
logger.error("Failed to create retention job and update DM request status.");
}
return true;
}
}
|
package com.ning.http.client.providers.grizzly;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.BodyGenerator;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.Part;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.UpgradeHandler;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.websocket.WebSocket;
import com.ning.http.client.websocket.WebSocketByteListener;
import com.ning.http.client.websocket.WebSocketListener;
import com.ning.http.client.websocket.WebSocketPingListener;
import com.ning.http.client.websocket.WebSocketTextListener;
import com.ning.http.client.websocket.WebSocketUpgradeHandler;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.CompletionHandler;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.EmptyCompletionHandler;
import org.glassfish.grizzly.FileTransfer;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.WriteResult;
import org.glassfish.grizzly.attributes.Attribute;
import org.glassfish.grizzly.attributes.AttributeStorage;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainBuilder;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.FilterChainEvent;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.filterchain.TransportFilter;
import org.glassfish.grizzly.http.ContentEncoding;
import org.glassfish.grizzly.http.EncodingFilter;
import org.glassfish.grizzly.http.GZipContentEncoding;
import org.glassfish.grizzly.http.HttpClientFilter;
import org.glassfish.grizzly.http.HttpContent;
import org.glassfish.grizzly.http.HttpHeader;
import org.glassfish.grizzly.http.HttpRequestPacket;
import org.glassfish.grizzly.http.HttpResponsePacket;
import org.glassfish.grizzly.http.Method;
import org.glassfish.grizzly.http.Protocol;
import org.glassfish.grizzly.utils.Charsets;
import org.glassfish.grizzly.http.util.CookieSerializerUtils;
import org.glassfish.grizzly.http.util.DataChunk;
import org.glassfish.grizzly.http.util.Header;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.grizzly.http.util.MimeHeaders;
import org.glassfish.grizzly.impl.SafeFutureImpl;
import org.glassfish.grizzly.memory.Buffers;
import org.glassfish.grizzly.memory.MemoryManager;
import org.glassfish.grizzly.nio.transport.TCPNIOConnectorHandler;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.grizzly.ssl.SSLFilter;
import org.glassfish.grizzly.strategies.SameThreadIOStrategy;
import org.glassfish.grizzly.strategies.WorkerThreadIOStrategy;
import org.glassfish.grizzly.utils.BufferOutputStream;
import org.glassfish.grizzly.utils.DelayedExecutor;
import org.glassfish.grizzly.utils.IdleTimeoutFilter;
import org.glassfish.grizzly.websockets.DataFrame;
import org.glassfish.grizzly.websockets.DefaultWebSocket;
import org.glassfish.grizzly.websockets.HandShake;
import org.glassfish.grizzly.websockets.ProtocolHandler;
import org.glassfish.grizzly.websockets.Version;
import org.glassfish.grizzly.websockets.WebSocketEngine;
import org.glassfish.grizzly.websockets.WebSocketFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.TRANSPORT_CUSTOMIZER;
/**
* A Grizzly 2.0-based implementation of {@link AsyncHttpProvider}.
*
* @author The Grizzly Team
* @since 1.7.0
*/
public class GrizzlyAsyncHttpProvider implements AsyncHttpProvider {
private final static Logger LOGGER = LoggerFactory.getLogger(GrizzlyAsyncHttpProvider.class);
private static final boolean SEND_FILE_SUPPORT;
static {
SEND_FILE_SUPPORT = configSendFileSupport();
}
private final Attribute<HttpTransactionContext> REQUEST_STATE_ATTR =
Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(HttpTransactionContext.class.getName());
private final BodyHandlerFactory bodyHandlerFactory = new BodyHandlerFactory();
private final TCPNIOTransport clientTransport;
private final AsyncHttpClientConfig clientConfig;
private final ConnectionManager connectionManager;
DelayedExecutor.Resolver<Connection> resolver;
private DelayedExecutor timeoutExecutor;
public GrizzlyAsyncHttpProvider(final AsyncHttpClientConfig clientConfig) {
this.clientConfig = clientConfig;
final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance();
clientTransport = builder.build();
initializeTransport(clientConfig);
connectionManager = new ConnectionManager(this, clientTransport);
try {
clientTransport.start();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings({"unchecked"})
public <T> ListenableFuture<T> execute(final Request request,
final AsyncHandler<T> handler) throws IOException {
final GrizzlyResponseFuture<T> future =
new GrizzlyResponseFuture<T>(this, request, handler);
future.setDelegate(SafeFutureImpl.<T>create());
final CompletionHandler<Connection> connectHandler = new CompletionHandler<Connection>() {
@Override
public void cancelled() {
future.cancel(true);
}
@Override
public void failed(final Throwable throwable) {
future.abort(throwable);
}
@Override
public void completed(final Connection c) {
try {
execute(c, request, handler, future);
} catch (Exception e) {
if (e instanceof RuntimeException) {
failed(e);
} else if (e instanceof IOException) {
failed(e);
}
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(e.toString(), e);
}
}
}
@Override
public void updated(final Connection c) {
// no-op
}
};
try {
connectionManager.doAsyncTrackedConnection(request, future, connectHandler);
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
}
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(e.toString(), e);
}
}
return future;
}
/**
* {@inheritDoc}
*/
public void close() {
try {
connectionManager.destroy();
clientTransport.stop();
final ExecutorService service = clientConfig.executorService();
if (service != null) {
service.shutdown();
}
if (timeoutExecutor != null) {
timeoutExecutor.stop();
}
} catch (IOException ignored) { }
}
/**
* {@inheritDoc}
*/
public Response prepareResponse(HttpResponseStatus status,
HttpResponseHeaders headers,
Collection<HttpResponseBodyPart> bodyParts) {
return new GrizzlyResponse(status, headers, bodyParts);
}
@SuppressWarnings({"unchecked"})
protected <T> ListenableFuture<T> execute(final Connection c,
final Request request,
final AsyncHandler<T> handler,
final GrizzlyResponseFuture<T> future)
throws IOException {
try {
if (getHttpTransactionContext(c) == null) {
setHttpTransactionContext(c,
new HttpTransactionContext(future, request, handler));
}
c.write(request, createWriteCompletionHandler(future));
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
}
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(e.toString(), e);
}
}
return future;
}
protected void initializeTransport(AsyncHttpClientConfig clientConfig) {
final FilterChainBuilder fcb = FilterChainBuilder.stateless();
fcb.add(new AsyncHttpClientTransportFilter());
final int timeout = clientConfig.getRequestTimeoutInMs();
if (timeout > 0) {
int delay = 500;
if (timeout < delay) {
delay = timeout - 10;
}
timeoutExecutor = IdleTimeoutFilter.createDefaultIdleDelayedExecutor(delay, TimeUnit.MILLISECONDS);
timeoutExecutor.start();
final IdleTimeoutFilter.TimeoutResolver timeoutResolver =
new IdleTimeoutFilter.TimeoutResolver() {
@Override
public long getTimeout(FilterChainContext ctx) {
final HttpTransactionContext context =
GrizzlyAsyncHttpProvider.this.getHttpTransactionContext(ctx.getConnection());
if (context != null) {
final PerRequestConfig config = context.request.getPerRequestConfig();
if (config != null) {
final long timeout = config.getRequestTimeoutInMs();
if (timeout > 0) {
return timeout;
}
}
}
return timeout;
}
};
final IdleTimeoutFilter timeoutFilter = new IdleTimeoutFilter(timeoutExecutor,
timeoutResolver,
new IdleTimeoutFilter.TimeoutHandler() {
public void onTimeout(Connection connection) {
timeout(connection);
}
});
fcb.add(timeoutFilter);
resolver = timeoutFilter.getResolver();
}
SSLContext context = clientConfig.getSSLContext();
boolean defaultSecState = (context != null);
if (context == null) {
try {
context = SslUtils.getSSLContext();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
final SSLEngineConfigurator configurator =
new SSLEngineConfigurator(context,
true,
false,
false);
final SwitchingSSLFilter filter = new SwitchingSSLFilter(configurator, defaultSecState);
fcb.add(filter);
final AsyncHttpClientEventFilter eventFilter = new
AsyncHttpClientEventFilter(this);
final AsyncHttpClientFilter clientFilter =
new AsyncHttpClientFilter(clientConfig);
ContentEncoding[] encodings = eventFilter.getContentEncodings();
if (encodings.length > 0) {
for (ContentEncoding encoding : encodings) {
eventFilter.removeContentEncoding(encoding);
}
}
if (clientConfig.isCompressionEnabled()) {
eventFilter.addContentEncoding(
new GZipContentEncoding(512,
512,
new ClientEncodingFilter()));
}
fcb.add(eventFilter);
fcb.add(clientFilter);
GrizzlyAsyncHttpProviderConfig providerConfig =
(GrizzlyAsyncHttpProviderConfig) clientConfig.getAsyncHttpProviderConfig();
if (providerConfig != null) {
final TransportCustomizer customizer = (TransportCustomizer)
providerConfig.getProperty(TRANSPORT_CUSTOMIZER);
if (customizer != null) {
customizer.customize(clientTransport, fcb);
} else {
doDefaultTransportConfig();
}
} else {
doDefaultTransportConfig();
}
fcb.add(new WebSocketFilter());
clientTransport.setProcessor(fcb.build());
}
void touchConnection(final Connection c, final Request request) {
final PerRequestConfig config = request.getPerRequestConfig();
if (config != null) {
final long timeout = config.getRequestTimeoutInMs();
if (timeout > 0) {
final long newTimeout = System.currentTimeMillis() + timeout;
if (resolver != null) {
resolver.setTimeoutMillis(c, newTimeout);
}
}
} else {
final long timeout = clientConfig.getRequestTimeoutInMs();
if (timeout > 0) {
if (resolver != null) {
resolver.setTimeoutMillis(c, System.currentTimeMillis() + timeout);
}
}
}
}
private static boolean configSendFileSupport() {
return !((System.getProperty("os.name").equalsIgnoreCase("linux")
&& !linuxSendFileSupported())
|| System.getProperty("os.name").equalsIgnoreCase("HP-UX"));
}
private static boolean linuxSendFileSupported() {
final String version = System.getProperty("java.version");
if (version.startsWith("1.6")) {
int idx = version.indexOf('_');
if (idx == -1) {
return false;
}
final int patchRev = Integer.parseInt(version.substring(idx + 1));
return (patchRev >= 18);
} else {
return version.startsWith("1.7") || version.startsWith("1.8");
}
}
private void doDefaultTransportConfig() {
final ExecutorService service = clientConfig.executorService();
if (service != null) {
clientTransport.setIOStrategy(WorkerThreadIOStrategy.getInstance());
clientTransport.setWorkerThreadPool(service);
} else {
clientTransport.setIOStrategy(SameThreadIOStrategy.getInstance());
}
}
private <T> CompletionHandler<WriteResult> createWriteCompletionHandler(final GrizzlyResponseFuture<T> future) {
return new CompletionHandler<WriteResult>() {
public void cancelled() {
future.cancel(true);
}
public void failed(Throwable throwable) {
future.abort(throwable);
}
public void completed(WriteResult result) {
}
public void updated(WriteResult result) {
// no-op
}
};
}
void setHttpTransactionContext(final AttributeStorage storage,
final HttpTransactionContext httpTransactionState) {
if (httpTransactionState == null) {
REQUEST_STATE_ATTR.remove(storage);
} else {
REQUEST_STATE_ATTR.set(storage, httpTransactionState);
}
}
HttpTransactionContext getHttpTransactionContext(final AttributeStorage storage) {
return REQUEST_STATE_ATTR.get(storage);
}
void timeout(final Connection c) {
final HttpTransactionContext context = getHttpTransactionContext(c);
setHttpTransactionContext(c, null);
context.abort(new TimeoutException("Timeout exceeded"));
}
static int getPort(final URI uri, final int p) {
int port = p;
if (port == -1) {
final String protocol = uri.getScheme().toLowerCase();
if ("http".equals(protocol)) {
port = 80;
} else if ("https".equals(protocol)) {
port = 443;
} else {
throw new IllegalArgumentException("Unknown protocol: " + protocol);
}
}
return port;
}
@SuppressWarnings({"unchecked"})
boolean sendRequest(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
boolean isWriteComplete = true;
if (requestHasEntityBody(request)) {
final HttpTransactionContext context = getHttpTransactionContext(ctx.getConnection());
BodyHandler handler = bodyHandlerFactory.getBodyHandler(request);
if (requestPacket.getHeaders().contains(Header.Expect)
&& requestPacket.getHeaders().getValue(1).equalsIgnoreCase("100-Continue")) {
handler = new ExpectHandler(handler);
}
context.bodyHandler = handler;
isWriteComplete = handler.doHandle(ctx, request, requestPacket);
} else {
ctx.write(requestPacket, ctx.getTransportContext().getCompletionHandler());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("REQUEST: " + requestPacket.toString());
}
return isWriteComplete;
}
private static boolean requestHasEntityBody(final Request request) {
final String method = request.getMethod();
return (Method.POST.matchesMethod(method)
|| Method.PUT.matchesMethod(method)
|| Method.PATCH.matchesMethod(method)
|| Method.DELETE.matchesMethod(method));
}
private interface StatusHandler {
public enum InvocationStatus {
CONTINUE,
STOP
}
boolean handleStatus(final HttpResponsePacket httpResponse,
final HttpTransactionContext httpTransactionContext,
final FilterChainContext ctx);
boolean handlesStatus(final int statusCode);
} // END StatusHandler
final class HttpTransactionContext {
final AtomicInteger redirectCount = new AtomicInteger(0);
final int maxRedirectCount;
final boolean redirectsAllowed;
final GrizzlyAsyncHttpProvider provider =
GrizzlyAsyncHttpProvider.this;
Request request;
String requestUrl;
AsyncHandler handler;
BodyHandler bodyHandler;
StatusHandler statusHandler;
StatusHandler.InvocationStatus invocationStatus =
StatusHandler.InvocationStatus.CONTINUE;
GrizzlyResponseStatus responseStatus;
GrizzlyResponseFuture future;
String lastRedirectURI;
AtomicLong totalBodyWritten = new AtomicLong();
AsyncHandler.STATE currentState;
String wsRequestURI;
boolean isWSRequest;
HandShake handshake;
ProtocolHandler protocolHandler;
WebSocket webSocket;
HttpTransactionContext(final GrizzlyResponseFuture future,
final Request request,
final AsyncHandler handler) {
this.future = future;
this.request = request;
this.handler = handler;
redirectsAllowed = provider.clientConfig.isRedirectEnabled();
maxRedirectCount = provider.clientConfig.getMaxRedirects();
this.requestUrl = request.getUrl();
}
HttpTransactionContext copy() {
final HttpTransactionContext newContext =
new HttpTransactionContext(future,
request,
handler);
newContext.invocationStatus = invocationStatus;
newContext.bodyHandler = bodyHandler;
newContext.currentState = currentState;
newContext.statusHandler = statusHandler;
newContext.lastRedirectURI = lastRedirectURI;
newContext.redirectCount.set(redirectCount.get());
return newContext;
}
void abort(final Throwable t) {
if (future != null) {
future.abort(t);
}
}
void done(final Callable c) {
if (future != null) {
future.done(c);
}
}
@SuppressWarnings({"unchecked"})
void result(Object result) {
if (future != null) {
future.delegate.result(result);
future.done(null);
}
}
} // END HttpTransactionContext
private static final class ContinueEvent implements FilterChainEvent {
private final HttpTransactionContext context;
ContinueEvent(final HttpTransactionContext context) {
this.context = context;
}
@Override
public Object type() {
return ContinueEvent.class;
}
} // END ContinueEvent
private final class AsyncHttpClientTransportFilter extends TransportFilter {
@Override
public NextAction handleRead(FilterChainContext ctx) throws IOException {
final HttpTransactionContext context = getHttpTransactionContext(ctx.getConnection());
if (context == null) {
return super.handleRead(ctx);
}
ctx.getTransportContext().setCompletionHandler(new CompletionHandler() {
@Override
public void cancelled() {
}
@Override
public void failed(Throwable throwable) {
if (throwable instanceof EOFException) {
context.abort(new IOException("Remotely Closed"));
}
context.abort(throwable);
}
@Override
public void completed(Object result) {
}
@Override
public void updated(Object result) {
}
});
return super.handleRead(ctx);
}
} // END AsyncHttpClientTransportFilter
private final class AsyncHttpClientFilter extends BaseFilter {
private final AsyncHttpClientConfig config;
AsyncHttpClientFilter(final AsyncHttpClientConfig config) {
this.config = config;
}
@Override
public NextAction handleWrite(final FilterChainContext ctx)
throws IOException {
Object message = ctx.getMessage();
if (message instanceof Request) {
ctx.setMessage(null);
if (!sendAsGrizzlyRequest((Request) message, ctx)) {
return ctx.getSuspendAction();
}
} else if (message instanceof Buffer) {
return ctx.getInvokeAction();
}
return ctx.getStopAction();
}
@Override
public NextAction handleEvent(final FilterChainContext ctx,
final FilterChainEvent event)
throws IOException {
final Object type = event.type();
if (type == ContinueEvent.class) {
final ContinueEvent continueEvent = (ContinueEvent) event;
((ExpectHandler) continueEvent.context.bodyHandler).finish(ctx);
}
return ctx.getStopAction();
}
// @Override
// public NextAction handleRead(FilterChainContext ctx) throws IOException {
// Object message = ctx.getMessage();
// if (HttpPacket.isHttp(message)) {
// final HttpPacket packet = (HttpPacket) message;
// HttpResponsePacket responsePacket;
// if (HttpContent.isContent(packet)) {
// responsePacket = (HttpResponsePacket) ((HttpContent) packet).getHttpHeader();
// } else {
// responsePacket = (HttpResponsePacket) packet;
// if (HttpStatus.SWITCHING_PROTOCOLS_101.statusMatches(responsePacket.getStatus())) {
// return ctx.getStopAction();
// return super.handleRead(ctx);
private boolean sendAsGrizzlyRequest(final Request request,
final FilterChainContext ctx)
throws IOException {
final HttpTransactionContext httpCtx = getHttpTransactionContext(ctx.getConnection());
if (isUpgradeRequest(httpCtx.handler) && isWSRequest(httpCtx.requestUrl)) {
httpCtx.isWSRequest = true;
convertToUpgradeRequest(httpCtx);
}
final URI uri = AsyncHttpProviderUtils.createUri(httpCtx.requestUrl);
final HttpRequestPacket.Builder builder = HttpRequestPacket.builder();
boolean secure = "https".equals(uri.getScheme());
builder.method(request.getMethod());
builder.protocol(Protocol.HTTP_1_1);
String host = request.getVirtualHost();
if (host != null) {
builder.header(Header.Host, host);
} else {
if (uri.getPort() == -1) {
builder.header(Header.Host, uri.getHost());
} else {
builder.header(Header.Host, uri.getHost() + ':' + uri.getPort());
}
}
final ProxyServer proxy = getProxyServer(request);
final boolean useProxy = (proxy != null);
if (useProxy) {
if (secure) {
builder.method(Method.CONNECT);
builder.uri(AsyncHttpProviderUtils.getAuthority(uri));
} else {
builder.uri(uri.toString());
}
} else {
builder.uri(uri.getPath());
}
if (requestHasEntityBody(request)) {
final long contentLength = request.getContentLength();
if (contentLength > 0) {
builder.contentLength(contentLength);
builder.chunked(false);
} else {
builder.chunked(true);
}
}
HttpRequestPacket requestPacket;
if (httpCtx.isWSRequest) {
try {
final URI wsURI = new URI(httpCtx.wsRequestURI);
httpCtx.protocolHandler = Version.DRAFT17.createHandler(true);
httpCtx.handshake = httpCtx.protocolHandler.createHandShake(wsURI);
requestPacket = (HttpRequestPacket)
httpCtx.handshake.composeHeaders().getHttpHeader();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid WS URI: " + httpCtx.wsRequestURI);
}
} else {
requestPacket = builder.build();
}
requestPacket.setSecure(true);
if (!useProxy) {
addQueryString(request, requestPacket);
}
addHeaders(request, requestPacket);
addCookies(request, requestPacket);
if (useProxy) {
boolean avoidProxy = ProxyUtils.avoidProxy(proxy, request);
if (!avoidProxy) {
if (!requestPacket.getHeaders().contains(Header.ProxyConnection)) {
requestPacket.setHeader(Header.ProxyConnection, "keep-alive");
}
if (proxy.getPrincipal() != null) {
requestPacket.setHeader(Header.ProxyAuthorization,
AuthenticatorUtils.computeBasicAuthentication(proxy));
}
}
}
final AsyncHandler h = httpCtx.handler;
if (h != null) {
if (TransferCompletionHandler.class.isAssignableFrom(h.getClass())) {
final FluentCaseInsensitiveStringsMap map =
new FluentCaseInsensitiveStringsMap(request.getHeaders());
TransferCompletionHandler.class.cast(h).transferAdapter(new GrizzlyTransferAdapter(map));
}
}
return sendRequest(ctx, request, requestPacket);
}
private boolean isUpgradeRequest(final AsyncHandler handler) {
return (handler instanceof UpgradeHandler);
}
private boolean isWSRequest(final String requestUri) {
return (requestUri.charAt(0) == 'w' && requestUri.charAt(1) == 's');
}
private void convertToUpgradeRequest(final HttpTransactionContext ctx) {
final int colonIdx = ctx.requestUrl.indexOf(':');
if (colonIdx < 2 || colonIdx > 3) {
throw new IllegalArgumentException("Invalid websocket URL: " + ctx.requestUrl);
}
final StringBuilder sb = new StringBuilder(ctx.requestUrl);
sb.replace(0, colonIdx, ((colonIdx == 2) ? "http" : "https"));
ctx.wsRequestURI = ctx.requestUrl;
ctx.requestUrl = sb.toString();
}
private ProxyServer getProxyServer(Request request) {
ProxyServer proxyServer = request.getProxyServer();
if (proxyServer == null) {
proxyServer = config.getProxyServer();
}
return proxyServer;
}
private void addHeaders(final Request request,
final HttpRequestPacket requestPacket) {
final FluentCaseInsensitiveStringsMap map = request.getHeaders();
if (map != null && !map.isEmpty()) {
for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
final String headerName = entry.getKey();
final List<String> headerValues = entry.getValue();
if (headerValues != null && !headerValues.isEmpty()) {
for (final String headerValue : headerValues) {
requestPacket.addHeader(headerName, headerValue);
}
}
}
}
final MimeHeaders headers = requestPacket.getHeaders();
if (!headers.contains(Header.Connection)) {
requestPacket.addHeader(Header.Connection, "keep-alive");
}
if (!headers.contains(Header.Accept)) {
requestPacket.addHeader(Header.Accept, "*/*");
}
if (!headers.contains(Header.UserAgent)) {
requestPacket.addHeader(Header.UserAgent, config.getUserAgent());
}
}
private void addCookies(final Request request,
final HttpRequestPacket requestPacket) {
final Collection<Cookie> cookies = request.getCookies();
if (cookies != null && !cookies.isEmpty()) {
StringBuilder sb = new StringBuilder(128);
org.glassfish.grizzly.http.Cookie[] gCookies =
new org.glassfish.grizzly.http.Cookie[cookies.size()];
convertCookies(cookies, gCookies);
CookieSerializerUtils.serializeClientCookies(sb, gCookies);
requestPacket.addHeader(Header.Cookie, sb.toString());
}
}
private void convertCookies(final Collection<Cookie> cookies,
final org.glassfish.grizzly.http.Cookie[] gCookies) {
int idx = 0;
for (final Cookie cookie : cookies) {
final org.glassfish.grizzly.http.Cookie gCookie =
new org.glassfish.grizzly.http.Cookie(cookie.getName(), cookie.getValue());
gCookie.setDomain(cookie.getDomain());
gCookie.setPath(cookie.getPath());
gCookie.setVersion(cookie.getVersion());
gCookie.setMaxAge(cookie.getMaxAge());
gCookie.setSecure(cookie.isSecure());
gCookies[idx] = gCookie;
idx++;
}
}
private void addQueryString(final Request request,
final HttpRequestPacket requestPacket) {
final FluentStringsMap map = request.getQueryParams();
if (map != null && !map.isEmpty()) {
StringBuilder sb = new StringBuilder(128);
for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
final String name = entry.getKey();
final List<String> values = entry.getValue();
if (values != null && !values.isEmpty()) {
try {
for (int i = 0, len = values.size(); i < len; i++) {
final String value = values.get(i);
if (value != null && value.length() > 0) {
sb.append(URLEncoder.encode(name, "UTF-8")).append('=')
.append(URLEncoder.encode(values.get(i), "UTF-8")).append('&');
} else {
sb.append(URLEncoder.encode(name, "UTF-8")).append('&');
}
}
} catch (UnsupportedEncodingException ignored) {
}
}
}
String queryString = sb.deleteCharAt((sb.length() - 1)).toString();
requestPacket.setQueryString(queryString);
}
}
} // END AsyncHttpClientFiler
private static final class AsyncHttpClientEventFilter extends HttpClientFilter {
private final Map<Integer,StatusHandler> HANDLER_MAP = new HashMap<Integer,StatusHandler>();
private final GrizzlyAsyncHttpProvider provider;
AsyncHttpClientEventFilter(final GrizzlyAsyncHttpProvider provider) {
this.provider = provider;
HANDLER_MAP.put(HttpStatus.UNAUTHORIZED_401.getStatusCode(),
AuthorizationHandler.INSTANCE);
HANDLER_MAP.put(HttpStatus.MOVED_PERMANENTLY_301.getStatusCode(),
RedirectHandler.INSTANCE);
HANDLER_MAP.put(HttpStatus.FOUND_302.getStatusCode(),
RedirectHandler.INSTANCE);
HANDLER_MAP.put(HttpStatus.TEMPORARY_REDIRECT_307.getStatusCode(),
RedirectHandler.INSTANCE);
}
@Override
public void exceptionOccurred(FilterChainContext ctx, Throwable error) {
provider.getHttpTransactionContext(ctx.getConnection()).abort(error);
}
@Override
protected void onHttpContentParsed(HttpContent content,
FilterChainContext ctx) {
final HttpTransactionContext context =
provider.getHttpTransactionContext(ctx.getConnection());
final AsyncHandler handler = context.handler;
if (handler != null && context.currentState != AsyncHandler.STATE.ABORT) {
try {
context.currentState = handler.onBodyPartReceived(
new GrizzlyResponseBodyPart(content,
null,
ctx.getConnection(),
provider));
} catch (Exception e) {
handler.onThrowable(e);
}
}
}
@Override
protected void onHttpHeadersEncoded(HttpHeader httpHeader, FilterChainContext ctx) {
final HttpTransactionContext context = provider.getHttpTransactionContext(ctx.getConnection());
final AsyncHandler handler = context.handler;
if (handler != null) {
if (TransferCompletionHandler.class.isAssignableFrom(handler.getClass())) {
((TransferCompletionHandler) handler).onHeaderWriteCompleted();
}
}
}
@Override
protected void onHttpContentEncoded(HttpContent content, FilterChainContext ctx) {
final HttpTransactionContext context = provider.getHttpTransactionContext(ctx.getConnection());
final AsyncHandler handler = context.handler;
if (handler != null) {
if (TransferCompletionHandler.class.isAssignableFrom(handler.getClass())) {
final int written = content.getContent().remaining();
final long total = context.totalBodyWritten.addAndGet(written);
((TransferCompletionHandler) handler).onContentWriteProgress(
written,
total,
content.getHttpHeader().getContentLength());
}
}
}
@Override
protected void onInitialLineParsed(HttpHeader httpHeader,
FilterChainContext ctx) {
super.onInitialLineParsed(httpHeader, ctx);
if (httpHeader.isSkipRemainder()) {
return;
}
final HttpTransactionContext context =
provider.getHttpTransactionContext(ctx.getConnection());
final int status = ((HttpResponsePacket) httpHeader).getStatus();
if (HttpStatus.CONINTUE_100.statusMatches(status)) {
try {
ctx.notifyUpstream(new ContinueEvent(context));
return;
} catch (IOException e) {
httpHeader.setSkipRemainder(true);
context.abort(e);
}
}
if (context.statusHandler != null && !context.statusHandler.handlesStatus(status)) {
context.statusHandler = null;
context.invocationStatus = StatusHandler.InvocationStatus.CONTINUE;
} else {
context.statusHandler = null;
}
if (context.invocationStatus == StatusHandler.InvocationStatus.CONTINUE) {
if (HANDLER_MAP.containsKey(status)) {
context.statusHandler = HANDLER_MAP.get(status);
}
if (context.statusHandler instanceof RedirectHandler) {
if (!isRedirectAllowed(context)) {
context.statusHandler = null;
}
}
}
if (isRedirectAllowed(context)) {
if (isRedirect(status)) {
if (context.statusHandler == null) {
context.statusHandler = RedirectHandler.INSTANCE;
}
context.redirectCount.incrementAndGet();
if (redirectCountExceeded(context)) {
httpHeader.setSkipRemainder(true);
context.abort(new MaxRedirectException());
}
} else {
if (context.redirectCount.get() > 0) {
context.redirectCount.set(0);
}
}
}
final GrizzlyResponseStatus responseStatus =
new GrizzlyResponseStatus((HttpResponsePacket) httpHeader,
getURI(context.requestUrl),
provider);
context.responseStatus = responseStatus;
if (context.statusHandler != null) {
return;
}
if (context.currentState != AsyncHandler.STATE.ABORT) {
try {
final AsyncHandler handler = context.handler;
if (handler != null) {
context.currentState = handler.onStatusReceived(responseStatus);
}
} catch (Exception e) {
httpHeader.setSkipRemainder(true);
context.abort(e);
}
}
}
@Override
protected void onHttpHeaderError(final HttpHeader httpHeader,
final FilterChainContext ctx,
final Throwable t) throws IOException {
t.printStackTrace();
httpHeader.setSkipRemainder(true);
final HttpTransactionContext context =
provider.getHttpTransactionContext(ctx.getConnection());
context.abort(t);
}
@SuppressWarnings({"unchecked"})
@Override
protected void onHttpHeadersParsed(HttpHeader httpHeader,
FilterChainContext ctx) {
super.onHttpHeadersParsed(httpHeader, ctx);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("RESPONSE: " + httpHeader.toString());
}
if (httpHeader.containsHeader(Header.Connection)) {
if ("close".equals(httpHeader.getHeader(Header.Connection))) {
ConnectionManager.markConnectionAsDoNotCache(ctx.getConnection());
}
}
if (httpHeader.isSkipRemainder()) {
return;
}
final HttpTransactionContext context =
provider.getHttpTransactionContext(ctx.getConnection());
final AsyncHandler handler = context.handler;
final List<ResponseFilter> filters = context.provider.clientConfig.getResponseFilters();
if (!filters.isEmpty()) {
FilterContext fc = new FilterContext.FilterContextBuilder()
.asyncHandler(handler).request(context.request)
.responseStatus(context.responseStatus).build();
try {
for (final ResponseFilter f : filters) {
fc = f.filter(fc);
}
} catch (Exception e) {
context.abort(e);
}
if (fc.replayRequest()) {
httpHeader.setSkipRemainder(true);
final Request newRequest = fc.getRequest();
final AsyncHandler newHandler = fc.getAsyncHandler();
try {
final ConnectionManager m =
context.provider.connectionManager;
final Connection c =
m.obtainConnection(newRequest,
context.future);
final HttpTransactionContext newContext =
context.copy();
context.future = null;
provider.setHttpTransactionContext(c, newContext);
try {
context.provider.execute(c,
newRequest,
newHandler,
context.future);
} catch (IOException ioe) {
newContext.abort(ioe);
}
} catch (Exception e) {
context.abort(e);
}
return;
}
}
if (context.statusHandler != null && context.invocationStatus == StatusHandler.InvocationStatus.CONTINUE) {
final boolean result = context.statusHandler.handleStatus(((HttpResponsePacket) httpHeader),
context,
ctx);
if (!result) {
httpHeader.setSkipRemainder(true);
return;
}
}
if (context.currentState != AsyncHandler.STATE.ABORT) {
boolean upgrade = context.currentState == AsyncHandler.STATE.UPGRADE;
try {
context.currentState = handler.onHeadersReceived(
new GrizzlyResponseHeaders((HttpResponsePacket) httpHeader,
null,
provider));
} catch (Exception e) {
httpHeader.setSkipRemainder(true);
context.abort(e);
return;
}
if (upgrade) {
try {
context.protocolHandler.setConnection(ctx.getConnection());
DefaultWebSocket ws = new DefaultWebSocket(context.protocolHandler);
ws.onConnect();
context.webSocket = new GrizzlyWebSocketAdapter(ws);
WebSocketEngine.getEngine().setWebSocketHolder(ctx.getConnection(),
context.protocolHandler,
ws);
((WebSocketUpgradeHandler) context.handler).onSuccess(context.webSocket);
context.result(handler.onCompleted());
} catch (Exception e) {
httpHeader.setSkipRemainder(true);
context.abort(e);
}
}
}
}
@SuppressWarnings({"unchecked"})
@Override
protected boolean onHttpPacketParsed(HttpHeader httpHeader, FilterChainContext ctx) {
boolean result;
if (httpHeader.isSkipRemainder()) {
clearResponse(ctx.getConnection());
cleanup(ctx, provider);
return false;
}
result = super.onHttpPacketParsed(httpHeader, ctx);
final HttpTransactionContext context = cleanup(ctx, provider);
final AsyncHandler handler = context.handler;
if (handler != null) {
try {
context.result(handler.onCompleted());
} catch (Exception e) {
context.abort(e);
}
} else {
context.done(null);
}
return result;
}
private static boolean isRedirectAllowed(final HttpTransactionContext ctx) {
boolean allowed = ctx.request.isRedirectEnabled();
if (ctx.request.isRedirectOverrideSet()) {
return allowed;
}
if (!allowed) {
allowed = ctx.redirectsAllowed;
}
return allowed;
}
private static HttpTransactionContext cleanup(final FilterChainContext ctx,
final GrizzlyAsyncHttpProvider provider) {
final Connection c = ctx.getConnection();
final HttpTransactionContext context =
provider.getHttpTransactionContext(c);
context.provider.setHttpTransactionContext(c, null);
if (!context.provider.connectionManager.canReturnConnection(c)) {
context.abort(new IOException("Maximum pooled connections exceeded"));
} else {
if (!context.provider.connectionManager.returnConnection(context.requestUrl, c)) {
try {
ctx.getConnection().close().markForRecycle(true);
} catch (IOException ignored) {
}
}
}
return context;
}
private static URI getURI(String url) {
return AsyncHttpProviderUtils.createUri(url);
}
private static boolean redirectCountExceeded(final HttpTransactionContext context) {
return (context.redirectCount.get() > context.maxRedirectCount);
}
private static boolean isRedirect(final int status) {
return HttpStatus.MOVED_PERMANENTLY_301.statusMatches(status)
|| HttpStatus.FOUND_302.statusMatches(status)
|| HttpStatus.TEMPORARY_REDIRECT_307.statusMatches(status);
}
private static final class AuthorizationHandler implements StatusHandler {
private static final AuthorizationHandler INSTANCE =
new AuthorizationHandler();
public boolean handlesStatus(int statusCode) {
return (HttpStatus.UNAUTHORIZED_401.statusMatches(statusCode));
}
@SuppressWarnings({"unchecked"})
public boolean handleStatus(final HttpResponsePacket responsePacket,
final HttpTransactionContext httpTransactionContext,
final FilterChainContext ctx) {
responsePacket.setSkipRemainder(true); // ignore the remainder of the response
final String auth = responsePacket.getHeader(Header.WWWAuthenticate);
if (auth == null) {
throw new IllegalStateException("401 response received, but no WWW-Authenticate header was present");
}
Realm realm = httpTransactionContext.request.getRealm();
if (realm == null) {
realm = httpTransactionContext.provider.clientConfig.getRealm();
}
if (realm == null) {
httpTransactionContext.invocationStatus = InvocationStatus.STOP;
return true;
}
final Request req = httpTransactionContext.request;
realm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(httpTransactionContext.requestUrl).getPath())
.setMethodName(req.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(auth)
.build();
if (auth.toLowerCase().startsWith("basic")) {
req.getHeaders().remove(Header.Authorization.toString());
try {
req.getHeaders().add(Header.Authorization.toString(),
AuthenticatorUtils.computeBasicAuthentication(realm));
} catch (UnsupportedEncodingException ignored) {
}
} else if (auth.toLowerCase().startsWith("digest")) {
req.getHeaders().remove(Header.Authorization.toString());
try {
req.getHeaders().add(Header.Authorization.toString(),
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Digest authentication not supported", e);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unsupported encoding.", e);
}
} else {
throw new IllegalStateException("Unsupported authorization method: " + auth);
}
final ConnectionManager m = httpTransactionContext.provider.connectionManager;
try {
final Connection c = m.obtainConnection(req,
httpTransactionContext.future);
final HttpTransactionContext newContext =
httpTransactionContext.copy();
httpTransactionContext.future = null;
httpTransactionContext.provider.setHttpTransactionContext(c, newContext);
newContext.invocationStatus = InvocationStatus.STOP;
try {
httpTransactionContext.provider.execute(c,
req,
httpTransactionContext.handler,
httpTransactionContext.future);
return false;
} catch (IOException ioe) {
newContext.abort(ioe);
return false;
}
} catch (Exception e) {
httpTransactionContext.abort(e);
}
httpTransactionContext.invocationStatus = InvocationStatus.STOP;
return false;
}
} // END AuthorizationHandler
private static final class RedirectHandler implements StatusHandler {
private static final RedirectHandler INSTANCE = new RedirectHandler();
public boolean handlesStatus(int statusCode) {
return (isRedirect(statusCode));
}
@SuppressWarnings({"unchecked"})
public boolean handleStatus(final HttpResponsePacket responsePacket,
final HttpTransactionContext httpTransactionContext,
final FilterChainContext ctx) {
final String redirectURL = responsePacket.getHeader(Header.Location);
if (redirectURL == null) {
throw new IllegalStateException("redirect received, but no location header was present");
}
URI orig;
if (httpTransactionContext.lastRedirectURI == null) {
orig = AsyncHttpProviderUtils.createUri(httpTransactionContext.requestUrl);
} else {
orig = AsyncHttpProviderUtils.getRedirectUri(AsyncHttpProviderUtils.createUri(httpTransactionContext.requestUrl),
httpTransactionContext.lastRedirectURI);
}
httpTransactionContext.lastRedirectURI = redirectURL;
Request requestToSend;
URI uri = AsyncHttpProviderUtils.getRedirectUri(orig, redirectURL);
if (!uri.toString().equalsIgnoreCase(orig.toString())) {
requestToSend = newRequest(uri,
responsePacket,
httpTransactionContext);
} else {
httpTransactionContext.statusHandler = null;
httpTransactionContext.invocationStatus = InvocationStatus.CONTINUE;
try {
httpTransactionContext.handler.onStatusReceived(httpTransactionContext.responseStatus);
} catch (Exception e) {
httpTransactionContext.abort(e);
}
return true;
}
final ConnectionManager m = httpTransactionContext.provider.connectionManager;
try {
final Connection c = m.obtainConnection(requestToSend,
httpTransactionContext.future);
if (switchingSchemes(orig, uri)) {
try {
notifySchemeSwitch(ctx, c, uri);
} catch (IOException ioe) {
httpTransactionContext.abort(ioe);
}
}
final HttpTransactionContext newContext =
httpTransactionContext.copy();
httpTransactionContext.future = null;
newContext.invocationStatus = InvocationStatus.CONTINUE;
newContext.request = requestToSend;
newContext.requestUrl = requestToSend.getUrl();
httpTransactionContext.provider.setHttpTransactionContext(c, newContext);
httpTransactionContext.provider.execute(c,
requestToSend,
newContext.handler,
newContext.future);
return false;
} catch (Exception e) {
httpTransactionContext.abort(e);
}
httpTransactionContext.invocationStatus = InvocationStatus.CONTINUE;
return true;
}
private boolean switchingSchemes(final URI oldUri,
final URI newUri) {
return !oldUri.getScheme().equals(newUri.getScheme());
}
private void notifySchemeSwitch(final FilterChainContext ctx,
final Connection c,
final URI uri) throws IOException {
ctx.notifyDownstream(new SwitchingSSLFilter.SSLSwitchingEvent(
"https".equals(uri.getScheme()), c));
}
} // END RedirectHandler
private static Request newRequest(final URI uri,
final HttpResponsePacket response,
final HttpTransactionContext ctx) {
final RequestBuilder builder = new RequestBuilder(ctx.request);
builder.setUrl(uri.toString());
if (ctx.provider.clientConfig.isRemoveQueryParamOnRedirect()) {
builder.setQueryParameters(null);
}
for (String cookieStr : response.getHeaders().values(Header.Cookie)) {
Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
builder.addOrReplaceCookie(c);
}
return builder.build();
}
} // END AsyncHttpClientEventFilter
private static final class ClientEncodingFilter implements EncodingFilter {
public boolean applyEncoding(HttpHeader httpPacket) {
httpPacket.addHeader(Header.AcceptEncoding, "gzip");
return true;
}
public boolean applyDecoding(HttpHeader httpPacket) {
final HttpResponsePacket httpResponse = (HttpResponsePacket) httpPacket;
final DataChunk bc = httpResponse.getHeaders().getValue(Header.ContentEncoding);
return bc != null && bc.indexOf("gzip", 0) != -1;
}
} // END ClientContentEncoding
private static final class NonCachingPool implements ConnectionsPool<String,Connection> {
public boolean offer(String uri, Connection connection) {
return false;
}
public Connection poll(String uri) {
return null;
}
public boolean removeAll(Connection connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
// no-op
}
} // END NonCachingPool
private static interface BodyHandler {
static int MAX_CHUNK_SIZE = 8192;
boolean handlesBodyType(final Request request);
boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket) throws IOException;
} // END BodyHandler
private final class BodyHandlerFactory {
private final BodyHandler[] HANDLERS = new BodyHandler[] {
new StringBodyHandler(),
new ByteArrayBodyHandler(),
new ParamsBodyHandler(),
new EntityWriterBodyHandler(),
new StreamDataBodyHandler(),
new PartsBodyHandler(),
new FileBodyHandler(),
new BodyGeneratorBodyHandler()
};
public BodyHandler getBodyHandler(final Request request) {
for (final BodyHandler h : HANDLERS) {
if (h.handlesBodyType(request)) {
return h;
}
}
return new NoBodyHandler();
}
} // END BodyHandlerFactory
private static final class ExpectHandler implements BodyHandler {
private final BodyHandler delegate;
private Request request;
private HttpRequestPacket requestPacket;
private ExpectHandler(final BodyHandler delegate) {
this.delegate = delegate;
}
public boolean handlesBodyType(Request request) {
return delegate.handlesBodyType(request);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(FilterChainContext ctx, Request request, HttpRequestPacket requestPacket) throws IOException {
this.request = request;
this.requestPacket = requestPacket;
ctx.write(requestPacket, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
return true;
}
public void finish(final FilterChainContext ctx) throws IOException {
delegate.doHandle(ctx, request, requestPacket);
}
} // END ContinueHandler
private final class ByteArrayBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getByteData() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
String charset = request.getBodyEncoding();
if (charset == null) {
charset = Charsets.DEFAULT_CHARACTER_ENCODING;
}
final byte[] data = new String(request.getByteData(), charset).getBytes(charset);
final MemoryManager mm = ctx.getMemoryManager();
final Buffer gBuffer = Buffers.wrap(mm, data);
if (requestPacket.getContentLength() == -1) {
if (!clientConfig.isCompressionEnabled()) {
requestPacket.setContentLengthLong(data.length);
}
}
final HttpContent content = requestPacket.httpContentBuilder().content(gBuffer).build();
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
return true;
}
}
private final class StringBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getStringData() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
String charset = request.getBodyEncoding();
if (charset == null) {
charset = Charsets.DEFAULT_CHARACTER_ENCODING;
}
final byte[] data = request.getStringData().getBytes(charset);
final MemoryManager mm = ctx.getMemoryManager();
final Buffer gBuffer = Buffers.wrap(mm, data);
if (requestPacket.getContentLength() == -1) {
if (!clientConfig.isCompressionEnabled()) {
requestPacket.setContentLengthLong(data.length);
}
}
final HttpContent content = requestPacket.httpContentBuilder().content(gBuffer).build();
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
return true;
}
} // END StringBodyHandler
private static final class NoBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return false;
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
final HttpContent content = requestPacket.httpContentBuilder().content(Buffers.EMPTY_BUFFER).build();
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
return true;
}
} // END NoBodyHandler
private final class ParamsBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
final FluentStringsMap params = request.getParams();
return (params != null && !params.isEmpty());
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
if (requestPacket.getContentType() == null) {
requestPacket.setContentType("application/x-www-form-urlencoded");
}
StringBuilder sb = null;
String charset = request.getBodyEncoding();
if (charset == null) {
charset = Charsets.DEFAULT_CHARACTER_ENCODING;
}
final FluentStringsMap params = request.getParams();
if (!params.isEmpty()) {
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String name = entry.getKey();
List<String> values = entry.getValue();
if (values != null && !values.isEmpty()) {
if (sb == null) {
sb = new StringBuilder(128);
}
for (String value : values) {
if (sb.length() > 0) {
sb.append('&');
}
sb.append(URLEncoder.encode(name, charset))
.append('=').append(URLEncoder.encode(value, charset));
}
}
}
}
if (sb != null) {
final byte[] data = sb.toString().getBytes(charset);
final MemoryManager mm = ctx.getMemoryManager();
final Buffer gBuffer = Buffers.wrap(mm, data);
final HttpContent content = requestPacket.httpContentBuilder().content(gBuffer).build();
if (requestPacket.getContentLength() == -1) {
if (!clientConfig.isCompressionEnabled()) {
requestPacket.setContentLengthLong(data.length);
}
}
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
return true;
}
} // END ParamsBodyHandler
private static final class EntityWriterBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getEntityWriter() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
final MemoryManager mm = ctx.getMemoryManager();
Buffer b = mm.allocate(512);
BufferOutputStream o = new BufferOutputStream(mm, b, true);
final Request.EntityWriter writer = request.getEntityWriter();
writer.writeEntity(o);
b = o.getBuffer();
b.trim();
if (b.hasRemaining()) {
final HttpContent content = requestPacket.httpContentBuilder().content(b).build();
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
return true;
}
} // END EntityWriterBodyHandler
private static final class StreamDataBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getStreamData() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
final MemoryManager mm = ctx.getMemoryManager();
Buffer buffer = mm.allocate(512);
final byte[] b = new byte[512];
int read;
final InputStream in = request.getStreamData();
try {
in.reset();
} catch (IOException ioe) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(ioe.toString(), ioe);
}
}
if (in.markSupported()) {
in.mark(0);
}
while ((read = in.read(b)) != -1) {
if (read > buffer.remaining()) {
buffer = mm.reallocate(buffer, buffer.capacity() + 512);
}
buffer.put(b, 0, read);
}
buffer.trim();
if (buffer.hasRemaining()) {
final HttpContent content = requestPacket.httpContentBuilder().content(buffer).build();
buffer.allowBufferDispose(false);
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
return true;
}
} // END StreamDataBodyHandler
private static final class PartsBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
final List<Part> parts = request.getParts();
return (parts != null && !parts.isEmpty());
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
MultipartRequestEntity mre =
AsyncHttpProviderUtils.createMultipartRequestEntity(
request.getParts(),
request.getParams());
requestPacket.setContentLengthLong(mre.getContentLength());
requestPacket.setContentType(mre.getContentType());
final MemoryManager mm = ctx.getMemoryManager();
Buffer b = mm.allocate(512);
BufferOutputStream o = new BufferOutputStream(mm, b, true);
mre.writeRequest(o);
b = o.getBuffer();
b.trim();
if (b.hasRemaining()) {
final HttpContent content = requestPacket.httpContentBuilder().content(b).build();
content.setLast(true);
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
return true;
}
} // END PartsBodyHandler
private final class FileBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getFile() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
final File f = request.getFile();
requestPacket.setContentLengthLong(f.length());
final HttpTransactionContext context = getHttpTransactionContext(ctx.getConnection());
if (!SEND_FILE_SUPPORT || requestPacket.isSecure()) {
final FileInputStream fis = new FileInputStream(request.getFile());
final MemoryManager mm = ctx.getMemoryManager();
AtomicInteger written = new AtomicInteger();
boolean last = false;
try {
for (byte[] buf = new byte[MAX_CHUNK_SIZE]; !last; ) {
Buffer b = null;
int read;
if ((read = fis.read(buf)) < 0) {
last = true;
b = Buffers.EMPTY_BUFFER;
}
if (b != Buffers.EMPTY_BUFFER) {
written.addAndGet(read);
b = Buffers.wrap(mm, buf, 0, read);
}
final HttpContent content =
requestPacket.httpContentBuilder().content(b).
last(last).build();
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
} finally {
try {
fis.close();
} catch (IOException ignored) {
}
}
} else {
// write the headers
ctx.write(requestPacket, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
ctx.write(new FileTransfer(f), new EmptyCompletionHandler<WriteResult>() {
@Override
public void updated(WriteResult result) {
final AsyncHandler handler = context.handler;
if (handler != null) {
if (TransferCompletionHandler.class.isAssignableFrom(handler.getClass())) {
final long written = result.getWrittenSize();
final long total = context.totalBodyWritten.addAndGet(written);
((TransferCompletionHandler) handler).onContentWriteProgress(
written,
total,
requestPacket.getContentLength());
}
}
}
});
}
return true;
}
} // END FileBodyHandler
private static final class BodyGeneratorBodyHandler implements BodyHandler {
public boolean handlesBodyType(final Request request) {
return (request.getBodyGenerator() != null);
}
@SuppressWarnings({"unchecked"})
public boolean doHandle(final FilterChainContext ctx,
final Request request,
final HttpRequestPacket requestPacket)
throws IOException {
final BodyGenerator generator = request.getBodyGenerator();
final Body bodyLocal = generator.createBody();
final long len = bodyLocal.getContentLength();
if (len > 0) {
requestPacket.setContentLengthLong(len);
} else {
requestPacket.setChunked(true);
}
final MemoryManager mm = ctx.getMemoryManager();
boolean last = false;
while (!last) {
Buffer buffer = mm.allocate(MAX_CHUNK_SIZE);
buffer.allowBufferDispose(true);
final long readBytes = bodyLocal.read(buffer.toByteBuffer());
if (readBytes > 0) {
buffer.position((int) readBytes);
buffer.trim();
} else {
buffer.dispose();
if (readBytes < 0) {
last = true;
buffer = Buffers.EMPTY_BUFFER;
} else {
// pass the context to bodyLocal to be able to
// continue body transferring once more data is available
if (generator instanceof FeedableBodyGenerator) {
((FeedableBodyGenerator) generator).initializeAsynchronousTransfer(ctx, requestPacket);
return false;
} else {
throw new IllegalStateException("BodyGenerator unexpectedly returned 0 bytes available");
}
}
}
final HttpContent content =
requestPacket.httpContentBuilder().content(buffer).
last(last).build();
ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
}
return true;
}
} // END BodyGeneratorBodyHandler
static class ConnectionManager {
private static final Attribute<Boolean> DO_NOT_CACHE =
Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(ConnectionManager.class.getName());
private final ConnectionsPool<String,Connection> pool;
private final TCPNIOConnectorHandler connectionHandler;
private final ConnectionMonitor connectionMonitor;
private final GrizzlyAsyncHttpProvider provider;
ConnectionManager(final GrizzlyAsyncHttpProvider provider,
final TCPNIOTransport transport) {
ConnectionsPool<String,Connection> connectionPool;
this.provider = provider;
final AsyncHttpClientConfig config = provider.clientConfig;
if (config.getAllowPoolingConnection()) {
ConnectionsPool pool = config.getConnectionsPool();
if (pool != null) {
//noinspection unchecked
connectionPool = (ConnectionsPool<String, Connection>) pool;
} else {
connectionPool = new GrizzlyConnectionsPool((config));
}
} else {
connectionPool = new NonCachingPool();
}
pool = connectionPool;
connectionHandler = TCPNIOConnectorHandler.builder(transport).build();
final int maxConns = provider.clientConfig.getMaxTotalConnections();
connectionMonitor = new ConnectionMonitor(maxConns);
}
static void markConnectionAsDoNotCache(final Connection c) {
DO_NOT_CACHE.set(c, Boolean.TRUE);
}
static boolean isConnectionCacheable(final Connection c) {
final Boolean canCache = DO_NOT_CACHE.get(c);
return ((canCache != null) ? canCache : false);
}
void doAsyncTrackedConnection(final Request request,
final GrizzlyResponseFuture requestFuture,
final CompletionHandler<Connection> connectHandler)
throws IOException, ExecutionException, InterruptedException {
final String url = request.getUrl();
Connection c = pool.poll(AsyncHttpProviderUtils.getBaseUrl(url));
if (c == null) {
if (!connectionMonitor.acquire()) {
throw new IOException("Max connections exceeded");
}
doAsyncConnect(url, request, requestFuture, connectHandler);
} else {
provider.touchConnection(c, request);
connectHandler.completed(c);
}
}
Connection obtainConnection(final Request request,
final GrizzlyResponseFuture requestFuture)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
final Connection c = (obtainConnection0(request.getUrl(),
request,
requestFuture));
DO_NOT_CACHE.set(c, Boolean.TRUE);
return c;
}
void doAsyncConnect(final String url,
final Request request,
final GrizzlyResponseFuture requestFuture,
final CompletionHandler<Connection> connectHandler)
throws IOException, ExecutionException, InterruptedException {
final URI uri = AsyncHttpProviderUtils.createUri(url);
ProxyServer proxy = getProxyServer(request);
if (ProxyUtils.avoidProxy(proxy, request)) {
proxy = null;
}
String host = ((proxy != null) ? proxy.getHost() : uri.getHost());
int port = ((proxy != null) ? proxy.getPort() : uri.getPort());
connectionHandler.connect(new InetSocketAddress(host, getPort(uri, port)),
createConnectionCompletionHandler(request, requestFuture, connectHandler));
}
private Connection obtainConnection0(final String url,
final Request request,
final GrizzlyResponseFuture requestFuture)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
final URI uri = AsyncHttpProviderUtils.createUri(url);
ProxyServer proxy = getProxyServer(request);
if (ProxyUtils.avoidProxy(proxy, request)) {
proxy = null;
}
String host = ((proxy != null) ? proxy.getHost() : uri.getHost());
int port = ((proxy != null) ? proxy.getPort() : uri.getPort());
int cTimeout = provider.clientConfig.getConnectionTimeoutInMs();
if (cTimeout > 0) {
return connectionHandler.connect(new InetSocketAddress(host, getPort(uri, port)),
createConnectionCompletionHandler(request,
requestFuture,
null)).get(cTimeout, TimeUnit.MILLISECONDS);
} else {
return connectionHandler.connect(new InetSocketAddress(host, getPort(uri, port)),
createConnectionCompletionHandler(request,
requestFuture,
null)).get();
}
}
private ProxyServer getProxyServer(Request request) {
ProxyServer proxyServer = request.getProxyServer();
if (proxyServer == null) {
proxyServer = provider.clientConfig.getProxyServer();
}
return proxyServer;
}
boolean returnConnection(final String url, final Connection c) {
final boolean result = (DO_NOT_CACHE.get(c) == null
&& pool.offer(AsyncHttpProviderUtils.getBaseUrl(url), c));
if (result) {
if (provider.resolver != null) {
provider.resolver.setTimeoutMillis(c, IdleTimeoutFilter.FOREVER);
}
}
return result;
}
boolean canReturnConnection(final Connection c) {
return (DO_NOT_CACHE.get(c) != null || pool.canCacheConnection());
}
void destroy() {
pool.destroy();
}
CompletionHandler<Connection> createConnectionCompletionHandler(final Request request,
final GrizzlyResponseFuture future,
final CompletionHandler<Connection> wrappedHandler) {
return new CompletionHandler<Connection>() {
public void cancelled() {
if (wrappedHandler != null) {
wrappedHandler.cancelled();
} else {
future.cancel(true);
}
}
public void failed(Throwable throwable) {
if (wrappedHandler != null) {
wrappedHandler.failed(throwable);
} else {
future.abort(throwable);
}
}
public void completed(Connection connection) {
future.setConnection(connection);
provider.touchConnection(connection, request);
if (wrappedHandler != null) {
connection.addCloseListener(connectionMonitor);
wrappedHandler.completed(connection);
}
}
public void updated(Connection result) {
if (wrappedHandler != null) {
wrappedHandler.updated(result);
}
}
};
}
private static class ConnectionMonitor implements Connection.CloseListener {
private final Semaphore connections;
ConnectionMonitor(final int maxConnections) {
if (maxConnections != -1) {
connections = new Semaphore(maxConnections);
} else {
connections = null;
}
}
public boolean acquire() {
return (connections == null || connections.tryAcquire());
}
@Override
public void onClosed(Connection connection, Connection.CloseType closeType) throws IOException {
if (connections != null) {
connections.release();
}
}
} // END ConnectionMonitor
} // END ConnectionManager
static final class SwitchingSSLFilter extends SSLFilter {
private final boolean secureByDefault;
final Attribute<Boolean> CONNECTION_IS_SECURE =
Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(SwitchingSSLFilter.class.getName());
SwitchingSSLFilter(final SSLEngineConfigurator clientConfig,
final boolean secureByDefault) {
super(null, clientConfig);
this.secureByDefault = secureByDefault;
}
@Override
public NextAction handleEvent(FilterChainContext ctx, FilterChainEvent event) throws IOException {
if (event.type() == SSLSwitchingEvent.class) {
final SSLSwitchingEvent se = (SSLSwitchingEvent) event;
CONNECTION_IS_SECURE.set(se.connection, se.secure);
return ctx.getStopAction();
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleRead(FilterChainContext ctx) throws IOException {
if (isSecure(ctx.getConnection())) {
return super.handleRead(ctx);
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleWrite(FilterChainContext ctx) throws IOException {
if (isSecure(ctx.getConnection())) {
return super.handleWrite(ctx);
}
return ctx.getInvokeAction();
}
private boolean isSecure(final Connection c) {
Boolean secStatus = CONNECTION_IS_SECURE.get(c);
if (secStatus == null) {
secStatus = secureByDefault;
}
return secStatus;
}
static final class SSLSwitchingEvent implements FilterChainEvent {
final boolean secure;
final Connection connection;
SSLSwitchingEvent(final boolean secure, final Connection c) {
this.secure = secure;
connection = c;
}
@Override
public Object type() {
return SSLSwitchingEvent.class;
}
} // END SSLSwitchingEvent
} // END SwitchingSSLFilter
private static final class GrizzlyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
public GrizzlyTransferAdapter(FluentCaseInsensitiveStringsMap headers) throws IOException {
super(headers);
}
@Override
public void getBytes(byte[] bytes) {
// TODO implement
}
} // END GrizzlyTransferAdapter
private static final class GrizzlyWebSocketAdapter implements WebSocket {
private final org.glassfish.grizzly.websockets.WebSocket gWebSocket;
GrizzlyWebSocketAdapter(final org.glassfish.grizzly.websockets.WebSocket gWebSocket) {
this.gWebSocket = gWebSocket;
}
@Override
public WebSocket sendMessage(byte[] message) {
gWebSocket.send(message);
return this;
}
@Override
public WebSocket sendTextMessage(String message) {
gWebSocket.send(message);
return this;
}
@Override
public WebSocket addMessageListener(WebSocketListener l) {
gWebSocket.add(new AHCWebSocketListenerAdapter(l, this));
return this;
}
@Override
public void close() {
gWebSocket.close();
}
} // END GrizzlyWebSocketAdapter
private static final class AHCWebSocketListenerAdapter implements org.glassfish.grizzly.websockets.WebSocketListener {
private final WebSocketListener ahcListener;
private final WebSocket webSocket;
AHCWebSocketListenerAdapter(final WebSocketListener ahcListener, WebSocket webSocket) {
this.ahcListener = ahcListener;
this.webSocket = webSocket;
}
@Override
public void onClose(org.glassfish.grizzly.websockets.WebSocket gWebSocket, DataFrame dataFrame) {
ahcListener.onClose(webSocket);
}
@Override
public void onConnect(org.glassfish.grizzly.websockets.WebSocket webSocket) {
// no-op
}
@Override
public void onMessage(org.glassfish.grizzly.websockets.WebSocket webSocket, String s) {
if (WebSocketTextListener.class.isAssignableFrom(ahcListener.getClass())) {
WebSocketTextListener.class.cast(ahcListener).onMessage(s);
}
}
@Override
public void onMessage(org.glassfish.grizzly.websockets.WebSocket webSocket, byte[] bytes) {
if (WebSocketByteListener.class.isAssignableFrom(ahcListener.getClass())) {
WebSocketByteListener.class.cast(ahcListener).onMessage(bytes);
}
}
@Override
public void onPing(org.glassfish.grizzly.websockets.WebSocket webSocket, byte[] bytes) {
if (WebSocketPingListener.class.isAssignableFrom(ahcListener.getClass())) {
WebSocketPingListener.class.cast(ahcListener).onPing(bytes);
}
}
@Override
public void onPong(org.glassfish.grizzly.websockets.WebSocket webSocket, byte[] bytes) {
// no-op
}
@Override
public void onFragment(org.glassfish.grizzly.websockets.WebSocket webSocket, String s, boolean b) {
// no-op
}
@Override
public void onFragment(org.glassfish.grizzly.websockets.WebSocket webSocket, byte[] bytes, boolean b) {
// no-op
}
} // END AHCWebSocketListenerAdapter
}
|
package com.openlattice.postgres.mapstores;
import static com.google.common.base.Preconditions.checkState;
import com.codahale.metrics.annotation.Timed;
import com.dataloom.streams.StreamUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Sets;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.kryptnostic.rhizome.mapstores.TestableSelfRegisteringMapStore;
import com.openlattice.postgres.CountdownConnectionCloser;
import com.openlattice.postgres.KeyIterator;
import com.openlattice.postgres.PostgresColumnDefinition;
import com.openlattice.postgres.PostgresTableDefinition;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Matthew Tamayo-Rios <matthew@openlattice.com>
*/
public abstract class AbstractBasePostgresMapstore<K, V> implements TestableSelfRegisteringMapStore<K, V> {
public static final int BATCH_SIZE = 1 << 12;
protected final Logger logger = LoggerFactory.getLogger( getClass() );
protected final PostgresTableDefinition table;
protected final HikariDataSource hds;
private final int batchSize;
private final int batchCapacity;
private final String mapName;
private final String insertQuery;
private final String deleteQuery;
private final String selectAllKeysQuery;
private final String selectByKeyQuery;
private final String selectInQuery;
private final Optional<String> oc;
private final List<PostgresColumnDefinition> keyColumns;
private final List<PostgresColumnDefinition> valueColumns;
public AbstractBasePostgresMapstore( String mapName, PostgresTableDefinition table, HikariDataSource hds ) {
this( mapName, table, hds, BATCH_SIZE );
}
public AbstractBasePostgresMapstore(
String mapName,
PostgresTableDefinition table,
HikariDataSource hds,
int batchSize ) {
this.table = table;
this.hds = hds;
this.mapName = mapName;
this.batchSize = batchSize;
this.keyColumns = initKeyColumns();
this.valueColumns = initValueColumns();
this.batchCapacity = batchSize * getSelectInParameterCount();
checkState( batchCapacity < ( 1 << 16 ),
"The selected batch size results in too large of batch capacity for Postgres (limit 65536 arguments for in statement" );
this.oc = buildOnConflictQuery();
this.insertQuery = buildInsertQuery();
this.deleteQuery = buildDeleteQuery();
this.selectAllKeysQuery = buildSelectAllKeysQuery();
this.selectByKeyQuery = buildSelectByKeyQuery();
this.selectInQuery = buildSelectInQuery();
}
protected Optional<String> buildOnConflictQuery() {
return Optional.of( ( " ON CONFLICT ("
+ keyColumns().stream()
.map( PostgresColumnDefinition::getName )
.collect( Collectors.joining( ", " ) )
+ ") DO "
+ table.updateQuery( keyColumns(), valueColumns(), false ) ) );
}
protected String buildInsertQuery() {
return table.insertQuery( onConflict(), getInsertColumns() );
}
protected String buildDeleteQuery() {
return table.deleteQuery( keyColumns() );
}
protected String buildSelectAllKeysQuery() {
return table.selectQuery( keyColumns() );
}
protected String buildSelectByKeyQuery() {
return table.selectQuery( ImmutableList.of(), keyColumns() );
}
protected String buildSelectInQuery() {
return table.selectInQuery( ImmutableList.of(), keyColumns(), batchSize );
}
protected int getSelectInParameterCount() {
return keyColumns().size();
}
@Timed
@Override
public void store( K key, V value ) {
try ( Connection connection = hds.getConnection(); PreparedStatement insertRow = prepareInsert( connection ) ) {
bind( insertRow, key, value );
logger.debug( "Insert query: {}", insertRow );
insertRow.execute();
handleStoreSucceeded( key, value );
} catch ( SQLException e ) {
String errMsg = "Error executing SQL during store for key " + key + "in map " + mapName + ".";
logger.error( errMsg, e );
handleStoreFailed( key, value );
throw new IllegalStateException( errMsg, e );
}
}
protected void handleStoreSucceeded( K key, V value ) {
}
@Timed
@Override
public void storeAll( Map<K, V> map ) {
K key = null;
try ( Connection connection = hds.getConnection(); PreparedStatement insertRow = prepareInsert( connection ) ) {
//TODO: We might want to do an inner try catch here to get specific logging on what failed
for ( Entry<K, V> entry : map.entrySet() ) {
key = entry.getKey();
bind( insertRow, key, entry.getValue() );
insertRow.addBatch();
}
insertRow.executeBatch();
} catch ( SQLException e ) {
logger.error( "Error executing SQL during store all for key {} in map {}", key, mapName, e );
}
}
@Timed
@Override
public void delete( K key ) {
try ( Connection connection = hds.getConnection(); PreparedStatement deleteRow = prepareDelete( connection ) ) {
bind( deleteRow, key );
deleteRow.executeUpdate();
connection.close();
} catch ( SQLException e ) {
logger.error( "Error executing SQL during delete for key {} in map {}.", key, mapName, e );
}
}
@Timed
@Override
public void deleteAll( Collection<K> keys ) {
K key = null;
try ( Connection connection = hds.getConnection(); PreparedStatement deleteRow = prepareDelete( connection ) ) {
for ( K k : keys ) {
key = k;
bind( deleteRow, key );
deleteRow.addBatch();
}
deleteRow.executeBatch();
connection.close();
} catch ( SQLException e ) {
logger.error( "Error executing SQL during delete all for key {} in map {}", key, mapName, e );
}
}
@Timed
@Override
public V load( K key ) {
try ( Connection connection = hds.getConnection() ) {
return loadUsing( key, connection );
} catch ( SQLException e ) {
final String errMsg =
"Unable to connecto to database to load key " + key.toString() + " map +" + mapName + "!";
logger.error( errMsg, key, e );
throw new IllegalStateException( errMsg, e );
}
}
protected V loadUsing( K key, Connection connection ) {
try ( PreparedStatement selectRow = prepareSelectByKey( connection ) ) {
bind( selectRow, key );
try ( ResultSet rs = selectRow.executeQuery() ) {
if ( rs.next() ) {
return readNext( rs );
}
} catch ( SQLException e ) {
final String errMsg = "Error executing SQL during select for key " + key + ".";
logger.error( errMsg, e );
throw new IllegalStateException( errMsg, e );
}
} catch ( SQLException e ) {
final String errMsg = "Error binding to select for key " + key + " in map " + mapName + ".";
logger.error( errMsg, key, e );
throw new IllegalArgumentException( errMsg, e );
}
return null;
}
private V readNext( ResultSet rs ) throws SQLException {
V val = mapToValue( rs );
logger.debug( "LOADED value {} in map {}", val, mapName );
return val;
}
@Timed
@Override
public Map<K, V> loadAll( Collection<K> keys ) {
Map<K, V> result = new MapMaker().initialCapacity( keys.size() ).makeMap();
K key = null;
try ( Connection connection = hds.getConnection();
PreparedStatement selectIn = prepareSelectIn( connection ) ) {
Iterator<K> kIterator = keys.iterator();
while ( kIterator.hasNext() ) {
for ( int parameterIndex = 1;
parameterIndex <= batchCapacity;
parameterIndex = bind( selectIn, key, parameterIndex ) ) {
//For now if we run out of keys, key binding the same key over and over again to pad it out
//In the future we should null out the parameter using postgres data type info in table.
if ( kIterator.hasNext() ) {
key = kIterator.next();
}
}
try ( ResultSet results = selectIn.executeQuery() ) {
while ( results.next() ) {
K k = mapToKey( results );
V v = readNext( results );
result.put( k, v );
}
}
}
// keys.parallelStream().forEach( key -> {
// V value = load( key );
// if ( value != null ) { result.put( key, value ); }
} catch ( SQLException e ) {
logger.error( "Error executing SQL during select for key {} in map {}.", key, mapName, e );
}
return result;
}
@Override public Iterable<K> loadAllKeys() {
logger.info( "Starting load all keys for map {}", mapName );
try {
Connection connection = hds.getConnection();
Statement stmt = connection.createStatement();
stmt.setFetchSize( 50000 );
final ResultSet rs = stmt.executeQuery( selectAllKeysQuery );
return StreamUtil
.stream( () -> new KeyIterator<K>( rs,
new CountdownConnectionCloser( connection, 1 ), this::mapToKey ) )
.peek( key -> logger.debug( "Key to load: {}", key ) )
::iterator;
} catch ( SQLException e ) {
logger.error( "Unable to acquire connection load all keys for map {}", mapName, e );
return null;
}
}
@Override public String getMapName() {
return mapName;
}
@Override public String getTable() {
return table.getName();
}
protected Optional<String> onConflict() {
return oc;
}
protected List<PostgresColumnDefinition> getInsertColumns() {
//An empty list of columns means all
return ImmutableList.of();
}
protected String getInsertQuery() {
return insertQuery;
}
protected PreparedStatement prepareInsert( Connection connection ) throws SQLException {
return connection.prepareStatement( getInsertQuery() );
}
protected String getDeleteQuery() {
return deleteQuery;
}
protected PreparedStatement prepareDelete( Connection connection ) throws SQLException {
return connection.prepareStatement( deleteQuery );
}
protected String getSelecAllKeysQuery() {
return selectAllKeysQuery;
}
protected PreparedStatement prepareSelectAllKeys( Connection connection ) throws SQLException {
return connection.prepareStatement( selectAllKeysQuery );
}
protected PreparedStatement prepareSelectIn( Connection connection ) throws SQLException {
return connection.prepareStatement( selectInQuery );
}
protected String selectByKeyQuery() {
return selectByKeyQuery;
}
protected PreparedStatement prepareSelectByKey( Connection connection ) throws SQLException {
return connection.prepareStatement( selectByKeyQuery );
}
@Override
public MapStoreConfig getMapStoreConfig() {
return new MapStoreConfig()
.setImplementation( this )
.setEnabled( true )
.setWriteDelaySeconds( 0 );
}
@Override
public MapConfig getMapConfig() {
return new MapConfig( getMapName() )
.setMapStoreConfig( getMapStoreConfig() );
}
protected void handleStoreFailed( K key, V value ) {
//Do nothing by default
}
protected final List<PostgresColumnDefinition> keyColumns() {
return keyColumns;
}
protected List<PostgresColumnDefinition> initKeyColumns() {
return ImmutableList.copyOf( table.getPrimaryKey() );
}
protected final List<PostgresColumnDefinition> valueColumns() {
return valueColumns;
}
protected List<PostgresColumnDefinition> initValueColumns() {
return ImmutableList.copyOf( Sets.difference( table.getColumns(), table.getPrimaryKey() ) );
}
/**
* You must bind update parameters as well as insert parameters
*/
protected abstract void bind( PreparedStatement ps, K key, V value ) throws SQLException;
protected abstract int bind( PreparedStatement ps, K key, int offset ) throws SQLException;
private int bind( PreparedStatement ps, K key ) throws SQLException {
return bind( ps, key, 1 );
}
protected abstract V mapToValue( ResultSet rs ) throws SQLException;
protected abstract K mapToKey( ResultSet rs ) throws SQLException;
}
|
package de.prob2.ui.consoles.groovy.codecompletion;
import java.io.IOException;
import javax.script.ScriptEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.prob2.ui.consoles.groovy.GroovyConsole;
import de.prob2.ui.consoles.groovy.objects.GroovyAbstractItem;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Point2D;
import javafx.scene.control.ListView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Popup;
public class GroovyCodeCompletion extends Popup {
private static final Logger logger = LoggerFactory.getLogger(GroovyCodeCompletion.class);
@FXML private ListView<GroovyAbstractItem> lvSuggestions;
private final ObservableList<GroovyAbstractItem> suggestions;
private ScriptEngine engine;
private GroovyConsole parent;
private String currentSuggestion;
private int currentPosInSuggestion;
private int charCounterInSuggestion;
private final GroovyCodeCompletionHandler completionHandler;
public GroovyCodeCompletion(FXMLLoader loader, ScriptEngine engine) {
this.engine = engine;
this.parent = null;
this.currentSuggestion = "";
this.currentPosInSuggestion = 0;
this.charCounterInSuggestion = 0;
this.suggestions = FXCollections.observableArrayList();
this.completionHandler = new GroovyCodeCompletionHandler(suggestions);
loader.setLocation(getClass().getResource("groovy_codecompletion_popup.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException e) {
logger.error("loading fxml failed", e);
}
}
@FXML
public void initialize() {
lvSuggestions.setItems(suggestions);
setListeners();
}
public void activate(GroovyConsole console, String currentLine, CodeCompletionTriggerAction action) {
this.parent = console;
if(action == CodeCompletionTriggerAction.POINT) {
currentLine = currentLine + ".";
}
String currentPrefix = handleActivation(currentLine);
completionHandler.handleMethodsFromObjects(currentPrefix, currentSuggestion, action, parent, engine);
completionHandler.handleStaticClasses(currentPrefix, currentSuggestion, action, parent);
completionHandler.handleObjects(currentSuggestion, action, engine);
showPopup(console);
}
private String handleActivation(String currentLine) {
String currentPrefix;
String newCurrentLine = currentLine.replaceAll("\\s","");
int indexOfPoint = newCurrentLine.lastIndexOf('.');
int indexOfSemicolon = newCurrentLine.lastIndexOf(';');
if((indexOfPoint < indexOfSemicolon && indexOfSemicolon > getParent().getCurrentPosInLine()) || (indexOfPoint != -1 && indexOfSemicolon == -1)) {
int index = Math.max(-1, indexOfPoint);
currentSuggestion = newCurrentLine.substring(index + 1, newCurrentLine.length());
currentPosInSuggestion = currentSuggestion.length();
charCounterInSuggestion = currentPosInSuggestion;
currentPrefix = newCurrentLine.substring(0, index + 1);
} else {
int index = Math.max(-1, indexOfSemicolon);
currentSuggestion = newCurrentLine.substring(index + 1, newCurrentLine.length());
charCounterInSuggestion = currentSuggestion.length();
currentPosInSuggestion = charCounterInSuggestion;
currentPrefix = currentSuggestion;
}
return currentPrefix;
}
private void showPopup(GroovyConsole console) {
if(suggestions.isEmpty()) {
return;
}
sortSuggestions();
lvSuggestions.getSelectionModel().selectFirst();
Point2D point = CaretFinder.findCaretPosition(CaretFinder.findCaret(console));
double x = point.getX() + 10;
double y = point.getY() + 20;
this.show(console, x, y);
}
private void sortSuggestions() {
suggestions.sort((o1,o2) -> o1.toString().compareToIgnoreCase(o2.toString()));
}
public void deactivate() {
suggestions.clear();
completionHandler.clear();
currentSuggestion ="";
currentPosInSuggestion = 0;
charCounterInSuggestion = 0;
this.hide();
}
public void filterSuggestions(String addition, CodeCompletionAction action) {
String currentInstruction = currentSuggestion;
if(action.equals(CodeCompletionAction.ARROWKEY)) {
//handle Arrow Key
currentInstruction = currentSuggestion.substring(0, currentPosInSuggestion);
} else if(action.equals(CodeCompletionAction.INSERTION)) {
currentInstruction = handleInsertChar(addition);
}
completionHandler.refresh(currentInstruction);
sortSuggestions();
lvSuggestions.getSelectionModel().selectFirst();
if(suggestions.isEmpty()) {
this.deactivate();
}
}
private String handleInsertChar(String addition) {
currentSuggestion = new StringBuilder(currentSuggestion).insert(currentPosInSuggestion, addition.charAt(0)).toString();
currentPosInSuggestion++;
charCounterInSuggestion++;
return currentSuggestion;
}
private void setListeners() {
lvSuggestions.setOnMouseClicked(this::chooseMethod);
lvSuggestions.setOnKeyPressed(e-> {
if(e.getCode().equals(KeyCode.SPACE)) {
getParent().fireEvent(new CodeCompletionEvent(e));
}
if(";".equals(e.getText()) || e.getCode().equals(KeyCode.ENTER)) {
//handle Enter in Groovy Code Completion
chooseMethod(e);
return;
}
if(e.getCode().equals(KeyCode.LEFT) || e.getCode().equals(KeyCode.RIGHT) || e.getCode().equals(KeyCode.UP) || e.getCode().equals(KeyCode.DOWN)) {
handleArrowKey(e);
return;
}
if(e.getCode().equals(KeyCode.DELETE) || e.getCode().equals(KeyCode.BACK_SPACE)) {
handleRemove(e);
return;
}
if(e.getText().length() == 1 && !".".equals(e.getText())) {
//handle Insert Char
filterSuggestions(e.getText(), CodeCompletionAction.INSERTION);
}
});
}
private void handleArrowKey(KeyEvent e) {
boolean needReturn;
if(e.getCode().equals(KeyCode.LEFT)) {
needReturn = handleLeft();
if(needReturn) {
return;
}
} else if(e.getCode().equals(KeyCode.RIGHT)) {
needReturn = handleRight();
if(needReturn) {
return;
}
} else if(e.getCode().equals(KeyCode.UP)) {
handleUp(e);
return;
} else if(e.getCode().equals(KeyCode.DOWN)) {
handleDown(e);
return;
}
filterSuggestions("", CodeCompletionAction.ARROWKEY);
}
private boolean handleLeft() {
if(getParent().getCurrentPosInLine() == 0 || ';' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1) || '.' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1)) {
deactivate();
return true;
}
currentPosInSuggestion = Math.max(0, currentPosInSuggestion-1);
return false;
}
private boolean handleRight() {
if(getParent().getCurrentPosInLine() == getParent().getCurrentLine().length() || ';' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine())) {
deactivate();
return true;
}
if(getParent().getCaretPosition() != getParent().getText().length()) {
currentSuggestion += getParent().getText().charAt(getParent().getCaretPosition());
charCounterInSuggestion += 1;
currentPosInSuggestion = Math.min(currentSuggestion.length(), currentPosInSuggestion + 1);
}
return false;
}
private void handleUp(KeyEvent e) {
if(lvSuggestions.getSelectionModel().getSelectedIndex() == 0) {
lvSuggestions.getSelectionModel().selectLast();
lvSuggestions.scrollTo(suggestions.size()-1);
e.consume();
}
}
private void handleDown(KeyEvent e) {
if(lvSuggestions.getSelectionModel().getSelectedIndex() == suggestions.size() - 1) {
lvSuggestions.getSelectionModel().selectFirst();
lvSuggestions.scrollTo(0);
e.consume();
}
}
private void handleRemove(KeyEvent e) {
if(e.getCode().equals(KeyCode.DELETE)) {
handleDeletion();
} else if(e.getCode().equals(KeyCode.BACK_SPACE)) {
handleBackspace();
}
filterSuggestions("", CodeCompletionAction.DELETION);
}
private void handleDeletion() {
if(currentPosInSuggestion != charCounterInSuggestion) {
charCounterInSuggestion
currentSuggestion = currentSuggestion.substring(0, currentPosInSuggestion) + currentSuggestion.substring(Math.min(currentPosInSuggestion + 1, currentSuggestion.length()), currentSuggestion.length());
}
if(getParent().getCaretPosition() == getParent().getText().length()) {
deactivate();
}
}
private void handleBackspace() {
if(currentPosInSuggestion != 0) {
currentPosInSuggestion
charCounterInSuggestion
currentSuggestion = currentSuggestion.substring(0, currentPosInSuggestion) + currentSuggestion.substring(Math.max(currentPosInSuggestion + 1, currentSuggestion.length()), currentSuggestion.length());
}
if(getParent().getCurrentPosInLine() == 0 || '.' == getParent().getCurrentLine().charAt(getParent().getCurrentPosInLine() - 1)) {
deactivate();
}
}
private void chooseMethod(Event e) {
if(lvSuggestions.getSelectionModel().getSelectedItem() != null) {
String choice = lvSuggestions.getSelectionModel().getSelectedItem().getNameAndParams();
getParent().fireEvent(new CodeCompletionEvent(e, choice, choice.substring(0, currentPosInSuggestion)));
}
deactivate();
}
public GroovyConsole getParent() {
return parent;
}
public boolean isVisible() {
return this.isShowing();
}
}
|
/*
* GeneralProperty.java
*
*/
package de.uni_stuttgart.vis.vowl.owl2vowl.parser;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.BaseNode;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.BaseClass;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.OwlThing;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.OwlUnionOf;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.BaseDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.parser.helper.ComparisonHelper;
import de.uni_stuttgart.vis.vowl.owl2vowl.parser.helper.IntersectionParser;
import de.uni_stuttgart.vis.vowl.owl2vowl.parser.helper.UnionParser;
import org.semanticweb.owlapi.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public abstract class GeneralPropertyParser extends GeneralParser {
protected String rdfsDomain = "";
protected String rdfsRange = "";
protected String rdfsInversOf = "";
private UnionParser unionParser = new UnionParser();
private IntersectionParser intersectionParser = new IntersectionParser();
public static void reset() {
}
protected String retrieveRange(OWLObjectProperty currentProperty) {
for (OWLClassExpression range : currentProperty.getRanges(GeneralParser.ontology)) {
if (!range.isAnonymous()) {
return range.asOWLClass().getIRI().toString();
} else {
// TODO
String classExpressionType = range.getClassExpressionType().toString();
Set<OWLClass> classesInSignature = range.getClassesInSignature();
for (OWLClass classInSig : classesInSignature) {
}
}
}
BaseClass union = unionParser.searchUnion(currentProperty, false);
BaseClass intersection = intersectionParser.searchIntersection(currentProperty, false);
if(union != null){
return union.getId();
} else if(intersection != null) {
return intersection.getId();
} else {
return "";
}
}
protected String retrieveRange(OWLDataProperty currentProperty) {
String rangeIRI;
for (OWLDataRange range : currentProperty.getRanges(GeneralParser.ontology)) {
rangeIRI = range.asOWLDatatype().getIRI().toString();
if (!rangeIRI.isEmpty()) {
return rangeIRI;
}
}
BaseClass union = unionParser.searchUnion(currentProperty, false);
BaseClass intersection = intersectionParser.searchIntersection(currentProperty, false);
if(union != null){
return union.getId();
} else if(intersection != null) {
return intersection.getId();
} else {
return "";
}
}
protected String retrieveDomain(OWLPropertyExpression currentProperty) {
for (Object domainObject : currentProperty.getDomains(GeneralParser.ontology)) {
OWLClassExpression domain = (OWLClassExpression) domainObject;
if (!domain.isAnonymous()) {
return domain.asOWLClass().getIRI().toString();
} else {
// TODO
String classExpressionType = domain.getClassExpressionType().toString();
Set<OWLClass> classesInSignature = domain.getClassesInSignature();
for (OWLClass classInSig : classesInSignature) {
}
}
}
BaseClass union = unionParser.searchUnion((OWLEntity) currentProperty, true);
BaseClass intersection = intersectionParser.searchIntersection((OWLProperty) currentProperty, true);
if(union != null){
return union.getId();
} else if(intersection != null) {
return intersection.getId();
} else {
return "";
}
}
protected BaseNode findDomain(BaseNode rdfsDomain) {
BaseClass classDomain = mapData.getClassMap().get(rdfsDomain.getIri());
BaseDatatype datatypeDomain = mapData.getDatatypeMap().get(rdfsDomain.getIri());
OwlThing thingDomain = mapData.getThingMap().get(rdfsDomain.getId());
if (classDomain != null) {
return classDomain;
} else if (datatypeDomain != null) {
return datatypeDomain;
} else if (thingDomain != null) {
return thingDomain;
}
return null;
}
protected BaseNode findRange(BaseNode rdfsRange) {
BaseClass classRange = mapData.getClassMap().get(rdfsRange.getIri());
BaseDatatype datatypeRange = mapData.getDatatypeMap().get(rdfsRange.getIri());
OwlThing thingRange = mapData.getThingMap().get(rdfsRange.getId());
if (classRange != null) {
return classRange;
} else if (datatypeRange != null) {
return datatypeRange;
} else if (thingRange != null) {
return thingRange;
}
return null;
}
protected List<String> retrieveSubProperties(OWLPropertyExpression property) {
Set subProperties = property.getSubProperties(ontology);
List<String> iriList = new ArrayList<String>();
if (subProperties.isEmpty()) {
return iriList;
}
for (Object curSub : subProperties) {
OWLNamedObject definedSub = (OWLNamedObject) curSub;
iriList.add(definedSub.getIRI().toString());
}
return iriList;
}
protected List<String> retrieveSuperProperties(OWLPropertyExpression property) {
Set subProperties = property.getSuperProperties(ontology);
List<String> iriList = new ArrayList<String>();
if (subProperties.isEmpty()) {
return iriList;
}
for (Object curSub : subProperties) {
OWLNamedObject definedSub = (OWLNamedObject) curSub;
iriList.add(definedSub.getIRI().toString());
}
return iriList;
}
protected List<String> retrieveDisjoints(OWLPropertyExpression property) {
Set subProperties = property.getDisjointProperties(ontology);
List<String> iriList = new ArrayList<String>();
if (subProperties.isEmpty()) {
return iriList;
}
for (Object curSub : subProperties) {
OWLNamedObject definedSub = (OWLNamedObject) curSub;
iriList.add(definedSub.getIRI().toString());
}
return iriList;
}
protected List<String> retrieveEquivalents(OWLPropertyExpression property) {
Set subProperties = property.getEquivalentProperties(ontology);
List<String> iriList = new ArrayList<String>();
// TODO Do not use external properties as base. But if there are equivalent external properties only?
if (ComparisonHelper.hasDifferentNameSpace((OWLEntity) property, ontology)) {
return iriList;
}
for (Object curSub : subProperties) {
OWLNamedObject definedSub = (OWLNamedObject) curSub;
iriList.add(definedSub.getIRI().toString());
}
return iriList;
}
protected OwlUnionOf getUnionDomain(OWLEntity property) {
return unionParser.searchUnion(property, true);
}
protected OwlUnionOf getUnionRange(OWLEntity property) {
return unionParser.searchUnion(property, false);
}
}
|
package dk.statsbiblioteket.medieplatform.newspaper.manualQA;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.DefaultTreeEventHandler;
import dk.statsbiblioteket.medieplatform.newspaper.manualQA.flagging.FlaggingCollector;
import dk.statsbiblioteket.util.xml.DOM;
import dk.statsbiblioteket.util.xml.XPathSelector;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
/**
* This class handles issues raised by metadata in mix-files which require manual QA intervention.
* These are typically changes in scanner-related hardware, software, and wetware.
*/
public class MixHandler extends DefaultTreeEventHandler {
private ResultCollector resultCollector;
private FlaggingCollector flaggingCollector;
private Properties properties;
private XPathSelector mixXpathSelector;
/**
* Constructor for this class.
* @param resultCollector for reporting on errors.
* @param properties properties used by this class. See Readme.md for the definition of the required properties
* for this class.
* @param flaggingCollector for reporting of issues requiring manual QA.
*/
public MixHandler(ResultCollector resultCollector, Properties properties, FlaggingCollector flaggingCollector) {
this.resultCollector = resultCollector;
this.properties = properties;
this.flaggingCollector = flaggingCollector;
this.mixXpathSelector = DOM.createXPathSelector(
"avis", "http:
"mix", "http:
}
@Override
public void handleAttribute(AttributeParsingEvent event) {
if (!event.getName().endsWith(".mix.xml")) {
return;
}
Document doc;
try {
doc = DOM.streamToDOM(event.getData(), true);
if (doc == null) {
resultCollector.addFailure(
event.getName(), "exception", getClass().getSimpleName(),
"Could not parse xml");
return;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
final String xpathManufacturer = "/mix:mix/mix:ImageCaptureMetadata/mix:ScannerCapture/mix:scannerManufacturer";
validate(event, doc, ConfigConstants.SCANNER_MANUFACTURERS, xpathManufacturer, "Found a new scanner manufacturer");
final String xpathModel = "/mix:mix/mix:ImageCaptureMetadata/mix:ScannerCapture/mix:ScannerModel/mix:scannerModelName";
validate(event, doc, ConfigConstants.SCANNER_MODELS, xpathModel, "Found new scanner model name");
final String xpathModelNumber
= "/mix:mix/mix:ImageCaptureMetadata/mix:ScannerCapture/mix:ScannerModel/mix:scannerModelNumber";
validate(event, doc, ConfigConstants.SCANNER_MODEL_NUMBERS, xpathModelNumber, "Found new scanner model number");
final String xpathModelSerialNo
= "/mix:mix/mix:ImageCaptureMetadata/mix:ScannerCapture/mix:ScannerModel/mix:scannerModelSerialNo";
validate(event, doc, ConfigConstants.SCANNER_SERIAL_NOS, xpathModelSerialNo, "Found new scanner serial number");
validateProducers(event, doc);
validateSoftwareVersions(event, doc);
if (!event.getName().endsWith("-brik.mix.xml")) {
validateDimensions(event, doc);
}
}
/**
* Check if a previously-unknown software version has been used to process this scanning.
* @param event
* @param doc
*/
private void validateSoftwareVersions(AttributeParsingEvent event, Document doc) {
String[] allowedSoftwareVersions = properties.getProperty(ConfigConstants.SCANNER_SOFTWARES).split(",");
final String xpathSoftwareVersions = "mix:mix/mix:ImageCaptureMetadata/mix:ScannerCapture/mix:ScanningSystemSoftware";
NodeList softwareVersionNodes = mixXpathSelector.selectNodeList(doc, xpathSoftwareVersions);
for (int i = 0; i < softwareVersionNodes.getLength(); i++) {
Node versionNode = softwareVersionNodes.item(i);
String softwareName = mixXpathSelector.selectString(versionNode, "mix:scanningSoftwareName");
String softwareVersion = mixXpathSelector.selectString(versionNode, "mix:scanningSoftwareVersionNo");
String foundSoftwareVersion = softwareName + ";" + softwareVersion;
if (!Arrays.asList(allowedSoftwareVersions).contains(foundSoftwareVersion)) {
addFlag(event, "Found new software version: " + foundSoftwareVersion);
}
}
}
/**
* Check if a previously unknown producer (e.g. scanner operator) has been involved in this scanning.
* @param event
* @param doc
*/
private void validateProducers(AttributeParsingEvent event, Document doc) {
String[] allowedProducers = properties.getProperty(ConfigConstants.IMAGE_PRODUCERS).split(",");
final String xpathProducers = "/mix:mix/mix:ImageCaptureMetadata/mix:GeneralCaptureInformation/mix:imageProducer";
String[] producers = mixXpathSelector.selectString(doc, xpathProducers).split(";");
for (String producer: producers) {
if (!Arrays.asList(allowedProducers).contains(producer)) {
addFlag(event, "Unknown or new producer found: " + producer);
}
}
}
/**
* Check that image dimensions fall within the allowed ranges.
* @param event
* @param doc
*/
private void validateDimensions(AttributeParsingEvent event, Document doc) {
int minImageWidth, maxImageWidth, minImageHeight, maxImageHeight, width, height;
try {
minImageWidth = Integer.parseInt(properties.getProperty(ConfigConstants.MIN_IMAGE_WIDTH));
} catch (NumberFormatException e) {
addFlag(event, "Internal error: couldn't get and parse MIN_IMAGE_WIDTH. " + e.getMessage());
return;
}
try {
maxImageWidth = Integer.parseInt(properties.getProperty(ConfigConstants.MAX_IMAGE_WIDTH));
} catch (NumberFormatException e) {
addFlag(event, "Internal error: couldn't get and parse MAX_IMAGE_WIDTH. " + e.getMessage());
return;
}
try {
minImageHeight = Integer.parseInt(properties.getProperty(ConfigConstants.MIN_IMAGE_HEIGHT));
} catch (NumberFormatException e) {
addFlag(event, "Internal error: couldn't get and parse MIN_IMAGE_HEIGHT. " + e.getMessage());
return;
}
try {
maxImageHeight = Integer.parseInt(properties.getProperty(ConfigConstants.MAX_IMAGE_HEIGHT));
} catch (NumberFormatException e) {
addFlag(event, "Internal error: couldn't get and parse MAX_IMAGE_HEIGHT. " + e.getMessage());
return;
}
final String xpathWidth = "/mix:mix/mix:BasicImageInformation/mix:BasicImageCharacteristics/mix:imageWidth";
final String xpathHeight = "/mix:mix/mix:BasicImageInformation/mix:BasicImageCharacteristics/mix:imageHeight";
try {
width = Integer.parseInt(mixXpathSelector.selectString(doc, xpathWidth));
} catch (NumberFormatException e) {
addFlag(event, "Couldn't get and parse xpathWidth. " + e.getMessage());
return;
}
try {
height = Integer.parseInt(mixXpathSelector.selectString(doc, xpathHeight));
} catch (NumberFormatException e) {
addFlag(event, "Couldn't get and parse xpathHeight. " + e.getMessage());
return;
}
if ((minImageWidth> width) || (width > maxImageWidth)) {
addFlag(event, "Image width should have a value from " + minImageWidth + " to " + maxImageWidth
+ " but was found " + " to be: " + width);
}
if ((minImageHeight > height) || (height > maxImageHeight)) {
addFlag(event, "Image height should have a value from " + minImageHeight + " to " + maxImageHeight
+ " but was found " + " to be: " + height);
}
}
/**
* Generic check used to determine whether the scanning machine (manufacturer, model, model number and serial
* number) match with previously known machines.
* @param event
* @param doc
* @param property
* @param xpath
* @param message
*/
private void validate(AttributeParsingEvent event, Document doc, String property, String xpath, String message) {
String[] allowedValues = properties.getProperty(property).split(",");
String actualValue = mixXpathSelector.selectString(doc, xpath).trim();
if (!Arrays.asList(allowedValues).contains(actualValue)) {
addFlag(event, message + ": " + actualValue);
}
}
private void addFlag(AttributeParsingEvent event, String message) {
flaggingCollector.addFlag(event, "metadata", getClass().getSimpleName(), message);
}
}
|
package org.jetbrains.idea.devkit.projectRoots;
import com.intellij.openapi.application.ApplicationStarter;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.projectRoots.impl.JavaDependentSdkType;
import com.intellij.openapi.roots.AnnotationOrderRootType;
import com.intellij.openapi.roots.JavadocOrderRootType;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.impl.compiled.ClsParsingUtil;
import com.intellij.util.ArrayUtilRt;
import icons.DevkitIcons;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.DevKitBundle;
import org.jetbrains.idea.devkit.util.PsiUtil;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
import org.jetbrains.jps.model.java.JpsJavaSdkType;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryRoot;
import org.jetbrains.jps.model.library.JpsOrderRootType;
import org.jetbrains.jps.model.library.sdk.JpsSdkReference;
import org.jetbrains.jps.model.module.JpsDependencyElement;
import org.jetbrains.jps.model.module.JpsLibraryDependency;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleSourceRoot;
import org.jetbrains.jps.model.serialization.JpsSerializationManager;
import javax.swing.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public final class IdeaJdk extends JavaDependentSdkType implements JavaSdkType {
private static final Logger LOG = Logger.getInstance(IdeaJdk.class);
private static final String LIB_DIR_NAME = "lib";
private static final String LIB_SRC_DIR_NAME = "lib/src";
private static final String PLUGINS_DIR = "plugins";
public IdeaJdk() {
super("IDEA JDK");
}
@Override
public Icon getIcon() {
return DevkitIcons.Sdk_closed;
}
@NotNull
@Override
public String getHelpTopic() {
return "reference.project.structure.sdk.idea";
}
@Override
@NotNull
public Icon getIconForAddAction() {
return DevkitIcons.Add_sdk;
}
@Override
public String suggestHomePath() {
return PathManager.getHomePath().replace(File.separatorChar, '/');
}
@NotNull
@Override
public String adjustSelectedSdkHome(@NotNull String homePath) {
if (SystemInfo.isMac) {
File home = new File(homePath, "Contents");
if (home.exists()) return home.getPath();
}
return super.adjustSelectedSdkHome(homePath);
}
@Override
public boolean isValidSdkHome(String path) {
if (PsiUtil.isPathToIntelliJIdeaSources(path)) {
return true;
}
File home = new File(path);
return home.exists() && getBuildNumber(path) != null && getPlatformApiJar(path) != null;
}
@Nullable
private static File getPlatformApiJar(String home) {
final File libDir = new File(home, LIB_DIR_NAME);
File f = new File(libDir, "platform-api.jar");
if (f.exists()) return f;
//in 173.* and earlier builds all IDEs included platform modules into openapi.jar (see org.jetbrains.intellij.build.ProductModulesLayout.platformApiModules)
f = new File(libDir, "openapi.jar");
if (f.exists()) return f;
return null;
}
@Override
@Nullable
public final String getVersionString(@NotNull final Sdk sdk) {
final Sdk internalJavaSdk = getInternalJavaSdk(sdk);
return internalJavaSdk != null ? internalJavaSdk.getVersionString() : null;
}
@Nullable
private static Sdk getInternalJavaSdk(final Sdk sdk) {
final SdkAdditionalData data = sdk.getSdkAdditionalData();
if (data instanceof Sandbox) {
return ((Sandbox)data).getJavaSdk();
}
return null;
}
@NotNull
@Override
public String suggestSdkName(@Nullable String currentSdkName, String sdkHome) {
if (PsiUtil.isPathToIntelliJIdeaSources(sdkHome)) return "Local IDEA [" + sdkHome + "]"; //NON-NLS
String buildNumber = getBuildNumber(sdkHome);
return IntelliJPlatformProduct.fromBuildNumber(buildNumber).getName() + " " + (buildNumber != null ? buildNumber : "");
}
@Nullable
public static String getBuildNumber(String ideaHome) {
try {
@NonNls final String buildTxt = SystemInfo.isMac ? "Resources/build.txt" : "build.txt";
File file = new File(ideaHome, buildTxt);
if (SystemInfo.isMac && !file.exists()) {
// IntelliJ IDEA 13 and earlier used a different location for build.txt on Mac;
// recognize the old location as well
file = new File(ideaHome, "build.txt");
}
return FileUtil.loadFile(file).trim();
}
catch (IOException e) {
return null;
}
}
private static VirtualFile[] getIdeaLibrary(String home) {
List<VirtualFile> result = new ArrayList<>();
appendIdeaLibrary(home, result, "junit.jar");
String plugins = home + File.separator + PLUGINS_DIR + File.separator;
appendIdeaLibrary(plugins + "java", result);
appendIdeaLibrary(plugins + "JavaEE", result, "javaee-impl.jar", "jpa-console.jar");
appendIdeaLibrary(plugins + "PersistenceSupport", result, "persistence-impl.jar");
appendIdeaLibrary(plugins + "DatabaseTools", result, "database-impl.jar", "jdbc-console.jar");
appendIdeaLibrary(plugins + "css", result, "css.jar");
appendIdeaLibrary(plugins + "uml", result, "uml-support.jar");
appendIdeaLibrary(plugins + "Spring", result,
"spring.jar", "spring-el.jar", "spring-jsf.jar", "spring-persistence-integration.jar");
return VfsUtilCore.toVirtualFileArray(result);
}
private static void appendIdeaLibrary(@NonNls @NotNull String libDirPath,
@NotNull List<VirtualFile> result,
@NonNls final String @NotNull ... forbidden) {
Arrays.sort(forbidden);
final String path = libDirPath + File.separator + LIB_DIR_NAME;
final JarFileSystem jfs = JarFileSystem.getInstance();
final File lib = new File(path);
if (lib.isDirectory()) {
File[] jars = lib.listFiles();
if (jars != null) {
for (File jar : jars) {
@NonNls String name = jar.getName();
if (jar.isFile() && Arrays.binarySearch(forbidden, name) < 0 && (name.endsWith(".jar") || name.endsWith(".zip"))) {
VirtualFile file = jfs.findFileByPath(jar.getPath() + JarFileSystem.JAR_SEPARATOR);
LOG.assertTrue(file != null, jar.getPath() + " not found");
result.add(file);
}
}
}
}
}
@Override
public boolean setupSdkPaths(@NotNull final Sdk sdk, @NotNull SdkModel sdkModel) {
final Sandbox additionalData = (Sandbox)sdk.getSdkAdditionalData();
if (additionalData != null) {
additionalData.cleanupWatchedRoots();
}
SdkModificator sdkModificator = sdk.getSdkModificator();
boolean result = setupSdkPaths(sdk, sdkModificator, sdkModel);
if (result && sdkModificator.getSdkAdditionalData() == null) {
List<String> javaSdks = new ArrayList<>();
Sdk[] sdks = sdkModel.getSdks();
for (Sdk jdk : sdks) {
if (isValidInternalJdk(sdk, jdk)) {
javaSdks.add(jdk.getName());
}
}
if (javaSdks.isEmpty()) {
JavaSdkVersion requiredVersion = getRequiredJdkVersion(sdk);
if (requiredVersion != null) {
Messages.showErrorDialog(DevKitBundle.message("sdk.no.java.sdk.for.idea.sdk.found", requiredVersion),
DevKitBundle.message("sdk.no.java.sdk.for.idea.sdk.found.title"));
}
else {
Messages.showErrorDialog(DevKitBundle.message("sdk.no.idea.sdk.version.found"),
DevKitBundle.message("sdk.no.java.sdk.for.idea.sdk.found.title"));
}
return false;
}
@NlsSafe String firstSdkName = javaSdks.get(0);
int choice = Messages.showChooseDialog(
DevKitBundle.message("sdk.select.java.sdk"),
DevKitBundle.message("sdk.select.java.sdk.title"),
ArrayUtilRt.toStringArray(javaSdks), firstSdkName, Messages.getQuestionIcon());
if (choice != -1) {
String name = javaSdks.get(choice);
Sdk internalJava = Objects.requireNonNull(sdkModel.findSdk(name));
//roots from internal jre
setInternalJdk(sdk, sdkModificator, internalJava);
}
else {
result = false;
}
}
sdkModificator.commitChanges();
return result;
}
private static void setInternalJdk(@NotNull Sdk sdk, @NotNull SdkModificator sdkModificator, @NotNull Sdk internalJava) {
addClasses(sdkModificator, internalJava);
addDocs(sdkModificator, internalJava);
addSources(sdkModificator, internalJava);
sdkModificator.setSdkAdditionalData(new Sandbox(getDefaultSandbox(), internalJava, sdk));
sdkModificator.setVersionString(internalJava.getVersionString());
}
static boolean isValidInternalJdk(@NotNull Sdk ideaSdk, @NotNull Sdk sdk) {
SdkTypeId sdkType = sdk.getSdkType();
if (sdkType instanceof JavaSdk) {
JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
JavaSdkVersion requiredVersion = getRequiredJdkVersion(ideaSdk);
if (version != null && requiredVersion != null) {
return version.isAtLeast(requiredVersion);
}
}
return false;
}
@Nullable
private static JavaSdkVersion getRequiredJdkVersion(Sdk ideaSdk) {
if (PsiUtil.isPathToIntelliJIdeaSources(ideaSdk.getHomePath())) return JavaSdkVersion.JDK_1_8;
File apiJar = getPlatformApiJar(ideaSdk.getHomePath());
return apiJar != null ? ClsParsingUtil.getJdkVersionByBytecode(getIdeaClassFileVersion(apiJar)) : null;
}
private static int getIdeaClassFileVersion(File apiJar) {
try {
try (ZipFile zipFile = new ZipFile(apiJar)) {
ZipEntry entry = zipFile.getEntry(ApplicationStarter.class.getName().replace('.', '/') + ".class");
if (entry != null) {
try (DataInputStream stream = new DataInputStream(zipFile.getInputStream(entry))) {
if (stream.skip(6) == 6) {
return stream.readUnsignedShort();
}
}
}
}
}
catch (IOException e) {
LOG.info(e);
}
return -1;
}
private static boolean setupSdkPaths(Sdk sdk, SdkModificator sdkModificator, SdkModel sdkModel) {
String sdkHome = Objects.requireNonNull(sdk.getHomePath());
if (PsiUtil.isPathToIntelliJIdeaSources(sdkHome)) {
try {
ProgressManager.getInstance().runProcessWithProgressSynchronously((ThrowableComputable<Void, IOException>)() -> {
setupSdkPathsFromIDEAProject(sdk, sdkModificator, sdkModel);
return null;
}, DevKitBundle.message("sdk.from.sources.scanning.roots"), true, null);
}
catch (ProcessCanceledException e) {
return false;
}
catch (IOException e) {
LOG.warn(e);
Messages.showErrorDialog(e.toString(), DevKitBundle.message("sdk.title"));
return false;
}
}
else {
VirtualFile[] ideaLib = getIdeaLibrary(sdkHome);
for (VirtualFile aIdeaLib : ideaLib) {
sdkModificator.addRoot(aIdeaLib, OrderRootType.CLASSES);
}
addSources(new File(sdkHome), sdkModificator);
}
return true;
}
private static void setupSdkPathsFromIDEAProject(Sdk sdk, SdkModificator sdkModificator, SdkModel sdkModel) throws IOException {
ProgressIndicator indicator = Objects.requireNonNull(ProgressManager.getInstance().getProgressIndicator());
String sdkHome = Objects.requireNonNull(sdk.getHomePath());
JpsModel model = JpsSerializationManager.getInstance().loadModel(sdkHome, PathManager.getOptionsPath());
JpsSdkReference<JpsDummyElement> sdkRef = model.getProject().getSdkReferencesTable().getSdkReference(JpsJavaSdkType.INSTANCE);
Sdk internalJava = sdkRef == null ? null : sdkModel.findSdk(sdkRef.getSdkName());
if (internalJava != null && isValidInternalJdk(sdk, internalJava)) {
setInternalJdk(sdk, sdkModificator, internalJava);
}
Map<String, JpsModule> moduleByName = model.getProject().getModules().stream().collect(Collectors.toMap(JpsModule::getName, Function.identity()));
@NonNls String[] mainModuleCandidates = {
"intellij.idea.ultimate.main",
"intellij.idea.community.main",
"main",
"community-main"
};
JpsModule mainModule = Arrays.stream(mainModuleCandidates).map(moduleByName::get).filter(Objects::nonNull).findFirst().orElse(null);
if (mainModule == null) {
LOG.error("Cannot find main module (" + Arrays.toString(mainModuleCandidates) + ") in IntelliJ IDEA sources at " + sdkHome);
return;
}
Set<JpsModule> modules = new LinkedHashSet<>();
JpsJavaExtensionService.dependencies(mainModule).recursively().processModules(modules::add);
indicator.setIndeterminate(false);
double delta = 1 / (2 * Math.max(0.5, modules.size()));
JpsJavaExtensionService javaService = JpsJavaExtensionService.getInstance();
VirtualFileManager vfsManager = VirtualFileManager.getInstance();
Set<VirtualFile> addedRoots = new HashSet<>();
for (JpsModule o : modules) {
indicator.setFraction(indicator.getFraction() + delta);
for (JpsDependencyElement dep : o.getDependenciesList().getDependencies()) {
ProgressManager.checkCanceled();
JpsLibrary library = dep instanceof JpsLibraryDependency ? ((JpsLibraryDependency)dep).getLibrary() : null;
if (library == null || library.getName().equals("jps-build-script-dependencies-bootstrap")) continue;
// do not check extension.getScope(), plugin projects need tests too
//JpsLibraryType<?> libraryType = library == null ? null : library.getType();
//if (!(libraryType instanceof JpsJavaLibraryType)) continue;
//JpsJavaDependencyExtension extension = javaService.getDependencyExtension(dep);
//if (extension == null) continue;
for (JpsLibraryRoot jps : library.getRoots(JpsOrderRootType.COMPILED)) {
VirtualFile root = vfsManager.findFileByUrl(jps.getUrl());
if (root == null || !addedRoots.add(root)) continue;
sdkModificator.addRoot(root, OrderRootType.CLASSES);
}
for (JpsLibraryRoot jps : library.getRoots(JpsOrderRootType.SOURCES)) {
VirtualFile root = vfsManager.findFileByUrl(jps.getUrl());
if (root == null || !addedRoots.add(root)) continue;
sdkModificator.addRoot(root, OrderRootType.SOURCES);
}
}
}
for (JpsModule o : modules) {
indicator.setFraction(indicator.getFraction() + delta);
String outputUrl = javaService.getOutputUrl(o, false);
VirtualFile outputRoot = outputUrl == null ? null : vfsManager.findFileByUrl(outputUrl);
if (outputRoot == null) continue;
sdkModificator.addRoot(outputRoot, OrderRootType.CLASSES);
for (JpsModuleSourceRoot jps : o.getSourceRoots()) {
ProgressManager.checkCanceled();
VirtualFile root = vfsManager.findFileByUrl(jps.getUrl());
if (root == null || !addedRoots.add(root)) continue;
sdkModificator.addRoot(root, OrderRootType.SOURCES);
}
}
indicator.setFraction(1.0);
}
static String getDefaultSandbox() {
@NonNls String defaultSandbox = "";
try {
defaultSandbox = new File(PathManager.getSystemPath()).getCanonicalPath() + File.separator + "plugins-sandbox";
}
catch (IOException e) {
//can't be on running instance
}
return defaultSandbox;
}
private static void addSources(File file, SdkModificator sdkModificator) {
File[] files = new File(file, LIB_SRC_DIR_NAME).listFiles();
if (files != null) {
JarFileSystem fs = JarFileSystem.getInstance();
for (File child : files) {
String path = child.getAbsolutePath();
if (!path.contains("generics") && (path.endsWith(".jar") || path.endsWith(".zip"))) {
fs.setNoCopyJarForPath(path);
VirtualFile vFile = fs.refreshAndFindFileByPath(path + JarFileSystem.JAR_SEPARATOR);
if (vFile != null) {
sdkModificator.addRoot(vFile, OrderRootType.SOURCES);
}
}
}
}
}
private static void addClasses(@NotNull SdkModificator sdkModificator, @NotNull Sdk javaSdk) {
addOrderEntries(OrderRootType.CLASSES, javaSdk, sdkModificator);
}
private static void addDocs(@NotNull SdkModificator sdkModificator, @NotNull Sdk javaSdk) {
if (!addOrderEntries(JavadocOrderRootType.getInstance(), javaSdk, sdkModificator) && SystemInfo.isMac) {
Sdk[] jdks = ProjectJdkTable.getInstance().getAllJdks();
for (Sdk jdk : jdks) {
if (jdk.getSdkType() instanceof JavaSdk) {
addOrderEntries(JavadocOrderRootType.getInstance(), jdk, sdkModificator);
break;
}
}
}
}
private static void addSources(SdkModificator sdkModificator, final Sdk javaSdk) {
if (javaSdk != null) {
if (!addOrderEntries(OrderRootType.SOURCES, javaSdk, sdkModificator)){
if (SystemInfo.isMac) {
Sdk[] jdks = ProjectJdkTable.getInstance().getAllJdks();
for (Sdk jdk : jdks) {
if (jdk.getSdkType() instanceof JavaSdk) {
addOrderEntries(OrderRootType.SOURCES, jdk, sdkModificator);
break;
}
}
}
else {
String homePath = javaSdk.getHomePath();
if (homePath == null) return;
File jarFile = new File(new File(homePath).getParentFile(), "src.zip");
if (jarFile.exists()) {
JarFileSystem jarFileSystem = JarFileSystem.getInstance();
String path = jarFile.getAbsolutePath();
jarFileSystem.setNoCopyJarForPath(path);
VirtualFile vFile = jarFileSystem.refreshAndFindFileByPath(path + JarFileSystem.JAR_SEPARATOR);
if (vFile != null) {
sdkModificator.addRoot(vFile, OrderRootType.SOURCES);
}
}
}
}
}
}
private static boolean addOrderEntries(@NotNull OrderRootType orderRootType, @NotNull Sdk sdk, @NotNull SdkModificator toModificator){
boolean wasSmthAdded = false;
final String[] entries = sdk.getRootProvider().getUrls(orderRootType);
for (String entry : entries) {
VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(entry);
if (virtualFile != null) {
toModificator.addRoot(virtualFile, orderRootType);
wasSmthAdded = true;
}
}
return wasSmthAdded;
}
@Override
public AdditionalDataConfigurable createAdditionalDataConfigurable(@NotNull final SdkModel sdkModel, @NotNull SdkModificator sdkModificator) {
return new IdeaJdkConfigurable(sdkModel, sdkModificator);
}
@Override
@Nullable
public String getBinPath(@NotNull Sdk sdk) {
final Sdk internalJavaSdk = getInternalJavaSdk(sdk);
return internalJavaSdk == null ? null : JavaSdk.getInstance().getBinPath(internalJavaSdk);
}
@Override
@Nullable
public String getToolsPath(@NotNull Sdk sdk) {
final Sdk jdk = getInternalJavaSdk(sdk);
if (jdk != null && jdk.getVersionString() != null){
return JavaSdk.getInstance().getToolsPath(jdk);
}
return null;
}
@Override
@Nullable
public String getVMExecutablePath(@NotNull Sdk sdk) {
final Sdk internalJavaSdk = getInternalJavaSdk(sdk);
return internalJavaSdk == null ? null : JavaSdk.getInstance().getVMExecutablePath(internalJavaSdk);
}
@Override
public void saveAdditionalData(@NotNull SdkAdditionalData additionalData, @NotNull Element additional) {
if (additionalData instanceof Sandbox) {
try {
((Sandbox)additionalData).writeExternal(additional);
}
catch (WriteExternalException e) {
LOG.error(e);
}
}
}
@Override
public SdkAdditionalData loadAdditionalData(@NotNull Sdk sdk, @NotNull Element additional) {
Sandbox sandbox = new Sandbox(sdk);
try {
sandbox.readExternal(additional);
}
catch (InvalidDataException e) {
LOG.error(e);
}
return sandbox;
}
@Override
@NotNull
public String getPresentableName() {
return DevKitBundle.message("sdk.title");
}
@Nullable
public static Sdk findIdeaJdk(@Nullable Sdk jdk) {
if (jdk == null) return null;
if (jdk.getSdkType() instanceof IdeaJdk) return jdk;
return null;
}
public static SdkType getInstance() {
return SdkType.findInstance(IdeaJdk.class);
}
@Override
public boolean isRootTypeApplicable(@NotNull OrderRootType type) {
return type == OrderRootType.CLASSES ||
type == OrderRootType.SOURCES ||
type == JavadocOrderRootType.getInstance() ||
type == AnnotationOrderRootType.getInstance();
}
@Override
public String getDefaultDocumentationUrl(@NotNull final Sdk sdk) {
return JavaSdk.getInstance().getDefaultDocumentationUrl(sdk);
}
}
|
package microsoft.exchange.webservices.data;
import javax.xml.stream.XMLStreamException;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
/**
* Represents a user configuration's Dictionary property.
*/
@EditorBrowsable(state = EditorBrowsableState.Never)
public final class UserConfigurationDictionary extends ComplexProperty
implements Iterable<Object> {
// TODO: Consider implementing IsDirty mechanism in ComplexProperty.
/** The dictionary. */
private Map<Object, Object> dictionary;
/** The is dirty. */
private boolean isDirty = false;
/**
* Initializes a new instance of "UserConfigurationDictionary" class.
*/
protected UserConfigurationDictionary() {
super();
this.dictionary = new HashMap<Object, Object>();
}
/**
* Gets the element with the specified key.
*
* @param key
* The key of the element to get or set.
* @return The element with the specified key.
*/
public Object getElements(Object key) {
return this.dictionary.get(key);
}
/**
* Sets the element with the specified key.
*
* @param key
* The key of the element to get or set
* @param value
* the value
* @throws Exception
* the exception
*/
public void setElements(Object key, Object value) throws Exception {
this.validateEntry(key, value);
this.dictionary.put(key, value);
this.changed();
}
/**
* Adds an element with the provided key and value to the user configuration
* dictionary.
*
* @param key
* The object to use as the key of the element to add.
* @param value
* The object to use as the value of the element to add.
* @throws Exception
* the exception
*/
public void addElement(Object key, Object value) throws Exception {
this.validateEntry(key, value);
this.dictionary.put(key, value);
this.changed();
}
/**
* Determines whether the user configuration dictionary contains an element
* with the specified key.
*
* @param key
* The key to locate in the user configuration dictionary.
* @return true if the user configuration dictionary contains an element
* with the key; otherwise false.
*/
public boolean containsKey(Object key) {
return this.dictionary.containsKey(key);
}
/**
* Removes the element with the specified key from the user configuration
* dictionary.
*
* @param key
* The key of the element to remove.
* @return true if the element is successfully removed; otherwise false.
*/
public boolean remove(Object key) {
boolean isRemoved = false;
if (key != null) {
this.dictionary.remove(key);
isRemoved = true;
}
if (isRemoved) {
this.changed();
}
return isRemoved;
}
/**
* Gets the value associated with the specified key.
*
* @param key
* The key whose value to get.
* @param value
* When this method returns, the value associated with the
* specified key, if the key is found; otherwise, null.
* @return true if the user configuration dictionary contains the key;
* otherwise false.
*/
public boolean tryGetValue(Object key, OutParam<Object> value) {
if (this.dictionary.containsKey(key)) {
value.setParam(this.dictionary.get(key));
return true;
} else {
value.setParam(null);
return false;
}
}
/**
* Gets the number of elements in the user configuration dictionary.
*
* @return the count
*/
public int getCount() {
return this.dictionary.size();
}
/**
* Removes all items from the user configuration dictionary.
*/
public void clear() {
if (this.dictionary.size() != 0) {
this.dictionary.clear();
this.changed();
}
}
/**
* Gets the enumerator.
*
* @return the enumerator
*/
@SuppressWarnings("unchecked")
/**
* Returns an enumerator that iterates through
* the user configuration dictionary.
* @return An IEnumerator that can be used
* to iterate through the user configuration dictionary.
*/
public Iterator getEnumerator() {
return (this.dictionary.values().iterator());
}
/**
* Gets the isDirty flag.
*
* @return the checks if is dirty
*/
protected boolean getIsDirty() {
return this.isDirty;
}
/**
* Sets the isDirty flag.
*
* @param value
* the new checks if is dirty
*/
protected void setIsDirty(boolean value) {
this.isDirty = value;
}
/**
* Instance was changed.
*/
@Override
protected void changed() {
super.changed();
this.isDirty = true;
}
/**
* Writes elements to XML.
*
* @param writer
* accepts EwsServiceXmlWriter
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws XMLStreamException, ServiceXmlSerializationException {
EwsUtilities.EwsAssert(writer != null,
"UserConfigurationDictionary.WriteElementsToXml",
"writer is null");
Iterator<Entry<Object, Object>> it = this.dictionary.entrySet()
.iterator();
while (it.hasNext()) {
Entry<Object, Object> dictionaryEntry = it.next();
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.DictionaryEntry);
this.writeObjectToXml(writer, XmlElementNames.DictionaryKey,
dictionaryEntry.getKey());
this.writeObjectToXml(writer, XmlElementNames.DictionaryValue,
dictionaryEntry.getValue());
writer.writeEndElement();
}
}
/**
* Writes a dictionary object (key or value) to Xml.
*
* @param writer
* The writer.
* @param xmlElementName
* The Xml element name.
* @param dictionaryObject
* The object to write.
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
private void writeObjectToXml(EwsServiceXmlWriter writer,
String xmlElementName, Object dictionaryObject)
throws XMLStreamException, ServiceXmlSerializationException {
EwsUtilities.EwsAssert(writer != null,
"UserConfigurationDictionary.WriteObjectToXml",
"writer is null");
EwsUtilities.EwsAssert(xmlElementName != null,
"UserConfigurationDictionary.WriteObjectToXml",
"xmlElementName is null");
writer.writeStartElement(XmlNamespace.Types, xmlElementName);
if (dictionaryObject == null) {
EwsUtilities.EwsAssert((!xmlElementName
.equals(XmlElementNames.DictionaryKey)),
"UserConfigurationDictionary.WriteObjectToXml",
"Key is null");
writer.writeAttributeValue(
EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix,
XmlAttributeNames.Nil, EwsUtilities.XSTrue);
} else {
this.writeObjectValueToXml(writer, dictionaryObject);
}
writer.writeEndElement();
}
/**
* Writes a dictionary Object's value to Xml.
*
* @param writer
* The writer.
* @param dictionaryObject
* The dictionary object to write. <br />
* Object values are either: <br />
* an array of strings, an array of bytes (which will be encoded into base64) <br />
* or a single value. Single values can be: <br />
* - datetime, boolean, byte, int, long, string
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
private void writeObjectValueToXml(final EwsServiceXmlWriter writer,
final Object dictionaryObject) throws XMLStreamException,
ServiceXmlSerializationException {
// Preconditions
if (dictionaryObject == null) {
throw new NullPointerException("DictionaryObject must not be null");
} else if (writer == null) {
throw new NullPointerException(
"EwsServiceXmlWriter must not be null");
}
// Processing
UserConfigurationDictionaryObjectType dictionaryObjectType = UserConfigurationDictionaryObjectType.StringArray;
if (dictionaryObject instanceof String[]) {
this.writeEntryTypeToXml(writer, dictionaryObjectType);
for (String arrayElement : (String[]) dictionaryObject) {
this.writeEntryValueToXml(writer, arrayElement);
}
} else {
String valueAsString = null;
if (dictionaryObject instanceof String) {
dictionaryObjectType = UserConfigurationDictionaryObjectType.String;
valueAsString = String.valueOf(dictionaryObject);
} else if (dictionaryObject instanceof Boolean) {
dictionaryObjectType = UserConfigurationDictionaryObjectType.Boolean;
valueAsString = EwsUtilities
.boolToXSBool((Boolean) dictionaryObject);
} else if (dictionaryObject instanceof Byte) {
dictionaryObjectType = UserConfigurationDictionaryObjectType.Byte;
valueAsString = String.valueOf(dictionaryObject);
} else if (dictionaryObject instanceof Date) {
dictionaryObjectType = UserConfigurationDictionaryObjectType.DateTime;
valueAsString = writer.getService()
.convertDateTimeToUniversalDateTimeString(
(Date) dictionaryObject);
} else if (dictionaryObject instanceof Integer) {
// removed unsigned integer because in Java, all types are
// signed, there are no unsigned versions
dictionaryObjectType = UserConfigurationDictionaryObjectType.Integer32;
valueAsString = String.valueOf(dictionaryObject);
} else if (dictionaryObject instanceof Long) {
// removed unsigned integer because in Java, all types are
// signed, there are no unsigned versions
dictionaryObjectType = UserConfigurationDictionaryObjectType.Integer64;
valueAsString = String.valueOf(dictionaryObject);
} else if (dictionaryObject instanceof Byte[]) {
dictionaryObjectType = UserConfigurationDictionaryObjectType.ByteArray;
valueAsString = Base64EncoderStream
.encode((byte[]) dictionaryObject);
} else {
throw new IllegalArgumentException(String.format(
"Unsupported type: %s", dictionaryObject.getClass()
.toString()));
}
this.writeEntryTypeToXml(writer, dictionaryObjectType);
this.writeEntryValueToXml(writer, valueAsString);
}
}
/**
* Writes a dictionary entry type to Xml.
*
* @param writer
* The writer.
* @param dictionaryObjectType
* Type to write.
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
private void writeEntryTypeToXml(EwsServiceXmlWriter writer,
UserConfigurationDictionaryObjectType dictionaryObjectType)
throws XMLStreamException, ServiceXmlSerializationException {
writer.writeStartElement(XmlNamespace.Types, XmlElementNames.Type);
writer
.writeValue(dictionaryObjectType.toString(),
XmlElementNames.Type);
writer.writeEndElement();
}
/**
* Writes a dictionary entry value to Xml.
*
* @param writer
* The writer.
* @param value
* Value to write.
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
private void writeEntryValueToXml(EwsServiceXmlWriter writer, String value)
throws XMLStreamException, ServiceXmlSerializationException {
writer.writeStartElement(XmlNamespace.Types, XmlElementNames.Value);
// While an entry value can't be null, if the entry is an array, an
// element of the array can be null.
if (value != null) {
writer.writeValue(value, XmlElementNames.Value);
}
writer.writeEndElement();
}
/*
* (non-Javadoc)
*
* @see
* microsoft.exchange.webservices.ComplexProperty#loadFromXml(microsoft.
* exchange.webservices.EwsServiceXmlReader,
* microsoft.exchange.webservices.XmlNamespace, java.lang.String)
*/
@Override
/**
* Loads this dictionary from the specified reader.
* @param reader The reader.
* @param xmlNamespace The dictionary's XML namespace.
* @param xmlElementName Name of the XML element
* representing the dictionary.
*/
protected void loadFromXml(EwsServiceXmlReader reader,
XmlNamespace xmlNamespace, String xmlElementName) throws Exception {
super.loadFromXml(reader, xmlNamespace, xmlElementName);
this.isDirty = false;
}
/*
* (non-Javadoc)
*
* @see
* microsoft.exchange.webservices.ComplexProperty#tryReadElementFromXml(
* microsoft.exchange.webservices.EwsServiceXmlReader)
*/
@Override
/**
* Tries to read element from XML.
* @param reader The reader.
* @return True if element was read.
*/
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
reader.ensureCurrentNodeIsStartElement(this.getNamespace(),
XmlElementNames.DictionaryEntry);
this.loadEntry(reader);
return true;
}
/**
* Loads an entry, consisting of a key value pair, into this dictionary from
* the specified reader.
*
* @param reader
* The reader.
* @throws Exception
* the exception
*/
private void loadEntry(EwsServiceXmlReader reader) throws Exception {
EwsUtilities.EwsAssert(reader != null,
"UserConfigurationDictionary.LoadEntry", "reader is null");
Object key;
Object value = null;
// Position at DictionaryKey
reader.readStartElement(this.getNamespace(),
XmlElementNames.DictionaryKey);
key = this.getDictionaryObject(reader);
// Position at DictionaryValue
reader.readStartElement(this.getNamespace(),
XmlElementNames.DictionaryValue);
String nil = reader.readAttributeValue(XmlNamespace.XmlSchemaInstance,
XmlAttributeNames.Nil);
boolean hasValue = (nil == null)
|| (!nil.getClass().equals(Boolean.TYPE));
if (hasValue) {
value = this.getDictionaryObject(reader);
}
this.dictionary.put(key, value);
}
/**
* Extracts a dictionary object (key or entry value) from the specified
* reader.
*
* @param reader
* The reader.
* @return Dictionary object.
* @throws Exception
* the exception
*/
private Object getDictionaryObject(EwsServiceXmlReader reader)
throws Exception {
EwsUtilities.EwsAssert(reader != null,
"UserConfigurationDictionary.loadFromXml", "reader is null");
UserConfigurationDictionaryObjectType type = this.getObjectType(reader);
List<String> values = this.getObjectValue(reader, type);
return this.constructObject(type, values, reader);
}
/**
* Extracts a dictionary object (key or entry value) as a string list from
* the specified reader.
*
* @param reader
* The reader.
* @param type
* The object type.
* @return String list representing a dictionary object.
* @throws Exception
* the exception
*/
private List<String> getObjectValue(EwsServiceXmlReader reader,
UserConfigurationDictionaryObjectType type) throws Exception {
EwsUtilities.EwsAssert(reader != null,
"UserConfigurationDictionary.LoadFromXml", "reader is null");
List<String> values = new ArrayList<String>();
reader.readStartElement(this.getNamespace(), XmlElementNames.Value);
do {
String value = null;
if (reader.isEmptyElement()) {
// Only string types can be represented with empty values.
if (type.equals(UserConfigurationDictionaryObjectType.String)
|| type
.equals(UserConfigurationDictionaryObjectType.
StringArray)) {
value = "";
} else {
EwsUtilities
.EwsAssert(
false,
"UserConfigurationDictionary." +
"GetObjectValue",
"Empty element passed for type: "
+ type.toString());
}
}
else {
value = reader.readElementValue();
}
values.add(value);
reader.read(); // Position at next element or
// DictionaryKey/DictionaryValue end element
} while (reader.isStartElement(this.getNamespace(),
XmlElementNames.Value));
return values;
}
/**
* Extracts the dictionary object (key or entry value) type from the
* specified reader.
*
* @param reader
* The reader.
* @return Dictionary object type.
* @throws Exception
* the exception
*/
private UserConfigurationDictionaryObjectType getObjectType(
EwsServiceXmlReader reader) throws Exception {
EwsUtilities.EwsAssert(reader != null,
"UserConfigurationDictionary.LoadFromXml", "reader is null");
reader.readStartElement(this.getNamespace(), XmlElementNames.Type);
String type = reader.readElementValue();
return UserConfigurationDictionaryObjectType.valueOf(type);
}
/**
* Constructs a dictionary object (key or entry value) from the specified
* type and string list.
*
* @param type
* Object type to construct.
* @param value
* Value of the dictionary object as a string list
* @param reader
* The reader.
* @return Dictionary object.
*/
private Object constructObject(UserConfigurationDictionaryObjectType type,
List<String> value, EwsServiceXmlReader reader) {
EwsUtilities.EwsAssert(value != null,
"UserConfigurationDictionary.ConstructObject", "value is null");
EwsUtilities
.EwsAssert(
(value.size() == 1 || type ==
UserConfigurationDictionaryObjectType.StringArray),
"UserConfigurationDictionary.ConstructObject",
"value is array but type is not StringArray");
EwsUtilities
.EwsAssert(reader != null,
"UserConfigurationDictionary.ConstructObject",
"reader is null");
Object dictionaryObject = null;
if (type.equals(UserConfigurationDictionaryObjectType.Boolean)) {
dictionaryObject = Boolean.parseBoolean(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.Byte)) {
dictionaryObject = Byte.parseByte(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.ByteArray)) {
dictionaryObject = Base64EncoderStream.decode(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.DateTime)) {
Date dateTime = reader.getService()
.convertUniversalDateTimeStringToDate(value.get(0));
if (dateTime != null) {
dictionaryObject = dateTime;
} else {
EwsUtilities.EwsAssert(false,
"UserConfigurationDictionary.ConstructObject",
"DateTime is null");
}
} else if (type.equals(UserConfigurationDictionaryObjectType.Integer32)) {
dictionaryObject = Integer.parseInt(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.Integer64)) {
dictionaryObject = Long.parseLong(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.String)) {
dictionaryObject = String.valueOf(value.get(0));
} else if (type
.equals(UserConfigurationDictionaryObjectType.StringArray)) {
dictionaryObject = value.toArray();
} else if (type
.equals(UserConfigurationDictionaryObjectType.
UnsignedInteger32)) {
dictionaryObject = Integer.parseInt(value.get(0));
} else if (type
.equals(UserConfigurationDictionaryObjectType.
UnsignedInteger64)) {
dictionaryObject = Long.parseLong(value.get(0));
} else {
EwsUtilities.EwsAssert(false,
"UserConfigurationDictionary.ConstructObject",
"Type not recognized: " + type.toString());
}
return dictionaryObject;
}
/**
* Validates the specified key and value.
*
* @param key
* The key.
* @param value
* The diction dictionary entry key.ary entry value.
* @throws Exception
* the exception
*/
private void validateEntry(Object key, Object value) throws Exception {
this.validateObject(key);
this.validateObject(value);
}
/**
* Validates the dictionary object (key or entry value).
*
* @param dictionaryObject
* Object to validate.
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
private void validateObject(Object dictionaryObject) throws Exception {
// Keys may not be null but we rely on the internal dictionary to throw
// if the key is null.
if (dictionaryObject != null) {
if(dictionaryObject.getClass().isArray() ){
int length = Array.getLength(dictionaryObject);
Class wrapperType = Array.get(dictionaryObject, 0).getClass();
Object[] newArray = (Object[]) Array.
newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(dictionaryObject, i);
}
this.validateArrayObject(newArray);
}
else{
this.validateObjectType(dictionaryObject.getClass());
}
} else {
throw new NullPointerException();
}
}
/**
* Validate the array object.
*
* @param dictionaryObjectAsArray
* Object to validate
* @throws microsoft.exchange.webservices.data.ServiceLocalException
* the service local exception
*/
private void validateArrayObject(Object[] dictionaryObjectAsArray)
throws ServiceLocalException {
// This logic is based on
// Microsoft.Exchange.Data.Storage.ConfigurationDictionary.
// CheckElementSupportedType().
// if (dictionaryObjectAsArray is string[])
if (dictionaryObjectAsArray instanceof String[]) {
if (dictionaryObjectAsArray.length > 0) {
for (Object arrayElement : dictionaryObjectAsArray) {
if (arrayElement == null) {
throw new ServiceLocalException(
Strings.NullStringArrayElementInvalid);
}
}
} else {
throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid);
}
} else if (dictionaryObjectAsArray instanceof Byte[]) {
if (dictionaryObjectAsArray.length <= 0) {
throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid);
}
} else {
throw new ServiceLocalException(String.format(
Strings.ObjectTypeNotSupported, dictionaryObjectAsArray
.getClass()));
}
}
/**
* Validates the dictionary object type.
*
* @param type
* Type to validate.
* @throws microsoft.exchange.webservices.data.ServiceLocalException
* the service local exception
*/
private void validateObjectType(Type type) throws ServiceLocalException {
// This logic is based on
// Microsoft.Exchange.Data.Storage.ConfigurationDictionary.
// CheckElementSupportedType().
boolean isValidType = false;
if (type.equals(Boolean.TYPE) || type.equals(Byte.TYPE)
|| type.equals(Date.class) || type.equals(Integer.TYPE)
|| type.equals(Long.TYPE) || type.equals(String.class)
|| type.equals(Integer.TYPE) || type.equals(Long.TYPE)) {
isValidType = true;
}
if (!isValidType) {
throw new ServiceLocalException(String.format(Strings.ObjectTypeNotSupported, type));
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<Object> iterator() {
return this.dictionary.values().iterator();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.