repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
gast-lib/gast-lib | jjil/src/jjil/algorithm/MaskedGray32SubImgGen.java | // Path: jjil/src/jjil/core/Image.java
// public abstract class Image {
// /**
// * The image height.
// */
// private final int mnHeight;
// /**
// * The image width.
// */
// private final int mnWidth;
//
// /** Creates a new instance of Image
// *
// * @param mnWidth the image width
// * @param mnHeight the image height
// */
// public Image(int mnWidth, int mnHeight) {
// this.mnWidth = mnWidth;
// this.mnHeight = mnHeight;
// }
//
// /**
// * Makes a copy of the image
// * @return the image copy
// */
// public abstract Object clone();
//
// /** Returns the image height
// *
// * @return the image height (rows)
// */
// public int getHeight()
// {
// return this.mnHeight;
// }
//
// /**
// * Returns a Point object giving the size of this image
// * (width x height)
// * @return a Point indicating the image size
// */
// public Point getSize() {
// return new Point(this.mnWidth, this.mnHeight);
// }
//
// /** Returns the image width
// *
// * @return the image width (columns)
// */
// public int getWidth()
// {
// return this.mnWidth;
// }
// }
| import jjil.core.Error;
import jjil.core.Gray32MaskedImage;
import jjil.core.Gray32OffsetImage;
import jjil.core.Gray8OffsetImage;
import jjil.core.Image;
import jjil.core.PipelineStage;
| this.nWidth / 2;
}
this.oSubImageReady = true;
return false;
}
// We are done producing images when the advance returns no more images
/**
* Returns true iff there is another image available from getFront().
* Note that the existence of another image from
* MaskedGray32SubImgGen depends on the mask image so there's no way to guarantee
* there will be even one subimage generated for a particular input. You must
* always call isEmpty().
* @return true iff there is another image available from getFront().
*/
public boolean isEmpty() {
return !advanceToNextSubImage();
}
// Return the next subimage and increment the indices
/**
* Returns the next subimage generated. The subimage will have its offset
* set to indicate where it was generated in the input image.
* @return a MaskedGray8SubImage that is the next subimage in the input Gray8Image to
* be processed.
* @throws jjil.core.Error if no subimage is available (you have to call isEmpty() to determine if
* a subimage is available. As few as 0 subimage can be generated for a
* given input if the entire image is masked.) Also throws if the output
* image (stored in the superclass) has been changed in type.
*/
| // Path: jjil/src/jjil/core/Image.java
// public abstract class Image {
// /**
// * The image height.
// */
// private final int mnHeight;
// /**
// * The image width.
// */
// private final int mnWidth;
//
// /** Creates a new instance of Image
// *
// * @param mnWidth the image width
// * @param mnHeight the image height
// */
// public Image(int mnWidth, int mnHeight) {
// this.mnWidth = mnWidth;
// this.mnHeight = mnHeight;
// }
//
// /**
// * Makes a copy of the image
// * @return the image copy
// */
// public abstract Object clone();
//
// /** Returns the image height
// *
// * @return the image height (rows)
// */
// public int getHeight()
// {
// return this.mnHeight;
// }
//
// /**
// * Returns a Point object giving the size of this image
// * (width x height)
// * @return a Point indicating the image size
// */
// public Point getSize() {
// return new Point(this.mnWidth, this.mnHeight);
// }
//
// /** Returns the image width
// *
// * @return the image width (columns)
// */
// public int getWidth()
// {
// return this.mnWidth;
// }
// }
// Path: jjil/src/jjil/algorithm/MaskedGray32SubImgGen.java
import jjil.core.Error;
import jjil.core.Gray32MaskedImage;
import jjil.core.Gray32OffsetImage;
import jjil.core.Gray8OffsetImage;
import jjil.core.Image;
import jjil.core.PipelineStage;
this.nWidth / 2;
}
this.oSubImageReady = true;
return false;
}
// We are done producing images when the advance returns no more images
/**
* Returns true iff there is another image available from getFront().
* Note that the existence of another image from
* MaskedGray32SubImgGen depends on the mask image so there's no way to guarantee
* there will be even one subimage generated for a particular input. You must
* always call isEmpty().
* @return true iff there is another image available from getFront().
*/
public boolean isEmpty() {
return !advanceToNextSubImage();
}
// Return the next subimage and increment the indices
/**
* Returns the next subimage generated. The subimage will have its offset
* set to indicate where it was generated in the input image.
* @return a MaskedGray8SubImage that is the next subimage in the input Gray8Image to
* be processed.
* @throws jjil.core.Error if no subimage is available (you have to call isEmpty() to determine if
* a subimage is available. As few as 0 subimage can be generated for a
* given input if the entire image is masked.) Also throws if the output
* image (stored in the superclass) has been changed in type.
*/
| public Image getFront() throws jjil.core.Error
|
gast-lib/gast-lib | jjil/src/jjil/algorithm/Gray8CannyVert.java | // Path: jjil/src/jjil/core/Image.java
// public abstract class Image {
// /**
// * The image height.
// */
// private final int mnHeight;
// /**
// * The image width.
// */
// private final int mnWidth;
//
// /** Creates a new instance of Image
// *
// * @param mnWidth the image width
// * @param mnHeight the image height
// */
// public Image(int mnWidth, int mnHeight) {
// this.mnWidth = mnWidth;
// this.mnHeight = mnHeight;
// }
//
// /**
// * Makes a copy of the image
// * @return the image copy
// */
// public abstract Object clone();
//
// /** Returns the image height
// *
// * @return the image height (rows)
// */
// public int getHeight()
// {
// return this.mnHeight;
// }
//
// /**
// * Returns a Point object giving the size of this image
// * (width x height)
// * @return a Point indicating the image size
// */
// public Point getSize() {
// return new Point(this.mnWidth, this.mnHeight);
// }
//
// /** Returns the image width
// *
// * @return the image width (columns)
// */
// public int getWidth()
// {
// return this.mnWidth;
// }
// }
| import jjil.core.Error;
import jjil.core.Gray8Image;
import jjil.core.Image;
import jjil.core.PipelineStage; | {-12, -11, -11, -10, -8, -6, -5, -3, -1, 0, 2, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -11, -10, -8, -6, -5, -3, -1, 0, 2, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -11, -9, -8, -6, -5, -3, -1, 0, 1, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -10, -9, -8, -6, -5, -3, -1, 0, 1, 3, 4, 5, 6, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 6, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 6, 5},
};
/**
* Creates a new instance of Gray8CannyVert
* @param cSigma the sigma value for the operator, which is the sigma
* in the Gaussian distribution multipied by 10.0 and converted to integer.
* @throws jjil.core.Error if cSigma is out of range.
*/
public Gray8CannyVert(int cSigma) throws jjil.core.Error {
this.setSigma(cSigma);
}
/**
* Apply the Canny operator vertically to the input input image.
* The sigma value for the operator is set in the class constructor.
* We handle the borders of the image a little carefully to avoid creating
* spurious edges at them. The image value at the border is reflected so
* that image(0,-1), for example, is made equal to image(0,1).
* @param image the input Gray8Image
* @throws jjil.core.Error if the input is not a Gray8Image.
*/ | // Path: jjil/src/jjil/core/Image.java
// public abstract class Image {
// /**
// * The image height.
// */
// private final int mnHeight;
// /**
// * The image width.
// */
// private final int mnWidth;
//
// /** Creates a new instance of Image
// *
// * @param mnWidth the image width
// * @param mnHeight the image height
// */
// public Image(int mnWidth, int mnHeight) {
// this.mnWidth = mnWidth;
// this.mnHeight = mnHeight;
// }
//
// /**
// * Makes a copy of the image
// * @return the image copy
// */
// public abstract Object clone();
//
// /** Returns the image height
// *
// * @return the image height (rows)
// */
// public int getHeight()
// {
// return this.mnHeight;
// }
//
// /**
// * Returns a Point object giving the size of this image
// * (width x height)
// * @return a Point indicating the image size
// */
// public Point getSize() {
// return new Point(this.mnWidth, this.mnHeight);
// }
//
// /** Returns the image width
// *
// * @return the image width (columns)
// */
// public int getWidth()
// {
// return this.mnWidth;
// }
// }
// Path: jjil/src/jjil/algorithm/Gray8CannyVert.java
import jjil.core.Error;
import jjil.core.Gray8Image;
import jjil.core.Image;
import jjil.core.PipelineStage;
{-12, -11, -11, -10, -8, -6, -5, -3, -1, 0, 2, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -11, -10, -8, -6, -5, -3, -1, 0, 2, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -11, -9, -8, -6, -5, -3, -1, 0, 1, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 4},
{-11, -11, -10, -9, -8, -6, -5, -3, -1, 0, 1, 3, 4, 5, 6, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 3, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 5, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 6, 5},
{-11, -11, -10, -9, -8, -7, -5, -3, -1, 0, 1, 2, 4, 5, 5, 6, 6, 6, 6, 6, 6, 5},
};
/**
* Creates a new instance of Gray8CannyVert
* @param cSigma the sigma value for the operator, which is the sigma
* in the Gaussian distribution multipied by 10.0 and converted to integer.
* @throws jjil.core.Error if cSigma is out of range.
*/
public Gray8CannyVert(int cSigma) throws jjil.core.Error {
this.setSigma(cSigma);
}
/**
* Apply the Canny operator vertically to the input input image.
* The sigma value for the operator is set in the class constructor.
* We handle the borders of the image a little carefully to avoid creating
* spurious edges at them. The image value at the border is reflected so
* that image(0,-1), for example, is made equal to image(0,1).
* @param image the input Gray8Image
* @throws jjil.core.Error if the input is not a Gray8Image.
*/ | public void push(Image image) throws jjil.core.Error { |
CERN-BE/Entwined-STM | src/test/java/cern/entwined/AllSTMTests.java | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
| import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest; | /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class, | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
// Path: src/test/java/cern/entwined/AllSTMTests.java
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class, | SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, |
CERN-BE/Entwined-STM | src/test/java/cern/entwined/AllSTMTests.java | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
| import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest; | /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class, | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
// Path: src/test/java/cern/entwined/AllSTMTests.java
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class, | SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, |
CERN-BE/Entwined-STM | src/test/java/cern/entwined/AllSTMTests.java | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
| import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest; | /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class,
SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
// Path: src/test/java/cern/entwined/AllSTMTests.java
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class,
SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, | NoTransactionExceptionTest.class, InvocationExceptionTest.class, GlobalReferenceTest.class, |
CERN-BE/Entwined-STM | src/test/java/cern/entwined/AllSTMTests.java | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
| import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest; | /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class,
SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, | // Path: src/test/java/cern/entwined/exception/ConflictExceptionTest.java
// public class ConflictExceptionTest {
//
// @Test
// public void testConflictException() {
// new ConflictException();
// }
//
// @Test
// public void testConflictExceptionString() {
// ConflictException dut = new ConflictException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testConflictExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testConflictExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// ConflictException dut = new ConflictException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/InvocationExceptionTest.java
// public class InvocationExceptionTest {
//
// @Test
// public void testMemoryException() {
// new InvocationException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// InvocationException dut = new InvocationException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// InvocationException dut = new InvocationException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/MemoryExceptionTest.java
// public class MemoryExceptionTest {
//
// @Test
// public void testMemoryException() {
// new MemoryException();
// }
//
// @Test
// public void testMemoryExceptionString() {
// MemoryException dut = new MemoryException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testMemoryExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testMemoryExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// MemoryException dut = new MemoryException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
//
// Path: src/test/java/cern/entwined/exception/NoTransactionExceptionTest.java
// public class NoTransactionExceptionTest {
//
// @Test
// public void testNoTransactionException() {
// new NoTransactionException();
// }
//
// @Test
// public void testNoTransactionExceptionString() {
// NoTransactionException dut = new NoTransactionException("Test message");
// assertEquals("wrong message", "Test message", dut.getMessage());
// }
//
// @Test
// public void testNoTransactionExceptionStringThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException(testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// }
//
// @Test
// public void testNoTransactionExceptionThrowable() {
// Exception testEx = new Exception("Test exception");
// NoTransactionException dut = new NoTransactionException("Test message", testEx);
// assertEquals("wrong message", testEx, dut.getCause());
// assertEquals("wrong message", "Test message, Test exception", dut.getMessage());
// }
// }
// Path: src/test/java/cern/entwined/AllSTMTests.java
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cern.entwined.exception.ConflictExceptionTest;
import cern.entwined.exception.InvocationExceptionTest;
import cern.entwined.exception.MemoryExceptionTest;
import cern.entwined.exception.NoTransactionExceptionTest;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* The route of all the STM unit tests.
*
* @author Ivan Koblik
*/
@RunWith(Suite.class)
@SuiteClasses({ TransactionalMapTest.class, TransactionalRefTest.class, NodeTest.class, MemoryTest.class,
SnapshotTest.class, CompositeCollectionTest.class, MemoryExceptionTest.class, ConflictExceptionTest.class, | NoTransactionExceptionTest.class, InvocationExceptionTest.class, GlobalReferenceTest.class, |
CERN-BE/Entwined-STM | src/test/java/cern/entwined/UtilsTest.java | // Path: src/main/java/cern/entwined/Utils.java
// public static Predicate<String> NOT_EMPTY = new Predicate<String>() {
// @Override
// public boolean apply(String input) {
// return null != input && input.trim().length() != 0;
// }
// };
| import static cern.entwined.Utils.NOT_EMPTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
| assertEquals("", Utils.join(Arrays.asList(EMPTY_ARRAY_LIST), ""));
assertEquals("", Utils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR));
assertEquals(TEXT_LIST, Utils.join(Arrays.asList(ARRAY_LIST), SEPARATOR));
}
@Test
public void testGetUnique_OnSingleElementCollection() {
Collection<String> col = Collections.singleton("unique");
assertEquals("The unique value in the collection", "unique", Utils.getUnique(col));
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("unchecked")
public void testGetUnique_FailOnEmptyCollection() {
Utils.getUnique(Collections.EMPTY_SET);
}
@Test(expected = IllegalArgumentException.class)
public void testGetUnique_FailOnBiggerCollection() {
Utils.getUnique(ImmutableSet.of(1, 2));
}
@Test(expected = IllegalArgumentException.class)
public void testGetUnique_FailOnNull() {
Utils.getUnique(null);
}
@Test
public void testNotEmpty() {
| // Path: src/main/java/cern/entwined/Utils.java
// public static Predicate<String> NOT_EMPTY = new Predicate<String>() {
// @Override
// public boolean apply(String input) {
// return null != input && input.trim().length() != 0;
// }
// };
// Path: src/test/java/cern/entwined/UtilsTest.java
import static cern.entwined.Utils.NOT_EMPTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
assertEquals("", Utils.join(Arrays.asList(EMPTY_ARRAY_LIST), ""));
assertEquals("", Utils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR));
assertEquals(TEXT_LIST, Utils.join(Arrays.asList(ARRAY_LIST), SEPARATOR));
}
@Test
public void testGetUnique_OnSingleElementCollection() {
Collection<String> col = Collections.singleton("unique");
assertEquals("The unique value in the collection", "unique", Utils.getUnique(col));
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("unchecked")
public void testGetUnique_FailOnEmptyCollection() {
Utils.getUnique(Collections.EMPTY_SET);
}
@Test(expected = IllegalArgumentException.class)
public void testGetUnique_FailOnBiggerCollection() {
Utils.getUnique(ImmutableSet.of(1, 2));
}
@Test(expected = IllegalArgumentException.class)
public void testGetUnique_FailOnNull() {
Utils.getUnique(null);
}
@Test
public void testNotEmpty() {
| assertTrue("On 123", NOT_EMPTY.apply("123"));
|
CERN-BE/Entwined-STM | src/main/java/cern/entwined/TransactionalQueue.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Queue;
import cern.entwined.exception.ConflictException;
| if (!onlyReadLogs) {
this.sourceIterator = changes.sourceIterator;
this.tail = changes.tail;
this.pollCount = changes.pollCount;
}
}
/**
* For performance purposes returned global state is initialized with empty iterator, therefore polling data from
* the collection is not possible. As it should never be done to the global state, it is safe to do that. This
* however does not affect clean or dirty copies.
*/
@Override
@SuppressWarnings("unchecked")
public TransactionalQueue<E> commit(TransactionalQueue<E> globalState) {
Utils.checkNull("Global state", globalState);
if (0 != globalState.peekCount || !globalState.tail.isEmpty()) {
throw new IllegalArgumentException("Global state map must be commited before calling this method");
}
// If not accessed, return the global state.
if (this.peekCount == 0 && tail.isEmpty()) {
return globalState;
}
int sourceSize = this.sourceQueue.size();
if (this.peekCount != 0) {
// There were readings, check for the conflicts.
if (globalState.globalPollCount != this.globalPollCount) {
// We were reading from the head, and it is different the global state.
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/cern/entwined/TransactionalQueue.java
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Queue;
import cern.entwined.exception.ConflictException;
if (!onlyReadLogs) {
this.sourceIterator = changes.sourceIterator;
this.tail = changes.tail;
this.pollCount = changes.pollCount;
}
}
/**
* For performance purposes returned global state is initialized with empty iterator, therefore polling data from
* the collection is not possible. As it should never be done to the global state, it is safe to do that. This
* however does not affect clean or dirty copies.
*/
@Override
@SuppressWarnings("unchecked")
public TransactionalQueue<E> commit(TransactionalQueue<E> globalState) {
Utils.checkNull("Global state", globalState);
if (0 != globalState.peekCount || !globalState.tail.isEmpty()) {
throw new IllegalArgumentException("Global state map must be commited before calling this method");
}
// If not accessed, return the global state.
if (this.peekCount == 0 && tail.isEmpty()) {
return globalState;
}
int sourceSize = this.sourceQueue.size();
if (this.peekCount != 0) {
// There were readings, check for the conflicts.
if (globalState.globalPollCount != this.globalPollCount) {
// We were reading from the head, and it is different the global state.
| throw new ConflictException("Queue's head was updated");
|
CERN-BE/Entwined-STM | src/main/java/cern/entwined/GlobalReference.java | // Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
| import cern.entwined.exception.NoTransactionException;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* This class enables aggregation of transactional references within non transactional entities. Global reference must
* be treated as transactional and thread local.
*
* @param <T> The reference value type.
* @author Ivan Koblik
*/
public class GlobalReference<T> {
/**
* Reference to the {@link Memory} class. It is used to access current snapshot.
*/
private final Memory<?> memory;
/**
* {@link GlobalReference} unique identifier.
*/
private final Long id;
/**
* Creates an instance of {@link GlobalReference} using given memory and object.
*
* @param memory The instance of {@link Memory} class.
* @param object The globally referenced object of type T.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public GlobalReference(final Memory<?> memory, final T object) {
Utils.checkNull("Memory", memory);
this.memory = memory;
this.id = memory.getNextId();
try {
memory.getBaseSnapshot().getGlobalMap().put(id, object);
| // Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/cern/entwined/GlobalReference.java
import cern.entwined.exception.NoTransactionException;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* This class enables aggregation of transactional references within non transactional entities. Global reference must
* be treated as transactional and thread local.
*
* @param <T> The reference value type.
* @author Ivan Koblik
*/
public class GlobalReference<T> {
/**
* Reference to the {@link Memory} class. It is used to access current snapshot.
*/
private final Memory<?> memory;
/**
* {@link GlobalReference} unique identifier.
*/
private final Long id;
/**
* Creates an instance of {@link GlobalReference} using given memory and object.
*
* @param memory The instance of {@link Memory} class.
* @param object The globally referenced object of type T.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public GlobalReference(final Memory<?> memory, final T object) {
Utils.checkNull("Memory", memory);
this.memory = memory;
this.id = memory.getNextId();
try {
memory.getBaseSnapshot().getGlobalMap().put(id, object);
| } catch (NoTransactionException ex) {
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalRefTest.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| TransactionalRef<Integer> globalState = new TransactionalRef<Integer>(100);
copy.commit(globalState);
}
// ==================== Dirty copy/update tests ====================
@Test
public void testDirtyCopy_sourceDataCopied() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
assertEquals("Source data", (Integer) 10, copyRef.deref());
}
@Test
public void testDirtyCopy_modificationCopied() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
ref.assoc(1);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
assertEquals("Local changes", (Integer) 1, copyRef.deref());
}
@Test
public void testDirtyCopy_sourceValuesReferentiallyEqual() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
ref.assoc(1);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
// Checks that source values are same.
ref.update(copyRef, false);
}
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalRefTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
TransactionalRef<Integer> globalState = new TransactionalRef<Integer>(100);
copy.commit(globalState);
}
// ==================== Dirty copy/update tests ====================
@Test
public void testDirtyCopy_sourceDataCopied() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
assertEquals("Source data", (Integer) 10, copyRef.deref());
}
@Test
public void testDirtyCopy_modificationCopied() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
ref.assoc(1);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
assertEquals("Local changes", (Integer) 1, copyRef.deref());
}
@Test
public void testDirtyCopy_sourceValuesReferentiallyEqual() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
ref.assoc(1);
TransactionalRef<Integer> copyRef = ref.dirtyCopy();
// Checks that source values are same.
ref.update(copyRef, false);
}
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/CompositeCollectionTest.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| // Clean copy of the original collection
CompositeCollection ccollection2 = ccollection.dirtyCopy();
SemiPersistent<SemiPersistent> ref21 = mock(SemiPersistent.class);
SemiPersistent<SemiPersistent> ref22 = mock(SemiPersistent.class);
CompositeCollection globalState = new CompositeCollection(ref21, ref22);
// Commit should be only called on previously accessed items.
ccollection2.commit(globalState);
// Calls dirtyCopy on ref11 because it was accessed in ccollection.
verify(ref11, times(1)).dirtyCopy();
verify(ref11, times(1)).commit(ref21);
verifyNoMoreInteractions(ref11, ref12, ref21, ref22);
}
@Test
public void testUpdateCompositeCollectionFalse_delegatesForEveryItem() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
TransactionalRef<Integer> ref2 = new TransactionalRef<Integer>(100);
CompositeCollection ccollection = new CompositeCollection(ref, ref2);
CompositeCollection copy = ccollection.dirtyCopy();
((TransactionalRef<Integer>) copy.get(0)).assoc(100);
((TransactionalRef<Integer>) copy.get(1)).assoc(1000);
ccollection.update(copy, false);
assertEquals("Updated reference", (Integer) 100, ((TransactionalRef<Integer>) ccollection.get(0)).deref());
assertEquals("Updated reference", (Integer) 1000, ((TransactionalRef<Integer>) ccollection.get(1)).deref());
}
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/CompositeCollectionTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
// Clean copy of the original collection
CompositeCollection ccollection2 = ccollection.dirtyCopy();
SemiPersistent<SemiPersistent> ref21 = mock(SemiPersistent.class);
SemiPersistent<SemiPersistent> ref22 = mock(SemiPersistent.class);
CompositeCollection globalState = new CompositeCollection(ref21, ref22);
// Commit should be only called on previously accessed items.
ccollection2.commit(globalState);
// Calls dirtyCopy on ref11 because it was accessed in ccollection.
verify(ref11, times(1)).dirtyCopy();
verify(ref11, times(1)).commit(ref21);
verifyNoMoreInteractions(ref11, ref12, ref21, ref22);
}
@Test
public void testUpdateCompositeCollectionFalse_delegatesForEveryItem() {
TransactionalRef<Integer> ref = new TransactionalRef<Integer>(10);
TransactionalRef<Integer> ref2 = new TransactionalRef<Integer>(100);
CompositeCollection ccollection = new CompositeCollection(ref, ref2);
CompositeCollection copy = ccollection.dirtyCopy();
((TransactionalRef<Integer>) copy.get(0)).assoc(100);
((TransactionalRef<Integer>) copy.get(1)).assoc(1000);
ccollection.update(copy, false);
assertEquals("Updated reference", (Integer) 100, ((TransactionalRef<Integer>) ccollection.get(0)).deref());
assertEquals("Updated reference", (Integer) 1000, ((TransactionalRef<Integer>) ccollection.get(1)).deref());
}
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalQueueTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link TransactionalQueue} unit tests.
*
* @author Ivan Koblik
*/
public class TransactionalQueueTest {
@Before
public void setUp() throws Exception {
}
// ==================== Constructor tests ====================
@Test
public void testTransactionalQueue() {
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>();
assertTrue("Queue is empty", queue.isEmpty());
}
@Test
public void testTransactionalQueueCollectionOfE_copiesCollection() {
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalQueueTest.java
import static cern.entwined.test.TestUtils.newList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link TransactionalQueue} unit tests.
*
* @author Ivan Koblik
*/
public class TransactionalQueueTest {
@Before
public void setUp() throws Exception {
}
// ==================== Constructor tests ====================
@Test
public void testTransactionalQueue() {
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>();
assertTrue("Queue is empty", queue.isEmpty());
}
@Test
public void testTransactionalQueueCollectionOfE_copiesCollection() {
| List<Integer> originalList = newList(1, 2, 3);
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalQueueTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| public void testDirtyCopy_sourceDataCopied() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
List<Integer> drainedTo = new ArrayList<Integer>();
queue.dirtyCopy().drainTo(drainedTo);
assertEquals("Original list and drained from the copy", originalList, drainedTo);
}
@Test
public void testDirtyCopy_sourceDataReferentiallyEqual() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
TransactionalQueue<Integer> copy = queue.dirtyCopy();
queue.update(copy, false);
}
@Test
public void testDirtyCopy_localModificationsAndDelitionsCopied() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
queue.poll();
queue.offer(4);
TransactionalQueue<Integer> copy = queue.dirtyCopy();
List<Integer> drainedTo = new ArrayList<Integer>();
copy.drainTo(drainedTo);
assertEquals("Modified queue", newList(2, 3, 4), drainedTo);
}
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalQueueTest.java
import static cern.entwined.test.TestUtils.newList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
public void testDirtyCopy_sourceDataCopied() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
List<Integer> drainedTo = new ArrayList<Integer>();
queue.dirtyCopy().drainTo(drainedTo);
assertEquals("Original list and drained from the copy", originalList, drainedTo);
}
@Test
public void testDirtyCopy_sourceDataReferentiallyEqual() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
TransactionalQueue<Integer> copy = queue.dirtyCopy();
queue.update(copy, false);
}
@Test
public void testDirtyCopy_localModificationsAndDelitionsCopied() {
List<Integer> originalList = newList(1, 2, 3);
TransactionalQueue<Integer> queue = new TransactionalQueue<Integer>(originalList);
queue.poll();
queue.offer(4);
TransactionalQueue<Integer> copy = queue.dirtyCopy();
List<Integer> drainedTo = new ArrayList<Integer>();
copy.drainTo(drainedTo);
assertEquals("Modified queue", newList(2, 3, 4), drainedTo);
}
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMultimapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link TransactionalMultimap} unit tests.
*
* @author Ivan Koblik
*/
public class TransactionalMultimapTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#TransactionalMultimap()}.
*/
@Test
public void testTransactionalMultimap() {
new TransactionalMultimap<Integer, Long>();
}
// ==================== Local operation tests ====================
/**
* Test method for {@link cern.entwined.TransactionalMultimap#get(java.lang.Object)}.
*/
@Test
public void testGet_onEmptyMap() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
assertEquals("Non existing pair with key=null", ImmutableSet.<Long> of(), map.get(null));
assertEquals("Non existing pair with key=1", ImmutableSet.<Long> of(), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#get(java.lang.Object)}.
*/
@Test
public void testGet_onExistingPair() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMultimapTest.java
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link TransactionalMultimap} unit tests.
*
* @author Ivan Koblik
*/
public class TransactionalMultimapTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#TransactionalMultimap()}.
*/
@Test
public void testTransactionalMultimap() {
new TransactionalMultimap<Integer, Long>();
}
// ==================== Local operation tests ====================
/**
* Test method for {@link cern.entwined.TransactionalMultimap#get(java.lang.Object)}.
*/
@Test
public void testGet_onEmptyMap() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
assertEquals("Non existing pair with key=null", ImmutableSet.<Long> of(), map.get(null));
assertEquals("Non existing pair with key=1", ImmutableSet.<Long> of(), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#get(java.lang.Object)}.
*/
@Test
public void testGet_onExistingPair() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
| Set<Long> expected = newSet(1l, 2l, 3l);
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMultimapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
| @Test
public void testClear() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
Set<Long> source = newSet(1l, 2l);
map.putAll(1, source);
map.clear();
assertEquals("Empty set in place of removed pair", ImmutableSet.<Long> of(), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#containsKey(java.lang.Object)}.
*/
@Test
public void testContainsKey() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
Set<Long> source = newSet(1l, 2l);
map.putAll(1, source);
assertFalse("Non existing pair for key=null", map.containsKey(null));
assertFalse("Non existing pair for key=0", map.containsKey(0));
assertTrue("Existing pair", map.containsKey(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#putAll(java.util.Map)}.
*/
@Test
public void testPutAllMapOfQextendsKQextendsSetOfV_storesAllPairs_extendsExisitingPairs() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMultimapTest.java
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
@Test
public void testClear() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
Set<Long> source = newSet(1l, 2l);
map.putAll(1, source);
map.clear();
assertEquals("Empty set in place of removed pair", ImmutableSet.<Long> of(), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#containsKey(java.lang.Object)}.
*/
@Test
public void testContainsKey() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
Set<Long> source = newSet(1l, 2l);
map.putAll(1, source);
assertFalse("Non existing pair for key=null", map.containsKey(null));
assertFalse("Non existing pair for key=0", map.containsKey(0));
assertTrue("Existing pair", map.containsKey(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#putAll(java.util.Map)}.
*/
@Test
public void testPutAllMapOfQextendsKQextendsSetOfV_storesAllPairs_extendsExisitingPairs() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
| Map<Integer, Set<Long>> source = newMap(//
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMultimapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
| committed.putAll(2, newSet(2l, 3l));
TransactionalMultimap<Integer, Long> dirtyCopy = committed.dirtyCopy();
assertEquals("Dirty copy map state", newSet(1l, 2l), dirtyCopy.get(1));
assertEquals("Dirty copy map state", newSet(2l, 3l), dirtyCopy.get(2));
committed.clear();
assertEquals("Change to the source doesn't affect the dirty copy", newSet(1l, 2l), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#update(cern.entwined.TransactionalMultimap, boolean)}.
*/
@Test
public void testUpdateTransactionalMultimapOfKVBoolean() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
map.putAll(1, newSet(1l, 2l));
TransactionalMultimap<Integer, Long> dirtyCopy = map.dirtyCopy();
dirtyCopy.putAll(2, newSet(2l, 3l));
dirtyCopy.put(1, 3l);
map.update(dirtyCopy, false);
assertEquals("Updated source", newSet(1l, 2l, 3l), map.get(1));
assertEquals("Updated source", newSet(2l, 3l), map.get(2));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#update(cern.entwined.TransactionalMultimap, boolean)}.
*/
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMultimapTest.java
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableSet;
committed.putAll(2, newSet(2l, 3l));
TransactionalMultimap<Integer, Long> dirtyCopy = committed.dirtyCopy();
assertEquals("Dirty copy map state", newSet(1l, 2l), dirtyCopy.get(1));
assertEquals("Dirty copy map state", newSet(2l, 3l), dirtyCopy.get(2));
committed.clear();
assertEquals("Change to the source doesn't affect the dirty copy", newSet(1l, 2l), map.get(1));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#update(cern.entwined.TransactionalMultimap, boolean)}.
*/
@Test
public void testUpdateTransactionalMultimapOfKVBoolean() {
TransactionalMultimap<Integer, Long> map = new TransactionalMultimap<Integer, Long>();
map.putAll(1, newSet(1l, 2l));
TransactionalMultimap<Integer, Long> dirtyCopy = map.dirtyCopy();
dirtyCopy.putAll(2, newSet(2l, 3l));
dirtyCopy.put(1, 3l);
map.update(dirtyCopy, false);
assertEquals("Updated source", newSet(1l, 2l, 3l), map.get(1));
assertEquals("Updated source", newSet(2l, 3l), map.get(2));
}
/**
* Test method for {@link cern.entwined.TransactionalMultimap#update(cern.entwined.TransactionalMultimap, boolean)}.
*/
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/STMUtilsTest.java | // Path: src/main/java/cern/entwined/exception/MemoryException.java
// public class MemoryException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public MemoryException() {
// super();
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public MemoryException(String message) {
// super(message);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public MemoryException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public MemoryException(Throwable cause) {
// super(cause);
// this.setUnwrap(false);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.MemoryException;
| memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot snapshot) {
assertTrue("Refrence to True", STMUtils.dereference(ref));
return true;
}
});
}
@Test
public void testInTransaction_notInTransaction() {
assertFalse("Not in a transaction", STMUtils.inTransaction(memory));
}
@Test
public void testInTransaction_inTransaction() {
memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot data) {
assertTrue("In transaction", STMUtils.inTransaction(memory));
return false;
}
});
}
@Test(expected = IllegalArgumentException.class)
public void testInTransaction_fail_nullMemory() {
STMUtils.inTransaction((Memory<?>) null);
}
| // Path: src/main/java/cern/entwined/exception/MemoryException.java
// public class MemoryException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public MemoryException() {
// super();
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public MemoryException(String message) {
// super(message);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public MemoryException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public MemoryException(Throwable cause) {
// super(cause);
// this.setUnwrap(false);
// }
//
// }
// Path: src/test/java/cern/entwined/STMUtilsTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.MemoryException;
memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot snapshot) {
assertTrue("Refrence to True", STMUtils.dereference(ref));
return true;
}
});
}
@Test
public void testInTransaction_notInTransaction() {
assertFalse("Not in a transaction", STMUtils.inTransaction(memory));
}
@Test
public void testInTransaction_inTransaction() {
memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot data) {
assertTrue("In transaction", STMUtils.inTransaction(memory));
return false;
}
});
}
@Test(expected = IllegalArgumentException.class)
public void testInTransaction_fail_nullMemory() {
STMUtils.inTransaction((Memory<?>) null);
}
| @Test(expected = MemoryException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/BaseSnapshotTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link BaseSnapshot} unit tests.
*
* @author Ivan Koblik
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseSnapshotTest extends SnapshotAbstractTest {
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/BaseSnapshotTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link BaseSnapshot} unit tests.
*
* @author Ivan Koblik
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseSnapshotTest extends SnapshotAbstractTest {
| Map<Long, Object> testMap = Collections.unmodifiableMap(newMap(newList(1L, 2L), (List) newList(10L, 20L)));
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/BaseSnapshotTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link BaseSnapshot} unit tests.
*
* @author Ivan Koblik
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseSnapshotTest extends SnapshotAbstractTest {
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/BaseSnapshotTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* {@link BaseSnapshot} unit tests.
*
* @author Ivan Koblik
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseSnapshotTest extends SnapshotAbstractTest {
| Map<Long, Object> testMap = Collections.unmodifiableMap(newMap(newList(1L, 2L), (List) newList(10L, 20L)));
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/BaseSnapshotTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
| * Creates a global state that has 1 set to ref1 in client snapshot and no elements in global map.
*
* @param clientSnapshot True if conflict need to be simulated in the client snapshot, false if in the global map.
* @return The conflicting global state.
*/
private BaseSnapshot<TestSnapshot> simulateConflict(boolean clientSnapshot) {
TestSnapshot conflictingSnapshot = new TestSnapshot(1, 0, Collections.EMPTY_MAP);
TransactionalMap<Long, Object> conflictingMap = new TransactionalMap<Long, Object>();
if (clientSnapshot) {
return new BaseSnapshot<TestSnapshot>(0l, conflictingSnapshot, transactionalMap.cleanCopy());
} else {
return new BaseSnapshot<TestSnapshot>(0l, testSnapshot.cleanCopy(), conflictingMap);
}
}
@Test
public void testUpdateBaseSnapshotOfVBooleanTrue_updatesOnlyLogs() {
prepareSUTForUpdateTest(true);
assertEquals("Old value preserved", (Integer) 10, baseSnapshot.getClientData().getRef1().deref());
assertEquals("Old value preserved", 100L, baseSnapshot.getGlobalMap().get(1L));
}
@Test
public void testUpdateBaseSnapshotOfVBooleanFalse_updatesValues() {
prepareSUTForUpdateTest(false);
assertEquals("New value", (Integer) 11, baseSnapshot.getClientData().getRef1().deref());
assertEquals("New value", 101L, baseSnapshot.getGlobalMap().get(1L));
}
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/BaseSnapshotTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
* Creates a global state that has 1 set to ref1 in client snapshot and no elements in global map.
*
* @param clientSnapshot True if conflict need to be simulated in the client snapshot, false if in the global map.
* @return The conflicting global state.
*/
private BaseSnapshot<TestSnapshot> simulateConflict(boolean clientSnapshot) {
TestSnapshot conflictingSnapshot = new TestSnapshot(1, 0, Collections.EMPTY_MAP);
TransactionalMap<Long, Object> conflictingMap = new TransactionalMap<Long, Object>();
if (clientSnapshot) {
return new BaseSnapshot<TestSnapshot>(0l, conflictingSnapshot, transactionalMap.cleanCopy());
} else {
return new BaseSnapshot<TestSnapshot>(0l, testSnapshot.cleanCopy(), conflictingMap);
}
}
@Test
public void testUpdateBaseSnapshotOfVBooleanTrue_updatesOnlyLogs() {
prepareSUTForUpdateTest(true);
assertEquals("Old value preserved", (Integer) 10, baseSnapshot.getClientData().getRef1().deref());
assertEquals("Old value preserved", 100L, baseSnapshot.getGlobalMap().get(1L));
}
@Test
public void testUpdateBaseSnapshotOfVBooleanFalse_updatesValues() {
prepareSUTForUpdateTest(false);
assertEquals("New value", (Integer) 11, baseSnapshot.getClientData().getRef1().deref());
assertEquals("New value", 101L, baseSnapshot.getGlobalMap().get(1L));
}
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/main/java/cern/entwined/TransactionalRef.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import cern.entwined.exception.ConflictException;
| /*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.SemiPersistent#update(java.lang.Object, boolean)
*/
@Override
protected void update(TransactionalRef<T> changes, boolean onlyReadLogs) {
Utils.checkNull("Local changes", changes);
if (changes.sourceValue != this.sourceValue) {
throw new IllegalArgumentException("Updates are only possible for references with the same source");
}
this.accessed = changes.accessed;
if (!onlyReadLogs) {
this.updated = changes.updated;
this.value = changes.value;
}
}
/*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.ConflictAware#commit(java.lang.Object)
*/
@Override
public TransactionalRef<T> commit(TransactionalRef<T> globalState) {
Utils.checkNull("Transactional reference", globalState);
if (globalState.accessed) {
throw new IllegalArgumentException("Global state must be commited before calling this method");
}
if (this.accessed && globalState.sourceValue != this.sourceValue) {
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/cern/entwined/TransactionalRef.java
import cern.entwined.exception.ConflictException;
/*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.SemiPersistent#update(java.lang.Object, boolean)
*/
@Override
protected void update(TransactionalRef<T> changes, boolean onlyReadLogs) {
Utils.checkNull("Local changes", changes);
if (changes.sourceValue != this.sourceValue) {
throw new IllegalArgumentException("Updates are only possible for references with the same source");
}
this.accessed = changes.accessed;
if (!onlyReadLogs) {
this.updated = changes.updated;
this.value = changes.value;
}
}
/*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.ConflictAware#commit(java.lang.Object)
*/
@Override
public TransactionalRef<T> commit(TransactionalRef<T> globalState) {
Utils.checkNull("Transactional reference", globalState);
if (globalState.accessed) {
throw new IllegalArgumentException("Global state must be commited before calling this method");
}
if (this.accessed && globalState.sourceValue != this.sourceValue) {
| throw new ConflictException("Conflicting update detected");
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/GlobalReferenceTest.java | // Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.NoTransactionException;
| public boolean run(TestSnapshot snapshot) {
globalLong.set(1l);
return true;
}
});
final int[] counter = { 0 };
memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot snapshot) {
if (counter[0]++ == 1) {
return true;
}
conflictingThread.start();
MemoryTest.joinThread(conflictingThread);
globalLong.get();
return true;
}
@Override
public void committed(TestSnapshot snapshot) {
assertEquals("Newly set value", (Long) 1l, globalLong.get());
}
});
assertEquals("Due to conflict transaction must have been re-run", 2, counter[0]);
}
| // Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/test/java/cern/entwined/GlobalReferenceTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cern.entwined.exception.NoTransactionException;
public boolean run(TestSnapshot snapshot) {
globalLong.set(1l);
return true;
}
});
final int[] counter = { 0 };
memory.runTransaction(new TransactionAdapter<TestSnapshot>() {
@Override
public boolean run(TestSnapshot snapshot) {
if (counter[0]++ == 1) {
return true;
}
conflictingThread.start();
MemoryTest.joinThread(conflictingThread);
globalLong.get();
return true;
}
@Override
public void committed(TestSnapshot snapshot) {
assertEquals("Newly set value", (Long) 1l, globalLong.get());
}
});
assertEquals("Due to conflict transaction must have been re-run", 2, counter[0]);
}
| @Test(expected = NoTransactionException.class)
|
CERN-BE/Entwined-STM | src/main/java/cern/entwined/TransactionalMap.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
| throw new IllegalArgumentException("Updates are only possible for collections with the same source");
}
if (changes.globallyAccessed) {
markGloballyAccessed();
}
this.markAccessed(changes.accessed);
if (!onlyReadLogs) {
this.pendingModifications.clear();
this.pendingModifications.putAll(changes.pendingModifications);
this.pendingDeletions.clear();
this.pendingDeletions.addAll(changes.pendingDeletions);
}
}
/*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.ConflictAware#commit(java.lang.Object)
*/
@Override
public TransactionalMap<K, V> commit(TransactionalMap<K, V> globalState) {
Utils.checkNull("Global state", globalState);
if (!globalState.pendingDeletions.isEmpty() || !globalState.pendingModifications.isEmpty()
|| !globalState.accessed.isEmpty() || globalState.globallyAccessed) {
throw new IllegalArgumentException("Global state map must be commited before calling this method");
}
// Checking for conflicts
if (this.globallyAccessed) {
if (!globalState.sourceMap.equals(this.sourceMap)) {
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/cern/entwined/TransactionalMap.java
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
throw new IllegalArgumentException("Updates are only possible for collections with the same source");
}
if (changes.globallyAccessed) {
markGloballyAccessed();
}
this.markAccessed(changes.accessed);
if (!onlyReadLogs) {
this.pendingModifications.clear();
this.pendingModifications.putAll(changes.pendingModifications);
this.pendingDeletions.clear();
this.pendingDeletions.addAll(changes.pendingDeletions);
}
}
/*
* (non-Javadoc)
*
* @see cern.oasis.server.stm.ConflictAware#commit(java.lang.Object)
*/
@Override
public TransactionalMap<K, V> commit(TransactionalMap<K, V> globalState) {
Utils.checkNull("Global state", globalState);
if (!globalState.pendingDeletions.isEmpty() || !globalState.pendingModifications.isEmpty()
|| !globalState.accessed.isEmpty() || globalState.globallyAccessed) {
throw new IllegalArgumentException("Global state map must be commited before calling this method");
}
// Checking for conflicts
if (this.globallyAccessed) {
if (!globalState.sourceMap.equals(this.sourceMap)) {
| throw new ConflictException("All the items of this map have been accessed "
|
CERN-BE/Entwined-STM | src/main/java/cern/entwined/Memory.java | // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/cern/entwined/exception/InvocationException.java
// public class InvocationException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public InvocationException() {
// super();
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public InvocationException(String message) {
// super(message);
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public InvocationException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public InvocationException(Throwable cause) {
// super(cause);
// this.setUnwrap(true);
// }
// }
//
// Path: src/main/java/cern/entwined/exception/MemoryException.java
// public class MemoryException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public MemoryException() {
// super();
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public MemoryException(String message) {
// super(message);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public MemoryException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public MemoryException(Throwable cause) {
// super(cause);
// this.setUnwrap(false);
// }
//
// }
//
// Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
| import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import cern.entwined.exception.ConflictException;
import cern.entwined.exception.InvocationException;
import cern.entwined.exception.MemoryException;
import cern.entwined.exception.NoTransactionException;
| this.postorder(transactionNode, newGlobalState);
} finally {
this.commitQueue.poll();
isCommitting.set(false);
notifyNextInQueue();
}
break;
}
return true;
}
/**
* Invokes after-transactional callback methods in commit order.
*
* @param node The callbacks root node.
* @param snapshot The commit time snapshot.
*/
private void postorder(Node<Transaction<T>> node, BaseSnapshot<T> snapshot) {
for (Node<Transaction<T>> child : node.getChildren()) {
this.postorder(child, snapshot);
}
// It is crucial to copy the global state or transactional memory will get broken.
LinkedList<BaseSnapshot<T>> stack = getSnapshotStack();
try {
BaseSnapshot<T> cleanCopy = snapshot.cleanCopy();
stack.push(cleanCopy);
node.getValue().committed(cleanCopy.getClientData());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
| // Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/cern/entwined/exception/InvocationException.java
// public class InvocationException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public InvocationException() {
// super();
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public InvocationException(String message) {
// super(message);
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public InvocationException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(true);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public InvocationException(Throwable cause) {
// super(cause);
// this.setUnwrap(true);
// }
// }
//
// Path: src/main/java/cern/entwined/exception/MemoryException.java
// public class MemoryException extends UnwrappableException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444927L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public MemoryException() {
// super();
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public MemoryException(String message) {
// super(message);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public MemoryException(String message, Throwable cause) {
// super(message, cause);
// this.setUnwrap(false);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public MemoryException(Throwable cause) {
// super(cause);
// this.setUnwrap(false);
// }
//
// }
//
// Path: src/main/java/cern/entwined/exception/NoTransactionException.java
// public class NoTransactionException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = 1232134715126838087L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public NoTransactionException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public NoTransactionException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public NoTransactionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public NoTransactionException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/cern/entwined/Memory.java
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import cern.entwined.exception.ConflictException;
import cern.entwined.exception.InvocationException;
import cern.entwined.exception.MemoryException;
import cern.entwined.exception.NoTransactionException;
this.postorder(transactionNode, newGlobalState);
} finally {
this.commitQueue.poll();
isCommitting.set(false);
notifyNextInQueue();
}
break;
}
return true;
}
/**
* Invokes after-transactional callback methods in commit order.
*
* @param node The callbacks root node.
* @param snapshot The commit time snapshot.
*/
private void postorder(Node<Transaction<T>> node, BaseSnapshot<T> snapshot) {
for (Node<Transaction<T>> child : node.getChildren()) {
this.postorder(child, snapshot);
}
// It is crucial to copy the global state or transactional memory will get broken.
LinkedList<BaseSnapshot<T>> stack = getSnapshotStack();
try {
BaseSnapshot<T> cleanCopy = snapshot.cleanCopy();
stack.push(cleanCopy);
node.getValue().committed(cleanCopy.getClientData());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
| throw new InvocationException("Exception in committed block", e);
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* Unit test for {@link TransactionalMap}.
*
* @author Ivan Koblik
*/
public class TransactionalMapTest {
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap()}.
*/
@Test
public void testTransactionalMap() {
new TransactionalMap<Integer, Integer>();
}
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap(java.util.Map)}.
*/
@Test
public void testTransactionalMapMapOfKV_checkPropertInit() {
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMapTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* Unit test for {@link TransactionalMap}.
*
* @author Ivan Koblik
*/
public class TransactionalMapTest {
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap()}.
*/
@Test
public void testTransactionalMap() {
new TransactionalMap<Integer, Integer>();
}
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap(java.util.Map)}.
*/
@Test
public void testTransactionalMapMapOfKV_checkPropertInit() {
| Map<Integer, Integer> sourceMap = newMap(newList(1, 2, 3, 4), newList(5, 6, 7, 8));
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
| /*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* Unit test for {@link TransactionalMap}.
*
* @author Ivan Koblik
*/
public class TransactionalMapTest {
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap()}.
*/
@Test
public void testTransactionalMap() {
new TransactionalMap<Integer, Integer>();
}
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap(java.util.Map)}.
*/
@Test
public void testTransactionalMapMapOfKV_checkPropertInit() {
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMapTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
/*
* Entwined STM
*
* (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.entwined;
/**
* Unit test for {@link TransactionalMap}.
*
* @author Ivan Koblik
*/
public class TransactionalMapTest {
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap()}.
*/
@Test
public void testTransactionalMap() {
new TransactionalMap<Integer, Integer>();
}
/**
* Test method for {@link cern.entwined.TransactionalMap#TransactionalMap(java.util.Map)}.
*/
@Test
public void testTransactionalMapMapOfKV_checkPropertInit() {
| Map<Integer, Integer> sourceMap = newMap(newList(1, 2, 3, 4), newList(5, 6, 7, 8));
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
| // Removed old entries
localMap.remove(i);
assertEquals("Size", i, localMap.size());
assertFalse("empty?", localMap.isEmpty());
}
// Removed new entry
localMap.remove(5);
assertEquals("Removed last key", 0, localMap.size());
assertTrue("empty?", localMap.isEmpty());
// Removed non-existing entry
localMap.remove(10);
assertEquals("After remove for unknown key", 0, localMap.size());
assertTrue("empty?", localMap.isEmpty());
// Added new entry to empty map
localMap.put(6, 7);
assertEquals("Added one key", 1, localMap.size());
assertFalse("empty?", localMap.isEmpty());
}
// ==================== Access logging tests. ====================
TransactionalMap<Integer, Integer> localMap;
TransactionalMap<Integer, Integer> globalState;
/**
* Test method for {@link cern.entwined.TransactionalMap#clear()}.
*/
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMapTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
// Removed old entries
localMap.remove(i);
assertEquals("Size", i, localMap.size());
assertFalse("empty?", localMap.isEmpty());
}
// Removed new entry
localMap.remove(5);
assertEquals("Removed last key", 0, localMap.size());
assertTrue("empty?", localMap.isEmpty());
// Removed non-existing entry
localMap.remove(10);
assertEquals("After remove for unknown key", 0, localMap.size());
assertTrue("empty?", localMap.isEmpty());
// Added new entry to empty map
localMap.put(6, 7);
assertEquals("Added one key", 1, localMap.size());
assertFalse("empty?", localMap.isEmpty());
}
// ==================== Access logging tests. ====================
TransactionalMap<Integer, Integer> localMap;
TransactionalMap<Integer, Integer> globalState;
/**
* Test method for {@link cern.entwined.TransactionalMap#clear()}.
*/
| @Test(expected = ConflictException.class)
|
CERN-BE/Entwined-STM | src/test/java/cern/entwined/TransactionalMapTest.java | // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
| import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
| int newValue = 10;
Map<Integer, Integer> modifiedSourceMap = newMap(newList(1, 2, 3, 4), newList(5, 6, newValue, 8));
globalState = new TransactionalMap<Integer, Integer>(modifiedSourceMap);
localMap.commit(globalState);
}
/**
* Test method for {@link cern.entwined.TransactionalMap#commit(cern.entwined.TransactionalMap)}.
*/
@Test(expected = ConflictException.class)
public void testCommit_GlobalUpdatedTuple_Conflicting() {
final int conflickKey = 2;
createAndQueryMap(conflickKey);
final int newValue = 10;
Map<Integer, Integer> modifiedSourceMap = newMap(newList(1, conflickKey, 3, 4), newList(5, newValue, 7, 8));
globalState = new TransactionalMap<Integer, Integer>(modifiedSourceMap);
localMap.commit(globalState);
}
/**
* Test method for {@link cern.entwined.TransactionalMap#commit(cern.entwined.TransactionalMap)}.
*/
@Test
public void testCommit_GloballyAccessed_NonConflicting() {
defaultFixture();
localMap.size();
localMap.remove(1);
| // Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> List<T> newList(T... values) {
// if (null == values) {
// return new ArrayList<T>();
// } else {
// return new ArrayList<T>(Arrays.asList(values));
// }
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <K, V> Map<K, V> newMap(List<K> keys, List<V> values) {
// Assert.assertEquals("Number of keys and values", keys.size(), values.size());
//
// Map<K, V> resultMap = new LinkedHashMap<K, V>(keys.size());
// for (int i = 0; i < keys.size(); i++) {
// resultMap.put(keys.get(i), values.get(i));
// }
// return resultMap;
// }
//
// Path: src/test/java/cern/entwined/test/TestUtils.java
// public static <T> Set<T> newSet(T... values) {
// return new HashSet<T>(Arrays.asList(values));
// }
//
// Path: src/main/java/cern/entwined/exception/ConflictException.java
// public class ConflictException extends MemoryException {
//
// /**
// * Exception version id.
// */
// private static final long serialVersionUID = -4855258409489444926L;
//
// /**
// * @see UnwrappableException#OasisUnavailableException()
// */
// public ConflictException() {
// super();
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String)
// */
// public ConflictException(String message) {
// super(message);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(String, Throwable)
// */
// public ConflictException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * @see UnwrappableException#OasisUnavailableException(Throwable)
// */
// public ConflictException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/test/java/cern/entwined/TransactionalMapTest.java
import static cern.entwined.test.TestUtils.newList;
import static cern.entwined.test.TestUtils.newMap;
import static cern.entwined.test.TestUtils.newSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import cern.entwined.exception.ConflictException;
import com.google.common.collect.ImmutableMap;
int newValue = 10;
Map<Integer, Integer> modifiedSourceMap = newMap(newList(1, 2, 3, 4), newList(5, 6, newValue, 8));
globalState = new TransactionalMap<Integer, Integer>(modifiedSourceMap);
localMap.commit(globalState);
}
/**
* Test method for {@link cern.entwined.TransactionalMap#commit(cern.entwined.TransactionalMap)}.
*/
@Test(expected = ConflictException.class)
public void testCommit_GlobalUpdatedTuple_Conflicting() {
final int conflickKey = 2;
createAndQueryMap(conflickKey);
final int newValue = 10;
Map<Integer, Integer> modifiedSourceMap = newMap(newList(1, conflickKey, 3, 4), newList(5, newValue, 7, 8));
globalState = new TransactionalMap<Integer, Integer>(modifiedSourceMap);
localMap.commit(globalState);
}
/**
* Test method for {@link cern.entwined.TransactionalMap#commit(cern.entwined.TransactionalMap)}.
*/
@Test
public void testCommit_GloballyAccessed_NonConflicting() {
defaultFixture();
localMap.size();
localMap.remove(1);
| assertEquals(newSet(2, 3, 4), localMap.commit(globalState).keySet());
|
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/AboutAppActivity.java | // Path: src/net/zhuoweizhang/pocketinveditor/util/ROFLCopter.java
// public final class ROFLCopter {
//
// public static final String[] r = { " ROFL|LFOR\n" +
// " |\n" +
// "LOL-------------------\n" +
// " \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " #\n" +
// "L |\n" +
// " O -------------------\n" +
// " L\\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " LFOR|ROFL\n" +
// " L |\n" +
// " O -------------------\n" +
// " L \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " @\n" +
// " L |\n" +
// " O -------------------\n" +
// "L \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\"};
// }
| import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import net.zhuoweizhang.pocketinveditor.util.ROFLCopter; |
public void startRofl() {
roflField.setVisibility(View.VISIBLE);
flipRunning = true;
flipActivated = true;
new Thread(flipTask).start();
}
public boolean onLongClick(View v) {
if (v == appNameText && !flipRunning) {
startRofl();
return true;
}
return false;
}
public void onClick(View v) {
if (v == gotoForumsButton) {
openForumsPage();
}
}
protected void openForumsPage() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(FORUMS_PAGE_URL));
startActivity(intent);
}
public void flipFrame() { | // Path: src/net/zhuoweizhang/pocketinveditor/util/ROFLCopter.java
// public final class ROFLCopter {
//
// public static final String[] r = { " ROFL|LFOR\n" +
// " |\n" +
// "LOL-------------------\n" +
// " \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " #\n" +
// "L |\n" +
// " O -------------------\n" +
// " L\\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " LFOR|ROFL\n" +
// " L |\n" +
// " O -------------------\n" +
// " L \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\",
//
// " @\n" +
// " L |\n" +
// " O -------------------\n" +
// "L \\________ LMAO \\\n" +
// " \\ /\n" +
// " \\_______/\n" +
// " / \\"};
// }
// Path: src/net/zhuoweizhang/pocketinveditor/AboutAppActivity.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import net.zhuoweizhang.pocketinveditor.util.ROFLCopter;
public void startRofl() {
roflField.setVisibility(View.VISIBLE);
flipRunning = true;
flipActivated = true;
new Thread(flipTask).start();
}
public boolean onLongClick(View v) {
if (v == appNameText && !flipRunning) {
startRofl();
return true;
}
return false;
}
public void onClick(View v) {
if (v == gotoForumsButton) {
openForumsPage();
}
}
protected void openForumsPage() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(FORUMS_PAGE_URL));
startActivity(intent);
}
public void flipFrame() { | frame = (frame + 1) % ROFLCopter.r.length; |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/nbt/entity/PaintingEntityStore.java | // Path: src/net/zhuoweizhang/pocketinveditor/entity/Painting.java
// public class Painting extends Entity {
//
// private Vector3f blockCoordinates = new Vector3f(0f, 0f, 0f);
//
// private String artType = "Alban";
//
// private byte direction = 0;
//
// public String getArt() {
// return artType;
// }
//
// public void setArt(String art) {
// artType = art;
// }
//
// public Vector3f getBlockCoordinates() {
// return blockCoordinates;
// }
//
// public byte getDirection() {
// return direction;
// }
//
// public void setDirection(byte dir) {
// this.direction = dir;
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import java.util.List;
import org.spout.nbt.*;
import net.zhuoweizhang.pocketinveditor.entity.Painting;
import net.zhuoweizhang.pocketinveditor.util.Vector3f; | package net.zhuoweizhang.pocketinveditor.io.nbt.entity;
public class PaintingEntityStore<T extends Painting> extends EntityStore<T> {
@Override
@SuppressWarnings("unchecked")
public void loadTag(T entity, Tag tag) {
String name = tag.getName();
if (name.equals("Dir")) {
entity.setDirection(((ByteTag) tag).getValue());
} else if (name.equals("Motive")) {
entity.setArt(((StringTag) tag).getValue());
} else if (name.equals("TileX")) {
entity.getBlockCoordinates().setX(((IntTag) tag).getValue());
} else if (name.equals("TileY")) {
entity.getBlockCoordinates().setY(((IntTag) tag).getValue());
} else if (name.equals("TileZ")) {
entity.getBlockCoordinates().setZ(((IntTag) tag).getValue());
} else {
super.loadTag(entity, tag);
}
}
@Override
public List<Tag> save(T entity) {
List<Tag> tags = super.save(entity);
tags.add(new ByteTag("Dir", entity.getDirection()));
tags.add(new StringTag("Motive", entity.getArt())); | // Path: src/net/zhuoweizhang/pocketinveditor/entity/Painting.java
// public class Painting extends Entity {
//
// private Vector3f blockCoordinates = new Vector3f(0f, 0f, 0f);
//
// private String artType = "Alban";
//
// private byte direction = 0;
//
// public String getArt() {
// return artType;
// }
//
// public void setArt(String art) {
// artType = art;
// }
//
// public Vector3f getBlockCoordinates() {
// return blockCoordinates;
// }
//
// public byte getDirection() {
// return direction;
// }
//
// public void setDirection(byte dir) {
// this.direction = dir;
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/nbt/entity/PaintingEntityStore.java
import java.util.List;
import org.spout.nbt.*;
import net.zhuoweizhang.pocketinveditor.entity.Painting;
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
package net.zhuoweizhang.pocketinveditor.io.nbt.entity;
public class PaintingEntityStore<T extends Painting> extends EntityStore<T> {
@Override
@SuppressWarnings("unchecked")
public void loadTag(T entity, Tag tag) {
String name = tag.getName();
if (name.equals("Dir")) {
entity.setDirection(((ByteTag) tag).getValue());
} else if (name.equals("Motive")) {
entity.setArt(((StringTag) tag).getValue());
} else if (name.equals("TileX")) {
entity.getBlockCoordinates().setX(((IntTag) tag).getValue());
} else if (name.equals("TileY")) {
entity.getBlockCoordinates().setY(((IntTag) tag).getValue());
} else if (name.equals("TileZ")) {
entity.getBlockCoordinates().setZ(((IntTag) tag).getValue());
} else {
super.loadTag(entity, tag);
}
}
@Override
public List<Tag> save(T entity) {
List<Tag> tags = super.save(entity);
tags.add(new ByteTag("Dir", entity.getDirection()));
tags.add(new StringTag("Motive", entity.getArt())); | Vector3f bc = entity.getBlockCoordinates(); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/geo/CuboidClipboard.java | // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import net.zhuoweizhang.pocketinveditor.util.Vector3f; | package net.zhuoweizhang.pocketinveditor.geo;
public class CuboidClipboard implements AreaBlockAccess, SizeLimitedArea {
public static final int AIR = 0;
protected int width, height, length;
public byte[] blocks, metaData;
| // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/geo/CuboidClipboard.java
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
package net.zhuoweizhang.pocketinveditor.geo;
public class CuboidClipboard implements AreaBlockAccess, SizeLimitedArea {
public static final int AIR = 0;
protected int width, height, length;
public byte[] blocks, metaData;
| public CuboidClipboard(Vector3f size, byte[] blocks, byte[] data) { |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/nbt/schematic/SchematicIO.java | // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import java.io.*;
import java.util.*;
import org.spout.nbt.*;
import org.spout.nbt.stream.*;
import net.zhuoweizhang.pocketinveditor.geo.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f; | stream.close();
int width = 0, height = 0, length = 0;
String materials = null;
byte[] blocks = null;
byte[] data = null;
List<Tag> tags = mainTag.getValue();
for (Tag tag: tags) {
String tagName = tag.getName();
if (tagName.equals("Width")) {
width = ((ShortTag) tag).getValue();
} else if (tagName.equals("Height")) {
height = ((ShortTag) tag).getValue();
} else if (tagName.equals("Length")) {
length = ((ShortTag) tag).getValue();
} else if (tagName.equals("Materials")) {
materials = ((StringTag) tag).getValue();
} else if (tagName.equals("Blocks")) {
blocks = ((ByteArrayTag) tag).getValue();
} else if (tagName.equals("Data")) {
data = ((ByteArrayTag) tag).getValue();
} else if (tagName.equals("Entities")) {
//Do nothing
} else if (tagName.equals("TileEntities")) {
//Do nothing
} else {
System.err.println("WTF: invalid tag name: " + tagName);
}
} | // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/nbt/schematic/SchematicIO.java
import java.io.*;
import java.util.*;
import org.spout.nbt.*;
import org.spout.nbt.stream.*;
import net.zhuoweizhang.pocketinveditor.geo.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
stream.close();
int width = 0, height = 0, length = 0;
String materials = null;
byte[] blocks = null;
byte[] data = null;
List<Tag> tags = mainTag.getValue();
for (Tag tag: tags) {
String tagName = tag.getName();
if (tagName.equals("Width")) {
width = ((ShortTag) tag).getValue();
} else if (tagName.equals("Height")) {
height = ((ShortTag) tag).getValue();
} else if (tagName.equals("Length")) {
length = ((ShortTag) tag).getValue();
} else if (tagName.equals("Materials")) {
materials = ((StringTag) tag).getValue();
} else if (tagName.equals("Blocks")) {
blocks = ((ByteArrayTag) tag).getValue();
} else if (tagName.equals("Data")) {
data = ((ByteArrayTag) tag).getValue();
} else if (tagName.equals("Entities")) {
//Do nothing
} else if (tagName.equals("TileEntities")) {
//Do nothing
} else {
System.err.println("WTF: invalid tag name: " + tagName);
}
} | return new CuboidClipboard(new Vector3f(width, height, length), blocks, data); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/EntitiesInfoActivity.java | // Path: src/net/zhuoweizhang/pocketinveditor/io/EntityDataConverter.java
// public final class EntityDataConverter {
// public static final byte[] header = {0x45, 0x4e, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00};
//
// public static class EntityData {
// public List<Entity> entities;
// public List<TileEntity> tileEntities;
// public EntityData(List<Entity> entities, List<TileEntity> tileEntities) {
// this.entities = entities;
// this.tileEntities = tileEntities;
// }
// }
//
// public static EntityData read(File file) throws IOException {
// FileInputStream fis = new FileInputStream(file);
// BufferedInputStream is = new BufferedInputStream(fis);
// is.skip(12);
// EntityData eDat = NBTConverter.readEntities((CompoundTag) new NBTInputStream(is, false, true).readTag());
// is.close();
// return eDat;
// }
//
// public static void write(List<Entity> entitiesList, List<TileEntity> tileEntitiesList, File file) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// new NBTOutputStream(bos, false, true).writeTag(NBTConverter.writeEntities(entitiesList, tileEntitiesList));
//
// FileOutputStream os = new FileOutputStream(file);
// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
//
// int length = bos.size();
// dos.write(header);
// dos.writeInt(Integer.reverseBytes(length));
// bos.writeTo(dos);
// dos.close();
// }
//
// public static void main(String[] args) throws Exception {
// EntityData entities = read(new File(args[0]));
// System.out.println(entities);
// write(entities.entities, entities.tileEntities, new File(args[1]));
// }
//
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.zhuoweizhang.pocketinveditor.entity.*;
import net.zhuoweizhang.pocketinveditor.io.EntityDataConverter;
import net.zhuoweizhang.pocketinveditor.tileentity.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f; | package net.zhuoweizhang.pocketinveditor;
public class EntitiesInfoActivity extends Activity implements View.OnClickListener, LevelDataLoadListener, EntityDataLoadListener {
private TextView entityCountText;
private List<Entity> entitiesList;
public static final int BABY_GROWTH_TICKS = -24000;
public static final int BREED_TICKS = 9999; //wait until release to find out actual value
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entities_info);
entityCountText = (TextView) findViewById(R.id.entities_main_count);
if (EditorActivity.level != null) {
onLevelDataLoad();
} else {
EditorActivity.loadLevelData(this, this, this.getIntent().getStringExtra("world"));
}
}
public void onLevelDataLoad() {
loadEntities();
}
protected void loadEntities() {
new Thread(new LoadEntitiesTask(this, this)).start();
}
| // Path: src/net/zhuoweizhang/pocketinveditor/io/EntityDataConverter.java
// public final class EntityDataConverter {
// public static final byte[] header = {0x45, 0x4e, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00};
//
// public static class EntityData {
// public List<Entity> entities;
// public List<TileEntity> tileEntities;
// public EntityData(List<Entity> entities, List<TileEntity> tileEntities) {
// this.entities = entities;
// this.tileEntities = tileEntities;
// }
// }
//
// public static EntityData read(File file) throws IOException {
// FileInputStream fis = new FileInputStream(file);
// BufferedInputStream is = new BufferedInputStream(fis);
// is.skip(12);
// EntityData eDat = NBTConverter.readEntities((CompoundTag) new NBTInputStream(is, false, true).readTag());
// is.close();
// return eDat;
// }
//
// public static void write(List<Entity> entitiesList, List<TileEntity> tileEntitiesList, File file) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// new NBTOutputStream(bos, false, true).writeTag(NBTConverter.writeEntities(entitiesList, tileEntitiesList));
//
// FileOutputStream os = new FileOutputStream(file);
// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
//
// int length = bos.size();
// dos.write(header);
// dos.writeInt(Integer.reverseBytes(length));
// bos.writeTo(dos);
// dos.close();
// }
//
// public static void main(String[] args) throws Exception {
// EntityData entities = read(new File(args[0]));
// System.out.println(entities);
// write(entities.entities, entities.tileEntities, new File(args[1]));
// }
//
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/EntitiesInfoActivity.java
import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.zhuoweizhang.pocketinveditor.entity.*;
import net.zhuoweizhang.pocketinveditor.io.EntityDataConverter;
import net.zhuoweizhang.pocketinveditor.tileentity.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
package net.zhuoweizhang.pocketinveditor;
public class EntitiesInfoActivity extends Activity implements View.OnClickListener, LevelDataLoadListener, EntityDataLoadListener {
private TextView entityCountText;
private List<Entity> entitiesList;
public static final int BABY_GROWTH_TICKS = -24000;
public static final int BREED_TICKS = 9999; //wait until release to find out actual value
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entities_info);
entityCountText = (TextView) findViewById(R.id.entities_main_count);
if (EditorActivity.level != null) {
onLevelDataLoad();
} else {
EditorActivity.loadLevelData(this, this, this.getIntent().getStringExtra("world"));
}
}
public void onLevelDataLoad() {
loadEntities();
}
protected void loadEntities() {
new Thread(new LoadEntitiesTask(this, this)).start();
}
| public void onEntitiesLoaded(EntityDataConverter.EntityData entitiesDat) { |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/EntitiesInfoActivity.java | // Path: src/net/zhuoweizhang/pocketinveditor/io/EntityDataConverter.java
// public final class EntityDataConverter {
// public static final byte[] header = {0x45, 0x4e, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00};
//
// public static class EntityData {
// public List<Entity> entities;
// public List<TileEntity> tileEntities;
// public EntityData(List<Entity> entities, List<TileEntity> tileEntities) {
// this.entities = entities;
// this.tileEntities = tileEntities;
// }
// }
//
// public static EntityData read(File file) throws IOException {
// FileInputStream fis = new FileInputStream(file);
// BufferedInputStream is = new BufferedInputStream(fis);
// is.skip(12);
// EntityData eDat = NBTConverter.readEntities((CompoundTag) new NBTInputStream(is, false, true).readTag());
// is.close();
// return eDat;
// }
//
// public static void write(List<Entity> entitiesList, List<TileEntity> tileEntitiesList, File file) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// new NBTOutputStream(bos, false, true).writeTag(NBTConverter.writeEntities(entitiesList, tileEntitiesList));
//
// FileOutputStream os = new FileOutputStream(file);
// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
//
// int length = bos.size();
// dos.write(header);
// dos.writeInt(Integer.reverseBytes(length));
// bos.writeTo(dos);
// dos.close();
// }
//
// public static void main(String[] args) throws Exception {
// EntityData entities = read(new File(args[0]));
// System.out.println(entities);
// write(entities.entities, entities.tileEntities, new File(args[1]));
// }
//
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.zhuoweizhang.pocketinveditor.entity.*;
import net.zhuoweizhang.pocketinveditor.io.EntityDataConverter;
import net.zhuoweizhang.pocketinveditor.tileentity.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f; | int newCount = 1;
Integer oldCount = countMap.get(entityType);
if (oldCount != null) {
newCount += oldCount;
}
countMap.put(entityType, newCount);
}
String entityCountString = buildEntityCountString(countMap);
if (entityCountString.length() == 0) {
entityCountString = this.getResources().getText(R.string.entities_none).toString();
}
entityCountText.setText(entityCountString);
}
private String buildEntityCountString(Map<EntityType, Integer> countMap) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<EntityType, Integer> entry: countMap.entrySet()) {
Integer resId = EntityTypeLocalization.namesMap.get(entry.getKey());
if (resId == null) resId = new Integer(R.string.entity_unknown);
builder.append(this.getResources().getText(resId));
builder.append(':');
builder.append(entry.getValue());
builder.append('\n');
}
return builder.toString();
}
public void apoCowlypse() {
List<Entity> list = EditorActivity.level.getEntities(); | // Path: src/net/zhuoweizhang/pocketinveditor/io/EntityDataConverter.java
// public final class EntityDataConverter {
// public static final byte[] header = {0x45, 0x4e, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00};
//
// public static class EntityData {
// public List<Entity> entities;
// public List<TileEntity> tileEntities;
// public EntityData(List<Entity> entities, List<TileEntity> tileEntities) {
// this.entities = entities;
// this.tileEntities = tileEntities;
// }
// }
//
// public static EntityData read(File file) throws IOException {
// FileInputStream fis = new FileInputStream(file);
// BufferedInputStream is = new BufferedInputStream(fis);
// is.skip(12);
// EntityData eDat = NBTConverter.readEntities((CompoundTag) new NBTInputStream(is, false, true).readTag());
// is.close();
// return eDat;
// }
//
// public static void write(List<Entity> entitiesList, List<TileEntity> tileEntitiesList, File file) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// new NBTOutputStream(bos, false, true).writeTag(NBTConverter.writeEntities(entitiesList, tileEntitiesList));
//
// FileOutputStream os = new FileOutputStream(file);
// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
//
// int length = bos.size();
// dos.write(header);
// dos.writeInt(Integer.reverseBytes(length));
// bos.writeTo(dos);
// dos.close();
// }
//
// public static void main(String[] args) throws Exception {
// EntityData entities = read(new File(args[0]));
// System.out.println(entities);
// write(entities.entities, entities.tileEntities, new File(args[1]));
// }
//
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/EntitiesInfoActivity.java
import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.zhuoweizhang.pocketinveditor.entity.*;
import net.zhuoweizhang.pocketinveditor.io.EntityDataConverter;
import net.zhuoweizhang.pocketinveditor.tileentity.*;
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
int newCount = 1;
Integer oldCount = countMap.get(entityType);
if (oldCount != null) {
newCount += oldCount;
}
countMap.put(entityType, newCount);
}
String entityCountString = buildEntityCountString(countMap);
if (entityCountString.length() == 0) {
entityCountString = this.getResources().getText(R.string.entities_none).toString();
}
entityCountText.setText(entityCountString);
}
private String buildEntityCountString(Map<EntityType, Integer> countMap) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<EntityType, Integer> entry: countMap.entrySet()) {
Integer resId = EntityTypeLocalization.namesMap.get(entry.getKey());
if (resId == null) resId = new Integer(R.string.entity_unknown);
builder.append(this.getResources().getText(resId));
builder.append(':');
builder.append(entry.getValue());
builder.append('\n');
}
return builder.toString();
}
public void apoCowlypse() {
List<Entity> list = EditorActivity.level.getEntities(); | Vector3f playerLoc = EditorActivity.level.getPlayer().getLocation(); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/tileentity/TileEntity.java | // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import net.zhuoweizhang.pocketinveditor.util.Vector3f; | package net.zhuoweizhang.pocketinveditor.tileentity;
public class TileEntity {
private String id = null;
private int x = 0;
private int y = 0;
private int z = 0;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
| // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/tileentity/TileEntity.java
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
package net.zhuoweizhang.pocketinveditor.tileentity;
public class TileEntity {
private String id = null;
private int x = 0;
private int y = 0;
private int z = 0;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
| public double distanceSquaredTo(Vector3f other) { |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialIconLoader.java | // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/icon/MaterialIcon.java
// public class MaterialIcon {
//
// public static Map<MaterialKey, MaterialIcon> icons;
//
// public int typeId;
//
// public short damage;
//
// public Bitmap bitmap;
//
// public MaterialIcon(int typeId, short damage, Bitmap bmp) {
// this.typeId = typeId;
// this.damage = damage;
// this.bitmap = bmp;
// }
// }
| import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import net.zhuoweizhang.pocketinveditor.R;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.icon.MaterialIcon; | bmpOptions.inDither = false;
bmpOptions.inScaled = false;
this.guiBlocksBitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks.png"));
this.guiBlocks2Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_2.png"));
this.guiBlocks3Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_3.png"));
this.guiBlocks4Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_4.png"));
this.terrainBitmap = BitmapFactory.decodeStream(asMgr.open("terrain_3x.png"));
this.itemsBitmap = BitmapFactory.decodeStream(asMgr.open("gui/items_3x.png"), null, bmpOptions);
loadBitmap("terrain-atlas", "new/terrain-atlas.png", bmpOptions);
loadBitmap("items-opaque", "new/items-opaque.png", bmpOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadBitmap(String name, String loc, BitmapFactory.Options bmpOptions) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(asMgr.open(loc), null, bmpOptions);
bitmaps.put(name, bitmap);
}
public void run() {
try {
loadMaterials(parser, guiBlocksBitmap, guiBlocks2Bitmap, guiBlocks3Bitmap, guiBlocks4Bitmap, terrainBitmap, itemsBitmap, bitmaps);
} finally {
parser.close();
}
}
public static void loadMaterials(XmlPullParser parser, Bitmap guiBlocksBitmap, Bitmap guiBlocks2Bitmap, Bitmap guiBlocks3Bitmap, Bitmap guiBlocks4Bitmap,
Bitmap terrainBitmap, Bitmap itemsBitmap, Map<String, Bitmap> additionalBitmaps) { | // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/icon/MaterialIcon.java
// public class MaterialIcon {
//
// public static Map<MaterialKey, MaterialIcon> icons;
//
// public int typeId;
//
// public short damage;
//
// public Bitmap bitmap;
//
// public MaterialIcon(int typeId, short damage, Bitmap bmp) {
// this.typeId = typeId;
// this.damage = damage;
// this.bitmap = bmp;
// }
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialIconLoader.java
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import net.zhuoweizhang.pocketinveditor.R;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.icon.MaterialIcon;
bmpOptions.inDither = false;
bmpOptions.inScaled = false;
this.guiBlocksBitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks.png"));
this.guiBlocks2Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_2.png"));
this.guiBlocks3Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_3.png"));
this.guiBlocks4Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_4.png"));
this.terrainBitmap = BitmapFactory.decodeStream(asMgr.open("terrain_3x.png"));
this.itemsBitmap = BitmapFactory.decodeStream(asMgr.open("gui/items_3x.png"), null, bmpOptions);
loadBitmap("terrain-atlas", "new/terrain-atlas.png", bmpOptions);
loadBitmap("items-opaque", "new/items-opaque.png", bmpOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadBitmap(String name, String loc, BitmapFactory.Options bmpOptions) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(asMgr.open(loc), null, bmpOptions);
bitmaps.put(name, bitmap);
}
public void run() {
try {
loadMaterials(parser, guiBlocksBitmap, guiBlocks2Bitmap, guiBlocks3Bitmap, guiBlocks4Bitmap, terrainBitmap, itemsBitmap, bitmaps);
} finally {
parser.close();
}
}
public static void loadMaterials(XmlPullParser parser, Bitmap guiBlocksBitmap, Bitmap guiBlocks2Bitmap, Bitmap guiBlocks3Bitmap, Bitmap guiBlocks4Bitmap,
Bitmap terrainBitmap, Bitmap itemsBitmap, Map<String, Bitmap> additionalBitmaps) { | Map<MaterialKey, MaterialIcon> retval = new HashMap<MaterialKey, MaterialIcon>(); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialIconLoader.java | // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/icon/MaterialIcon.java
// public class MaterialIcon {
//
// public static Map<MaterialKey, MaterialIcon> icons;
//
// public int typeId;
//
// public short damage;
//
// public Bitmap bitmap;
//
// public MaterialIcon(int typeId, short damage, Bitmap bmp) {
// this.typeId = typeId;
// this.damage = damage;
// this.bitmap = bmp;
// }
// }
| import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import net.zhuoweizhang.pocketinveditor.R;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.icon.MaterialIcon; | bmpOptions.inDither = false;
bmpOptions.inScaled = false;
this.guiBlocksBitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks.png"));
this.guiBlocks2Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_2.png"));
this.guiBlocks3Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_3.png"));
this.guiBlocks4Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_4.png"));
this.terrainBitmap = BitmapFactory.decodeStream(asMgr.open("terrain_3x.png"));
this.itemsBitmap = BitmapFactory.decodeStream(asMgr.open("gui/items_3x.png"), null, bmpOptions);
loadBitmap("terrain-atlas", "new/terrain-atlas.png", bmpOptions);
loadBitmap("items-opaque", "new/items-opaque.png", bmpOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadBitmap(String name, String loc, BitmapFactory.Options bmpOptions) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(asMgr.open(loc), null, bmpOptions);
bitmaps.put(name, bitmap);
}
public void run() {
try {
loadMaterials(parser, guiBlocksBitmap, guiBlocks2Bitmap, guiBlocks3Bitmap, guiBlocks4Bitmap, terrainBitmap, itemsBitmap, bitmaps);
} finally {
parser.close();
}
}
public static void loadMaterials(XmlPullParser parser, Bitmap guiBlocksBitmap, Bitmap guiBlocks2Bitmap, Bitmap guiBlocks3Bitmap, Bitmap guiBlocks4Bitmap,
Bitmap terrainBitmap, Bitmap itemsBitmap, Map<String, Bitmap> additionalBitmaps) { | // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/icon/MaterialIcon.java
// public class MaterialIcon {
//
// public static Map<MaterialKey, MaterialIcon> icons;
//
// public int typeId;
//
// public short damage;
//
// public Bitmap bitmap;
//
// public MaterialIcon(int typeId, short damage, Bitmap bmp) {
// this.typeId = typeId;
// this.damage = damage;
// this.bitmap = bmp;
// }
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialIconLoader.java
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import net.zhuoweizhang.pocketinveditor.R;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.icon.MaterialIcon;
bmpOptions.inDither = false;
bmpOptions.inScaled = false;
this.guiBlocksBitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks.png"));
this.guiBlocks2Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_2.png"));
this.guiBlocks3Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_3.png"));
this.guiBlocks4Bitmap = BitmapFactory.decodeStream(asMgr.open("gui/gui_blocks_4.png"));
this.terrainBitmap = BitmapFactory.decodeStream(asMgr.open("terrain_3x.png"));
this.itemsBitmap = BitmapFactory.decodeStream(asMgr.open("gui/items_3x.png"), null, bmpOptions);
loadBitmap("terrain-atlas", "new/terrain-atlas.png", bmpOptions);
loadBitmap("items-opaque", "new/items-opaque.png", bmpOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadBitmap(String name, String loc, BitmapFactory.Options bmpOptions) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(asMgr.open(loc), null, bmpOptions);
bitmaps.put(name, bitmap);
}
public void run() {
try {
loadMaterials(parser, guiBlocksBitmap, guiBlocks2Bitmap, guiBlocks3Bitmap, guiBlocks4Bitmap, terrainBitmap, itemsBitmap, bitmaps);
} finally {
parser.close();
}
}
public static void loadMaterials(XmlPullParser parser, Bitmap guiBlocksBitmap, Bitmap guiBlocks2Bitmap, Bitmap guiBlocks3Bitmap, Bitmap guiBlocks4Bitmap,
Bitmap terrainBitmap, Bitmap itemsBitmap, Map<String, Bitmap> additionalBitmaps) { | Map<MaterialKey, MaterialIcon> retval = new HashMap<MaterialKey, MaterialIcon>(); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/geo/GeoUtils.java | // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialCount.java
// public class MaterialCount {
//
// public MaterialKey key;
//
// public int count;
//
// public MaterialCount(MaterialKey key, int count) {
//
// this.key = key;
// this.count = count;
//
// }
//
// public String toString() {
// return "[" + key.typeId + ":" + key.damage + "]: " + count;
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.MaterialCount;
import net.zhuoweizhang.pocketinveditor.util.Vector3f; | public static int replaceBlocks(AreaBlockAccess mgr, CuboidRegion region, MaterialKey from, MaterialKey to) {
int replacedCount = 0;
for (int x = region.x; x < region.x + region.width; ++x) {
for (int z = region.z; z < region.z + region.length; ++z) {
for (int y = region.y; y < region.y + region.height; ++y) {
int type = mgr.getBlockTypeId(x, y, z);
int data = mgr.getBlockData(x, y, z);
if (type == from.typeId && (data == from.damage || from.damage == -1)) {
mgr.setBlockTypeId(x, y, z, to.typeId);
mgr.setBlockData(x, y, z, to.damage);
replacedCount++;
}
}
}
}
return replacedCount;
}
public static void setBlocks(AreaBlockAccess mgr, CuboidRegion region, MaterialKey to) {
int replacedCount = 0;
for (int x = region.x; x < region.x + region.width; ++x) {
for (int z = region.z; z < region.z + region.length; ++z) {
for (int y = region.y; y < region.y + region.height; ++y) {
mgr.setBlockTypeId(x, y, z, to.typeId);
mgr.setBlockData(x, y, z, to.damage);
}
}
}
}
| // Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialCount.java
// public class MaterialCount {
//
// public MaterialKey key;
//
// public int count;
//
// public MaterialCount(MaterialKey key, int count) {
//
// this.key = key;
// this.count = count;
//
// }
//
// public String toString() {
// return "[" + key.typeId + ":" + key.damage + "]: " + count;
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/geo/GeoUtils.java
import java.util.HashMap;
import java.util.Map;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
import net.zhuoweizhang.pocketinveditor.material.MaterialCount;
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
public static int replaceBlocks(AreaBlockAccess mgr, CuboidRegion region, MaterialKey from, MaterialKey to) {
int replacedCount = 0;
for (int x = region.x; x < region.x + region.width; ++x) {
for (int z = region.z; z < region.z + region.length; ++z) {
for (int y = region.y; y < region.y + region.height; ++y) {
int type = mgr.getBlockTypeId(x, y, z);
int data = mgr.getBlockData(x, y, z);
if (type == from.typeId && (data == from.damage || from.damage == -1)) {
mgr.setBlockTypeId(x, y, z, to.typeId);
mgr.setBlockData(x, y, z, to.damage);
replacedCount++;
}
}
}
}
return replacedCount;
}
public static void setBlocks(AreaBlockAccess mgr, CuboidRegion region, MaterialKey to) {
int replacedCount = 0;
for (int x = region.x; x < region.x + region.width; ++x) {
for (int z = region.z; z < region.z + region.length; ++z) {
for (int y = region.y; y < region.y + region.height; ++y) {
mgr.setBlockTypeId(x, y, z, to.typeId);
mgr.setBlockData(x, y, z, to.damage);
}
}
}
}
| public static int makeSphere(AreaBlockAccess mgr, Vector3f center, int radius, MaterialKey to, boolean hollow) { |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialLoader.java | // Path: src/net/zhuoweizhang/pocketinveditor/material/Material.java
// public class Material {
//
// public static List<Material> materials;
//
// public static Map<MaterialKey, Material> materialMap = new HashMap<MaterialKey, Material>();
//
// private int id;
//
// private String name;
//
// private short damage;
//
// private boolean hasSubtypes;
//
// private boolean damageable = false;
//
// public Material(int id, String name) {
// this(id, name, (short) 0, false);
// }
//
// public Material(int id, String name, short damage) {
// this(id, name, damage, true);
// }
//
// public Material(int id, String name, short damage, boolean hasSubtypes) {
// this.id = id;
// this.name = name;
// this.damage = damage;
// this.hasSubtypes = hasSubtypes;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public short getDamage() {
// return damage;
// }
//
// public boolean hasSubtypes() {
// return hasSubtypes;
// }
//
// public void setDamageable(boolean damageable) {
// this.damageable = damageable;
// }
//
// public boolean isDamageable() {
// return damageable;
// }
//
// public String toString() {
// return getName() + " : " + getId() + (damage != 0 ? ":" + damage : "");
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import net.zhuoweizhang.pocketinveditor.material.Material;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey; | package net.zhuoweizhang.pocketinveditor.io.xml;
public final class MaterialLoader implements Runnable {
public XmlResourceParser parser;
public MaterialLoader(XmlResourceParser parser) {
this.parser = parser;
}
public void run() {
try { | // Path: src/net/zhuoweizhang/pocketinveditor/material/Material.java
// public class Material {
//
// public static List<Material> materials;
//
// public static Map<MaterialKey, Material> materialMap = new HashMap<MaterialKey, Material>();
//
// private int id;
//
// private String name;
//
// private short damage;
//
// private boolean hasSubtypes;
//
// private boolean damageable = false;
//
// public Material(int id, String name) {
// this(id, name, (short) 0, false);
// }
//
// public Material(int id, String name, short damage) {
// this(id, name, damage, true);
// }
//
// public Material(int id, String name, short damage, boolean hasSubtypes) {
// this.id = id;
// this.name = name;
// this.damage = damage;
// this.hasSubtypes = hasSubtypes;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public short getDamage() {
// return damage;
// }
//
// public boolean hasSubtypes() {
// return hasSubtypes;
// }
//
// public void setDamageable(boolean damageable) {
// this.damageable = damageable;
// }
//
// public boolean isDamageable() {
// return damageable;
// }
//
// public String toString() {
// return getName() + " : " + getId() + (damage != 0 ? ":" + damage : "");
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialLoader.java
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import net.zhuoweizhang.pocketinveditor.material.Material;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
package net.zhuoweizhang.pocketinveditor.io.xml;
public final class MaterialLoader implements Runnable {
public XmlResourceParser parser;
public MaterialLoader(XmlResourceParser parser) {
this.parser = parser;
}
public void run() {
try { | List<Material> materials = loadMaterials(parser); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialLoader.java | // Path: src/net/zhuoweizhang/pocketinveditor/material/Material.java
// public class Material {
//
// public static List<Material> materials;
//
// public static Map<MaterialKey, Material> materialMap = new HashMap<MaterialKey, Material>();
//
// private int id;
//
// private String name;
//
// private short damage;
//
// private boolean hasSubtypes;
//
// private boolean damageable = false;
//
// public Material(int id, String name) {
// this(id, name, (short) 0, false);
// }
//
// public Material(int id, String name, short damage) {
// this(id, name, damage, true);
// }
//
// public Material(int id, String name, short damage, boolean hasSubtypes) {
// this.id = id;
// this.name = name;
// this.damage = damage;
// this.hasSubtypes = hasSubtypes;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public short getDamage() {
// return damage;
// }
//
// public boolean hasSubtypes() {
// return hasSubtypes;
// }
//
// public void setDamageable(boolean damageable) {
// this.damageable = damageable;
// }
//
// public boolean isDamageable() {
// return damageable;
// }
//
// public String toString() {
// return getName() + " : " + getId() + (damage != 0 ? ":" + damage : "");
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import net.zhuoweizhang.pocketinveditor.material.Material;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey; | }
}
public static List<Material> loadMaterials(XmlPullParser parser) {
List<Material> materials = new ArrayList<Material>();
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
int itemId = 0;
String itemName = null;
short itemDamage = 0;
boolean itemHasSubtypes = false;
if (tagName != null && tagName.equals("item")) {
int size = parser.getAttributeCount();
for (int i = 0; i < size; i++) {
String attrName = parser.getAttributeName(i);
String attrValue = parser.getAttributeValue(i);
if (attrName == null) continue;
if (attrName.equals("dec")) {
itemId = Integer.parseInt(attrValue);
} else if (attrName.equals("name")) {
itemName = attrValue;
} else if (attrName.equals("id")) {
itemHasSubtypes = true;
itemDamage = Short.parseShort(attrValue);
}
}
if (itemName != null) {
Material matt = new Material(itemId, itemName, itemDamage, itemHasSubtypes);
materials.add(matt); | // Path: src/net/zhuoweizhang/pocketinveditor/material/Material.java
// public class Material {
//
// public static List<Material> materials;
//
// public static Map<MaterialKey, Material> materialMap = new HashMap<MaterialKey, Material>();
//
// private int id;
//
// private String name;
//
// private short damage;
//
// private boolean hasSubtypes;
//
// private boolean damageable = false;
//
// public Material(int id, String name) {
// this(id, name, (short) 0, false);
// }
//
// public Material(int id, String name, short damage) {
// this(id, name, damage, true);
// }
//
// public Material(int id, String name, short damage, boolean hasSubtypes) {
// this.id = id;
// this.name = name;
// this.damage = damage;
// this.hasSubtypes = hasSubtypes;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public short getDamage() {
// return damage;
// }
//
// public boolean hasSubtypes() {
// return hasSubtypes;
// }
//
// public void setDamageable(boolean damageable) {
// this.damageable = damageable;
// }
//
// public boolean isDamageable() {
// return damageable;
// }
//
// public String toString() {
// return getName() + " : " + getId() + (damage != 0 ? ":" + damage : "");
// }
// }
//
// Path: src/net/zhuoweizhang/pocketinveditor/material/MaterialKey.java
// public final class MaterialKey {
//
// public short typeId;
//
// public short damage;
//
// /**
// * @param damage the damage/data value of the material. -1 is a pseudo-value that tells any replacement routines to match all data values.
// */
// public MaterialKey(short typeId, short damage) {
// this.typeId = typeId;
// this.damage = damage;
// }
//
// public MaterialKey(MaterialKey other) {
// this(other.typeId, other.damage);
// }
//
// @Override
// public boolean equals(Object other) {
// if (other == this) return true;
// if (!(other instanceof MaterialKey)) return false;
// MaterialKey another = (MaterialKey) other;
// return another.typeId == this.typeId && another.damage == this.damage;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + typeId;
// result = prime * result + damage;
// return result;
// }
//
// @Override
// public String toString() {
// return "MaterialKey[typeId=" + typeId + ";damage=" + damage + "]";
// }
//
// public static MaterialKey parse(String str, int radix) {
// String[] parts = str.split(":");
// if (parts.length == 0) throw new IllegalArgumentException("Why is the string blank?!");
// else if (parts.length == 1) {
// return new MaterialKey(Short.parseShort(parts[0], radix), (short) -1);
// } else {
// return new MaterialKey(Short.parseShort(parts[0], radix), Short.parseShort(parts[1], radix));
// }
// }
// }
// Path: src/net/zhuoweizhang/pocketinveditor/io/xml/MaterialLoader.java
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import net.zhuoweizhang.pocketinveditor.material.Material;
import net.zhuoweizhang.pocketinveditor.material.MaterialKey;
}
}
public static List<Material> loadMaterials(XmlPullParser parser) {
List<Material> materials = new ArrayList<Material>();
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
int itemId = 0;
String itemName = null;
short itemDamage = 0;
boolean itemHasSubtypes = false;
if (tagName != null && tagName.equals("item")) {
int size = parser.getAttributeCount();
for (int i = 0; i < size; i++) {
String attrName = parser.getAttributeName(i);
String attrValue = parser.getAttributeValue(i);
if (attrName == null) continue;
if (attrName.equals("dec")) {
itemId = Integer.parseInt(attrValue);
} else if (attrName.equals("name")) {
itemName = attrValue;
} else if (attrName.equals("id")) {
itemHasSubtypes = true;
itemDamage = Short.parseShort(attrValue);
}
}
if (itemName != null) {
Material matt = new Material(itemId, itemName, itemDamage, itemHasSubtypes);
materials.add(matt); | Material.materialMap.put(new MaterialKey((short) itemId, itemDamage), matt); |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/geo/CuboidRegion.java | // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
| import net.zhuoweizhang.pocketinveditor.util.Vector3f; | package net.zhuoweizhang.pocketinveditor.geo;
public class CuboidRegion {
public int x, y, z, width, height, length;
/**
* @param width Width on the X axis
* @param height Height on the Y axis
* @param length Length on the Z axis
*/
public CuboidRegion(int x, int y, int z, int width, int height, int length) {
this.x = x;
this.y = y;
this.z = z;
this.width = width;
this.height = height;
this.length = length;
}
| // Path: src/net/zhuoweizhang/pocketinveditor/util/Vector3f.java
// public class Vector3f {
//
// public float x, y, z;
//
// public Vector3f() {
// this(0f, 0f, 0f);
// }
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
//
// public float getX() {
// return x;
// }
//
// public Vector3f setX(float x) {
// this.x = x;
// return this;
// }
//
// public float getY() {
// return y;
// }
//
// public Vector3f setY(float y) {
// this.y = y;
// return this;
// }
//
// public float getZ() {
// return z;
// }
//
// public Vector3f setZ(float z) {
// this.z = z;
// return this;
// }
//
// public int getBlockX() {
// return (int) x;
// }
//
// public int getBlockY() {
// return (int) y;
// }
//
// public int getBlockZ() {
// return (int) z;
// }
//
// public double distSquared(Vector3f other) {
// return Math.pow(other.x - (double) this.x, 2) + Math.pow(other.y - (double) this.y, 2) + Math.pow(other.z - (double) this.z, 2);
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/geo/CuboidRegion.java
import net.zhuoweizhang.pocketinveditor.util.Vector3f;
package net.zhuoweizhang.pocketinveditor.geo;
public class CuboidRegion {
public int x, y, z, width, height, length;
/**
* @param width Width on the X axis
* @param height Height on the Y axis
* @param length Length on the Z axis
*/
public CuboidRegion(int x, int y, int z, int width, int height, int length) {
this.x = x;
this.y = y;
this.z = z;
this.width = width;
this.height = height;
this.length = length;
}
| public CuboidRegion(Vector3f pos, Vector3f size) { |
zhuowei/PocketInvEditor | src/net/zhuoweizhang/pocketinveditor/entity/Player.java | // Path: src/net/zhuoweizhang/pocketinveditor/ItemStack.java
// public class ItemStack {
//
// private short id;
//
// private short durability;
//
// private int amount;
//
// public ItemStack(short id, short durability, int amount) {
// this.id = id;
// this.durability = durability;
// this.amount = amount;
// }
//
// public ItemStack(ItemStack other) {
// this(other.getTypeId(), other.getDurability(), other.getAmount());
// }
//
// public short getTypeId() {
// return id;
// }
//
// public void setTypeId(short id) {
// this.id = id;
// }
//
// public short getDurability() {
// return durability;
// }
//
// public void setDurability(short durability) {
// this.durability = durability;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String toString() {
// return "ItemStack: type=" + getTypeId() + ", durability=" + getDurability() + ", amount=" + getAmount();
// }
//
// }
| import java.util.List;
import net.zhuoweizhang.pocketinveditor.InventorySlot;
import net.zhuoweizhang.pocketinveditor.ItemStack; | package net.zhuoweizhang.pocketinveditor.entity;
public class Player extends LivingEntity {
private List<InventorySlot> inventory;
private int score;
private int dimension;
private int bedPositionX = 0, bedPositionY = 0, bedPositionZ = 0;
private int spawnX = 0, spawnY = 64, spawnZ = 0;
private short sleepTimer = 0;
private boolean sleeping = false; | // Path: src/net/zhuoweizhang/pocketinveditor/ItemStack.java
// public class ItemStack {
//
// private short id;
//
// private short durability;
//
// private int amount;
//
// public ItemStack(short id, short durability, int amount) {
// this.id = id;
// this.durability = durability;
// this.amount = amount;
// }
//
// public ItemStack(ItemStack other) {
// this(other.getTypeId(), other.getDurability(), other.getAmount());
// }
//
// public short getTypeId() {
// return id;
// }
//
// public void setTypeId(short id) {
// this.id = id;
// }
//
// public short getDurability() {
// return durability;
// }
//
// public void setDurability(short durability) {
// this.durability = durability;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String toString() {
// return "ItemStack: type=" + getTypeId() + ", durability=" + getDurability() + ", amount=" + getAmount();
// }
//
// }
// Path: src/net/zhuoweizhang/pocketinveditor/entity/Player.java
import java.util.List;
import net.zhuoweizhang.pocketinveditor.InventorySlot;
import net.zhuoweizhang.pocketinveditor.ItemStack;
package net.zhuoweizhang.pocketinveditor.entity;
public class Player extends LivingEntity {
private List<InventorySlot> inventory;
private int score;
private int dimension;
private int bedPositionX = 0, bedPositionY = 0, bedPositionZ = 0;
private int spawnX = 0, spawnY = 64, spawnZ = 0;
private short sleepTimer = 0;
private boolean sleeping = false; | private List<ItemStack> armorSlots; |
redkale/redkale-demo | src/main/java/org/redkale/demo/notice/RandomCodeHis.java | // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
| import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import java.io.Serializable;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "验证码历史表")
@DistributeTable(strategy = RandomCodeHis.TableStrategy.class)
| // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
// Path: src/main/java/org/redkale/demo/notice/RandomCodeHis.java
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import java.io.Serializable;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "验证码历史表")
@DistributeTable(strategy = RandomCodeHis.TableStrategy.class)
| public class RandomCodeHis extends BaseEntity {
|
redkale/redkale-demo | src/main/java/org/redkale/demo/notice/NoticeRecord.java | // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
| import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import java.io.Serializable;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "消息推送表")
@DistributeTable(strategy = NoticeRecord.TableStrategy.class)
| // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
// Path: src/main/java/org/redkale/demo/notice/NoticeRecord.java
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import java.io.Serializable;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "消息推送表")
@DistributeTable(strategy = NoticeRecord.TableStrategy.class)
| public class NoticeRecord extends BaseEntity {
|
redkale/redkale-demo | src/main/java/org/redkale/demo/base/UserInfoLoader.java | // Path: src/main/java/org/redkale/demo/user/UserDetail.java
// @Cacheable
// @LogLevel("FINER")
// @Table(comment = "用户信息表")
// public class UserDetail extends UserInfo {
//
// private static final Reproduce<UserInfo, UserDetail> reproduce = Reproduce.create(UserInfo.class, UserDetail.class);
//
// public static final short REGTYPE_ACCOUNT = 10; //账号注册
//
// public static final short REGTYPE_MOBILE = 20; //手机注册
//
// public static final short REGTYPE_EMAIL = 30; //邮箱注册
//
// public static final short REGTYPE_WEIXIN = 40; //微信注册
//
// public static final short REGTYPE_QQOPEN = 50; //QQ注册
//
// @Column(updatable = false, comment = "[注册类型]: 10:账号注册; 20:手机注册; 30:邮箱注册; 40:微信注册; 50:QQ注册")
// private short regtype;
//
// @Column(updatable = false, comment = "[创建时间]")
// private long createtime;
//
// @Column(updatable = false, length = 255, comment = "[注册终端]")
// private String regagent = "";//注册终端
//
// @Column(updatable = false, length = 64, comment = "[注册IP]")
// private String regaddr = "";//注册IP
//
// @Column(length = 255, comment = "[备注]")
// private String remark = ""; //备注
//
// @Column(comment = "[更新时间]")
// private long updatetime; //修改时间
//
// public UserInfo createUserInfo() {
// return reproduce.apply(new UserInfo(), this);
// }
//
// @Override
// public String getMobile() {
// return mobile;
// }
//
// @Override
// public String getEmail() {
// return email;
// }
//
// @Override
// public String getWxunionid() {
// return wxunionid;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public short getRegtype() {
// return regtype;
// }
//
// public void setRegtype(short regtype) {
// this.regtype = regtype;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public long getCreatetime() {
// return createtime;
// }
//
// public void setCreatetime(long createtime) {
// this.createtime = createtime;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public long getUpdatetime() {
// return updatetime;
// }
//
// public void setUpdatetime(long updatetime) {
// this.updatetime = updatetime;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRegagent() {
// return regagent;
// }
//
// public void setRegagent(String regagent) {
// this.regagent = regagent;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRegaddr() {
// return regaddr;
// }
//
// public void setRegaddr(String regaddr) {
// this.regaddr = regaddr;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRemark() {
// return remark;
// }
//
// public void setRemark(String remark) {
// this.remark = remark;
// }
//
// }
| import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.redkale.demo.user.UserDetail;
import org.redkale.source.*;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.base;
/**
*
* @author zhangjx
*/
public class UserInfoLoader implements BiFunction<DataSource, EntityInfo, CompletableFuture<List>> {
@Override
public CompletableFuture<List> apply(DataSource source, EntityInfo info) {
| // Path: src/main/java/org/redkale/demo/user/UserDetail.java
// @Cacheable
// @LogLevel("FINER")
// @Table(comment = "用户信息表")
// public class UserDetail extends UserInfo {
//
// private static final Reproduce<UserInfo, UserDetail> reproduce = Reproduce.create(UserInfo.class, UserDetail.class);
//
// public static final short REGTYPE_ACCOUNT = 10; //账号注册
//
// public static final short REGTYPE_MOBILE = 20; //手机注册
//
// public static final short REGTYPE_EMAIL = 30; //邮箱注册
//
// public static final short REGTYPE_WEIXIN = 40; //微信注册
//
// public static final short REGTYPE_QQOPEN = 50; //QQ注册
//
// @Column(updatable = false, comment = "[注册类型]: 10:账号注册; 20:手机注册; 30:邮箱注册; 40:微信注册; 50:QQ注册")
// private short regtype;
//
// @Column(updatable = false, comment = "[创建时间]")
// private long createtime;
//
// @Column(updatable = false, length = 255, comment = "[注册终端]")
// private String regagent = "";//注册终端
//
// @Column(updatable = false, length = 64, comment = "[注册IP]")
// private String regaddr = "";//注册IP
//
// @Column(length = 255, comment = "[备注]")
// private String remark = ""; //备注
//
// @Column(comment = "[更新时间]")
// private long updatetime; //修改时间
//
// public UserInfo createUserInfo() {
// return reproduce.apply(new UserInfo(), this);
// }
//
// @Override
// public String getMobile() {
// return mobile;
// }
//
// @Override
// public String getEmail() {
// return email;
// }
//
// @Override
// public String getWxunionid() {
// return wxunionid;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public short getRegtype() {
// return regtype;
// }
//
// public void setRegtype(short regtype) {
// this.regtype = regtype;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public long getCreatetime() {
// return createtime;
// }
//
// public void setCreatetime(long createtime) {
// this.createtime = createtime;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public long getUpdatetime() {
// return updatetime;
// }
//
// public void setUpdatetime(long updatetime) {
// this.updatetime = updatetime;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRegagent() {
// return regagent;
// }
//
// public void setRegagent(String regagent) {
// this.regagent = regagent;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRegaddr() {
// return regaddr;
// }
//
// public void setRegaddr(String regaddr) {
// this.regaddr = regaddr;
// }
//
// @ConvertColumn(ignore = true, type = ConvertType.JSON)
// public String getRemark() {
// return remark;
// }
//
// public void setRemark(String remark) {
// this.remark = remark;
// }
//
// }
// Path: src/main/java/org/redkale/demo/base/UserInfoLoader.java
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.redkale.demo.user.UserDetail;
import org.redkale.source.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.demo.base;
/**
*
* @author zhangjx
*/
public class UserInfoLoader implements BiFunction<DataSource, EntityInfo, CompletableFuture<List>> {
@Override
public CompletableFuture<List> apply(DataSource source, EntityInfo info) {
| CompletableFuture<List<UserDetail>> future = source.queryListAsync(UserDetail.class, (FilterNode) null);
|
redkale/redkale-demo | src/main/java/org/redkale/demo/notice/SmsRecord.java | // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
| import java.io.Serializable;
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
| package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "发送短信记录表")
@DistributeTable(strategy = SmsRecord.TableStrategy.class)
| // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
// Path: src/main/java/org/redkale/demo/notice/SmsRecord.java
import java.io.Serializable;
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
package org.redkale.demo.notice;
/**
*
* @author zhangjx
*/
@Table(comment = "发送短信记录表")
@DistributeTable(strategy = SmsRecord.TableStrategy.class)
| public class SmsRecord extends BaseEntity {
|
redkale/redkale-demo | src/main/java/org/redkale/demo/pay/PayRecord.java | // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
| import javax.persistence.*;
import java.io.Serializable;
import java.util.Map;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import org.redkalex.pay.*;
| package org.redkale.demo.pay;
/**
*
* @author zhangjx
*/
@Table(comment = "支付表")
@DistributeTable(strategy = PayRecord.TableStrategy.class)
| // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
// Path: src/main/java/org/redkale/demo/pay/PayRecord.java
import javax.persistence.*;
import java.io.Serializable;
import java.util.Map;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
import org.redkalex.pay.*;
package org.redkale.demo.pay;
/**
*
* @author zhangjx
*/
@Table(comment = "支付表")
@DistributeTable(strategy = PayRecord.TableStrategy.class)
| public class PayRecord extends BaseEntity {
|
redkale/redkale-demo | src/main/java/org/redkale/demo/pay/PayAction.java | // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
| import java.io.Serializable;
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
| package org.redkale.demo.pay;
/**
*
* @author zhangjx
*/
@Table(comment = "支付接口结果表")
@DistributeTable(strategy = PayAction.TableStrategy.class)
| // Path: src/main/java/org/redkale/demo/base/BaseEntity.java
// @Entity
// public abstract class BaseEntity implements Serializable {
//
// //状态间隔10,便于以后扩展意义接近的状态值比较靠近
// //正常
// public static final short STATUS_NORMAL = 10;
//
// //待审批
// public static final short STATUS_PENDING = 20;
//
// //审批不通过
// public static final short STATUS_PENDNO = 30;
//
// //冻结
// public static final short STATUS_FREEZE = 40;
//
// //隐藏
// public static final short STATUS_HIDDEN = 50;
//
// //关闭
// public static final short STATUS_CLOSED = 60;
//
// //过期
// public static final short STATUS_EXPIRE = 70;
//
// //删除
// public static final short STATUS_DELTED = 80;
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// }
// Path: src/main/java/org/redkale/demo/pay/PayAction.java
import java.io.Serializable;
import javax.persistence.*;
import org.redkale.demo.base.BaseEntity;
import org.redkale.source.*;
package org.redkale.demo.pay;
/**
*
* @author zhangjx
*/
@Table(comment = "支付接口结果表")
@DistributeTable(strategy = PayAction.TableStrategy.class)
| public class PayAction extends BaseEntity {
|
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/topology/OutbreakDetectionTopology.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventSpout.java
// @SuppressWarnings("rawtypes")
// public class DiagnosisEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new DiagnosisEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("event");
// }
// }
//
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/state/OutbreakTrendFactory.java
// @SuppressWarnings("rawtypes")
// public class OutbreakTrendFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// return new OutbreakTrendState(new OutbreakTrendBackingMap());
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.packtpub.storm.trident.operator.*;
import com.packtpub.storm.trident.spout.DiagnosisEventSpout;
import com.packtpub.storm.trident.state.OutbreakTrendFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
import storm.trident.operation.builtin.Count; | package com.packtpub.storm.trident.topology;
public class OutbreakDetectionTopology {
public static StormTopology buildTopology() {
TridentTopology topology = new TridentTopology(); | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventSpout.java
// @SuppressWarnings("rawtypes")
// public class DiagnosisEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new DiagnosisEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("event");
// }
// }
//
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/state/OutbreakTrendFactory.java
// @SuppressWarnings("rawtypes")
// public class OutbreakTrendFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// return new OutbreakTrendState(new OutbreakTrendBackingMap());
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/topology/OutbreakDetectionTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.packtpub.storm.trident.operator.*;
import com.packtpub.storm.trident.spout.DiagnosisEventSpout;
import com.packtpub.storm.trident.state.OutbreakTrendFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
import storm.trident.operation.builtin.Count;
package com.packtpub.storm.trident.topology;
public class OutbreakDetectionTopology {
public static StormTopology buildTopology() {
TridentTopology topology = new TridentTopology(); | DiagnosisEventSpout spout = new DiagnosisEventSpout(); |
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/topology/OutbreakDetectionTopology.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventSpout.java
// @SuppressWarnings("rawtypes")
// public class DiagnosisEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new DiagnosisEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("event");
// }
// }
//
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/state/OutbreakTrendFactory.java
// @SuppressWarnings("rawtypes")
// public class OutbreakTrendFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// return new OutbreakTrendState(new OutbreakTrendBackingMap());
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.packtpub.storm.trident.operator.*;
import com.packtpub.storm.trident.spout.DiagnosisEventSpout;
import com.packtpub.storm.trident.state.OutbreakTrendFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
import storm.trident.operation.builtin.Count; | package com.packtpub.storm.trident.topology;
public class OutbreakDetectionTopology {
public static StormTopology buildTopology() {
TridentTopology topology = new TridentTopology();
DiagnosisEventSpout spout = new DiagnosisEventSpout();
Stream inputStream = topology.newStream("event", spout);
inputStream.each(new Fields("event"), new DiseaseFilter())
.each(new Fields("event"), new CityAssignment(), new Fields("city"))
.each(new Fields("event", "city"), new HourAssignment(), new Fields("hour", "cityDiseaseHour"))
.groupBy(new Fields("cityDiseaseHour")) | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventSpout.java
// @SuppressWarnings("rawtypes")
// public class DiagnosisEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new DiagnosisEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("event");
// }
// }
//
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/state/OutbreakTrendFactory.java
// @SuppressWarnings("rawtypes")
// public class OutbreakTrendFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// return new OutbreakTrendState(new OutbreakTrendBackingMap());
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/topology/OutbreakDetectionTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.packtpub.storm.trident.operator.*;
import com.packtpub.storm.trident.spout.DiagnosisEventSpout;
import com.packtpub.storm.trident.state.OutbreakTrendFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
import storm.trident.operation.builtin.Count;
package com.packtpub.storm.trident.topology;
public class OutbreakDetectionTopology {
public static StormTopology buildTopology() {
TridentTopology topology = new TridentTopology();
DiagnosisEventSpout spout = new DiagnosisEventSpout();
Stream inputStream = topology.newStream("event", spout);
inputStream.each(new Fields("event"), new DiseaseFilter())
.each(new Fields("event"), new CityAssignment(), new Fields("city"))
.each(new Fields("event", "city"), new HourAssignment(), new Fields("hour", "cityDiseaseHour"))
.groupBy(new Fields("cityDiseaseHour")) | .persistentAggregate(new OutbreakTrendFactory(), new Count(), new Fields("count")).newValuesStream() |
jfmwz/storm-example | Chapter06/src/main/java/com/packtpub/storm/operators/ScoreUpdater.java | // Path: Chapter06/src/main/java/com/packtpub/storm/model/Board.java
// public class Board implements Serializable {
// private static final long serialVersionUID = 1L;
// public static final String EMPTY = " ";
// public String[][] board = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}};
//
// public Board() {
// }
//
// public Board(String key) {
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// this.board[i][j] = "" + key.charAt(i * 3 + j);
// }
// }
// }
//
// public List<Board> nextBoards(String player) {
// List<Board> boards = new ArrayList<Board>();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// if (board[i][j].equals(EMPTY)) {
// Board newBoard = this.clone();
// newBoard.board[i][j] = player;
// boards.add(newBoard);
// }
// }
// }
// return boards;
// }
//
// public boolean isEndState() {
// return (nextBoards("X").size() == 0 || Math.abs(score("X")) > 1000);
// }
//
// public int score(String player) {
// return scoreLines(player) - scoreLines(Player.next(player));
// }
//
// public int scoreLines(String player) {
// int score = 0;
// // Columns
// score += scoreLine(board[0][0], board[1][0], board[2][0], player);
// score += scoreLine(board[0][1], board[1][1], board[2][1], player);
// score += scoreLine(board[0][2], board[1][2], board[2][2], player);
//
// // Rows
// score += scoreLine(board[0][0], board[0][1], board[0][2], player);
// score += scoreLine(board[1][0], board[1][1], board[1][2], player);
// score += scoreLine(board[2][0], board[2][1], board[2][2], player);
//
// // Diagonals
// score += scoreLine(board[0][0], board[1][1], board[2][2], player);
// score += scoreLine(board[2][0], board[1][1], board[0][2], player);
// return score;
// }
//
// public int scoreLine(String pos1, String pos2, String pos3, String player) {
// int score = 0;
// if (pos1.equals(player) && pos2.equals(player) && pos3.equals(player)) {
// score = 10000;
// } else if (pos1.equals(player) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(player)) {
// score = 100;
// } else {
// if (pos1.equals(player) && pos2.equals(EMPTY) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(EMPTY) && pos3.equals(player)) {
// score = 10;
// }
// }
// return score;
// }
//
// public Board clone() {
// Board clone = new Board();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// clone.board[i][j] = this.board[i][j];
// }
// }
// return clone;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("\n---------\n");
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append("|").append(board[i][j]).append("|");
// }
// sb.append("\n---------\n");
// }
// return sb.toString();
// }
//
// public String toKey() {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append(board[i][j]);
// }
// }
// return sb.toString();
// }
// }
| import com.packtpub.storm.model.Board;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.HashMap;
import java.util.Map; | package com.packtpub.storm.operators;
public class ScoreUpdater extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(ScoreUpdater.class);
private static final Map<String, Integer> scores = new HashMap<String, Integer>();
private static final String MUTEX = "MUTEX";
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | // Path: Chapter06/src/main/java/com/packtpub/storm/model/Board.java
// public class Board implements Serializable {
// private static final long serialVersionUID = 1L;
// public static final String EMPTY = " ";
// public String[][] board = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}};
//
// public Board() {
// }
//
// public Board(String key) {
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// this.board[i][j] = "" + key.charAt(i * 3 + j);
// }
// }
// }
//
// public List<Board> nextBoards(String player) {
// List<Board> boards = new ArrayList<Board>();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// if (board[i][j].equals(EMPTY)) {
// Board newBoard = this.clone();
// newBoard.board[i][j] = player;
// boards.add(newBoard);
// }
// }
// }
// return boards;
// }
//
// public boolean isEndState() {
// return (nextBoards("X").size() == 0 || Math.abs(score("X")) > 1000);
// }
//
// public int score(String player) {
// return scoreLines(player) - scoreLines(Player.next(player));
// }
//
// public int scoreLines(String player) {
// int score = 0;
// // Columns
// score += scoreLine(board[0][0], board[1][0], board[2][0], player);
// score += scoreLine(board[0][1], board[1][1], board[2][1], player);
// score += scoreLine(board[0][2], board[1][2], board[2][2], player);
//
// // Rows
// score += scoreLine(board[0][0], board[0][1], board[0][2], player);
// score += scoreLine(board[1][0], board[1][1], board[1][2], player);
// score += scoreLine(board[2][0], board[2][1], board[2][2], player);
//
// // Diagonals
// score += scoreLine(board[0][0], board[1][1], board[2][2], player);
// score += scoreLine(board[2][0], board[1][1], board[0][2], player);
// return score;
// }
//
// public int scoreLine(String pos1, String pos2, String pos3, String player) {
// int score = 0;
// if (pos1.equals(player) && pos2.equals(player) && pos3.equals(player)) {
// score = 10000;
// } else if (pos1.equals(player) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(player)) {
// score = 100;
// } else {
// if (pos1.equals(player) && pos2.equals(EMPTY) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(EMPTY) && pos3.equals(player)) {
// score = 10;
// }
// }
// return score;
// }
//
// public Board clone() {
// Board clone = new Board();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// clone.board[i][j] = this.board[i][j];
// }
// }
// return clone;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("\n---------\n");
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append("|").append(board[i][j]).append("|");
// }
// sb.append("\n---------\n");
// }
// return sb.toString();
// }
//
// public String toKey() {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append(board[i][j]);
// }
// }
// return sb.toString();
// }
// }
// Path: Chapter06/src/main/java/com/packtpub/storm/operators/ScoreUpdater.java
import com.packtpub.storm.model.Board;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.HashMap;
import java.util.Map;
package com.packtpub.storm.operators;
public class ScoreUpdater extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(ScoreUpdater.class);
private static final Map<String, Integer> scores = new HashMap<String, Integer>();
private static final String MUTEX = "MUTEX";
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | Board board = (Board) tuple.get(0); |
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/operator/DiseaseFilter.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
| import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple; | package com.packtpub.storm.trident.operator;
public class DiseaseFilter extends BaseFilter {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DiseaseFilter.class);
@Override
public boolean isKeep(TridentTuple tuple) { | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/operator/DiseaseFilter.java
import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple;
package com.packtpub.storm.trident.operator;
public class DiseaseFilter extends BaseFilter {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DiseaseFilter.class);
@Override
public boolean isKeep(TridentTuple tuple) { | DiagnosisEvent diagnosis = (DiagnosisEvent) tuple.getValue(0); |
jfmwz/storm-example | Chapter06/src/main/java/com/packtpub/storm/operators/isEndGame.java | // Path: Chapter06/src/main/java/com/packtpub/storm/model/GameState.java
// public class GameState implements Serializable {
// private static final long serialVersionUID = 1L;
// private Board board;
// private List<Board> history;
// private String player;
// static private Random generator = new Random();
//
// public GameState(Board board, List<Board> history, String player) {
// this.board = board;
// this.history = history;
// this.player = player;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("GAME [");
// sb.append(board.toKey()).append("]");
// sb.append(": player(").append(player).append(")\n");
// sb.append(" history [");
// for (Board b : history) {
// sb.append(b.toKey()).append(",");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public Board getBoard() {
// return board;
// }
//
// public List<Board> getHistory() {
// return history;
// }
//
// public String getPlayer() {
// return player;
// }
//
// public static GameState playAtRandom(Board currentBoard, String player) {
// List<Board> history = new ArrayList<Board>();
// while (!currentBoard.isEndState()) {
// List<Board> boards = currentBoard.nextBoards(player);
// int move = generator.nextInt(boards.size());
//
// history.add(currentBoard);
// player = Player.next(player);
// currentBoard = boards.get(move);
// }
// return new GameState(currentBoard, history, player);
// }
//
// public int score() {
// return this.board.score(this.player);
// }
//
// }
| import com.packtpub.storm.model.GameState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple; | package com.packtpub.storm.operators;
public class isEndGame extends BaseFilter {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(isEndGame.class);
@Override
public boolean isKeep(TridentTuple tuple) { | // Path: Chapter06/src/main/java/com/packtpub/storm/model/GameState.java
// public class GameState implements Serializable {
// private static final long serialVersionUID = 1L;
// private Board board;
// private List<Board> history;
// private String player;
// static private Random generator = new Random();
//
// public GameState(Board board, List<Board> history, String player) {
// this.board = board;
// this.history = history;
// this.player = player;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("GAME [");
// sb.append(board.toKey()).append("]");
// sb.append(": player(").append(player).append(")\n");
// sb.append(" history [");
// for (Board b : history) {
// sb.append(b.toKey()).append(",");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public Board getBoard() {
// return board;
// }
//
// public List<Board> getHistory() {
// return history;
// }
//
// public String getPlayer() {
// return player;
// }
//
// public static GameState playAtRandom(Board currentBoard, String player) {
// List<Board> history = new ArrayList<Board>();
// while (!currentBoard.isEndState()) {
// List<Board> boards = currentBoard.nextBoards(player);
// int move = generator.nextInt(boards.size());
//
// history.add(currentBoard);
// player = Player.next(player);
// currentBoard = boards.get(move);
// }
// return new GameState(currentBoard, history, player);
// }
//
// public int score() {
// return this.board.score(this.player);
// }
//
// }
// Path: Chapter06/src/main/java/com/packtpub/storm/operators/isEndGame.java
import com.packtpub.storm.model.GameState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple;
package com.packtpub.storm.operators;
public class isEndGame extends BaseFilter {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(isEndGame.class);
@Override
public boolean isKeep(TridentTuple tuple) { | GameState gameState = (GameState) tuple.get(0); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
| import backtype.storm.task.IMetricsContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.druid.realtime.RealtimeNode;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.state.StateFactory;
import java.util.Map; | package com.packtpub.storm.trident.state;
@SuppressWarnings("rawtypes")
public class DruidStateFactory implements StateFactory {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
private static RealtimeNode rn = null;
private static synchronized void startRealtime() {
if (rn == null) {
final Lifecycle lifecycle = new Lifecycle();
rn = RealtimeNode.builder().build();
lifecycle.addManagedInstance(rn); | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
import backtype.storm.task.IMetricsContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.druid.realtime.RealtimeNode;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.state.StateFactory;
import java.util.Map;
package com.packtpub.storm.trident.state;
@SuppressWarnings("rawtypes")
public class DruidStateFactory implements StateFactory {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
private static RealtimeNode rn = null;
private static synchronized void startRealtime() {
if (rn == null) {
final Lifecycle lifecycle = new Lifecycle();
rn = RealtimeNode.builder().build();
lifecycle.addManagedInstance(rn); | rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm")); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple; | package com.packtpub.storm.trident.operator;
public class MessageTypeFilter extends BaseFilter {
private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
@Override
public boolean isKeep(TridentTuple tuple) { | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.BaseFilter;
import storm.trident.tuple.TridentTuple;
package com.packtpub.storm.trident.operator;
public class MessageTypeFilter extends BaseFilter {
private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
@Override
public boolean isKeep(TridentTuple tuple) { | FixMessageDto message = (FixMessageDto) tuple.getValue(0); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/operator/PrinterFunction.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.esotericsoftware.minlog.Log;
import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List; | package com.packtpub.storm.trident.operator;
public class PrinterFunction extends BaseFunction {
private static final long serialVersionUID = 1L;
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/PrinterFunction.java
import com.esotericsoftware.minlog.Log;
import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List;
package com.packtpub.storm.trident.operator;
public class PrinterFunction extends BaseFunction {
private static final long serialVersionUID = 1L;
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | FixMessageDto message = (FixMessageDto) tuple.getValue(0); |
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventEmitter.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
| import com.packtpub.storm.trident.model.DiagnosisEvent;
import storm.trident.operation.TridentCollector;
import storm.trident.spout.ITridentSpout.Emitter;
import storm.trident.topology.TransactionAttempt;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; | package com.packtpub.storm.trident.spout;
public class DiagnosisEventEmitter implements Emitter<Long>, Serializable {
private static final long serialVersionUID = 1L;
AtomicInteger successfulTransactions = new AtomicInteger(0);
@Override
public void emitBatch(TransactionAttempt tx, Long coordinatorMeta, TridentCollector collector) {
for (int i = 0; i < 10000; i++) {
List<Object> events = new ArrayList<Object>();
double lat = new Double(-30 + (int) (Math.random() * 75));
double lng = new Double(-120 + (int) (Math.random() * 70));
long time = System.currentTimeMillis();
String diag = new Integer(320 + (int) (Math.random() * 7)).toString(); | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/spout/DiagnosisEventEmitter.java
import com.packtpub.storm.trident.model.DiagnosisEvent;
import storm.trident.operation.TridentCollector;
import storm.trident.spout.ITridentSpout.Emitter;
import storm.trident.topology.TransactionAttempt;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
package com.packtpub.storm.trident.spout;
public class DiagnosisEventEmitter implements Emitter<Long>, Serializable {
private static final long serialVersionUID = 1L;
AtomicInteger successfulTransactions = new AtomicInteger(0);
@Override
public void emitBatch(TransactionAttempt tx, Long coordinatorMeta, TridentCollector collector) {
for (int i = 0; i < 10000; i++) {
List<Object> events = new ArrayList<Object>();
double lat = new Double(-30 + (int) (Math.random() * 75));
double lng = new Double(-120 + (int) (Math.random() * 70));
long time = System.currentTimeMillis();
String diag = new Integer(320 + (int) (Math.random() * 7)).toString(); | DiagnosisEvent event = new DiagnosisEvent(lat, lng, time, diag); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector; | package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class); | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java
import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector;
package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class); | private Vector<FixMessageDto> messages = new Vector<FixMessageDto>(); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector; | package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private Vector<FixMessageDto> messages = new Vector<FixMessageDto>();
private int partitionIndex;
public DruidState(int partitionIndex){
this.partitionIndex = partitionIndex;
}
@Override
public void beginCommit(Long batchId) {
}
@Override
public void commit(Long batchId) {
String partitionId = batchId.toString() + "-" + partitionIndex;
LOG.info("Committing partition [" + partitionIndex + "] of batch [" + batchId + "]");
try { | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java
import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector;
package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private Vector<FixMessageDto> messages = new Vector<FixMessageDto>();
private int partitionIndex;
public DruidState(int partitionIndex){
this.partitionIndex = partitionIndex;
}
@Override
public void beginCommit(Long batchId) {
}
@Override
public void commit(Long batchId) {
String partitionId = batchId.toString() + "-" + partitionIndex;
LOG.info("Committing partition [" + partitionIndex + "] of batch [" + batchId + "]");
try { | if (StormFirehose.STATUS.isCompleted(partitionId)) { |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector; | package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private Vector<FixMessageDto> messages = new Vector<FixMessageDto>();
private int partitionIndex;
public DruidState(int partitionIndex){
this.partitionIndex = partitionIndex;
}
@Override
public void beginCommit(Long batchId) {
}
@Override
public void commit(Long batchId) {
String partitionId = batchId.toString() + "-" + partitionIndex;
LOG.info("Committing partition [" + partitionIndex + "] of batch [" + batchId + "]");
try {
if (StormFirehose.STATUS.isCompleted(partitionId)) {
LOG.warn("Encountered completed partition [" + partitionIndex + "] of batch [" + batchId + "]");
return;
} else if (StormFirehose.STATUS.isInLimbo(partitionId)) {
LOG.warn("Encountered limbo partition [" + partitionIndex + "] of batch [" + batchId + "] : NOTIFY THE AUTHORITIES!");
return;
} else if (StormFirehose.STATUS.isInProgress(partitionId)) {
LOG.warn("Encountered in-progress partition [\" + partitionIndex + \"] of batch [" + batchId + "] : NOTIFY THE AUTHORITIES!");
return;
}
StormFirehose.STATUS.putInProgress(partitionId); | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidState.java
import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import com.packtpub.storm.model.FixMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import java.util.Vector;
package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private Vector<FixMessageDto> messages = new Vector<FixMessageDto>();
private int partitionIndex;
public DruidState(int partitionIndex){
this.partitionIndex = partitionIndex;
}
@Override
public void beginCommit(Long batchId) {
}
@Override
public void commit(Long batchId) {
String partitionId = batchId.toString() + "-" + partitionIndex;
LOG.info("Committing partition [" + partitionIndex + "] of batch [" + batchId + "]");
try {
if (StormFirehose.STATUS.isCompleted(partitionId)) {
LOG.warn("Encountered completed partition [" + partitionIndex + "] of batch [" + batchId + "]");
return;
} else if (StormFirehose.STATUS.isInLimbo(partitionId)) {
LOG.warn("Encountered limbo partition [" + partitionIndex + "] of batch [" + batchId + "] : NOTIFY THE AUTHORITIES!");
return;
} else if (StormFirehose.STATUS.isInProgress(partitionId)) {
LOG.warn("Encountered in-progress partition [\" + partitionIndex + \"] of batch [" + batchId + "] : NOTIFY THE AUTHORITIES!");
return;
}
StormFirehose.STATUS.putInProgress(partitionId); | StormFirehoseFactory.getFirehose().sendMessages(partitionId, messages); |
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/operator/HourAssignment.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
| import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List; | package com.packtpub.storm.trident.operator;
public class HourAssignment extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(HourAssignment.class);
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/operator/HourAssignment.java
import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List;
package com.packtpub.storm.trident.operator;
public class HourAssignment extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(HourAssignment.class);
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | DiagnosisEvent diagnosis = (DiagnosisEvent) tuple.getValue(0); |
jfmwz/storm-example | Chapter03/src/main/java/com/packtpub/storm/trident/operator/CityAssignment.java | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
| import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; | package com.packtpub.storm.trident.operator;
public class CityAssignment extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(CityAssignment.class);
private static Map<String, double[]> CITIES = new HashMap<String, double[]>();
{ // Initialize the cities we care about.
double[] phl = {39.875365, -75.249524};
CITIES.put("PHL", phl);
double[] nyc = {40.71448, -74.00598};
CITIES.put("NYC", nyc);
double[] sf = {-31.4250142, -62.0841809};
CITIES.put("SF", sf);
double[] la = {-34.05374, -118.24307};
CITIES.put("LA", la);
}
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | // Path: Chapter03/src/main/java/com/packtpub/storm/trident/model/DiagnosisEvent.java
// public class DiagnosisEvent implements Serializable {
// private static final long serialVersionUID = 1L;
// public double lat;
// public double lng;
// public long time;
// public String diagnosisCode;
//
// public DiagnosisEvent(double lat, double lng, long time, String diagnosisCode) {
// super();
// this.time = time;
// this.lat = lat;
// this.lng = lng;
// this.diagnosisCode = diagnosisCode;
// }
// }
// Path: Chapter03/src/main/java/com/packtpub/storm/trident/operator/CityAssignment.java
import com.packtpub.storm.trident.model.DiagnosisEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
package com.packtpub.storm.trident.operator;
public class CityAssignment extends BaseFunction {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(CityAssignment.class);
private static Map<String, double[]> CITIES = new HashMap<String, double[]>();
{ // Initialize the cities we care about.
double[] phl = {39.875365, -75.249524};
CITIES.put("PHL", phl);
double[] nyc = {40.71448, -74.00598};
CITIES.put("NYC", nyc);
double[] sf = {-31.4250142, -62.0841809};
CITIES.put("SF", sf);
double[] la = {-34.05374, -118.24307};
CITIES.put("LA", la);
}
@Override
public void execute(TridentTuple tuple, TridentCollector collector) { | DiagnosisEvent diagnosis = (DiagnosisEvent) tuple.getValue(0); |
jfmwz/storm-example | Chapter06/src/main/java/com/packtpub/storm/operators/FindBestMove.java | // Path: Chapter06/src/main/java/com/packtpub/storm/model/BestMove.java
// public class BestMove {
// public Board bestMove;
// public Integer score = Integer.MIN_VALUE;
//
// public String toString() {
// return bestMove.toString() + "[" + score + "]";
// }
// }
//
// Path: Chapter06/src/main/java/com/packtpub/storm/model/Board.java
// public class Board implements Serializable {
// private static final long serialVersionUID = 1L;
// public static final String EMPTY = " ";
// public String[][] board = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}};
//
// public Board() {
// }
//
// public Board(String key) {
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// this.board[i][j] = "" + key.charAt(i * 3 + j);
// }
// }
// }
//
// public List<Board> nextBoards(String player) {
// List<Board> boards = new ArrayList<Board>();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// if (board[i][j].equals(EMPTY)) {
// Board newBoard = this.clone();
// newBoard.board[i][j] = player;
// boards.add(newBoard);
// }
// }
// }
// return boards;
// }
//
// public boolean isEndState() {
// return (nextBoards("X").size() == 0 || Math.abs(score("X")) > 1000);
// }
//
// public int score(String player) {
// return scoreLines(player) - scoreLines(Player.next(player));
// }
//
// public int scoreLines(String player) {
// int score = 0;
// // Columns
// score += scoreLine(board[0][0], board[1][0], board[2][0], player);
// score += scoreLine(board[0][1], board[1][1], board[2][1], player);
// score += scoreLine(board[0][2], board[1][2], board[2][2], player);
//
// // Rows
// score += scoreLine(board[0][0], board[0][1], board[0][2], player);
// score += scoreLine(board[1][0], board[1][1], board[1][2], player);
// score += scoreLine(board[2][0], board[2][1], board[2][2], player);
//
// // Diagonals
// score += scoreLine(board[0][0], board[1][1], board[2][2], player);
// score += scoreLine(board[2][0], board[1][1], board[0][2], player);
// return score;
// }
//
// public int scoreLine(String pos1, String pos2, String pos3, String player) {
// int score = 0;
// if (pos1.equals(player) && pos2.equals(player) && pos3.equals(player)) {
// score = 10000;
// } else if (pos1.equals(player) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(player)) {
// score = 100;
// } else {
// if (pos1.equals(player) && pos2.equals(EMPTY) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(EMPTY) && pos3.equals(player)) {
// score = 10;
// }
// }
// return score;
// }
//
// public Board clone() {
// Board clone = new Board();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// clone.board[i][j] = this.board[i][j];
// }
// }
// return clone;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("\n---------\n");
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append("|").append(board[i][j]).append("|");
// }
// sb.append("\n---------\n");
// }
// return sb.toString();
// }
//
// public String toKey() {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append(board[i][j]);
// }
// }
// return sb.toString();
// }
// }
| import backtype.storm.tuple.Values;
import com.esotericsoftware.minlog.Log;
import com.packtpub.storm.model.BestMove;
import com.packtpub.storm.model.Board;
import storm.trident.operation.BaseAggregator;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple; | package com.packtpub.storm.operators;
public class FindBestMove extends BaseAggregator<BestMove> {
private static final long serialVersionUID = 1L;
@Override
public BestMove init(Object batchId, TridentCollector collector) {
Log.info("Batch Id = [" + batchId + "]");
return new BestMove();
}
@Override
public void aggregate(BestMove currentBestMove, TridentTuple tuple, TridentCollector collector) { | // Path: Chapter06/src/main/java/com/packtpub/storm/model/BestMove.java
// public class BestMove {
// public Board bestMove;
// public Integer score = Integer.MIN_VALUE;
//
// public String toString() {
// return bestMove.toString() + "[" + score + "]";
// }
// }
//
// Path: Chapter06/src/main/java/com/packtpub/storm/model/Board.java
// public class Board implements Serializable {
// private static final long serialVersionUID = 1L;
// public static final String EMPTY = " ";
// public String[][] board = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}};
//
// public Board() {
// }
//
// public Board(String key) {
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// this.board[i][j] = "" + key.charAt(i * 3 + j);
// }
// }
// }
//
// public List<Board> nextBoards(String player) {
// List<Board> boards = new ArrayList<Board>();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// if (board[i][j].equals(EMPTY)) {
// Board newBoard = this.clone();
// newBoard.board[i][j] = player;
// boards.add(newBoard);
// }
// }
// }
// return boards;
// }
//
// public boolean isEndState() {
// return (nextBoards("X").size() == 0 || Math.abs(score("X")) > 1000);
// }
//
// public int score(String player) {
// return scoreLines(player) - scoreLines(Player.next(player));
// }
//
// public int scoreLines(String player) {
// int score = 0;
// // Columns
// score += scoreLine(board[0][0], board[1][0], board[2][0], player);
// score += scoreLine(board[0][1], board[1][1], board[2][1], player);
// score += scoreLine(board[0][2], board[1][2], board[2][2], player);
//
// // Rows
// score += scoreLine(board[0][0], board[0][1], board[0][2], player);
// score += scoreLine(board[1][0], board[1][1], board[1][2], player);
// score += scoreLine(board[2][0], board[2][1], board[2][2], player);
//
// // Diagonals
// score += scoreLine(board[0][0], board[1][1], board[2][2], player);
// score += scoreLine(board[2][0], board[1][1], board[0][2], player);
// return score;
// }
//
// public int scoreLine(String pos1, String pos2, String pos3, String player) {
// int score = 0;
// if (pos1.equals(player) && pos2.equals(player) && pos3.equals(player)) {
// score = 10000;
// } else if (pos1.equals(player) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(player)) {
// score = 100;
// } else {
// if (pos1.equals(player) && pos2.equals(EMPTY) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(EMPTY) ||
// pos1.equals(EMPTY) && pos2.equals(EMPTY) && pos3.equals(player)) {
// score = 10;
// }
// }
// return score;
// }
//
// public Board clone() {
// Board clone = new Board();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// clone.board[i][j] = this.board[i][j];
// }
// }
// return clone;
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder("\n---------\n");
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append("|").append(board[i][j]).append("|");
// }
// sb.append("\n---------\n");
// }
// return sb.toString();
// }
//
// public String toKey() {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// sb.append(board[i][j]);
// }
// }
// return sb.toString();
// }
// }
// Path: Chapter06/src/main/java/com/packtpub/storm/operators/FindBestMove.java
import backtype.storm.tuple.Values;
import com.esotericsoftware.minlog.Log;
import com.packtpub.storm.model.BestMove;
import com.packtpub.storm.model.Board;
import storm.trident.operation.BaseAggregator;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
package com.packtpub.storm.operators;
public class FindBestMove extends BaseAggregator<BestMove> {
private static final long serialVersionUID = 1L;
@Override
public BestMove init(Object batchId, TridentCollector collector) {
Log.info("Batch Id = [" + batchId + "]");
return new BestMove();
}
@Override
public void aggregate(BestMove currentBestMove, TridentTuple tuple, TridentCollector collector) { | Board board = (Board) tuple.get(0); |
jfmwz/storm-example | Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java | // Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidBatchStatus.java
// public class DruidBatchStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidBatchStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidBatchStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + txId) != null);
// }
//
// public boolean isInLimbo(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + txId) != null);
// }
//
// public boolean isInProgress(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + txId) != null);
// }
//
// public void putInProgress(Long txId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + txId);
// }
//
// public void putInLimbo(Long txId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + txId)
// .and().create().forPath(LIMBO_PATH + "/" + txId).and().commit();
// }
//
// public void complete(List<Long> txIds) throws Exception {
// Iterator<Long> iterator = txIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// Long txId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + txId)
// .and().create().forPath(COMPLETED_PATH + "/" + txId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
| import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.trident.state.DruidBatchStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.tuple.TridentTuple;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; | package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object();
private static BlockingQueue<TridentTuple> BLOCKING_QUEUE; | // Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidBatchStatus.java
// public class DruidBatchStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidBatchStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidBatchStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + txId) != null);
// }
//
// public boolean isInLimbo(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + txId) != null);
// }
//
// public boolean isInProgress(Long txId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + txId) != null);
// }
//
// public void putInProgress(Long txId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + txId);
// }
//
// public void putInLimbo(Long txId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + txId)
// .and().create().forPath(LIMBO_PATH + "/" + txId).and().commit();
// }
//
// public void complete(List<Long> txIds) throws Exception {
// Iterator<Long> iterator = txIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// Long txId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + txId)
// .and().create().forPath(COMPLETED_PATH + "/" + txId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.trident.state.DruidBatchStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.tuple.TridentTuple;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object();
private static BlockingQueue<TridentTuple> BLOCKING_QUEUE; | public static final DruidBatchStatus STATUS = new DruidBatchStatus(); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventEmitter.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.storm.model.FixMessageDto;
import net.java.fixparser.SimpleFixMessage;
import net.java.fixparser.SimpleFixParser;
import net.java.util.IoUtils;
import net.java.util.TagValue;
import storm.trident.operation.TridentCollector;
import storm.trident.spout.ITridentSpout.Emitter;
import storm.trident.topology.TransactionAttempt;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; | package com.packtpub.storm.trident.spout;
public class FixEventEmitter implements Emitter<Long>, Serializable {
private static final long serialVersionUID = 1L;
public static AtomicInteger successfulTransactions = new AtomicInteger(0);
public static AtomicInteger uids = new AtomicInteger(0);
@SuppressWarnings("rawtypes")
@Override
public void emitBatch(TransactionAttempt tx, Long coordinatorMeta, TridentCollector collector) {
InputStream inputStream = null;
File file = new File("fix_data.txt");
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
SimpleFixParser parser = new SimpleFixParser(inputStream);
SimpleFixMessage msg = null;
do {
msg = parser.readFixMessage();
if (null != msg) { | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventEmitter.java
import com.packtpub.storm.model.FixMessageDto;
import net.java.fixparser.SimpleFixMessage;
import net.java.fixparser.SimpleFixParser;
import net.java.util.IoUtils;
import net.java.util.TagValue;
import storm.trident.operation.TridentCollector;
import storm.trident.spout.ITridentSpout.Emitter;
import storm.trident.topology.TransactionAttempt;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
package com.packtpub.storm.trident.spout;
public class FixEventEmitter implements Emitter<Long>, Serializable {
private static final long serialVersionUID = 1L;
public static AtomicInteger successfulTransactions = new AtomicInteger(0);
public static AtomicInteger uids = new AtomicInteger(0);
@SuppressWarnings("rawtypes")
@Override
public void emitBatch(TransactionAttempt tx, Long coordinatorMeta, TridentCollector collector) {
InputStream inputStream = null;
File file = new File("fix_data.txt");
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
SimpleFixParser parser = new SimpleFixParser(inputStream);
SimpleFixMessage msg = null;
do {
msg = parser.readFixMessage();
if (null != msg) { | FixMessageDto dto = new FixMessageDto(); |
jfmwz/storm-example | Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidState.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
| import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List; | package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private List<TridentTuple> batch = new ArrayList<TridentTuple>();
@Override
public void beginCommit(Long txid) {
}
@Override
public void commit(Long txId) {
LOG.info("Committing [" + txId + "]");
try { | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidState.java
import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List;
package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private List<TridentTuple> batch = new ArrayList<TridentTuple>();
@Override
public void beginCommit(Long txid) {
}
@Override
public void commit(Long txId) {
LOG.info("Committing [" + txId + "]");
try { | if (StormFirehose.STATUS.isCompleted(txId)) { |
jfmwz/storm-example | Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidState.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
| import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List; | package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private List<TridentTuple> batch = new ArrayList<TridentTuple>();
@Override
public void beginCommit(Long txid) {
}
@Override
public void commit(Long txId) {
LOG.info("Committing [" + txId + "]");
try {
if (StormFirehose.STATUS.isCompleted(txId)) {
LOG.warn("Encountered previously completed txId [" + txId + "]");
return;
} else if (StormFirehose.STATUS.isInLimbo(txId)) {
LOG.error("Encountered txId in limbo [" + txId + "] : NOTIFY THE AUTHORITIES!");
return;
} else if (StormFirehose.STATUS.isInProgress(txId)) {
LOG.error("Encountered txId in processing [" + txId + "] : NOTIFY THE AUTHORITIES!");
return;
}
StormFirehose.STATUS.putInProgress(txId); | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
// public class StormFirehose implements Firehose {
// private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
// private static final Object START = new Object();
// private static final Object FINISHED = new Object();
// private static BlockingQueue<TridentTuple> BLOCKING_QUEUE;
// public static final DruidBatchStatus STATUS = new DruidBatchStatus();
// private static Long TRANSACTION_ID = null;
// private static BlockingQueue<Long> LIMBO_TRANSACTIONS = new ArrayBlockingQueue<Long>(99999);
//
// @Override
// public boolean hasMore() {
// if (BLOCKING_QUEUE != null && !BLOCKING_QUEUE.isEmpty())
// return true;
// try {
// synchronized (START) {
// START.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("hasMore() blocking was interrupted.", e);
// }
// return true;
// }
//
// @Override
// public InputRow nextRow() {
// final Map<String, Object> theMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
// try {
// TridentTuple tuple = null;
// tuple = BLOCKING_QUEUE.poll();
// if (tuple != null) {
// String phrase = (String) tuple.getValue(0);
// String word = (String) tuple.getValue(2);
// Long baseline = (Long) tuple.getValue(3);
// theMap.put("searchphrase", phrase);
// theMap.put("word", word);
// theMap.put("baseline", baseline);
// }
//
// if (BLOCKING_QUEUE.isEmpty()) {
// STATUS.putInLimbo(TRANSACTION_ID);
// LIMBO_TRANSACTIONS.add(TRANSACTION_ID);
// LOG.info("Batch is fully consumed by Druid. Unlocking [FINISH]");
// synchronized (FINISHED) {
// FINISHED.notify();
// }
// }
// } catch (Exception e) {
// LOG.error("Error occurred in nextRow.", e);
// }
// final LinkedList<String> dimensions = new LinkedList<String>();
// dimensions.add("searchphrase");
// dimensions.add("word");
// return new MapBasedInputRow(System.currentTimeMillis(), dimensions, theMap);
// }
//
// @Override
// public Runnable commit() {
// List<Long> limboTransactions = new ArrayList<Long>();
// LIMBO_TRANSACTIONS.drainTo(limboTransactions);
// return new StormCommitRunnable(limboTransactions);
// }
//
// public synchronized void sendBatch(Long txId, List<TridentTuple> tuples) {
// BLOCKING_QUEUE = new ArrayBlockingQueue<TridentTuple>(tuples.size(), false, tuples);
// TRANSACTION_ID = txId;
// LOG.error("Beginning commit to Druid. [" + tuples.size() + "] messages, unlocking [START]");
// synchronized (START) {
// START.notify();
// }
// try {
// synchronized (FINISHED) {
// FINISHED.wait();
// }
// } catch (InterruptedException e) {
// LOG.error("Commit to Druid interrupted.");
// }
// LOG.info("Returning control to Storm.");
// }
//
// @Override
// public void close() throws IOException {
// // do nothing
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidState.java
import com.packtpub.druid.firehose.StormFirehose;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.tuple.TridentTuple;
import java.util.ArrayList;
import java.util.List;
package com.packtpub.storm.trident.state;
public class DruidState implements State {
private static final Logger LOG = LoggerFactory.getLogger(DruidState.class);
private List<TridentTuple> batch = new ArrayList<TridentTuple>();
@Override
public void beginCommit(Long txid) {
}
@Override
public void commit(Long txId) {
LOG.info("Committing [" + txId + "]");
try {
if (StormFirehose.STATUS.isCompleted(txId)) {
LOG.warn("Encountered previously completed txId [" + txId + "]");
return;
} else if (StormFirehose.STATUS.isInLimbo(txId)) {
LOG.error("Encountered txId in limbo [" + txId + "] : NOTIFY THE AUTHORITIES!");
return;
} else if (StormFirehose.STATUS.isInProgress(txId)) {
LOG.error("Encountered txId in processing [" + txId + "] : NOTIFY THE AUTHORITIES!");
return;
}
StormFirehose.STATUS.putInProgress(txId); | StormFirehoseFactory.getFirehose().sendBatch(txId, batch); |
jfmwz/storm-example | Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
| import backtype.storm.task.IMetricsContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.druid.realtime.RealtimeNode;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.state.StateFactory;
import java.util.Map; | package com.packtpub.storm.trident.state;
@SuppressWarnings("rawtypes")
public class DruidStateFactory implements StateFactory {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
private static RealtimeNode rn = null;
private static synchronized void startRealtime() {
if (rn == null) {
final Lifecycle lifecycle = new Lifecycle();
rn = RealtimeNode.builder().build();
lifecycle.addManagedInstance(rn); | // Path: Chapter08/src/main/java/com/packtpub/druid/firehose/StormFirehoseFactory.java
// @JsonTypeName("storm")
// public class StormFirehoseFactory implements FirehoseFactory {
// private static final StormFirehose FIREHOSE = new StormFirehose();
//
// @JsonCreator
// public StormFirehoseFactory() {
// }
//
// @Override
// public Firehose connect() throws IOException {
// return FIREHOSE;
// }
//
// public static StormFirehose getFirehose() {
// return FIREHOSE;
// }
// }
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
import backtype.storm.task.IMetricsContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.druid.realtime.RealtimeNode;
import com.packtpub.druid.firehose.StormFirehoseFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.state.State;
import storm.trident.state.StateFactory;
import java.util.Map;
package com.packtpub.storm.trident.state;
@SuppressWarnings("rawtypes")
public class DruidStateFactory implements StateFactory {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
private static RealtimeNode rn = null;
private static synchronized void startRealtime() {
if (rn == null) {
final Lifecycle lifecycle = new Lifecycle();
rn = RealtimeNode.builder().build();
lifecycle.addManagedInstance(rn); | rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm")); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology; | package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology(); | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology(); | FixEventSpout spout = new FixEventSpout(); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology; | package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
| // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
| inputStream.each(new Fields("message"), new MessageTypeFilter()) |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology; | package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
inputStream.each(new Fields("message"), new MessageTypeFilter()) | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
inputStream.each(new Fields("message"), new MessageTypeFilter()) | .partitionPersist(new DruidStateFactory(), new Fields("message"), new DruidStateUpdater()); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
| import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology; | package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
inputStream.each(new Fields("message"), new MessageTypeFilter()) | // Path: Chapter07/src/main/java/com/packtpub/storm/trident/operator/MessageTypeFilter.java
// public class MessageTypeFilter extends BaseFilter {
// private static final long serialVersionUID = 1L;
// // private static final Logger LOG = LoggerFactory.getLogger(MessageTypeFilter.class);
//
// @Override
// public boolean isKeep(TridentTuple tuple) {
// FixMessageDto message = (FixMessageDto) tuple.getValue(0);
// if (message.msgType.equals("8") && message.price > 0) {
// return true;
// }
// return false;
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/spout/FixEventSpout.java
// @SuppressWarnings("rawtypes")
// public class FixEventSpout implements ITridentSpout<Long> {
// private static final long serialVersionUID = 1L;
// SpoutOutputCollector collector;
// BatchCoordinator<Long> coordinator = new DefaultCoordinator();
// Emitter<Long> emitter = new FixEventEmitter();
//
// @Override
// public BatchCoordinator<Long> getCoordinator(String txStateId, Map conf, TopologyContext context) {
// return coordinator;
// }
//
// @Override
// public Emitter<Long> getEmitter(String txStateId, Map conf, TopologyContext context) {
// return emitter;
// }
//
// @Override
// public Map getComponentConfiguration() {
// return null;
// }
//
// @Override
// public Fields getOutputFields() {
// return new Fields("message");
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateFactory.java
// @SuppressWarnings("rawtypes")
// public class DruidStateFactory implements StateFactory {
// private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateFactory.class);
// private static RealtimeNode rn = null;
//
// private static synchronized void startRealtime() {
// if (rn == null) {
// final Lifecycle lifecycle = new Lifecycle();
// rn = RealtimeNode.builder().build();
// lifecycle.addManagedInstance(rn);
// rn.registerJacksonSubtype(new NamedType(StormFirehoseFactory.class, "storm"));
// Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// LOG.info("Running shutdown hook");
// lifecycle.stop();
// }
// }));
//
// try {
// lifecycle.start();
// } catch (Throwable t) {
// LOG.info("Throwable caught at startup, committing seppuku", t);
// t.printStackTrace();
// System.exit(2);
// }
// }
// }
//
// @Override
// public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
// DruidStateFactory.startRealtime();
// return new DruidState(partitionIndex);
// }
// }
//
// Path: Chapter08/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
// public class DruidStateUpdater implements StateUpdater<DruidState> {
// private static final long serialVersionUID = 1L;
//
// // private static final Logger LOG =
// // LoggerFactory.getLogger(DruidStateUpdater.class);
//
// @SuppressWarnings("rawtypes")
// @Override
// public void prepare(Map conf, TridentOperationContext context) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
// state.aggregateTuples(tuples);
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/topology/FinancialAnalyticsTopology.java
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import com.metamx.druid.log.LogLevelAdjuster;
import com.packtpub.storm.trident.operator.MessageTypeFilter;
import com.packtpub.storm.trident.spout.FixEventSpout;
import com.packtpub.storm.trident.state.DruidStateFactory;
import com.packtpub.storm.trident.state.DruidStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.trident.Stream;
import storm.trident.TridentTopology;
package com.packtpub.storm.trident.topology;
public class FinancialAnalyticsTopology {
private static final Logger LOG = LoggerFactory.getLogger(FinancialAnalyticsTopology.class);
public static StormTopology buildTopology() {
LOG.info("Building topology.");
TridentTopology topology = new TridentTopology();
FixEventSpout spout = new FixEventSpout();
Stream inputStream = topology.newStream("message", spout);
inputStream.each(new Fields("message"), new MessageTypeFilter()) | .partitionPersist(new DruidStateFactory(), new Fields("message"), new DruidStateUpdater()); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
| import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.TridentCollector;
import storm.trident.operation.TridentOperationContext;
import storm.trident.state.StateUpdater;
import storm.trident.tuple.TridentTuple;
import java.util.List;
import java.util.Map; | package com.packtpub.storm.trident.state;
public class DruidStateUpdater implements StateUpdater<DruidState> {
private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateUpdater.class);
@SuppressWarnings("rawtypes")
@Override
public void prepare(Map conf, TridentOperationContext context) {
}
@Override
public void cleanup() {
}
@Override
public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
//LOG.info("Updating [" + state + "]");
for (TridentTuple tuple : tuples) { | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidStateUpdater.java
import com.packtpub.storm.model.FixMessageDto;
import storm.trident.operation.TridentCollector;
import storm.trident.operation.TridentOperationContext;
import storm.trident.state.StateUpdater;
import storm.trident.tuple.TridentTuple;
import java.util.List;
import java.util.Map;
package com.packtpub.storm.trident.state;
public class DruidStateUpdater implements StateUpdater<DruidState> {
private static final long serialVersionUID = 1L;
// private static final Logger LOG = LoggerFactory.getLogger(DruidStateUpdater.class);
@SuppressWarnings("rawtypes")
@Override
public void prepare(Map conf, TridentOperationContext context) {
}
@Override
public void cleanup() {
}
@Override
public void updateState(DruidState state, List<TridentTuple> tuples, TridentCollector collector) {
//LOG.info("Updating [" + state + "]");
for (TridentTuple tuple : tuples) { | FixMessageDto message = (FixMessageDto) tuple.getValue(0); |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/druid/firehose/StormFirehose.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidPartitionStatus.java
// public class DruidPartitionStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidPartitionStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidPartitionStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInLimbo(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInProgress(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + partitionId) != null);
// }
//
// public void putInProgress(String partitionId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + partitionId);
// }
//
// public void putInLimbo(String partitionId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + partitionId)
// .and().create().forPath(LIMBO_PATH + "/" + partitionId).and().commit();
// }
//
// public void complete(List<String> partitionIds) throws Exception {
// Iterator<String> iterator = partitionIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// String partitionId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + partitionId)
// .and().create().forPath(COMPLETED_PATH + "/" + partitionId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
| import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.model.FixMessageDto;
import com.packtpub.storm.trident.state.DruidPartitionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; | package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object(); | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidPartitionStatus.java
// public class DruidPartitionStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidPartitionStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidPartitionStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInLimbo(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInProgress(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + partitionId) != null);
// }
//
// public void putInProgress(String partitionId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + partitionId);
// }
//
// public void putInLimbo(String partitionId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + partitionId)
// .and().create().forPath(LIMBO_PATH + "/" + partitionId).and().commit();
// }
//
// public void complete(List<String> partitionIds) throws Exception {
// Iterator<String> iterator = partitionIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// String partitionId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + partitionId)
// .and().create().forPath(COMPLETED_PATH + "/" + partitionId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.model.FixMessageDto;
import com.packtpub.storm.trident.state.DruidPartitionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object(); | private static BlockingQueue<FixMessageDto> BLOCKING_QUEUE; |
jfmwz/storm-example | Chapter07/src/main/java/com/packtpub/druid/firehose/StormFirehose.java | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidPartitionStatus.java
// public class DruidPartitionStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidPartitionStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidPartitionStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInLimbo(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInProgress(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + partitionId) != null);
// }
//
// public void putInProgress(String partitionId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + partitionId);
// }
//
// public void putInLimbo(String partitionId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + partitionId)
// .and().create().forPath(LIMBO_PATH + "/" + partitionId).and().commit();
// }
//
// public void complete(List<String> partitionIds) throws Exception {
// Iterator<String> iterator = partitionIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// String partitionId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + partitionId)
// .and().create().forPath(COMPLETED_PATH + "/" + partitionId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
| import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.model.FixMessageDto;
import com.packtpub.storm.trident.state.DruidPartitionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; | package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object();
private static BlockingQueue<FixMessageDto> BLOCKING_QUEUE; | // Path: Chapter07/src/main/java/com/packtpub/storm/model/FixMessageDto.java
// public class FixMessageDto implements Serializable {
// private static final long serialVersionUID = 1L;
// public String symbol;
// public String uid;
// public String msgType;
// public Double price;
//
// public String toString() {
// return "[" + symbol + "] @ [" + price + "] for [" + msgType + "]";
// }
// }
//
// Path: Chapter07/src/main/java/com/packtpub/storm/trident/state/DruidPartitionStatus.java
// public class DruidPartitionStatus {
// private static final Logger LOG = LoggerFactory.getLogger(DruidPartitionStatus.class);
// final String COMPLETED_PATH = "completed";
// final String LIMBO_PATH = "limbo";
// final String CURRENT_PATH = "current";
// private CuratorFramework curatorFramework;
//
// public DruidPartitionStatus() {
// try {
// curatorFramework = CuratorFrameworkFactory.builder().namespace("stormdruid")
// .connectString("localhost:2181").retryPolicy(new RetryNTimes(1, 1000)).connectionTimeoutMs(5000)
// .build();
//
// curatorFramework.start();
//
// if (curatorFramework.checkExists().forPath(COMPLETED_PATH) == null) {
// curatorFramework.create().forPath(COMPLETED_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(CURRENT_PATH) == null) {
// curatorFramework.create().forPath(CURRENT_PATH);
// }
//
// if (curatorFramework.checkExists().forPath(LIMBO_PATH) == null) {
// curatorFramework.create().forPath(LIMBO_PATH);
// }
// } catch (Exception e) {
// LOG.error("Could not establish conneciton to Zookeeper", e);
// }
// }
//
// public boolean isCompleted(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(COMPLETED_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInLimbo(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(LIMBO_PATH + "/" + partitionId) != null);
// }
//
// public boolean isInProgress(String partitionId) throws Exception {
// return (curatorFramework.checkExists().forPath(CURRENT_PATH + "/" + partitionId) != null);
// }
//
// public void putInProgress(String partitionId) throws Exception {
// curatorFramework.create().forPath(CURRENT_PATH + "/" + partitionId);
// }
//
// public void putInLimbo(String partitionId) throws Exception {
// curatorFramework.inTransaction().
// delete().forPath(CURRENT_PATH + "/" + partitionId)
// .and().create().forPath(LIMBO_PATH + "/" + partitionId).and().commit();
// }
//
// public void complete(List<String> partitionIds) throws Exception {
// Iterator<String> iterator = partitionIds.iterator();
// CuratorTransaction transaction = curatorFramework.inTransaction();
// while (iterator.hasNext()) {
// String partitionId = iterator.next();
// transaction = transaction.delete().forPath(LIMBO_PATH + "/" + partitionId)
// .and().create().forPath(COMPLETED_PATH + "/" + partitionId).and();
// }
// CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
// tx.commit();
// }
// }
// Path: Chapter07/src/main/java/com/packtpub/druid/firehose/StormFirehose.java
import com.google.common.collect.Maps;
import com.metamx.druid.input.InputRow;
import com.metamx.druid.input.MapBasedInputRow;
import com.metamx.druid.realtime.firehose.Firehose;
import com.packtpub.storm.model.FixMessageDto;
import com.packtpub.storm.trident.state.DruidPartitionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
package com.packtpub.druid.firehose;
public class StormFirehose implements Firehose {
private static final Logger LOG = LoggerFactory.getLogger(StormFirehose.class);
private static final Object START = new Object();
private static final Object FINISHED = new Object();
private static BlockingQueue<FixMessageDto> BLOCKING_QUEUE; | public static final DruidPartitionStatus STATUS = new DruidPartitionStatus(); |
ncalderon/oca-java8-guide | Practice/Chapter 5/Animal.java | // Path: Practice/Chapter 5/pkg/Lion.java
// public class Lion {
//
// }
| import pkg.Lion; |
class Animal {
public static void main (String ... args) {
System.out.println("Testing"); | // Path: Practice/Chapter 5/pkg/Lion.java
// public class Lion {
//
// }
// Path: Practice/Chapter 5/Animal.java
import pkg.Lion;
class Animal {
public static void main (String ... args) {
System.out.println("Testing"); | Lion lion2 = new Lion(); |
Lyneira/MachinaCraft | MachinaFactory/src/me/lyneira/MachinaFactory/PipelineNode.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
| package me.lyneira.MachinaFactory;
/**
* A node in a {@link Pipeline}.
*
* @author Lyneira
*/
class PipelineNode {
/**
* Points back towards the start of the pipeline.
*/
final PipelineNode previous;
final BlockLocation location;
final Material type;
final int distance;
/**
* Constructs a new root PipelineNode from the given location.
*
* @param location
*/
PipelineNode(BlockLocation location) {
this.previous = null;
this.location = location;
type = location.getType();
distance = 0;
}
/**
* Constructs a new PipelineNode for the given location, with the given previous node.
* @param previous
* @param location
* @param type
*/
PipelineNode(PipelineNode previous, BlockLocation location, Material type) {
this.previous = previous;
this.location = location;
this.type = type;
distance = previous.distance + 1;
}
/**
* Returns a list of neighbors for this node.
* @param material
* @return
*/
List<PipelineNode> neighbors(Material material) {
List<PipelineNode> neighbors = new ArrayList<PipelineNode>(4);
| // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
// Path: MachinaFactory/src/me/lyneira/MachinaFactory/PipelineNode.java
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
package me.lyneira.MachinaFactory;
/**
* A node in a {@link Pipeline}.
*
* @author Lyneira
*/
class PipelineNode {
/**
* Points back towards the start of the pipeline.
*/
final PipelineNode previous;
final BlockLocation location;
final Material type;
final int distance;
/**
* Constructs a new root PipelineNode from the given location.
*
* @param location
*/
PipelineNode(BlockLocation location) {
this.previous = null;
this.location = location;
type = location.getType();
distance = 0;
}
/**
* Constructs a new PipelineNode for the given location, with the given previous node.
* @param previous
* @param location
* @param type
*/
PipelineNode(PipelineNode previous, BlockLocation location, Material type) {
this.previous = previous;
this.location = location;
this.type = type;
distance = previous.distance + 1;
}
/**
* Returns a list of neighbors for this node.
* @param material
* @return
*/
List<PipelineNode> neighbors(Material material) {
List<PipelineNode> neighbors = new ArrayList<PipelineNode>(4);
| for (BlockRotation i : BlockRotation.values()) {
|
Lyneira/MachinaCraft | MachinaFactory/src/me/lyneira/ItemRelay/FurnaceRelay.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.MachinaFactory.ComponentActivateException;
import me.lyneira.MachinaFactory.ComponentDetectException;
import me.lyneira.MachinaFactory.FurnaceEndpoint;
import me.lyneira.MachinaFactory.PacketHandler;
import me.lyneira.MachinaFactory.PacketListener;
import me.lyneira.MachinaFactory.PacketTypeUnsupportedException;
import me.lyneira.MachinaFactory.PipelineEndpoint;
import me.lyneira.MachinaFactory.PipelineException;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Furnace;
import org.bukkit.entity.Player;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
| package me.lyneira.ItemRelay;
public class FurnaceRelay extends ItemRelay {
private final List<FurnaceEndpoint> furnaces = new ArrayList<FurnaceEndpoint>(7);
| // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
// Path: MachinaFactory/src/me/lyneira/ItemRelay/FurnaceRelay.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.MachinaFactory.ComponentActivateException;
import me.lyneira.MachinaFactory.ComponentDetectException;
import me.lyneira.MachinaFactory.FurnaceEndpoint;
import me.lyneira.MachinaFactory.PacketHandler;
import me.lyneira.MachinaFactory.PacketListener;
import me.lyneira.MachinaFactory.PacketTypeUnsupportedException;
import me.lyneira.MachinaFactory.PipelineEndpoint;
import me.lyneira.MachinaFactory.PipelineException;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Furnace;
import org.bukkit.entity.Player;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
package me.lyneira.ItemRelay;
public class FurnaceRelay extends ItemRelay {
private final List<FurnaceEndpoint> furnaces = new ArrayList<FurnaceEndpoint>(7);
| FurnaceRelay(Blueprint blueprint, BlockLocation anchor, BlockRotation yaw, Player player) throws ComponentActivateException, ComponentDetectException {
|
Lyneira/MachinaCraft | HoverPad/src/me/lyneira/HoverPad/HoverPad.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
| import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Lever;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.HeartBeatEvent;
import me.lyneira.MachinaCore.Movable;
import me.lyneira.MachinaCore.MovableBlueprint;
import me.lyneira.MachinaCore.block.BlockRotation;
| package me.lyneira.HoverPad;
/**
* HoverPad operation class
*
* @author Lyneira
* @author Nividica
*/
class HoverPad extends Movable {
/**
* The number of server ticks to wait for a move action.
*/
private static final int baseMoveDelay = 8;
private static final int halfMoveDelay = baseMoveDelay / 2;
private int moveDelay = baseMoveDelay;
// Constructor
| // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
// Path: HoverPad/src/me/lyneira/HoverPad/HoverPad.java
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Lever;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.HeartBeatEvent;
import me.lyneira.MachinaCore.Movable;
import me.lyneira.MachinaCore.MovableBlueprint;
import me.lyneira.MachinaCore.block.BlockRotation;
package me.lyneira.HoverPad;
/**
* HoverPad operation class
*
* @author Lyneira
* @author Nividica
*/
class HoverPad extends Movable {
/**
* The number of server ticks to wait for a move action.
*/
private static final int baseMoveDelay = 8;
private static final int halfMoveDelay = baseMoveDelay / 2;
private int moveDelay = baseMoveDelay;
// Constructor
| HoverPad(MovableBlueprint blueprint, List<Integer> moduleIndices, BlockRotation yaw, Player player) {
|
Lyneira/MachinaCraft | MachinaBuilder/src/me/lyneira/MachinaBuilder/BridgeBuilder.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
| import java.util.List;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.BlueprintBlock;
import me.lyneira.MachinaCore.HeartBeatEvent;
import me.lyneira.MachinaCore.Movable;
import me.lyneira.MachinaCore.MovableBlueprint;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.util.InventoryManager;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
| package me.lyneira.MachinaBuilder;
/**
* Builder with a movable head piece that can build bridges.
*
* @author Lyneira
*/
public class BridgeBuilder extends Builder {
private static final int headMoveDelay = 5;
private final State retractState = new Retract();
private final State buildState = new Build();
private final MovableHead head;
private final int width;
private final int height;
private int offset;
private final int[][] typeMatrix;
private final byte[][] dataMatrix;
| // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
// Path: MachinaBuilder/src/me/lyneira/MachinaBuilder/BridgeBuilder.java
import java.util.List;
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.BlueprintBlock;
import me.lyneira.MachinaCore.HeartBeatEvent;
import me.lyneira.MachinaCore.Movable;
import me.lyneira.MachinaCore.MovableBlueprint;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.util.InventoryManager;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
package me.lyneira.MachinaBuilder;
/**
* Builder with a movable head piece that can build bridges.
*
* @author Lyneira
*/
public class BridgeBuilder extends Builder {
private static final int headMoveDelay = 5;
private final State retractState = new Retract();
private final State buildState = new Build();
private final MovableHead head;
private final int width;
private final int height;
private int offset;
private final int[][] typeMatrix;
private final byte[][] dataMatrix;
| BridgeBuilder(Blueprint blueprint, List<Integer> modules, BlockRotation yaw, Player player, BlockLocation anchor, List<Integer> headModules, List<BlueprintBlock> heads, int offset) {
|
Lyneira/MachinaCraft | MachinaCore/src/me/lyneira/MachinaCore/BlockData.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import me.lyneira.MachinaCore.plugin.MPConfig;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
| this.hasInventory = value;
return this;
}
private final BlockData attached(boolean value) {
this.attached = value;
return this;
}
private static final BlockData set(final int typeId) {
if (typeId >= blockId.length || typeId < 0)
return null;
if (blockId[typeId] == null)
blockId[typeId] = new BlockData();
return blockId[typeId];
}
static final void loadBlockConfiguration(ConfigurationSection configuration) {
if (configuration == null)
return;
Map<String, Object> blockSections = configuration.getValues(false);
for (String configItem : blockSections.keySet()) {
BlockData data;
if (configuration.isList(configItem)) {
if (configItem.equals("drill-block")) {
for (String s : configuration.getStringList(configItem)) {
| // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
// Path: MachinaCore/src/me/lyneira/MachinaCore/BlockData.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import me.lyneira.MachinaCore.plugin.MPConfig;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
this.hasInventory = value;
return this;
}
private final BlockData attached(boolean value) {
this.attached = value;
return this;
}
private static final BlockData set(final int typeId) {
if (typeId >= blockId.length || typeId < 0)
return null;
if (blockId[typeId] == null)
blockId[typeId] = new BlockData();
return blockId[typeId];
}
static final void loadBlockConfiguration(ConfigurationSection configuration) {
if (configuration == null)
return;
Map<String, Object> blockSections = configuration.getValues(false);
for (String configItem : blockSections.keySet()) {
BlockData data;
if (configuration.isList(configItem)) {
if (configItem.equals("drill-block")) {
for (String s : configuration.getStringList(configItem)) {
| int typeId = MPConfig.parseTypeId(s, -1);
|
Lyneira/MachinaCraft | MachinaCore/src/me/lyneira/MachinaCore/MachinaCoreListener.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
//
// Path: MachinaCore/src/me/lyneira/MachinaCore/tool/ToolInteractResult.java
// public enum ToolInteractResult {
// FAILURE,
// SUCCESS_DAMAGE,
// SUCCESS_NODAMAGE,
// }
| import me.lyneira.MachinaCore.plugin.MPConfig;
import me.lyneira.MachinaCore.tool.ToolInteractResult;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.ItemStack;
| package me.lyneira.MachinaCore;
/**
* Listener for Bukkit events.
*
* @author Lyneira
*/
public class MachinaCoreListener implements Listener {
private final MachinaCore plugin;
private final int wrenchId;
private final int tinkerToolId;
MachinaCoreListener(MachinaCore plugin) {
this.plugin = plugin;
| // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
//
// Path: MachinaCore/src/me/lyneira/MachinaCore/tool/ToolInteractResult.java
// public enum ToolInteractResult {
// FAILURE,
// SUCCESS_DAMAGE,
// SUCCESS_NODAMAGE,
// }
// Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCoreListener.java
import me.lyneira.MachinaCore.plugin.MPConfig;
import me.lyneira.MachinaCore.tool.ToolInteractResult;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.ItemStack;
package me.lyneira.MachinaCore;
/**
* Listener for Bukkit events.
*
* @author Lyneira
*/
public class MachinaCoreListener implements Listener {
private final MachinaCore plugin;
private final int wrenchId;
private final int tinkerToolId;
MachinaCoreListener(MachinaCore plugin) {
this.plugin = plugin;
| MPConfig config = plugin.mpGetConfig();
|
Lyneira/MachinaCraft | MachinaCore/src/me/lyneira/MachinaCore/MachinaCoreListener.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
//
// Path: MachinaCore/src/me/lyneira/MachinaCore/tool/ToolInteractResult.java
// public enum ToolInteractResult {
// FAILURE,
// SUCCESS_DAMAGE,
// SUCCESS_NODAMAGE,
// }
| import me.lyneira.MachinaCore.plugin.MPConfig;
import me.lyneira.MachinaCore.tool.ToolInteractResult;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.ItemStack;
| package me.lyneira.MachinaCore;
/**
* Listener for Bukkit events.
*
* @author Lyneira
*/
public class MachinaCoreListener implements Listener {
private final MachinaCore plugin;
private final int wrenchId;
private final int tinkerToolId;
MachinaCoreListener(MachinaCore plugin) {
this.plugin = plugin;
MPConfig config = plugin.mpGetConfig();
wrenchId = config.getPathTypeId("machina-wrench", Material.WOOD_AXE.getId());
tinkerToolId = config.getPathTypeId("machina-tinkertool", Material.WOOD_HOE.getId());
plugin.logInfo("Using id " + wrenchId + " as wrench tool.");
plugin.logInfo("Using id " + tinkerToolId + " as tinkering tool.");
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
ItemStack item = event.getItem();
if (item == null)
return;
int typeId = item.getTypeId();
| // Path: MachinaCore/src/me/lyneira/MachinaCore/plugin/MPConfig.java
// public class MPConfig {
//
// private final MachinaCraftPlugin plugin;
// public final FileConfiguration config;
//
// MPConfig(MachinaCraftPlugin plugin, FileConfiguration config) {
// this.plugin = plugin;
// this.config = config;
// }
//
// /**
// * Returns the typeId specified by the given config path. Will match either an integer or a material enum name.
// * @param path The config path to get
// * @param defaultValue The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public int getPathTypeId(String path, int defaultValue) {
// if (config.isInt(path)) {
// return config.getInt(path);
// } else if (config.isString(path)) {
// Material material = Material.matchMaterial(config.getString(path));
// if (material != null) {
// return material.getId();
// }
// }
// plugin.logWarning("Config option '" + path + "' was not a valid material id, loading default value " + defaultValue);
// return defaultValue;
// }
//
// /**
// * Returns the typeId specified by the given string. Will match either an integer or a material enum name.
// * @param configItem The string to parse
// * @param The default value to return if a typeId could not be matched.
// * @return A type id
// */
// public static int parseTypeId(String stringType, int defaultValue) {
// try {
// return Integer.parseInt(stringType);
// } catch (NumberFormatException e) {
// }
// Material material = Material.matchMaterial(stringType);
// if (material != null) {
// return material.getId();
// }
// return defaultValue;
// }
// }
//
// Path: MachinaCore/src/me/lyneira/MachinaCore/tool/ToolInteractResult.java
// public enum ToolInteractResult {
// FAILURE,
// SUCCESS_DAMAGE,
// SUCCESS_NODAMAGE,
// }
// Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCoreListener.java
import me.lyneira.MachinaCore.plugin.MPConfig;
import me.lyneira.MachinaCore.tool.ToolInteractResult;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.ItemStack;
package me.lyneira.MachinaCore;
/**
* Listener for Bukkit events.
*
* @author Lyneira
*/
public class MachinaCoreListener implements Listener {
private final MachinaCore plugin;
private final int wrenchId;
private final int tinkerToolId;
MachinaCoreListener(MachinaCore plugin) {
this.plugin = plugin;
MPConfig config = plugin.mpGetConfig();
wrenchId = config.getPathTypeId("machina-wrench", Material.WOOD_AXE.getId());
tinkerToolId = config.getPathTypeId("machina-tinkertool", Material.WOOD_HOE.getId());
plugin.logInfo("Using id " + wrenchId + " as wrench tool.");
plugin.logInfo("Using id " + tinkerToolId + " as tinkering tool.");
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
ItemStack item = event.getItem();
if (item == null)
return;
int typeId = item.getTypeId();
| ToolInteractResult result = ToolInteractResult.FAILURE;
|
Lyneira/MachinaCraft | MachinaPump/src/me/lyneira/MachinaPump/MachinaPump.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
| import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
| package me.lyneira.MachinaPump;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class MachinaPump extends JavaPlugin {
final static Logger log = Logger.getLogger("Minecraft");
| // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
// Path: MachinaPump/src/me/lyneira/MachinaPump/MachinaPump.java
import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
package me.lyneira.MachinaPump;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class MachinaPump extends JavaPlugin {
final static Logger log = Logger.getLogger("Minecraft");
| private MachinaCore machinaCore;
|
Lyneira/MachinaCraft | MachinaPlanter/src/me/lyneira/MachinaPlanter/MachinaPlanter.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
| import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
| package me.lyneira.MachinaPlanter;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class MachinaPlanter extends JavaPlugin {
private final static Logger log = Logger.getLogger("Minecraft");
| // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
// Path: MachinaPlanter/src/me/lyneira/MachinaPlanter/MachinaPlanter.java
import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
package me.lyneira.MachinaPlanter;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class MachinaPlanter extends JavaPlugin {
private final static Logger log = Logger.getLogger("Minecraft");
| private MachinaCore machinaCore;
|
Lyneira/MachinaCraft | MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
| import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.MachinaFactory.ComponentActivateException;
import me.lyneira.MachinaFactory.ComponentDetectException;
import me.lyneira.util.InventoryTransaction;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
| package me.lyneira.ItemRelay;
/**
* Item Relay with a dispenser as container. Will also suck in items near it on
* each tick.
*
* @author Lyneira
*/
public class DispenserRelay extends ItemRelay {
private static final double suctionDistance = 3;
| // Path: MachinaCore/src/me/lyneira/MachinaCore/block/BlockRotation.java
// public enum BlockRotation {
// ROTATE_0, ROTATE_90, ROTATE_180, ROTATE_270;
//
// private final static BlockFace[] yawFace = { BlockFace.SOUTH, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST };
// private final static BlockVector[] yawVector = { new BlockVector(yawFace[0]), new BlockVector(yawFace[1]), new BlockVector(yawFace[2]), new BlockVector(yawFace[3]) };
// private final static byte[] yawData = { 0x5, 0x2, 0x4, 0x3 };
// private final static BlockRotation[] byOrdinal = BlockRotation.values();
//
//
// /**
// * Returns the opposite rotation.
// */
// public final BlockRotation getOpposite() {
// return byOrdinal[(this.ordinal() + 2) % 4];
// }
//
// /**
// * Returns the rotation left of this one.
// */
// public final BlockRotation getLeft() {
// return byOrdinal[(this.ordinal() + 1) % 4];
// }
//
// /**
// * Returns the rotation right of this one.
// */
// public final BlockRotation getRight() {
// return byOrdinal[(this.ordinal() + 3) % 4];
// }
//
// /**
// * Adds the given {@link BlockRotation} to this one and returns the result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation add(final BlockRotation other) {
// return byOrdinal[(this.ordinal() + other.ordinal()) % 4];
// }
//
// /**
// * Subtracts the given {@link BlockRotation} from this one and returns the
// * result.
// *
// * @param other
// * The rotation to add.
// * @return The new rotation
// */
// public final BlockRotation subtract(final BlockRotation other) {
// return byOrdinal[(this.ordinal() - other.ordinal() + 4) % 4];
// }
//
// /**
// * Converts a BlockRotation into a BlockFace in the XZ plane.
// *
// * @return The BlockFace corresponding to this rotation.
// */
// public final BlockFace getYawFace() {
// return yawFace[this.ordinal()];
// }
//
// /**
// * Converts a BlockRotation into a BlockVector in the XZ plane.
// *
// * @return The BlockVector corresponding to this rotation.
// */
// public final BlockVector getYawVector() {
// return yawVector[this.ordinal()];
// }
//
// /**
// * Returns the proper data value to set the direction of a Wall Sign, Furnace, Dispenser or Chest.
// *
// * @return
// */
// public final byte getYawData() {
// return yawData[this.ordinal()];
// }
//
// /**
// * Converts the yaw from a float-based {@link Location} to a BlockRotation
// *
// * @param yaw
// * @return
// */
// public static final BlockRotation yawFromLocation(Location location) {
// // Normalize yaw (which can be negative) to an integer between 0 and 360 (exclusive).
// int yaw = ((int)location.getYaw() % 360 + 360) % 360;
// if (yaw < 45) {
// // WEST
// return ROTATE_270;
// } else if (yaw < 135) {
// // NORTH
// return ROTATE_180;
// } else if (yaw < 225) {
// // EAST
// return ROTATE_90;
// } else if (yaw < 315) {
// // SOUTH
// return ROTATE_0;
// } else {
// // WEST
// return ROTATE_270;
// }
// }
//
// public static final BlockRotation yawFromBlockFace(BlockFace face) throws Exception {
// switch(face) {
// case SOUTH:
// return ROTATE_0;
// case EAST:
// return ROTATE_90;
// case NORTH:
// return ROTATE_180;
// case WEST:
// return ROTATE_270;
// default:
// throw new Exception("Invalid BlockFace given to yawFromBlockFace, must be one of: SOUTH, EAST, NORTH, WEST");
// }
// }
// }
// Path: MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java
import me.lyneira.MachinaCore.BlockLocation;
import me.lyneira.MachinaCore.block.BlockRotation;
import me.lyneira.MachinaFactory.ComponentActivateException;
import me.lyneira.MachinaFactory.ComponentDetectException;
import me.lyneira.util.InventoryTransaction;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
package me.lyneira.ItemRelay;
/**
* Item Relay with a dispenser as container. Will also suck in items near it on
* each tick.
*
* @author Lyneira
*/
public class DispenserRelay extends ItemRelay {
private static final double suctionDistance = 3;
| DispenserRelay(Blueprint blueprint, BlockLocation anchor, BlockRotation yaw, Player player) throws ComponentActivateException, ComponentDetectException {
|
Lyneira/MachinaCraft | HoverPad/src/me/lyneira/HoverPad/HoverPadPlugin.java | // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
| import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
| package me.lyneira.HoverPad;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class HoverPadPlugin extends JavaPlugin {
final static Logger log = Logger.getLogger("Minecraft");
| // Path: MachinaCore/src/me/lyneira/MachinaCore/MachinaCore.java
// public final class MachinaCore extends MachinaCraftPlugin {
// private static MachinaCore plugin;
// private static BukkitScheduler scheduler;
// // private static PluginManager pluginManager;
//
// private final BlueprintStore blueprints = new BlueprintStore();
// final Multiverse multiverse = new Multiverse();
//
//
// @Override
// public void onEnable() {
// super.onEnable();
// // Call super.onEnable first.
//
// plugin = this;
// scheduler = getServer().getScheduler();
//
// // Set listener
// getServer().getPluginManager().registerEvents(new MachinaCoreListener(this), this);
//
// // Initialize the currently loaded worlds
// for (World world : getServer().getWorlds()) {
// multiverse.load(world);
// }
// }
//
// @Override
// public void onDisable() {
// blueprints.clear();
// HandlerList.unregisterAll(this);
//
// // Call super.onDisable last.
// super.onDisable();
// }
//
// /**
// * Initiates actions for when the wrench is used: machina detection, status
// * info, removal.
// *
// * @param player
// * The player who activated the wrench
// * @param block
// * The block the wrench was used on
// * @return DAMAGE if the wrench should be damaged
// */
// public ToolInteractResult wrenchClick(Player player, Block block, boolean rightClick) {
// final BlockVector location = new BlockVector(block);
// final Universe universe = multiverse.get(block.getWorld());
// Machina machina = universe.get(location);
// if (rightClick) {
// if (machina != null) {
// machina.callEvent(new StatusEvent(player));
// } else {
// for (MachinaBlueprint blueprint : blueprints.blueprints()) {
//
// switch (blueprint.detect(universe, block, player)) {
// case SUCCESS:
// return ToolInteractResult.SUCCESS_DAMAGE;
// case COLLISION:
// return ToolInteractResult.SUCCESS_NODAMAGE;
// case FAILURE:
// }
// }
// }
// } else {
// if (machina != null) {
// // TODO Make it a destroy event rather than instant removal
// universe.remove(machina);
// return ToolInteractResult.SUCCESS_NODAMAGE;
// }
// }
// return ToolInteractResult.FAILURE;
// }
//
// public void registerDetectors(MachinaPlugin plugin, List<MachinaDetector> detectorList) {
// MachinaBlueprint[] blueprintArray = new MachinaBlueprint[detectorList.size()];
// int i = 0;
// for (MachinaDetector detector : detectorList) {
// final MachinaBlueprint blueprint = detector.getBlueprint();
// if (blueprint == null) {
// logSevere("Detector registration for " + plugin.getName() + " encountered a null blueprint, not continuing!");
// return;
// }
// MachinaBlueprint.machinaCoreFriend.setDetector(blueprint, detector);
// blueprintArray[i++] = blueprint;
// }
// blueprints.put(plugin, blueprintArray);
// }
//
// public void unregisterDetectors(MachinaPlugin plugin) {
// blueprints.remove(plugin);
// }
//
// /* **************
// * Static methods
// */
//
// /**
// * Schedules a runnable task to occur after the specified number of server ticks
// * @param task
// * @param delay
// * @return A BukkitTask with the task id
// */
// public final static BukkitTask runTask(Runnable task, long delay) {
// return scheduler.runTaskLater(plugin, task, delay);
// }
//
// /**
// * Send an informational message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void info(String message) {
// plugin.logInfo(message);
// }
//
// /**
// * Send a warning message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void warning(String message) {
// plugin.logWarning(message);
// }
//
// /**
// * Send a severe message to the server log.
// *
// * @param message
// * Message to send
// */
// public final static void severe(String message) {
// plugin.logSevere(message);
// }
//
// /**
// * Send a severe message and an exception to the server log.
// *
// * @param message
// * Message to send
// * @param ex
// * Exception to send
// */
// public final static void exception(String message, Throwable ex) {
// plugin.logException(message, ex);
// }
//
// public static abstract class MachinaBlueprintFriend {
// protected abstract void setDetector(MachinaBlueprint blueprint, MachinaDetector detector);
// }
// }
// Path: HoverPad/src/me/lyneira/HoverPad/HoverPadPlugin.java
import java.util.logging.Logger;
import me.lyneira.MachinaCore.ConfigurationManager;
import me.lyneira.MachinaCore.MachinaCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
package me.lyneira.HoverPad;
/**
* Main Plugin.
*
* @author Lyneira
*/
public class HoverPadPlugin extends JavaPlugin {
final static Logger log = Logger.getLogger("Minecraft");
| private MachinaCore machinaCore;
|
ybakos/proclipsing | proclipsing.core/src/proclipsing/processingprovider/ProcessingLibrary.java | // Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
| import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import proclipsing.os.OS;
import proclipsing.util.LogHelper; | package proclipsing.processingprovider;
public class ProcessingLibrary {
private String identifier;
private String processing_path;
public ProcessingLibrary(String processingPath, String identifier) {
this.identifier = identifier;
this.processing_path = processingPath;
}
public String getIdentifier() {
return identifier;
}
/**
* Gets urls to all the library files (.jar, .zip, .dll, .so)
*
* @return
*/
public URL[] getUrls(boolean isContributed) {
File realPath = new File(getResourcePath(isContributed));
if (!isContributed && !isCore() && !realPath.exists()) { | // Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
// Path: proclipsing.core/src/proclipsing/processingprovider/ProcessingLibrary.java
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import proclipsing.os.OS;
import proclipsing.util.LogHelper;
package proclipsing.processingprovider;
public class ProcessingLibrary {
private String identifier;
private String processing_path;
public ProcessingLibrary(String processingPath, String identifier) {
this.identifier = identifier;
this.processing_path = processingPath;
}
public String getIdentifier() {
return identifier;
}
/**
* Gets urls to all the library files (.jar, .zip, .dll, .so)
*
* @return
*/
public URL[] getUrls(boolean isContributed) {
File realPath = new File(getResourcePath(isContributed));
if (!isContributed && !isCore() && !realPath.exists()) { | realPath = new File(processing_path + OS.helper().getPathToP2Library(identifier)); |
ybakos/proclipsing | proclipsing.core/src/proclipsing/processingprovider/ProcessingLibrary.java | // Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
| import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import proclipsing.os.OS;
import proclipsing.util.LogHelper; | "macosx64",
"opengl.jar",
// "windows32",
"windows64"};
public static final String pluginsDir = "plugins";
private URL[] getUrls(File[] files) {
ArrayList<URL> urls = new ArrayList<URL>();
ArrayList<URL> nativeLibs = new ArrayList<URL>();
for(File file : files) {
if (file.isDirectory()){
boolean isNativeLib = false;
for(String nativeLibDir: newNativeLibDirs){
isNativeLib = isNativeLib || file.getAbsolutePath().endsWith(nativeLibDir);
}
if(isNativeLib){
for(File nativeLib: file.listFiles()){
try{
if(nativeLib.isDirectory() && nativeLib.getAbsolutePath().contains(pluginsDir)){
for(File plugin: nativeLib.listFiles()){
System.out.println(plugin.getAbsolutePath());
nativeLibs.add(plugin.toURI().toURL());
}
nativeLibs.add(nativeLib.toURI().toURL());
}
nativeLibs.add(nativeLib.toURI().toURL());
} catch (MalformedURLException e) { | // Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
// Path: proclipsing.core/src/proclipsing/processingprovider/ProcessingLibrary.java
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import proclipsing.os.OS;
import proclipsing.util.LogHelper;
"macosx64",
"opengl.jar",
// "windows32",
"windows64"};
public static final String pluginsDir = "plugins";
private URL[] getUrls(File[] files) {
ArrayList<URL> urls = new ArrayList<URL>();
ArrayList<URL> nativeLibs = new ArrayList<URL>();
for(File file : files) {
if (file.isDirectory()){
boolean isNativeLib = false;
for(String nativeLibDir: newNativeLibDirs){
isNativeLib = isNativeLib || file.getAbsolutePath().endsWith(nativeLibDir);
}
if(isNativeLib){
for(File nativeLib: file.listFiles()){
try{
if(nativeLib.isDirectory() && nativeLib.getAbsolutePath().contains(pluginsDir)){
for(File plugin: nativeLib.listFiles()){
System.out.println(plugin.getAbsolutePath());
nativeLibs.add(plugin.toURI().toURL());
}
nativeLibs.add(nativeLib.toURI().toURL());
}
nativeLibs.add(nativeLib.toURI().toURL());
} catch (MalformedURLException e) { | LogHelper.LogError(e); |
ybakos/proclipsing | proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
//
// Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import proclipsing.core.Activator;
import proclipsing.os.OS; | String appPath, String sketchPath,
List<String> baselibs, List<String> userlibs) {
this.name = name;
this.app_path = appPath;
this.sketch_path = sketchPath;
this.baselibs = baselibs;
this.userlibs = userlibs;
}
public List<String> getBaselibs() {
return baselibs;
}
public List<String> getUserlibs() {
return userlibs;
}
public String getName() {
return name;
}
public String getSketchPath() {
return sketch_path;
}
public String getAppPath() {
return app_path;
}
private static String getDefaultAppPath() { | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
//
// Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
// Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import proclipsing.core.Activator;
import proclipsing.os.OS;
String appPath, String sketchPath,
List<String> baselibs, List<String> userlibs) {
this.name = name;
this.app_path = appPath;
this.sketch_path = sketchPath;
this.baselibs = baselibs;
this.userlibs = userlibs;
}
public List<String> getBaselibs() {
return baselibs;
}
public List<String> getUserlibs() {
return userlibs;
}
public String getName() {
return name;
}
public String getSketchPath() {
return sketch_path;
}
public String getAppPath() {
return app_path;
}
private static String getDefaultAppPath() { | return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get( |
ybakos/proclipsing | proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
//
// Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import proclipsing.core.Activator;
import proclipsing.os.OS; | List<String> baselibs, List<String> userlibs) {
this.name = name;
this.app_path = appPath;
this.sketch_path = sketchPath;
this.baselibs = baselibs;
this.userlibs = userlibs;
}
public List<String> getBaselibs() {
return baselibs;
}
public List<String> getUserlibs() {
return userlibs;
}
public String getName() {
return name;
}
public String getSketchPath() {
return sketch_path;
}
public String getAppPath() {
return app_path;
}
private static String getDefaultAppPath() {
return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get( | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
//
// Path: proclipsing.core/src/proclipsing/os/OS.java
// public class OS {
//
// private static OSHelper helper;
//
// /**
// * Get a platform specific version of OSHelper
// * Keep the instance around and re-use it after it's created
// *
// * @return
// */
// public static synchronized OSHelper helper() {
// if (helper == null) {
// synchronized (OSHelper.class) {
// if (helper == null)
// helper = createHelper();
// }
// }
// return helper;
// }
//
// private static OSHelper createHelper() {
// if (isWindows())
// return new WindowsOSHelper();
// if (isMac())
// return new MacOSHelper();
// if (isLinux())
// return new LinuxOSHelper();
//
// throw new RuntimeException(
// "Your Platform " + System.getProperty("os.name") + " is not supported.");
// }
//
// private static boolean isWindows() {
// return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
// }
//
// private static boolean isMac() {
// return System.getProperty("os.name").toLowerCase().indexOf("mac") > -1;
// }
//
// private static boolean isLinux () {
// return System.getProperty("os.name").toLowerCase().indexOf("linux") > -1;
// }
// }
// Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import proclipsing.core.Activator;
import proclipsing.os.OS;
List<String> baselibs, List<String> userlibs) {
this.name = name;
this.app_path = appPath;
this.sketch_path = sketchPath;
this.baselibs = baselibs;
this.userlibs = userlibs;
}
public List<String> getBaselibs() {
return baselibs;
}
public List<String> getUserlibs() {
return userlibs;
}
public String getName() {
return name;
}
public String getSketchPath() {
return sketch_path;
}
public String getAppPath() {
return app_path;
}
private static String getDefaultAppPath() {
return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get( | APP_PATH_KEY, OS.helper().getDefaultAppPath()); |
ybakos/proclipsing | proclipsing.core/src/proclipsing/util/LogHelper.java | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
| import org.eclipse.core.runtime.Status;
import proclipsing.core.Activator; | package proclipsing.util;
/**
* Real simple abstraction for logging until I can figure out how to do it
* the right way
*
* @author brian
*
*/
public class LogHelper {
/**
* Still need to figure out how to hook into debug level in eclipse
*
* @return
*/
private static boolean isDebug() { return true; }
/**
* Log an error.
* This will print the stack trace if in debug mode.
*
* @param e
* @param message
*/
public static void LogError(Exception e) {
LogError(e, e.getMessage());
}
/**
* Log an error.
* This will print the stack trace if in debug mode.
*
* @param e
* @param message
*/
public static void LogError(Exception e, String message) { | // Path: proclipsing.core/src/proclipsing/core/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "proclipsing.core";
//
// // The shared instance
// private static Activator plugin;
//
// public static final String PROJECT_DECORATOR = "icons/project_decorator.png";
//
// /**
// * The constructor
// */
// public Activator() {
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static Activator getDefault() {
// return plugin;
// }
//
// @Override
// protected void initializeImageRegistry(ImageRegistry reg) {
// super.initializeImageRegistry(reg);
// reg.put(PROJECT_DECORATOR, imageDescriptorFromPlugin(PLUGIN_ID, PROJECT_DECORATOR));
// }
// }
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
import org.eclipse.core.runtime.Status;
import proclipsing.core.Activator;
package proclipsing.util;
/**
* Real simple abstraction for logging until I can figure out how to do it
* the right way
*
* @author brian
*
*/
public class LogHelper {
/**
* Still need to figure out how to hook into debug level in eclipse
*
* @return
*/
private static boolean isDebug() { return true; }
/**
* Log an error.
* This will print the stack trace if in debug mode.
*
* @param e
* @param message
*/
public static void LogError(Exception e) {
LogError(e, e.getMessage());
}
/**
* Log an error.
* This will print the stack trace if in debug mode.
*
* @param e
* @param message
*/
public static void LogError(Exception e, String message) { | Activator.getDefault().getLog().log( |
ybakos/proclipsing | proclipsing.core/src/proclipsing/core/createproject/NewProcessingProjectWizard.java | // Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
// public class ProjectPreferences {
//
// public static final String PROJECT_PREFS_NODE = "PROJECT_PREFS_NODE";
// public static final String APP_PATH_KEY = "PROCESSING_APP_PATH";
// public static final String SKETCH_PATH_KEY = "PROCESSING_SKETCH_PATH";
// public static final String BIN_DIR = "bin";
// public static final String SRC_DIR = "src";
// public static final String DATA_DIR = "data";
// public static final String BASELIB_DIR = "lib/base";
// public static final String USERLIB_DIR = "lib/user";
//
// //private List<String> libraries;
// private List<String> baselibs;
// private List<String> userlibs;
// private String name;
// private String app_path;
// private String sketch_path;
//
//
// public ProjectPreferences() {
// this(null, getDefaultAppPath(), getDefaultSketchPath(),
// new ArrayList<String>(), new ArrayList<String>());
// }
//
// public ProjectPreferences(ProjectPreferences prefs) {
// this(prefs.getName(), prefs.getAppPath(), prefs.getSketchPath(),
// new ArrayList<String>(prefs.getBaselibs()),
// new ArrayList<String>(prefs.getUserlibs()));
// }
//
// public ProjectPreferences(String name,
// String appPath, String sketchPath,
// List<String> baselibs, List<String> userlibs) {
// this.name = name;
// this.app_path = appPath;
// this.sketch_path = sketchPath;
// this.baselibs = baselibs;
// this.userlibs = userlibs;
// }
//
// public List<String> getBaselibs() {
// return baselibs;
// }
//
// public List<String> getUserlibs() {
// return userlibs;
// }
//
// public String getName() {
// return name;
// }
//
// public String getSketchPath() {
// return sketch_path;
// }
//
// public String getAppPath() {
// return app_path;
// }
//
// private static String getDefaultAppPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// APP_PATH_KEY, OS.helper().getDefaultAppPath());
// }
//
// private static String getDefaultSketchPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// SKETCH_PATH_KEY, OS.helper().getDefaultSketchPath());
//
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
| import java.util.ArrayList;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import proclipsing.core.preferences.ProjectPreferences;
import proclipsing.util.LogHelper; | package proclipsing.core.createproject;
public class NewProcessingProjectWizard extends Wizard implements INewWizard {
private NewProcessingProjectPage1 page1; | // Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
// public class ProjectPreferences {
//
// public static final String PROJECT_PREFS_NODE = "PROJECT_PREFS_NODE";
// public static final String APP_PATH_KEY = "PROCESSING_APP_PATH";
// public static final String SKETCH_PATH_KEY = "PROCESSING_SKETCH_PATH";
// public static final String BIN_DIR = "bin";
// public static final String SRC_DIR = "src";
// public static final String DATA_DIR = "data";
// public static final String BASELIB_DIR = "lib/base";
// public static final String USERLIB_DIR = "lib/user";
//
// //private List<String> libraries;
// private List<String> baselibs;
// private List<String> userlibs;
// private String name;
// private String app_path;
// private String sketch_path;
//
//
// public ProjectPreferences() {
// this(null, getDefaultAppPath(), getDefaultSketchPath(),
// new ArrayList<String>(), new ArrayList<String>());
// }
//
// public ProjectPreferences(ProjectPreferences prefs) {
// this(prefs.getName(), prefs.getAppPath(), prefs.getSketchPath(),
// new ArrayList<String>(prefs.getBaselibs()),
// new ArrayList<String>(prefs.getUserlibs()));
// }
//
// public ProjectPreferences(String name,
// String appPath, String sketchPath,
// List<String> baselibs, List<String> userlibs) {
// this.name = name;
// this.app_path = appPath;
// this.sketch_path = sketchPath;
// this.baselibs = baselibs;
// this.userlibs = userlibs;
// }
//
// public List<String> getBaselibs() {
// return baselibs;
// }
//
// public List<String> getUserlibs() {
// return userlibs;
// }
//
// public String getName() {
// return name;
// }
//
// public String getSketchPath() {
// return sketch_path;
// }
//
// public String getAppPath() {
// return app_path;
// }
//
// private static String getDefaultAppPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// APP_PATH_KEY, OS.helper().getDefaultAppPath());
// }
//
// private static String getDefaultSketchPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// SKETCH_PATH_KEY, OS.helper().getDefaultSketchPath());
//
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
// Path: proclipsing.core/src/proclipsing/core/createproject/NewProcessingProjectWizard.java
import java.util.ArrayList;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import proclipsing.core.preferences.ProjectPreferences;
import proclipsing.util.LogHelper;
package proclipsing.core.createproject;
public class NewProcessingProjectWizard extends Wizard implements INewWizard {
private NewProcessingProjectPage1 page1; | private ProjectPreferences preferences; |
ybakos/proclipsing | proclipsing.core/src/proclipsing/core/createproject/NewProcessingProjectWizard.java | // Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
// public class ProjectPreferences {
//
// public static final String PROJECT_PREFS_NODE = "PROJECT_PREFS_NODE";
// public static final String APP_PATH_KEY = "PROCESSING_APP_PATH";
// public static final String SKETCH_PATH_KEY = "PROCESSING_SKETCH_PATH";
// public static final String BIN_DIR = "bin";
// public static final String SRC_DIR = "src";
// public static final String DATA_DIR = "data";
// public static final String BASELIB_DIR = "lib/base";
// public static final String USERLIB_DIR = "lib/user";
//
// //private List<String> libraries;
// private List<String> baselibs;
// private List<String> userlibs;
// private String name;
// private String app_path;
// private String sketch_path;
//
//
// public ProjectPreferences() {
// this(null, getDefaultAppPath(), getDefaultSketchPath(),
// new ArrayList<String>(), new ArrayList<String>());
// }
//
// public ProjectPreferences(ProjectPreferences prefs) {
// this(prefs.getName(), prefs.getAppPath(), prefs.getSketchPath(),
// new ArrayList<String>(prefs.getBaselibs()),
// new ArrayList<String>(prefs.getUserlibs()));
// }
//
// public ProjectPreferences(String name,
// String appPath, String sketchPath,
// List<String> baselibs, List<String> userlibs) {
// this.name = name;
// this.app_path = appPath;
// this.sketch_path = sketchPath;
// this.baselibs = baselibs;
// this.userlibs = userlibs;
// }
//
// public List<String> getBaselibs() {
// return baselibs;
// }
//
// public List<String> getUserlibs() {
// return userlibs;
// }
//
// public String getName() {
// return name;
// }
//
// public String getSketchPath() {
// return sketch_path;
// }
//
// public String getAppPath() {
// return app_path;
// }
//
// private static String getDefaultAppPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// APP_PATH_KEY, OS.helper().getDefaultAppPath());
// }
//
// private static String getDefaultSketchPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// SKETCH_PATH_KEY, OS.helper().getDefaultSketchPath());
//
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
| import java.util.ArrayList;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import proclipsing.core.preferences.ProjectPreferences;
import proclipsing.util.LogHelper; | package proclipsing.core.createproject;
public class NewProcessingProjectWizard extends Wizard implements INewWizard {
private NewProcessingProjectPage1 page1;
private ProjectPreferences preferences;
private boolean isApp;
@Override
public boolean performFinish() {
IRunnableWithProgress job = new CreateProcessingProjectJob(preferences, isApp);
try {
getContainer().run(false, false, job);
} catch (Exception e) { | // Path: proclipsing.core/src/proclipsing/core/preferences/ProjectPreferences.java
// public class ProjectPreferences {
//
// public static final String PROJECT_PREFS_NODE = "PROJECT_PREFS_NODE";
// public static final String APP_PATH_KEY = "PROCESSING_APP_PATH";
// public static final String SKETCH_PATH_KEY = "PROCESSING_SKETCH_PATH";
// public static final String BIN_DIR = "bin";
// public static final String SRC_DIR = "src";
// public static final String DATA_DIR = "data";
// public static final String BASELIB_DIR = "lib/base";
// public static final String USERLIB_DIR = "lib/user";
//
// //private List<String> libraries;
// private List<String> baselibs;
// private List<String> userlibs;
// private String name;
// private String app_path;
// private String sketch_path;
//
//
// public ProjectPreferences() {
// this(null, getDefaultAppPath(), getDefaultSketchPath(),
// new ArrayList<String>(), new ArrayList<String>());
// }
//
// public ProjectPreferences(ProjectPreferences prefs) {
// this(prefs.getName(), prefs.getAppPath(), prefs.getSketchPath(),
// new ArrayList<String>(prefs.getBaselibs()),
// new ArrayList<String>(prefs.getUserlibs()));
// }
//
// public ProjectPreferences(String name,
// String appPath, String sketchPath,
// List<String> baselibs, List<String> userlibs) {
// this.name = name;
// this.app_path = appPath;
// this.sketch_path = sketchPath;
// this.baselibs = baselibs;
// this.userlibs = userlibs;
// }
//
// public List<String> getBaselibs() {
// return baselibs;
// }
//
// public List<String> getUserlibs() {
// return userlibs;
// }
//
// public String getName() {
// return name;
// }
//
// public String getSketchPath() {
// return sketch_path;
// }
//
// public String getAppPath() {
// return app_path;
// }
//
// private static String getDefaultAppPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// APP_PATH_KEY, OS.helper().getDefaultAppPath());
// }
//
// private static String getDefaultSketchPath() {
// return new ConfigurationScope().getNode(Activator.PLUGIN_ID).get(
// SKETCH_PATH_KEY, OS.helper().getDefaultSketchPath());
//
// }
// }
//
// Path: proclipsing.core/src/proclipsing/util/LogHelper.java
// public class LogHelper {
//
// /**
// * Still need to figure out how to hook into debug level in eclipse
// *
// * @return
// */
// private static boolean isDebug() { return true; }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e) {
// LogError(e, e.getMessage());
// }
//
// /**
// * Log an error.
// * This will print the stack trace if in debug mode.
// *
// * @param e
// * @param message
// */
// public static void LogError(Exception e, String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.ERROR, Activator.PLUGIN_ID, 0, message, e));
// if (isDebug()) e.printStackTrace();
// }
//
// /**
// * Log info.
// * This will print the message if in debug mode
// *
// * @param message
// */
// public static void LogInfo(String message) {
// Activator.getDefault().getLog().log(
// new Status(Status.INFO, Activator.PLUGIN_ID, message));
// if (isDebug()) System.out.println("[INFO] " + message);
// }
// }
// Path: proclipsing.core/src/proclipsing/core/createproject/NewProcessingProjectWizard.java
import java.util.ArrayList;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import proclipsing.core.preferences.ProjectPreferences;
import proclipsing.util.LogHelper;
package proclipsing.core.createproject;
public class NewProcessingProjectWizard extends Wizard implements INewWizard {
private NewProcessingProjectPage1 page1;
private ProjectPreferences preferences;
private boolean isApp;
@Override
public boolean performFinish() {
IRunnableWithProgress job = new CreateProcessingProjectJob(preferences, isApp);
try {
getContainer().run(false, false, job);
} catch (Exception e) { | LogHelper.LogError(e); |
suspend0/java-properties | src/ca/hullabaloo/properties/CglibPropertyImpl.java | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
| import net.sf.cglib.proxy.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import static ca.hullabaloo.properties.Utils.checkArgument; | package ca.hullabaloo.properties;
/**
* Implements a class based on a properties file using <b>cglib</b> to generate the bytecode.
*
* @see #create
*/
class CglibPropertyImpl<T> {
public static <T> T create(Class<T> type, Resolver props, Converter converter) {
validateType(type);
return new CglibPropertyImpl<T>(type, props, converter).createInstance();
}
private static <T> void validateType(Class<T> type) {
if (!Modifier.isPublic(type.getModifiers()) || Modifier.isFinal(type.getModifiers())) {
throw JavaPropertiesException.nonPublicOrFinalClass(type);
}
if (type.getEnclosingClass() != null && !Modifier.isStatic(type.getModifiers())) {
throw JavaPropertiesException.nonStaticInnerClass(type);
}
}
private final Class<T> type;
private final Resolver props;
private final Converter converter;
private CglibPropertyImpl(Class<T> type, Resolver props, Converter converter) {
this.props = props;
this.type = type;
this.converter = converter;
}
private T createInstance() {
JavaPropertiesException.Builder errors = JavaPropertiesException.builder();
// see potentialMethods(), but basically we don't support subtypes because
// validating that the types we construct involves walking the class tree
// looking for methods which might override the methods we're concerned about
// and that is super hard and better left to compiler writers. Simple is the key. | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
// Path: src/ca/hullabaloo/properties/CglibPropertyImpl.java
import net.sf.cglib.proxy.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import static ca.hullabaloo.properties.Utils.checkArgument;
package ca.hullabaloo.properties;
/**
* Implements a class based on a properties file using <b>cglib</b> to generate the bytecode.
*
* @see #create
*/
class CglibPropertyImpl<T> {
public static <T> T create(Class<T> type, Resolver props, Converter converter) {
validateType(type);
return new CglibPropertyImpl<T>(type, props, converter).createInstance();
}
private static <T> void validateType(Class<T> type) {
if (!Modifier.isPublic(type.getModifiers()) || Modifier.isFinal(type.getModifiers())) {
throw JavaPropertiesException.nonPublicOrFinalClass(type);
}
if (type.getEnclosingClass() != null && !Modifier.isStatic(type.getModifiers())) {
throw JavaPropertiesException.nonStaticInnerClass(type);
}
}
private final Class<T> type;
private final Resolver props;
private final Converter converter;
private CglibPropertyImpl(Class<T> type, Resolver props, Converter converter) {
this.props = props;
this.type = type;
this.converter = converter;
}
private T createInstance() {
JavaPropertiesException.Builder errors = JavaPropertiesException.builder();
// see potentialMethods(), but basically we don't support subtypes because
// validating that the types we construct involves walking the class tree
// looking for methods which might override the methods we're concerned about
// and that is super hard and better left to compiler writers. Simple is the key. | checkArgument(type.getSuperclass() == Object.class || type.isInterface()); |
suspend0/java-properties | test/ca/hullabaloo/properties/JavaPropertiesTest.java | // Path: test/ca/hullabaloo/properties/TestSupport.java
// public static <T> T bind(Class<T> type, String... keyValuePairs) {
// Properties p = props(keyValuePairs);
// return bind(type, p);
// }
| import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Properties;
import static ca.hullabaloo.properties.TestSupport.bind; | package ca.hullabaloo.properties;
@Test()
public class JavaPropertiesTest {
@Test(dataProvider = TestTypes.HAS_DEFAULT, dataProviderClass = TestTypes.class)
public void testDefault(Class<? extends Foo> type) { | // Path: test/ca/hullabaloo/properties/TestSupport.java
// public static <T> T bind(Class<T> type, String... keyValuePairs) {
// Properties p = props(keyValuePairs);
// return bind(type, p);
// }
// Path: test/ca/hullabaloo/properties/JavaPropertiesTest.java
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Properties;
import static ca.hullabaloo.properties.TestSupport.bind;
package ca.hullabaloo.properties;
@Test()
public class JavaPropertiesTest {
@Test(dataProvider = TestTypes.HAS_DEFAULT, dataProviderClass = TestTypes.class)
public void testDefault(Class<? extends Foo> type) { | Foo instance = bind(type); |
suspend0/java-properties | src/ca/hullabaloo/properties/EnumConverter.java | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
| import static ca.hullabaloo.properties.Utils.checkArgument; | package ca.hullabaloo.properties;
/**
* Converts an enum type from its string name to the enum value
*/
enum EnumConverter implements Converter {
INSTANCE;
@Override public boolean supportsTarget(Class<?> type) {
return type.isEnum();
}
@Override @SuppressWarnings({"unchecked"})
public <T> T convert(String s, Class<T> targetType) { | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
// Path: src/ca/hullabaloo/properties/EnumConverter.java
import static ca.hullabaloo.properties.Utils.checkArgument;
package ca.hullabaloo.properties;
/**
* Converts an enum type from its string name to the enum value
*/
enum EnumConverter implements Converter {
INSTANCE;
@Override public boolean supportsTarget(Class<?> type) {
return type.isEnum();
}
@Override @SuppressWarnings({"unchecked"})
public <T> T convert(String s, Class<T> targetType) { | checkArgument(supportsTarget(targetType)); |
suspend0/java-properties | src/ca/hullabaloo/properties/ArrayConverter.java | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: src/ca/hullabaloo/properties/Utils.java
// public static String q(String str) {
// return "'" + str + "'";
// }
| import java.lang.reflect.Array;
import static ca.hullabaloo.properties.Utils.checkArgument;
import static ca.hullabaloo.properties.Utils.q; | package ca.hullabaloo.properties;
/**
* Wraps a regular {@Converter} to parse arrays of same from strings formatted the way
* {@link java.util.Arrays#toString} writes them: [a,b]
*
* @see #wrap(Converter)
*/
class ArrayConverter implements Converter {
public static ArrayConverter wrap(Converter componentConverter) {
return new ArrayConverter(componentConverter);
}
private final Converter componentConverter;
private ArrayConverter(Converter componentConverter) {
if (componentConverter == null) {
throw new NullPointerException();
}
this.componentConverter = componentConverter;
}
@Override public boolean supportsTarget(Class<?> type) {
return type.isArray() && componentConverter.supportsTarget(type.getComponentType());
}
@Override public <T> T convert(String s, Class<T> arrayType) { | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: src/ca/hullabaloo/properties/Utils.java
// public static String q(String str) {
// return "'" + str + "'";
// }
// Path: src/ca/hullabaloo/properties/ArrayConverter.java
import java.lang.reflect.Array;
import static ca.hullabaloo.properties.Utils.checkArgument;
import static ca.hullabaloo.properties.Utils.q;
package ca.hullabaloo.properties;
/**
* Wraps a regular {@Converter} to parse arrays of same from strings formatted the way
* {@link java.util.Arrays#toString} writes them: [a,b]
*
* @see #wrap(Converter)
*/
class ArrayConverter implements Converter {
public static ArrayConverter wrap(Converter componentConverter) {
return new ArrayConverter(componentConverter);
}
private final Converter componentConverter;
private ArrayConverter(Converter componentConverter) {
if (componentConverter == null) {
throw new NullPointerException();
}
this.componentConverter = componentConverter;
}
@Override public boolean supportsTarget(Class<?> type) {
return type.isArray() && componentConverter.supportsTarget(type.getComponentType());
}
@Override public <T> T convert(String s, Class<T> arrayType) { | checkArgument(supportsTarget(arrayType)); |
suspend0/java-properties | src/ca/hullabaloo/properties/ArrayConverter.java | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: src/ca/hullabaloo/properties/Utils.java
// public static String q(String str) {
// return "'" + str + "'";
// }
| import java.lang.reflect.Array;
import static ca.hullabaloo.properties.Utils.checkArgument;
import static ca.hullabaloo.properties.Utils.q; | String[] parts = str.split(COMMA);
int partCount = parts.length;
// get rid of any whitespace
for (int i = 0; i < parts.length; i++) {
parts[i] = parts[i].trim();
}
// reassemble strings split on backslash-escaped commas
for (int i = 0, j = 1; j < parts.length; j++) {
if (parts[i].endsWith("\\")) {
parts[i] = parts[i].substring(0, parts[i].length() - 1);
parts[i] += COMMA + parts[j];
parts[j] = null;
--partCount;
} else {
i = j;
}
}
// Convert each component piece
Object result = Array.newInstance(componentType, partCount);
for (int i = 0, j = 0; i < parts.length; i++) {
if (parts[i] != null) {
Object value = componentConverter.convert(parts[i], componentType);
Array.set(result, j++, value);
}
}
return arrayType.cast(result);
} | // Path: src/ca/hullabaloo/properties/Utils.java
// static void checkArgument(boolean b) {
// if (!b) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: src/ca/hullabaloo/properties/Utils.java
// public static String q(String str) {
// return "'" + str + "'";
// }
// Path: src/ca/hullabaloo/properties/ArrayConverter.java
import java.lang.reflect.Array;
import static ca.hullabaloo.properties.Utils.checkArgument;
import static ca.hullabaloo.properties.Utils.q;
String[] parts = str.split(COMMA);
int partCount = parts.length;
// get rid of any whitespace
for (int i = 0; i < parts.length; i++) {
parts[i] = parts[i].trim();
}
// reassemble strings split on backslash-escaped commas
for (int i = 0, j = 1; j < parts.length; j++) {
if (parts[i].endsWith("\\")) {
parts[i] = parts[i].substring(0, parts[i].length() - 1);
parts[i] += COMMA + parts[j];
parts[j] = null;
--partCount;
} else {
i = j;
}
}
// Convert each component piece
Object result = Array.newInstance(componentType, partCount);
for (int i = 0, j = 0; i < parts.length; i++) {
if (parts[i] != null) {
Object value = componentConverter.convert(parts[i], componentType);
Array.set(result, j++, value);
}
}
return arrayType.cast(result);
} | throw new IllegalArgumentException("Expected array format like [a,b] got " + q(str)); |
azeckoski/lti_starter | src/test/java/ltistarter/lti/LTITests.java | // Path: src/test/java/ltistarter/BaseApplicationTest.java
// @SpringApplicationConfiguration(classes = Application.class)
// @WebAppConfiguration
// @ActiveProfiles("testing") // make the active profile "testing"
// public abstract class BaseApplicationTest {
//
// @Autowired
// @SuppressWarnings("SpringJavaAutowiredMembersInspection")
// public ApplicationConfig applicationConfig;
//
// @Autowired
// @SuppressWarnings("SpringJavaAutowiredMembersInspection")
// public ConfigurableWebApplicationContext context;
//
// @PostConstruct
// public void init() {
// applicationConfig.getEnvironment().setActiveProfiles("testing");
// }
//
// @Test
// public void checkSpring() {
// assertNotNull(context);
// assertNotNull(applicationConfig);
// assertTrue(applicationConfig.getEnvironment().acceptsProfiles("testing"));
// }
//
// /**
// * Makes a new session which contains authentication roles,
// * this allows us to test requests with varying types of security
// *
// * @param username the username to set for the session
// * @param roles all the roles to grant for this session
// * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session))
// */
// public MockHttpSession makeAuthSession(String username, String... roles) {
// if (StringUtils.isEmpty(username)) {
// username = "azeckoski";
// }
// MockHttpSession session = new MockHttpSession();
// session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
// Collection<GrantedAuthority> authorities = new HashSet<>();
// if (roles != null && roles.length > 0) {
// for (String role : roles) {
// authorities.add(new SimpleGrantedAuthority(role));
// }
// }
// //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal
// Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities,
// "key", "signature", "HMAC-SHA-1", "signaturebase", "token");
// Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities);
// SecurityContextHolder.getContext().setAuthentication(authToken);
// return session;
// }
//
// }
| import ltistarter.BaseApplicationTest;
import ltistarter.model.*;
import ltistarter.repository.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.*; | /**
* Copyright 2014 Unicon (R)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ltistarter.lti;
@SuppressWarnings({"UnusedAssignment", "SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"})
@RunWith(SpringJUnit4ClassRunner.class) | // Path: src/test/java/ltistarter/BaseApplicationTest.java
// @SpringApplicationConfiguration(classes = Application.class)
// @WebAppConfiguration
// @ActiveProfiles("testing") // make the active profile "testing"
// public abstract class BaseApplicationTest {
//
// @Autowired
// @SuppressWarnings("SpringJavaAutowiredMembersInspection")
// public ApplicationConfig applicationConfig;
//
// @Autowired
// @SuppressWarnings("SpringJavaAutowiredMembersInspection")
// public ConfigurableWebApplicationContext context;
//
// @PostConstruct
// public void init() {
// applicationConfig.getEnvironment().setActiveProfiles("testing");
// }
//
// @Test
// public void checkSpring() {
// assertNotNull(context);
// assertNotNull(applicationConfig);
// assertTrue(applicationConfig.getEnvironment().acceptsProfiles("testing"));
// }
//
// /**
// * Makes a new session which contains authentication roles,
// * this allows us to test requests with varying types of security
// *
// * @param username the username to set for the session
// * @param roles all the roles to grant for this session
// * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session))
// */
// public MockHttpSession makeAuthSession(String username, String... roles) {
// if (StringUtils.isEmpty(username)) {
// username = "azeckoski";
// }
// MockHttpSession session = new MockHttpSession();
// session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
// Collection<GrantedAuthority> authorities = new HashSet<>();
// if (roles != null && roles.length > 0) {
// for (String role : roles) {
// authorities.add(new SimpleGrantedAuthority(role));
// }
// }
// //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal
// Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities,
// "key", "signature", "HMAC-SHA-1", "signaturebase", "token");
// Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities);
// SecurityContextHolder.getContext().setAuthentication(authToken);
// return session;
// }
//
// }
// Path: src/test/java/ltistarter/lti/LTITests.java
import ltistarter.BaseApplicationTest;
import ltistarter.model.*;
import ltistarter.repository.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.*;
/**
* Copyright 2014 Unicon (R)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ltistarter.lti;
@SuppressWarnings({"UnusedAssignment", "SpringJavaAutowiredMembersInspection", "SpringJavaAutowiringInspection"})
@RunWith(SpringJUnit4ClassRunner.class) | public class LTITests extends BaseApplicationTest { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.