answer stringlengths 17 10.2M |
|---|
package com.b2international.snowowl.snomed.api.impl.validation.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.ihtsdo.drools.domain.Concept;
import org.ihtsdo.drools.domain.Relationship;
import org.ihtsdo.drools.service.ConceptService;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.snomed.SnomedConstants.Concepts;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.domain.SnomedConcepts;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
public class ValidationConceptService implements ConceptService {
private final String branchPath;
private final IEventBus bus;
public ValidationConceptService(String branchPath, IEventBus bus) {
this.branchPath = branchPath;
this.bus = bus;
}
@Override
public boolean isActive(String conceptId) {
return SnomedRequests.prepareGetConcept(conceptId)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(bus)
.getSync()
.isActive();
}
@Override
public Set<String> findStatedAncestorsOfConcept(Concept concept) {
return Collections.emptySet();
}
@Override
public Set<String> findTopLevelHierachiesOfConcept(Concept concept) {
// Can not perform ECL on the Concept because it may not be saved
// Gather the stated parents and use those in ECL
List<String> statedParents = new ArrayList<>(concept.getRelationships().stream()
.filter(r -> Concepts.STATED_RELATIONSHIP.equals(r.getCharacteristicTypeId()) && Concepts.IS_A.equals(r.getTypeId()))
.map(Relationship::getDestinationId).collect(Collectors.toSet()));
if (statedParents.isEmpty()) {
return Collections.emptySet();
}
// Direct descendant of root
String ecl = "<!" + Concepts.ROOT_CONCEPT + " AND ";
if (statedParents.size() > 1) {
// We need to open brackets only if more than one parent
ecl += "(";
}
for (int a = 0; a < statedParents.size(); a++) {
if (a > 0) {
ecl += " AND ";
}
// Ancestor and self of stated parent
ecl += ">>" + statedParents.get(a);
}
if (statedParents.size() > 1) {
ecl += ")";
}
SnomedConcepts concepts = SnomedRequests.prepareSearchConcept()
.filterByEcl(ecl)
.filterByActive(true)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(bus)
.getSync();
return concepts.getItems().stream().map(SnomedConcept::getId).collect(Collectors.toSet());
}
@Override
public Set<String> getAllTopLevelHierachies() {
SnomedConcepts concepts = SnomedRequests.prepareSearchConcept()
.filterByEcl("<!" + Concepts.ROOT_CONCEPT)
.filterByActive(true)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(bus)
.getSync();
return concepts.getItems().stream().map(SnomedConcept::getId).collect(Collectors.toSet());
}
} |
package org.eclipse.birt.report.item.crosstab.internal.ui.editors.action;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.dialogs.DataColumnBindingDialog;
import org.eclipse.birt.report.designer.internal.ui.views.actions.AbstractViewAction;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.ComputedMeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.util.CrosstabUtil;
import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabAdaptUtil;
import org.eclipse.birt.report.item.crosstab.internal.ui.util.CrosstabUIHelper;
import org.eclipse.birt.report.item.crosstab.ui.i18n.Messages;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.metadata.DimensionValue;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.util.DimensionUtil;
import org.eclipse.birt.report.model.elements.interfaces.ICubeModel;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
public class AddRelativeTimePeriodAction extends AbstractViewAction
{
public static final String ID = "com.actuate.birt.report.designer.internal.ui.croostab.AddRelativeTimePeriodAction"; //$NON-NLS-1$
private static final double DEFAULT_COLUMN_WIDTH = 1.0;
private static final String ICON = "/icons/obj16/relativetime.gif"; //$NON-NLS-1$
private MeasureViewHandle measureViewHandle;
private CrosstabReportItemHandle reportHandle;
public AddRelativeTimePeriodAction( Object selectedObject )
{
super( selectedObject );
setId( ID );
setText( Messages.getString("AddRelativeTimePeriodAction_action_label") ); //$NON-NLS-1$
Image image = CrosstabUIHelper.getImage( CrosstabUIHelper.ADD_RELATIVETIMEPERIOD );
setImageDescriptor( ImageDescriptor.createFromImage( image ) );
}
public void run( )
{
if(measureViewHandle != null)
{
reportHandle = measureViewHandle.getCrosstab( );
}
reportHandle.getModuleHandle( ).getCommandStack( ).startTrans( Messages.getString("AddRelativeTimePeriodAction_trans_label") ); //$NON-NLS-1$
// AddRelativeTimePeriodDialog computedSummaryDialog = new AddRelativeTimePeriodDialog(UIUtil.getDefaultShell( ), "Add Relative TimeP eriod");
// computedSummaryDialog.setBindingHolder( (ReportItemHandle)reportHandle.getModelHandle( ) );
// String measureName = "TempName";
DataColumnBindingDialog dialog = new DataColumnBindingDialog( true );
dialog.setInput( (ReportItemHandle)reportHandle.getModelHandle( ) );
dialog.setAggreate( true );
dialog.setTimePeriod( true );
if(dialog.open( ) == Dialog.OK)
{
int index = caleIndex( );
try
{
ComputedColumnHandle bindingHandle = dialog.getBindingColumn( );
ComputedMeasureViewHandle computedMeasure = reportHandle.insertComputedMeasure( bindingHandle.getName( ), index );
computedMeasure.addHeader( );
ExtendedItemHandle crosstabModelHandle = (ExtendedItemHandle) reportHandle.getModelHandle( );
if (bindingHandle == null)
{
reportHandle.getModuleHandle( ).getCommandStack( ).rollbackAll( );
return;
}
DataItemHandle dataHandle = DesignElementFactory.getInstance( )
.newDataItem( bindingHandle.getName( ) );
CrosstabAdaptUtil.formatDataItem( computedMeasure.getCubeMeasure( ), dataHandle );
dataHandle.setResultSetColumn( bindingHandle.getName( ) );
AggregationCellHandle cell = computedMeasure.getCell( );
//There must a set a value to the column
if (ICrosstabConstants.MEASURE_DIRECTION_HORIZONTAL.equals( reportHandle.getMeasureDirection( ) ))
{
CrosstabCellHandle cellHandle = computedMeasure.getHeader( );
if (cellHandle == null)
{
cellHandle = cell;
}
String defaultUnit = reportHandle.getModelHandle( ).getModuleHandle( ).getDefaultUnits( );
// DimensionValue dimensionValue = DimensionUtil.convertTo( DEFAULT_COLUMN_WIDTH, DesignChoiceConstants.UNITS_IN, defaultUnit );
// reportHandle.setColumnWidth( cellHandle,
// dimensionValue );
}
cell.addContent( dataHandle );
}
catch ( SemanticException e )
{
reportHandle.getModuleHandle( ).getCommandStack( ).rollbackAll( );
}
}
reportHandle.getModuleHandle( ).getCommandStack( ).commit( );
}
@Override
public boolean isEnabled( )
{
Object selection = getSelection( );
if ( selection == null || !(selection instanceof DesignElementHandle))
{
return false;
}
ExtendedItemHandle extendedHandle = CrosstabAdaptUtil.getExtendedItemHandle( (DesignElementHandle)selection );
if (extendedHandle == null)
{
return false;
}
if (extendedHandle.getExtensionName( ).equals( "Crosstab" ))
{
try
{
reportHandle = (CrosstabReportItemHandle)extendedHandle.getReportItem( );
}
catch ( ExtendedElementException e )
{
return false;
}
}
else
{
measureViewHandle = CrosstabAdaptUtil.getMeasureViewHandle( extendedHandle );
if ( measureViewHandle == null )
{
return false;
}
reportHandle = measureViewHandle.getCrosstab( );
}
if (DEUtil.isReferenceElement( reportHandle.getCrosstabHandle( ) ))
{
return false;
}
if( CrosstabUtil.isBoundToLinkedDataSet( reportHandle) )
{
for( int i = 0; i < reportHandle.getDimensionCount(ICrosstabConstants.ROW_AXIS_TYPE); i++ )
{
DimensionHandle dimension = reportHandle.getDimension(ICrosstabConstants.ROW_AXIS_TYPE, i).getCubeDimension();
if( dimension.isTimeType() )
{
return true;
}
}
for( int i = 0; i < reportHandle.getDimensionCount(ICrosstabConstants.COLUMN_AXIS_TYPE); i++ )
{
DimensionHandle dimension = reportHandle.getDimension(ICrosstabConstants.COLUMN_AXIS_TYPE, i).getCubeDimension();
if( dimension.isTimeType() )
{
return true;
}
}
return false;
}
CubeHandle cube = reportHandle.getCube( );
if (cube == null)
{
return false;
}
if (cube.getPropertyHandle( ICubeModel.DIMENSIONS_PROP ) == null)
{
return false;
}
List list = cube.getContents( ICubeModel.DIMENSIONS_PROP );
for (int i=0; i<list.size( ); i++)
{
DimensionHandle dimension = (DimensionHandle)list.get( i );
if (CrosstabAdaptUtil.isTimeDimension(dimension))
{
DimensionViewHandle viewHandle = reportHandle.getDimension(dimension.getName());
if (viewHandle == null)
{
int count = dimension.getDefaultHierarchy().getLevelCount();
if (count == 0)
{
continue;
}
LevelHandle levelHandle = dimension.getDefaultHierarchy().getLevel(0);
if (DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR
.equals(levelHandle.getDateTimeLevelType()))
{
return true;
}
}
else
{
int count = viewHandle.getLevelCount();
if (count == 0)
{
continue;
}
LevelViewHandle levelViewHandle = viewHandle.getLevel(0);
if (DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR
.equals(levelViewHandle.getCubeLevel().getDateTimeLevelType()))
{
return true;
}
}
}
}
return false;
}
private int caleIndex()
{
if (measureViewHandle != null)
{
return reportHandle.getAllMeasures().indexOf( measureViewHandle ) + 1;
}
else
{
return reportHandle.getAllMeasures().size( );
}
}
} |
package org.deviceconnect.android.deviceplugin.host.recorder.camera;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.SurfaceTexture;
import android.media.Image;
import android.media.ImageReader;
import android.opengl.GLES20;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.Surface;
import com.serenegiant.glutils.EGLBase;
import com.serenegiant.glutils.EglTask;
import com.serenegiant.glutils.GLDrawer2D;
import org.deviceconnect.android.deviceplugin.host.BuildConfig;
import org.deviceconnect.android.deviceplugin.host.camera.CameraWrapperException;
import org.deviceconnect.android.deviceplugin.host.camera.CameraWrapper;
import org.deviceconnect.android.deviceplugin.host.recorder.HostDeviceRecorder;
import org.deviceconnect.android.deviceplugin.host.recorder.PreviewServer;
import org.deviceconnect.android.deviceplugin.host.recorder.util.MixedReplaceMediaServer;
import java.io.ByteArrayOutputStream;
import java.nio.IntBuffer;
class Camera2MJPEGPreviewServer implements PreviewServer {
private static final boolean DEBUG = BuildConfig.DEBUG;
private static final String TAG = "host.dplugin";
private static final String MIME_TYPE = "video/x-mjpeg";
private final Camera2Recorder mRecorder;
private final Object mLockObj = new Object();
private MixedReplaceMediaServer mServer;
private ImageReader mPreviewReader;
private HandlerThread mPreviewThread;
private Handler mPreviewHandler;
private boolean mIsRecording;
private boolean requestDraw;
private Object mSync = new Object();
private final MixedReplaceMediaServer.Callback mMediaServerCallback = new MixedReplaceMediaServer.Callback() {
@Override
public boolean onAccept() {
try {
if (DEBUG) {
Log.d(TAG, "MediaServerCallback.onAccept: recorder=" + mRecorder.getName());
}
CameraWrapper camera = mRecorder.getCameraWrapper();
mPreviewReader = camera.createPreviewReader(ImageFormat.JPEG);
mPreviewReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(final ImageReader reader) {
try {
Image image = reader.acquireNextImage();
Log.d(TAG, "onImageAvailable");
if (image == null) {
return;
}
image.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}, mPreviewHandler);
new Thread(new DrawTask()).start();
return true;
} catch (Exception e) {
Log.e(TAG, "Failed to start preview.", e);
return false;
}
}
};
private ImageReader.OnImageAvailableListener mPreviewListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(final ImageReader reader) {
try {
final Image image = reader.acquireNextImage();
if (image == null || image.getPlanes() == null) {
return;
}
byte[] jpeg = Camera2Recorder.convertToJPEG(image);
jpeg = mRecorder.rotateJPEG(jpeg, 100); // NOTE: swap width and height.
image.close();
offerMedia(jpeg);
} catch (Exception e) {
Log.e(TAG, "Failed to send preview frame.", e);
}
}
};
Camera2MJPEGPreviewServer(final Camera2Recorder recorder) {
mRecorder = recorder;
}
private void offerMedia(final byte[] jpeg) {
MixedReplaceMediaServer server = mServer;
if (server != null) {
server.offerMedia(jpeg);
}
}
@Override
public int getQuality() {
return mRecorder.getCameraWrapper().getPreviewJpegQuality();
}
@Override
public void setQuality(int quality) {
mRecorder.getCameraWrapper().setPreviewJpegQuality(quality);
}
@Override
public String getMimeType() {
return MIME_TYPE;
}
@Override
public void startWebServer(final OnWebServerStartCallback callback) {
synchronized (mLockObj) {
if (mIsRecording) {
callback.onStart(mServer.getUrl());
return;
}
mIsRecording = true;
mPreviewThread = new HandlerThread("MotionJPEG");
mPreviewThread.start();
mPreviewHandler = new Handler(mPreviewThread.getLooper());
final String uri;
if (mServer == null) {
mServer = new MixedReplaceMediaServer();
mServer.setServerName("HostDevicePlugin Server");
mServer.setContentType("image/jpg");
mServer.setCallback(mMediaServerCallback);
uri = mServer.start();
} else {
uri = mServer.getUrl();
}
callback.onStart(uri);
}
}
@Override
public void stopWebServer() {
synchronized (mLockObj) {
if (!mIsRecording) {
return;
}
mIsRecording = false;
if (mServer != null) {
mServer.stop();
mServer = null;
}
CameraWrapper camera = mRecorder.getCameraWrapper();
if (camera != null) {
try {
camera.stopPreview();
} catch (CameraWrapperException e) {
Log.e(TAG, "Failed to stop preview.", e);
}
}
if (mPreviewReader != null) {
mPreviewReader.close();
mPreviewReader = null;
}
mPreviewThread.quit();
mPreviewThread = null;
mPreviewHandler = null;
mRecorder.hideNotification();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private final class DrawTask extends EglTask {
// R () B ()
// ColorMatrix Matrix
/*
* ColorMatrix ColorMatrixFilter
*
* 5x4 : [
* a, b, c, d, e,
* f, g, h, i, j,
* k, l, m, n, o,
* p, q, r, s, t
* ]
*
* RGBA :
*
* R' = a * R + b * G + c * B + d * A + e;
* G' = f * R + g * G + h * B + i * A + j;
* B' = k * R + l * G + m * B + n * A + o;
* A' = p * R + q * G + r * B + s * A + t;
*
* R () B ()
*
* R' = B => 0, 0, 1, 0, 0
* G' = G => 0, 1, 0, 0, 0
* B' = R => 1, 0, 0, 0, 0
* A' = A => 0, 0, 0, 1, 0
*/
private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
{
// R () B ()
mPaint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(new float[] {
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 0, 0, 0, 0,
0, 0, 0, 1, 0
})));
}
private long intervals;
private EGLBase.IEglSurface mEncoderSurface;
private GLDrawer2D mDrawer;
private final float[] mTexMatrix = new float[16];
private int mTexId;
private SurfaceTexture mSourceTexture;
private Surface mSourceSurface;
private HostDeviceRecorder.PictureSize mSize;
private Bitmap mBitmap;
private Canvas mCanvas;
private int[] mPixels;
private IntBuffer mPixelBuffer;
private ByteArrayOutputStream mOutput;
private int mJpegQuality;
public DrawTask() {
super(null, 0);
}
@Override
protected void onStart() {
mDrawer = new GLDrawer2D(true);
mTexId = mDrawer.initTex();
mSourceTexture = new SurfaceTexture(mTexId);
HostDeviceRecorder.PictureSize size = mRecorder.getPreviewSize();
mSize = new HostDeviceRecorder.PictureSize(size.getHeight(), size.getWidth());
mBitmap = Bitmap.createBitmap(mSize.getWidth(), mSize.getHeight(), Bitmap.Config.ARGB_8888);
final Matrix matrix = new Matrix();
matrix.postScale(1.0f, -1.0f);
matrix.postTranslate(0, mSize.getHeight());
mCanvas = new Canvas(mBitmap);
mCanvas.concat(matrix);
mPixels = new int[mSize.getWidth() * mSize.getHeight()];
mPixelBuffer = IntBuffer.wrap(mPixels);
mOutput = new ByteArrayOutputStream(mSize.getWidth() * mSize.getHeight());
mSourceTexture.setDefaultBufferSize(mSize.getWidth(), mSize.getHeight());
mSourceSurface = new Surface(mSourceTexture);
mSourceTexture.setOnFrameAvailableListener(mOnFrameAvailableListener, mPreviewHandler);
mEncoderSurface = getEgl().createOffscreen(mSize.getWidth(), mSize.getHeight()); //.createFromSurface(mPreviewReader.getSurface());
intervals = (long)(1000f / mRecorder.getMaxFrameRate());
mJpegQuality = getQuality();
try {
mRecorder.startPreview(mSourceSurface);
Log.d(TAG, "Started camera preview.");
} catch (CameraWrapperException e) {
Log.e(TAG, "Failed to start camera preview.", e);
}
queueEvent(mDrawTask);
}
@Override
protected void onStop() {
if (mDrawer != null) {
mDrawer.release();
mDrawer = null;
}
if (mSourceSurface != null) {
mSourceSurface.release();
mSourceSurface = null;
}
if (mSourceTexture != null) {
mSourceTexture.release();
mSourceTexture = null;
}
if (mEncoderSurface != null) {
mEncoderSurface.release();
mEncoderSurface = null;
}
if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
}
try {
mRecorder.stopPreview();
} catch (CameraWrapperException e) {
Log.e(TAG, "Failed to stop camera preview.", e);
}
makeCurrent();
}
@Override
protected boolean onError(final Exception e) {
Log.w(TAG, "mScreenCaptureTask:", e);
return false;
}
@Override
protected Object processRequest(final int request, final int arg1, final int arg2, final Object obj) {
return null;
}
// TextureSurface
private final SurfaceTexture.OnFrameAvailableListener mOnFrameAvailableListener = new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(final SurfaceTexture surfaceTexture) {
if (mIsRecording) {
synchronized (mSync) {
requestDraw = true;
mSync.notifyAll();
}
}
}
};
private long mLastTime = 0;
private final Runnable mDrawTask = new Runnable() {
@Override
public void run() {
boolean localRequestDraw;
synchronized (mSync) {
localRequestDraw = requestDraw;
if (!requestDraw) {
try {
mSync.wait(intervals);
localRequestDraw = requestDraw;
requestDraw = false;
} catch (final InterruptedException e) {
Log.v(TAG, "draw:InterruptedException");
return;
}
}
}
long now = System.currentTimeMillis();
long interval = intervals - (now - mLastTime);
if (interval > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
return;
}
}
mLastTime = now;
if (mIsRecording) {
if (localRequestDraw) {
mSourceTexture.updateTexImage();
mSourceTexture.getTransformMatrix(mTexMatrix);
}
// SurfaceTextureMediaCodecSurface
mEncoderSurface.makeCurrent();
mDrawer.draw(mTexId, mTexMatrix, 0);
GLES20.glFinish();
mPixelBuffer.clear();
mPixelBuffer.position(0);
GLES20.glReadPixels(0, 0, mSize.getWidth(), mSize.getHeight(), GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mPixelBuffer);
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
mCanvas.drawBitmap(mPixels, 0, mSize.getWidth(), 0, 0, mSize.getWidth(), mSize.getHeight(), false, mPaint);
mOutput.reset();
mBitmap.compress(Bitmap.CompressFormat.JPEG, mJpegQuality, mOutput);
mServer.offerMedia(mOutput.toByteArray());
queueEvent(this);
} else {
releaseSelf();
}
}
};
}
} |
package org.opendaylight.controller.cluster.datastore.modification;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.Optional;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public abstract class AbstractModificationTest {
private static SchemaContext TEST_SCHEMA_CONTEXT;
protected InMemoryDOMDataStore store;
@BeforeClass
public static void beforeClass() {
TEST_SCHEMA_CONTEXT = TestModel.createTestContext();
}
@AfterClass
public static void afterClass() {
TEST_SCHEMA_CONTEXT = null;
}
@Before
public void setUp() {
store = new InMemoryDOMDataStore("test", MoreExecutors.newDirectExecutorService());
store.onGlobalContextUpdated(TEST_SCHEMA_CONTEXT);
}
protected void commitTransaction(final DOMStoreWriteTransaction transaction) {
DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
cohort.preCommit();
cohort.commit();
}
protected Optional<NormalizedNode<?, ?>> readData(final YangInstanceIdentifier path) throws Exception {
DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
return future.get();
}
} |
package be.cegeka.batchers.taxcalculator.presentation.rest.controller;
import be.cegeka.batchers.taxcalculator.application.domain.*;
import be.cegeka.batchers.taxcalculator.presentation.rest.model.EmployeeTaxTo;
import be.cegeka.batchers.taxcalculator.to.EmployeeTo;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.integration.support.json.Jackson2JsonObjectMapper;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import static java.util.Arrays.asList;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(MockitoJUnitRunner.class)
public class EmployeeRestControllerTest {
private MockMvc mockMvc;
@InjectMocks
private EmployeeRestController employeeRestController;
@Mock
private MonthlyTaxForEmployeeRepository monthlyTaxForEmployeeRepository;
@Mock
private EmployeeService employeeServiceMock;
@Mock
private TaxCalculationRepository taxCalculationRepositoryMock;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(employeeRestController)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.build();
}
@Test
public void givenOneEmployee_whenGetEmployees_thenReturnCorrectJson() throws Exception {
Employee employee = new EmployeeTestBuilder()
.withIncome(200)
.withFirstName("firstName")
.build();
EmployeeTo employeeTo = new EmployeeTo(employee.getFirstName(), employee.getLastName(), employee.getEmail(), employee.getIncome(), Money.parse("EUR 200"), 1L);
String expectedJSON = new Jackson2JsonObjectMapper().toJson(asList(employeeTo));
when(employeeServiceMock.getEmployees(0, 10)).thenReturn(asList(employeeTo));
MvcResult mvcResult = mockMvc.perform(get("/employees?page=0&pageSize=10").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String actualJSON = mvcResult.getResponse().getContentAsString();
assertThat(actualJSON).isEqualTo(expectedJSON);
}
@Test
public void givenOneEmployee_whenGetEmployeeCount_thenReturnCorrectJson() throws Exception {
when(employeeServiceMock.getEmployeeCount()).thenReturn(1L);
MvcResult mvcResult = mockMvc.perform(get("/employees/count").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String actualResult = mvcResult.getResponse().getContentAsString();
assertThat(actualResult).isEqualTo("1");
}
@Test
public void testGetEmployeeTaxes() throws Exception {
long employeeId = 12L;
int year = 2012;
int month = 2;
Money tax = Money.of(CurrencyUnit.EUR, 10);
Employee employee = new Employee();
TaxCalculation taxCalculation = TaxCalculation.from(1L, employee, year, month, tax);
when(employeeServiceMock.getEmployee(employeeId)).thenReturn(employee);
when(employeeServiceMock.getEmployeeTaxes(employeeId)).thenReturn(asList(taxCalculation));
List<EmployeeTaxTo> employeeTaxes = employeeRestController.getEmployeeTaxes(employeeId);
assertThat(employeeTaxes).hasSize(1);
assertThat(employeeTaxes.get(0).getStatus()).isEqualTo("IN PROGRESS");
assertThat(employeeTaxes.get(0).getYear()).isEqualTo(year);
assertThat(employeeTaxes.get(0).getMonth()).isEqualTo(month);
assertThat(employeeTaxes.get(0).getTax()).isEqualTo(tax);
verify(employeeServiceMock).getEmployee(employeeId);
verify(employeeServiceMock).getEmployeeTaxes(employeeId);
verify(monthlyTaxForEmployeeRepository).find(employee, year, month);
}
} |
package edu.pitt.apollo.client.wrapper;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import edu.pitt.apollo.client.wrapper.SeirModelTestHelper;
import edu.pitt.apollo.types.EpidemicModelInput;
import edu.pitt.apollo.types.SimulationRunResult;
import edu.pitt.rods.SeirEpiModelSimulator;
import edu.pitt.rods.SimulatorService;
public class SeirModelServiceWrapper {
private static final QName SERVICE_NAME = new QName(
"http://rods.pitt.edu/", "SimulatorService");
private URL wsdlURL = null;
private String workingDirectory;
public SeirModelServiceWrapper(URL wsdlURL, String workingDirectory)
throws MalformedURLException {
this.wsdlURL = wsdlURL;
this.workingDirectory = workingDirectory;
if (!this.workingDirectory.endsWith("/")) {
this.workingDirectory += "/";
}
}
private SeirEpiModelSimulator getPort() {
SeirEpiModelSimulator port = null;
SimulatorService ss = new SimulatorService(wsdlURL, SERVICE_NAME);
port = ss.getSimulationServerPort();
return port;
}
public SimulationRunResult run(EpidemicModelInput input) {
SeirEpiModelSimulator port = getPort();
return port.run(input);
}
// public Iterator<EpidemicModelOutput> runBatch(List<EpidemicModelInput> input)
// throws IOException {
// EpidemicSimulator port = getPort();
// GsonHelper<EpidemicModelInput> gsonHelper = new GsonHelper<EpidemicModelInput>(
// EpidemicModelInput.class);
// String fn = workingDirectory + System.currentTimeMillis() + ".gz";
// FileOutputStream fos = new FileOutputStream(fn);
// GZIPOutputStream gos = new GZIPOutputStream(fos);
// gsonHelper.writeJsonStream(gos, input);
// DataSource fds = new FileDataSource(fn);
// DataHandler dataHandler = new DataHandler(fds);
// DataHandler result = port.runGzipBatch(dataHandler);
// GZIPInputStream gis = new GZIPInputStream(result.getInputStream());
// return new EpidemicModelOutputIterator(gis, "UTF-8");
public static void main(String[] args) throws Exception {
SeirModelTestHelper
.testRun(new URL(
"https://betaweb.rods.pitt.edu/SeirEpiModelService/services/seirepimodelsimulator?wsdl"));
// SeirModelTestHelper
// .testRunBatch(
// new URL(
}
} |
package yuku.alkitab.base.ac;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import yuku.afw.D;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.alkitab.base.App;
import yuku.alkitab.base.S;
import yuku.alkitab.base.U;
import yuku.alkitab.base.ac.base.BaseActivity;
import yuku.alkitab.base.dialog.LabelEditorDialog;
import yuku.alkitab.base.sync.SyncSettingsActivity;
import yuku.alkitab.base.util.BookmarkImporter;
import yuku.alkitab.debug.R;
import yuku.alkitab.model.Label;
import yuku.alkitab.model.Marker;
import yuku.ambilwarna.AmbilWarnaDialog;
import yuku.ambilwarna.AmbilWarnaDialog.OnAmbilWarnaListener;
import yuku.filechooser.FileChooserActivity;
import yuku.filechooser.FileChooserConfig;
import yuku.filechooser.FileChooserResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class MarkersActivity extends BaseActivity {
public static final String TAG = MarkersActivity.class.getSimpleName();
private static final int REQCODE_markerList = 1;
private static final int REQCODE_share = 2;
private static final int REQCODE_migrateFromV3 = 3;
/** Action to broadcast when label list needs to be reloaded due to some background changes */
public static final String ACTION_RELOAD = MarkersActivity.class.getName() + ".action.RELOAD";
DragSortListView lv;
View bGotoSync;
MarkerFilterAdapter adapter;
public static Intent createIntent() {
return new Intent(App.context, MarkersActivity.class);
}
@Override protected void onCreate(Bundle savedInstanceState) {
enableNonToolbarUpButton();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_markers);
setTitle(R.string.activity_title_markers);
adapter = new MarkerFilterAdapter();
adapter.reload();
lv = V.get(this, android.R.id.list);
lv.setDropListener(adapter);
lv.setOnItemClickListener(lv_click);
lv.setAdapter(adapter);
MarkerFilterController c = new MarkerFilterController(lv, adapter);
lv.setFloatViewManager(c);
lv.setOnTouchListener(c);
registerForContextMenu(lv);
bGotoSync = V.get(this, R.id.bGotoSync);
bGotoSync.setOnClickListener(v -> startActivity(SyncSettingsActivity.createIntent()));
App.getLbm().registerReceiver(br, new IntentFilter(ACTION_RELOAD));
}
@Override
protected void onStart() {
super.onStart();
// hide sync button if we are already syncing
final String syncAccountName = Preferences.getString(getString(R.string.pref_syncAccountName_key));
V.get(this, R.id.panelGotoSync).setVisibility(syncAccountName != null ? View.GONE : View.VISIBLE);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_markers, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final MenuItem menuLabelSort = menu.findItem(R.id.menuLabelSort);
final int labelCount = adapter.getLabelCount();
menuLabelSort.setVisible(labelCount > 1);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menuMigrateFromV3: {
final FileChooserConfig config = new FileChooserConfig();
config.mode = FileChooserConfig.Mode.Open;
config.pattern = "(yuku\\.alkitab|yuku\\.alkitab\\.kjv|org\\.sabda\\.alkitab|org\\.sabda\\.online)-(backup|autobackup-[0-9-]+)\\.xml";
config.title = getString(R.string.marker_migrate_file_chooser_title);
final Intent intent = FileChooserActivity.createIntent(this, config);
startActivityForResult(intent, REQCODE_migrateFromV3);
} return true;
case R.id.menuLabelSort:
S.getDb().sortLabelsAlphabetically();
adapter.reload();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
App.getLbm().unregisterReceiver(br);
}
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
if (ACTION_RELOAD.equals(intent.getAction())) {
adapter.reload();
}
}
};
private OnItemClickListener lv_click = new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent;
if (position == 0) {
intent = MarkerListActivity.createIntent(App.context, Marker.Kind.bookmark, 0);
} else if (position == 1) {
intent = MarkerListActivity.createIntent(App.context, Marker.Kind.note, 0);
} else if (position == 2) {
intent = MarkerListActivity.createIntent(App.context, Marker.Kind.highlight, 0);
} else if (position == 3) {
intent = MarkerListActivity.createIntent(App.context, Marker.Kind.bookmark, MarkerListActivity.LABELID_noLabel);
} else {
Label label = adapter.getItem(position);
if (label != null) {
intent = MarkerListActivity.createIntent(getApplicationContext(), Marker.Kind.bookmark, label._id);
} else {
return;
}
}
startActivityForResult(intent, REQCODE_markerList);
}
};
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position >= 4) {
getMenuInflater().inflate(R.menu.context_markers, menu);
}
}
@Override public boolean onContextItemSelected(android.view.MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int itemId = item.getItemId();
if (itemId == R.id.menuRenameLabel) {
final Label label = adapter.getItem(info.position);
if (label == null) {
return true;
}
LabelEditorDialog.show(this, label.title, getString(R.string.rename_label_title), title -> {
label.title = title;
S.getDb().insertOrUpdateLabel(label);
adapter.notifyDataSetChanged();
});
return true;
} else if (itemId == R.id.menuDeleteLabel) {
final Label label = adapter.getItem(info.position);
if (label == null) {
return true;
}
final int marker_count = S.getDb().countMarkersWithLabel(label);
if (marker_count == 0) {
// no markers, just delete straight away
S.getDb().deleteLabelAndMarker_LabelsByLabelId(label._id);
adapter.reload();
} else {
new AlertDialogWrapper.Builder(this)
.setMessage(getString(R.string.are_you_sure_you_want_to_delete_the_label_label, label.title, marker_count))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.delete, (dialog, which) -> {
S.getDb().deleteLabelAndMarker_LabelsByLabelId(label._id);
adapter.reload();
})
.show();
}
return true;
} else if (itemId == R.id.menuChangeLabelColor) {
final Label label = adapter.getItem(info.position);
if (label == null) {
return true;
}
int warnaLatarRgb = U.decodeLabelBackgroundColor(label.backgroundColor);
new AmbilWarnaDialog(MarkersActivity.this, 0xff000000 | warnaLatarRgb, new OnAmbilWarnaListener() {
@Override public void onOk(AmbilWarnaDialog dialog, int color) {
label.backgroundColor = U.encodeLabelBackgroundColor(0x00ffffff & color);
S.getDb().insertOrUpdateLabel(label);
adapter.notifyDataSetChanged();
}
@Override public void onCancel(AmbilWarnaDialog dialog) {
// nop
}
}).show();
return true;
}
return false;
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQCODE_markerList) {
adapter.reload();
return;
} else if (requestCode == REQCODE_share && resultCode == RESULT_OK) {
final ShareActivity.Result result = ShareActivity.obtainResult(data);
startActivity(result.chosenIntent);
return;
} else if (requestCode == REQCODE_migrateFromV3 && resultCode == RESULT_OK) {
final FileChooserResult result = FileChooserActivity.obtainResult(data);
if (result != null) {
final File file = new File(result.firstFilename);
try {
final FileInputStream fis = new FileInputStream(file);
BookmarkImporter.importBookmarks(this, fis, false);
adapter.reload();
} catch (IOException e) {
new AlertDialogWrapper.Builder(this)
.setMessage(R.string.marker_migrate_error_opening_backup_file)
.setPositiveButton(R.string.ok, null)
.show();
}
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
private class MarkerFilterController extends DragSortController {
int mDivPos;
int mDraggedPos;
final DragSortListView lv;
public MarkerFilterController(DragSortListView lv, MarkerFilterAdapter adapter) {
super(lv, R.id.drag_handle, DragSortController.ON_DOWN, 0);
this.lv = lv;
mDivPos = adapter.getDivPosition();
setRemoveEnabled(false);
}
@Override public int startDragPosition(MotionEvent ev) {
int res = super.dragHandleHitPosition(ev);
if (res < mDivPos) {
return DragSortController.MISS;
}
return res;
}
@Override public View onCreateFloatView(int position) {
mDraggedPos = position;
final View res = adapter.getView(position, null, lv);
res.setBackgroundColor(0x22ffffff);
return res;
}
@Override public void onDestroyFloatView(View floatView) {
// Do not call super and do not remove this override.
floatView.setBackgroundColor(0);
}
@Override public void onDragFloatView(View floatView, Point floatPoint, Point touchPoint) {
super.onDragFloatView(floatView, floatPoint, touchPoint);
final int first = lv.getFirstVisiblePosition();
final int lvDivHeight = lv.getDividerHeight();
View div = lv.getChildAt(mDivPos - first - 1);
if (div != null) {
if (mDraggedPos >= mDivPos) {
// don't allow floating View to go above section divider
final int limit = div.getBottom() + lvDivHeight;
if (floatPoint.y < limit) {
floatPoint.y = limit;
}
}
}
}
}
private class MarkerFilterAdapter extends BaseAdapter implements DragSortListView.DropListener {
// 0. [icon] All bookmarks
// 1. [icon] Notes
// 2. [icon] Highlights
// 3. Unlabeled bookmarks
// 4 and so on. labels
List<Label> labels;
private String[] presetCaptions = {
getString(R.string.bmcat_all_bookmarks),
getString(R.string.bmcat_notes),
getString(R.string.bmcat_highlights),
getString(R.string.bmcat_unlabeled_bookmarks),
};
@Override public Label getItem(int position) {
if (position < 4) return null;
return labels.get(position - 4);
}
@Override public long getItemId(int position) {
return position;
}
@Override public void drop(int from, int to) {
if (from != to) {
Label fromLabel = getItem(from);
Label toLabel = getItem(to);
if (fromLabel != null && toLabel != null) {
S.getDb().reorderLabels(fromLabel, toLabel);
adapter.reload();
}
}
}
private boolean hasLabels() {
return labels != null && labels.size() > 0;
}
@Override public int getCount() {
return 3 + (hasLabels() ? 1 + labels.size() : 0);
}
public int getDivPosition() {
return 4;
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final View res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_marker_filter, parent, false);
ImageView imgFilterIcon = V.get(res, R.id.imgFilterIcon);
if (position < 3) {
imgFilterIcon.setVisibility(View.VISIBLE);
imgFilterIcon.setImageResource(position == 0? R.drawable.ic_attr_bookmark: position == 1? R.drawable.ic_attr_note: position == 2? R.drawable.ic_attr_highlight: 0);
} else {
imgFilterIcon.setVisibility(View.GONE);
}
TextView lFilterCaption = V.get(res, R.id.lFilterCaption);
if (position < 4) {
lFilterCaption.setVisibility(View.VISIBLE);
lFilterCaption.setText(presetCaptions[position]);
} else {
lFilterCaption.setVisibility(View.GONE);
}
TextView lFilterLabel = V.get(res, R.id.lFilterLabel);
if (position < 4) {
lFilterLabel.setVisibility(View.GONE);
} else {
Label label = getItem(position);
lFilterLabel.setVisibility(View.VISIBLE);
lFilterLabel.setText(label.title);
U.applyLabelColor(label, lFilterLabel);
}
View drag_handle = V.get(res, R.id.drag_handle);
if (position < 4) {
drag_handle.setVisibility(View.GONE);
} else {
drag_handle.setVisibility(View.VISIBLE);
}
return res;
}
void reload() {
labels = S.getDb().listAllLabels();
if (D.EBUG) {
Log.d(TAG, "_id title ordering backgroundColor");
for (Label label: labels) {
Log.d(TAG, String.format("%4d %20s %8d %s", label._id, label.title, label.ordering, label.backgroundColor));
}
}
notifyDataSetChanged();
supportInvalidateOptionsMenu();
}
public int getLabelCount() {
return labels.size();
}
}
} |
//$HeadURL$
package org.deegree.feature.persistence.sql.mapper;
import java.util.Map;
import javax.xml.namespace.QName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Keeps track of {@link MappingContext}s generated during a pass of the {@link AppSchemaMapper}.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
class MappingContextManager {
private static Logger LOG = LoggerFactory.getLogger( MappingContextManager.class );
private int maxColumnLengthInChararacters;
private int id = 0;
private int count = 0;
private final Map<String, String> nsToPrefix;
private final boolean usePrefix;
/**
* @param nsToPrefix
* contains the mapping of namespaces to prefixes to create column names, may be empty but never
* <code>null</code>
* @param maxColumnLengthInChararacters
* max length of column names in characters. If -1 the default value (64) is used.
* @param usePrefix
* <code>null</code> if the column name should contain the xml prefix, <code>false</code> otherwise
*/
MappingContextManager( Map<String, String> nsToPrefix, int maxColumnLengthInChararacters, boolean usePrefix ) {
this.nsToPrefix = nsToPrefix;
this.maxColumnLengthInChararacters = maxColumnLengthInChararacters == -1 ? 64 : maxColumnLengthInChararacters;
this.usePrefix = usePrefix;
}
MappingContext newContext( QName name, String idColumn ) {
count++;
return new MappingContext( getSQLIdentifier( "", toString( name ) ), idColumn );
}
MappingContext mapOneToOneElement( MappingContext mc, QName childElement ) {
count++;
String newColumn = getSQLIdentifier( mc.getColumn(), toString( childElement ) );
return new MappingContext( mc.getTable(), mc.getIdColumn(), newColumn );
}
MappingContext mapOneToOneAttribute( MappingContext mc, QName attribute ) {
count++;
String newColumn = getSQLIdentifier( mc.getColumn(), "attr_" + toString( attribute ) );
return new MappingContext( mc.getTable(), mc.getIdColumn(), newColumn );
}
MappingContext mapOneToManyElements( MappingContext mc, QName childElement ) {
count++;
String prefix = mc.getTable();
if ( mc.getColumn() != null && !mc.getColumn().isEmpty() ) {
prefix += "_" + mc.getColumn();
}
String newTable = getSQLIdentifier( prefix, toString( childElement ) );
return new MappingContext( newTable, "id", mc.getColumn() );
}
private String getSQLIdentifier( String prefix, String name ) {
String id = name;
if ( !prefix.isEmpty() ) {
id = prefix + "_" + name;
}
if ( id.length() >= maxColumnLengthInChararacters ) {
String substring = id.substring( 0, maxColumnLengthInChararacters - 6 );
id = substring + "_" + ( this.id++ );
}
return id;
}
private String toString( QName qName ) {
String name = toSQL( qName.getLocalPart() );
if ( qName.getNamespaceURI() != null && !qName.getNamespaceURI().equals( "" ) ) {
String nsPrefix = nsToPrefix.get( qName.getNamespaceURI() );
if ( nsPrefix == null ) {
LOG.warn( "No prefix for namespace {}!?", qName.getNamespaceURI() );
nsPrefix = "app";
}
if ( usePrefix ) {
name = toSQL( nsPrefix.toLowerCase() ) + "_" + toSQL( qName.getLocalPart() );
} else {
name = toSQL( qName.getLocalPart() );
}
}
return name;
}
private String toSQL( String identifier ) {
String sql = identifier.toLowerCase();
sql = sql.replace( "-", "_" );
return sql;
}
public int getContextCount() {
return count;
}
} |
package org.eclipse.smarthome.binding.hue.internal.discovery;
import static org.eclipse.smarthome.binding.hue.HueBindingConstants.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.smarthome.binding.hue.handler.HueBridgeHandler;
import org.eclipse.smarthome.binding.hue.handler.HueLightHandler;
import org.eclipse.smarthome.binding.hue.handler.LightStatusListener;
import org.eclipse.smarthome.binding.hue.internal.FullLight;
import org.eclipse.smarthome.binding.hue.internal.HueBridge;
import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
public class HueLightDiscoveryService extends AbstractDiscoveryService implements LightStatusListener {
private final Logger logger = LoggerFactory.getLogger(HueLightDiscoveryService.class);
private final static int SEARCH_TIME = 60;
private final static String MODEL_ID = "modelId";
// @formatter:off
private final static Map<String, String> TYPE_TO_ZIGBEE_ID_MAP = new ImmutableMap.Builder<String, String>()
.put("on_off_light", "0000")
.put("on_off_plug_in_unit", "0010")
.put("dimmable_light", "0100")
.put("dimmable_plug_in_unit", "0110")
.put("color_light", "0200")
.put("extended_color_light", "0210")
.put("color_temperature_light", "0220")
.build();
// @formatter:on
private HueBridgeHandler hueBridgeHandler;
public HueLightDiscoveryService(HueBridgeHandler hueBridgeHandler) {
super(SEARCH_TIME);
this.hueBridgeHandler = hueBridgeHandler;
}
public void activate() {
hueBridgeHandler.registerLightStatusListener(this);
}
@Override
public void deactivate() {
removeOlderResults(new Date().getTime());
hueBridgeHandler.unregisterLightStatusListener(this);
}
@Override
public Set<ThingTypeUID> getSupportedThingTypes() {
return HueLightHandler.SUPPORTED_THING_TYPES;
}
@Override
public void startScan() {
if (hueBridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) {
return;
}
List<FullLight> lights = hueBridgeHandler.getFullLights();
if (lights != null) {
for (FullLight l : lights) {
onLightAddedInternal(l);
}
}
// search for unpaired lights
hueBridgeHandler.startSearch();
}
@Override
protected synchronized void stopScan() {
super.stopScan();
removeOlderResults(getTimestampOfLastScan());
}
@Override
public void onLightAdded(HueBridge bridge, FullLight light) {
onLightAddedInternal(light);
}
private void onLightAddedInternal(FullLight light) {
ThingUID thingUID = getThingUID(light);
ThingTypeUID thingTypeUID = getThingTypeUID(light);
String modelId = light.getModelID().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_");
if (thingUID != null && thingTypeUID != null) {
ThingUID bridgeUID = hueBridgeHandler.getThing().getUID();
Map<String, Object> properties = new HashMap<>(1);
properties.put(LIGHT_ID, light.getId());
properties.put(MODEL_ID, modelId);
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
.withProperties(properties).withBridge(bridgeUID).withLabel(light.getName()).build();
thingDiscovered(discoveryResult);
} else {
logger.debug("discovered unsupported light of type '{}' and model '{}' with id {}", light.getType(),
modelId, light.getId());
}
}
@Override
public void onLightRemoved(HueBridge bridge, FullLight light) {
ThingUID thingUID = getThingUID(light);
if (thingUID != null) {
thingRemoved(thingUID);
}
}
@Override
public void onLightStateChanged(HueBridge bridge, FullLight light) {
// nothing to do
}
private ThingUID getThingUID(FullLight light) {
ThingUID bridgeUID = hueBridgeHandler.getThing().getUID();
ThingTypeUID thingTypeUID = getThingTypeUID(light);
if (thingTypeUID != null && getSupportedThingTypes().contains(thingTypeUID)) {
return new ThingUID(thingTypeUID, bridgeUID, light.getId());
} else {
return null;
}
}
private ThingTypeUID getThingTypeUID(FullLight light) {
String thingTypeId = TYPE_TO_ZIGBEE_ID_MAP
.get(light.getType().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_").toLowerCase());
return thingTypeId != null ? new ThingTypeUID(BINDING_ID, thingTypeId) : null;
}
} |
package org.opendaylight.controller.cluster.databroker;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import com.google.common.util.concurrent.FluentFuture;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class AbstractDOMBrokerWriteTransactionTest {
@Mock
private AbstractDOMTransactionFactory<?> abstractDOMTransactionFactory;
@Mock
private DOMStoreWriteTransaction domStoreWriteTransaction;
private class AbstractDOMBrokerWriteTransactionTestImpl
extends AbstractDOMBrokerWriteTransaction<DOMStoreWriteTransaction> {
AbstractDOMBrokerWriteTransactionTestImpl() {
super(new Object(), Collections.emptyMap(), abstractDOMTransactionFactory);
}
@Override
protected DOMStoreWriteTransaction createTransaction(final LogicalDatastoreType key) {
return null;
}
@Override
protected Collection<DOMStoreWriteTransaction> getSubtransactions() {
return Collections.singletonList(domStoreWriteTransaction);
}
}
@Test
public void readyRuntimeExceptionAndCancel() throws InterruptedException {
RuntimeException thrown = new RuntimeException();
doThrow(thrown).when(domStoreWriteTransaction).ready();
AbstractDOMBrokerWriteTransactionTestImpl abstractDOMBrokerWriteTransactionTestImpl =
new AbstractDOMBrokerWriteTransactionTestImpl();
FluentFuture<? extends CommitInfo> submitFuture = abstractDOMBrokerWriteTransactionTestImpl.commit();
try {
submitFuture.get();
Assert.fail("TransactionCommitFailedException expected");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TransactionCommitFailedException);
assertTrue(e.getCause().getCause() == thrown);
abstractDOMBrokerWriteTransactionTestImpl.cancel();
}
}
@Test
public void submitRuntimeExceptionAndCancel() throws InterruptedException {
RuntimeException thrown = new RuntimeException();
doThrow(thrown).when(abstractDOMTransactionFactory).commit(any(), any());
AbstractDOMBrokerWriteTransactionTestImpl abstractDOMBrokerWriteTransactionTestImpl
= new AbstractDOMBrokerWriteTransactionTestImpl();
FluentFuture<? extends CommitInfo> submitFuture = abstractDOMBrokerWriteTransactionTestImpl.commit();
try {
submitFuture.get();
Assert.fail("TransactionCommitFailedException expected");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TransactionCommitFailedException);
assertTrue(e.getCause().getCause() == thrown);
abstractDOMBrokerWriteTransactionTestImpl.cancel();
}
}
} |
package game;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import structures.*;
/**
* Object that handles the writing of data for the gamelog. Includes static
* methods for other writing purposes, such as saving of games and settings.
* @author Sean Lewis
*/
public class DataWriter {
private PrintWriter gameWriter;
/**
* Initializes a new DataWriter.
* @throws FileNotFoundException
*/
public DataWriter() throws FileNotFoundException {
gameWriter = new PrintWriter(new File("logs/gamelog.txt"));
}
/**
* Closes the output stream.
*/
public void close() {
gameWriter.close();
}
/**
* Writes that a level was finished.
* @param levelNumber the level that was finished
* @param swings the swings taken on that level
*/
public void levelFinished(int levelNumber, int swings) {
gameWriter.println("Level " + Integer.toString(levelNumber)
+ " complete. " + Integer.toString(swings) + " swings.");
gameWriter.println();
}
/**
* Writes that the game was finished.
* @param totalSwings the total number of swings taken in the game
*/
public void gameFinished(int totalSwings) {
gameWriter.println("Game complete. " + Integer.toString(totalSwings)
+ " swings total.");
}
/**
* Writes that the game was saved
* @param fileName the file the game was saved to
*/
public void gameSaved(String fileName) {
gameWriter.println("Game saved to " + fileName + ".");
}
/**
* Writes that the ball was launched.
* @param p the point clicked on screen
* @param launchMagnitude the launch magnitude
* @param launchAngle the launch angle
*/
public void ballLaunched(java.awt.Point p, double launchMagnitude,
double launchAngle) {
gameWriter.println("Ball launched. Point: (" + p.getX() + ", "
+ p.getY() + "). Magnitude: " + launchMagnitude + ", Angle: "
+ Math.toDegrees(launchAngle));
}
/**
* Prints a String to the output stream.
* @param str a parameter
*/
public void println(String str) {
gameWriter.println(str);
}
/**
* Writes that a game was loaded.
* @param fileName a parameter
*/
public void gameLoaded(String fileName) {
// TODO
}
/**
* Returns an encoded value based of the input value and unique key.
* @param value the input value
* @param key the unique input key
* @return the encoded value
*/
private static long encode(int value, int key) {
if (CalcHelp.isPrime(key)) {
return (value * 3) + key * key * key;
}
if (key % 6 == 0) {
return (value + key) * (key + 5);
}
if (key % 4 == 0) {
return -15 * value + key;
}
if (key % 5 == 0) {
return value * value + key;
}
if (key % 7 == 0) {
return value + key * key * key;
}
if (key % 2 == 0) {
return 10 * value - 20 - key * key;
}
return 8 * value - 6 * key * key;
}
/**
* Saves the current game to a file.
* @param file the file to save to.
* @throws FileNotFoundException if the file could not be written to
*/
public static void saveGame(GameManager game, File file)
throws FileNotFoundException {
PrintWriter saveWriter = new PrintWriter(file);
for (int i = 1; i <= game.getNumberOfLevels(); i++) {
saveWriter
.print(DataWriter.encode(game.getLevelSwings(i), i) + " ");
}
saveWriter.print(DataWriter.encode(game.getLevelNumber() - 1,
game.getNumberOfLevels())
+ " ");
saveWriter.print(DataWriter.encode(game.getTotalSwings(),
game.getNumberOfLevels() + 1));
saveWriter.close();
GravityGolf.DataWriter.gameSaved(file.getName());
}
} |
package gameWorld;
import gameRender.IsoCanvas;
import java.awt.Point;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Stack;
import tile.TileMultiton.type;
import com.sun.jmx.remote.internal.ArrayQueue;
import com.sun.xml.internal.bind.v2.runtime.Coordinator;
import dataStorage.Data;
import dataStorage.Tuple;
/**
*
* @author ChrisMcIntosh
*
*/
public class World {
private Unit[] units;
private GameObject[][] gameBoard;
private LogicalTile[][] worldMap;
private Unit activePlayer;
private IsoCanvas canvas;
/**
* Constructor
*
* @return
*/
public World(String save, int width, int height, IsoCanvas cvs) {
Tuple t = Data.testSet(null);
this.canvas = cvs;
units = t.units;
worldMap = new LogicalTile[t.tiles.length][t.tiles[0].length];
gameBoard = new GameObject[t.tiles.length][t.tiles[0].length];
populateWorldMape(t.tiles);
activePlayer = units[0];
checkPlayerStatus();
}
/**
* This is very niaeve and may break will be fixed affter discussing the Tuple class
* with group members
* @param tiles
*/
private void populateWorldMape(type[][] tiles) {
for(int x = 0; x < tiles.length; x++)
for(int y = 0; y < tiles[0].length; y++)
worldMap[x][y] = new LogicalTile(tiles[x][y] != null);
}
public void checkPlayerStatus() {
if(activePlayer == null){
activePlayer = units[0];
}
else if(!activePlayer.isActive()){
//activePlayer = units[nextPlayerID()]; //Removed while Testing is being done
activePlayer.activate();
}
calculatePossibleMovments(activePlayer.curLocation);
canvas.highlight(tilesToHightlight());
}
private int nextPlayerID() {
if(activePlayer.getID() == units.length-1)
return 0;
return activePlayer.getID() +1;
}
/**
* takes a mouse command and causes the active player to take the relevant action
*/
public void intepretMouseCommand(Point coords){
//Currently just handles movement will be extended to interact with game objects
int x = coords.x;
int y = coords.y;
//x = canvas.toCart(x, y).x; // sorry chris this dosnt work yet
//y = canvas.toCart(x, y).y;
if(move(x, y)) return;
}
public void moveFromKeyBoard(int i){
//0 is up
//1 is down
//2 is left
//3 is right
// if(i==0)
// System.out.println("World.moveFromKeyBoard(): UP");
// move(activePlayer.getLocation().x,activePlayer.getLocation().y+1);
// if(i==1)
// System.out.println("World.moveFromKeyBoard(): DOWN");
// move(activePlayer.getLocation().x,activePlayer.getLocation().y-1);
// if(i==2)
// System.out.println("World.moveFromKeyBoard(): LEFT");
// move(activePlayer.getLocation().x-1,activePlayer.getLocation().y);
// if(i==3)
// System.out.println("World.moveFromKeyBoard(): RIGHT");
// move(activePlayer.getLocation().x+1,activePlayer.getLocation().y);
int x = activePlayer.getLocation().x;
int y = activePlayer.getLocation().y;
if(i==0)y++;
if(i==1)y
if(i==2)x
if(i==3)x++;
if(inBounds(x, y))
if (worldMap[x][y].isIsTile()) {
ArrayDeque<Point> step = new ArrayDeque<Point>();
step.add(new Point(x, y));
canvas.moveUnit(activePlayer, step);
gameBoard[x][y] = activePlayer;
gameBoard[activePlayer.getLocation().x][activePlayer
.getLocation().y] = null;
}
}
/**
* Works out which tiles can be reached in one action.
* This is used to be passed to the renderer.
* @return
*/
private ArrayList<Point> tilesToHightlight() {
ArrayList<Point> highPoints = new ArrayList<Point>();
for(int x = 0; x < worldMap.length; x++)
for(int y = 0; y < worldMap[0].length; y++)
if(worldMap[x][y].isReachableByActive())
highPoints.add(new Point(x, y));
return highPoints;
}
/**
* Resets information about what can move where.
* @param u
*/
private void refresh(Unit u) {
for(int x = 0; x < worldMap.length; x++)
for(int y =0; y < worldMap[0].length; y++){
worldMap[x][y].setPath(null);
worldMap[x][y].setReachableByActive(false);
}
}
private void calculatePossibleMovments(Point curLocation) {
checkMoveFrom(curLocation.x, curLocation.y, 6, new ArrayDeque<Point>());
}
private void checkMoveFrom(int x, int y, int numMoves, ArrayDeque<Point> path){
path.add(new Point(x, y));
worldMap[x][y].setPath(path);
worldMap[x][y].setReachableByActive(true);
if(numMoves==0) return;
if(validMove(x+1, y, path))
checkMoveFrom(x+1, y, numMoves-1, path.clone());
if(validMove(x-1, y, path))
checkMoveFrom(x-1, y, numMoves-1, path.clone());
if(validMove(x,y-1, path))
checkMoveFrom(x,y-1, numMoves-1,path.clone());
if(validMove(x,y+1, path))
checkMoveFrom(x,y+1, numMoves-1,path.clone());
}
private boolean validMove(int x, int y, ArrayDeque<Point> path){
if(!inBounds(x,y))
return false;
if(!worldMap[x][y].isIsTile())
return false;
if(worldMap[x][y].getPath() == null)
return true;
if(worldMap[x][y].getPath().size() < path.size())
return false;
return true;
}
/**
* Gives a unit a new movement order by calling the find path method
*
* @param ID
* @param destination
* @return
*/
public boolean move(int x, int y) {
if (!inBounds(x, y))
return false;
if(worldMap[x][y].isIsTile())
if(worldMap[x][y].isReachableByActive()){
canvas.moveUnit(activePlayer, worldMap[x][y].getPath());
activePlayer.depleateMoves();
gameBoard[x][y] = activePlayer;
gameBoard[activePlayer.getLocation().x][activePlayer.getLocation().y] = null;
return true;
}
return false;
}
private boolean inBounds(int x, int y) {
if (x >= gameBoard.length)
return false;
if (y >= gameBoard[0].length)
return false;
if (x < 0)
return false;
if (y < 0)
return false;
return true;
}
/**
* @return the canvas
*/
public IsoCanvas getCanvas() {
return canvas;
}
/**
* @param canvas the canvas to set
*/
public void setCanvas(IsoCanvas canvas) {
this.canvas = canvas;
}
} |
package com.bitdubai.fermat_p2p_api.layer.p2p_communication.cloud_server.events;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.CommunicationChannels;
import com.bitdubai.fermat_api.layer.all_definition.event.PlatformEvent;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventSource;
import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventType;
import java.util.UUID;
public class IncomingNetworkServiceConnectionRequestEvent implements PlatformEvent {
/**
* Represent the eventType
*/
private EventType eventType;
/**
* Represent the eventSource
*/
private EventSource eventSource;
/**
* Represent the remoteNetworkServicePublicKey
*/
private String remoteNetworkServicePublicKey;
/**
* Represent the communicationChannels
*/
private CommunicationChannels communicationChannels;
/**
* Constructor with parameter
*
* @param eventType
*/
public IncomingNetworkServiceConnectionRequestEvent(EventType eventType){
this.eventType = eventType;
}
/**
* Constructor with parameters
*
* @param communicationChannels
* @param eventSource
* @param eventType
* @param remoteNetworkServicePublicKey
*/
public IncomingNetworkServiceConnectionRequestEvent(CommunicationChannels communicationChannels, EventSource eventSource, EventType eventType, String remoteNetworkServicePublicKey) {
this.communicationChannels = communicationChannels;
this.eventSource = eventSource;
this.eventType = eventType;
this.remoteNetworkServicePublicKey = remoteNetworkServicePublicKey;
}
/**
* (non-Javadoc)
*
* @see PlatformEvent#getEventType()
*/
@Override
public EventType getEventType() {
return this.eventType;
}
/**
* (non-Javadoc)
*
* @see PlatformEvent#setSource(EventSource)
*/
@Override
public void setSource(EventSource eventSource) {
this.eventSource = eventSource;
}
/**
* (non-Javadoc)
*
* @see PlatformEvent#getSource()
*/
@Override
public EventSource getSource() {
return this.eventSource;
}
/**
* Return the communication channels for the connection
*
* @return CommunicationChannels
*/
public CommunicationChannels getCommunicationChannels() {
return communicationChannels;
}
/**
* Set the communication channels for the connection
*
* @return CommunicationChannels
*/
public void setCommunicationChannels(CommunicationChannels communicationChannels) {
this.communicationChannels = communicationChannels;
}
/**
* Return the public key of the remote network service
* @return
*/
public String getRemoteNetworkServicePublicKey() {
return remoteNetworkServicePublicKey;
}
} |
package org.innovateuk.ifs.project.projectdetails.controller;
import org.innovateuk.ifs.project.BaseProjectSetupControllerSecurityTest;
import org.innovateuk.ifs.project.resource.ProjectCompositeId;
import org.innovateuk.ifs.project.security.ProjectLookupStrategy;
import org.innovateuk.ifs.user.resource.UserResource;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.when;
public class ProjectDetailsControllerSecurityTest extends BaseProjectSetupControllerSecurityTest<ProjectDetailsController> {
private ProjectCompositeId projectCompositeId;
@Override
@Before
public void lookupPermissionRules() {
super.lookupPermissionRules();
ProjectLookupStrategy projectLookupStrategy = getMockPermissionEntityLookupStrategiesBean(ProjectLookupStrategy.class);
projectCompositeId = ProjectCompositeId.id(123L);
when(projectLookupStrategy.getProjectCompositeId(projectCompositeId.id())).thenReturn(projectCompositeId);
}
@Override
protected Class<? extends ProjectDetailsController> getClassUnderTest() {
return ProjectDetailsController.class;
}
@Test
public void viewProjectDetails() {
assertSecured(() -> classUnderTest.viewProjectDetails(projectCompositeId.id(), null, null),
permissionRules -> permissionRules.partnerCanAccessProjectDetailsSection(eq(projectCompositeId), isA(UserResource.class)));
}
} |
package com.akjava.gwt.poseeditor.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.akjava.bvh.client.BVH;
import com.akjava.bvh.client.BVHMotion;
import com.akjava.bvh.client.BVHNode;
import com.akjava.bvh.client.BVHParser;
import com.akjava.bvh.client.BVHParser.InvalidLineException;
import com.akjava.bvh.client.BVHParser.ParserListener;
import com.akjava.bvh.client.BVHWriter;
import com.akjava.gwt.bvh.client.poseframe.PoseEditorData;
import com.akjava.gwt.bvh.client.poseframe.PoseFrameData;
import com.akjava.gwt.bvh.client.threejs.AnimationBoneConverter;
import com.akjava.gwt.bvh.client.threejs.AnimationDataConverter;
import com.akjava.gwt.bvh.client.threejs.BVHConverter;
import com.akjava.gwt.html5.client.InputRangeWidget;
import com.akjava.gwt.html5.client.download.HTML5Download;
import com.akjava.gwt.html5.client.extra.HTML5Builder;
import com.akjava.gwt.html5.client.file.File;
import com.akjava.gwt.html5.client.file.FileUploadForm;
import com.akjava.gwt.html5.client.file.FileUtils;
import com.akjava.gwt.html5.client.file.FileUtils.DataURLListener;
import com.akjava.gwt.html5.client.file.ui.DropVerticalPanelBase;
import com.akjava.gwt.lib.client.IStorageControler;
import com.akjava.gwt.lib.client.JsonValueUtils;
import com.akjava.gwt.lib.client.LogUtils;
import com.akjava.gwt.lib.client.StorageControler;
import com.akjava.gwt.lib.client.StorageException;
import com.akjava.gwt.lib.client.datalist.SimpleTextData;
import com.akjava.gwt.poseeditor.client.PreferenceTabPanel.PreferenceListener;
import com.akjava.gwt.poseeditor.client.resources.PoseEditorBundles;
import com.akjava.gwt.three.client.gwt.JSONModelFile;
import com.akjava.gwt.three.client.gwt.JSParameter;
import com.akjava.gwt.three.client.gwt.animation.AngleAndPosition;
import com.akjava.gwt.three.client.gwt.animation.AnimationBone;
import com.akjava.gwt.three.client.gwt.animation.AnimationBonesData;
import com.akjava.gwt.three.client.gwt.animation.AnimationData;
import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem;
import com.akjava.gwt.three.client.gwt.animation.AnimationKey;
import com.akjava.gwt.three.client.gwt.animation.BoneLimit;
import com.akjava.gwt.three.client.gwt.animation.NameAndVector3;
import com.akjava.gwt.three.client.gwt.animation.ik.CDDIK;
import com.akjava.gwt.three.client.gwt.animation.ik.IKData;
import com.akjava.gwt.three.client.gwt.core.BoundingBox;
import com.akjava.gwt.three.client.gwt.core.Intersect;
import com.akjava.gwt.three.client.gwt.materials.MeshBasicMaterialParameter;
import com.akjava.gwt.three.client.gwt.materials.MeshLambertMaterialParameter;
import com.akjava.gwt.three.client.java.GWTDragObjectControler;
import com.akjava.gwt.three.client.java.ThreeLog;
import com.akjava.gwt.three.client.java.animation.WeightBuilder;
import com.akjava.gwt.three.client.java.ui.SimpleTabDemoEntryPoint;
import com.akjava.gwt.three.client.java.utils.GWTGeometryUtils;
import com.akjava.gwt.three.client.java.utils.GWTThreeUtils;
import com.akjava.gwt.three.client.java.utils.GWTThreeUtils.InvalidModelFormatException;
import com.akjava.gwt.three.client.java.utils.Object3DUtils;
import com.akjava.gwt.three.client.js.THREE;
import com.akjava.gwt.three.client.js.cameras.Camera;
import com.akjava.gwt.three.client.js.core.Geometry;
import com.akjava.gwt.three.client.js.core.Object3D;
import com.akjava.gwt.three.client.js.core.Projector;
import com.akjava.gwt.three.client.js.extras.GeometryUtils;
import com.akjava.gwt.three.client.js.extras.ImageUtils;
import com.akjava.gwt.three.client.js.extras.helpers.GridHelper;
import com.akjava.gwt.three.client.js.lights.Light;
import com.akjava.gwt.three.client.js.loaders.JSONLoader.JSONLoadHandler;
import com.akjava.gwt.three.client.js.materials.Material;
import com.akjava.gwt.three.client.js.math.Euler;
import com.akjava.gwt.three.client.js.math.Matrix4;
import com.akjava.gwt.three.client.js.math.Vector3;
import com.akjava.gwt.three.client.js.math.Vector4;
import com.akjava.gwt.three.client.js.objects.Line;
import com.akjava.gwt.three.client.js.objects.Mesh;
import com.akjava.gwt.three.client.js.renderers.WebGLRenderer;
import com.akjava.gwt.three.client.js.scenes.Scene;
import com.akjava.gwt.three.client.js.textures.Texture;
import com.akjava.lib.common.utils.FileNames;
import com.akjava.lib.common.utils.ValuesUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayNumber;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.ValueListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class PoseEditor extends SimpleTabDemoEntryPoint implements PreferenceListener{
public static Logger logger = Logger.getLogger(PoseEditor.class.getName());
private BVH bvh;
protected JsArray<AnimationBone> animationBones;
private AnimationData animationData;
public static DateTimeFormat dateFormat=DateTimeFormat.getFormat("yy/MM/dd HH:mm");
private String version="6.0(for three.r66)";
private static boolean debug;
private static final String KEY_TRANSPARENT="poseeditor_key_transparent";
private static final String KEY_BASIC_MATERIAL="poseeditor_key_basicmaterial";
@Override
protected void beforeUpdate(WebGLRenderer renderer) {
if(root!=null){
/*
root.getScale().set(upscale,upscale,upscale);
if(bone3D!=null){
//bone3D.getScale().set(upscale,upscale,upscale);
double itemScale=(1.0/upscale);
for(int i=0;i<bone3D.getChildren().length();i++){
if(bone3D.getChildren().get(i) instanceof Mesh){
bone3D.getChildren().get(i).getScale().set(itemScale,itemScale,itemScale);
}
}
}
*/
root.setPosition((double)positionXRange.getValue()/posDivided, (double)positionYRange.getValue()/posDivided, (double)positionZRange.getValue()/posDivided);
root.getRotation().set(Math.toRadians(rotationXRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()),Euler.XYZ);
//camera rotation style
//cameraHolder.setPosition((double)positionXRange.getValue()/10, (double)positionYRange.getValue()/10, (double)positionZRange.getValue()/10);
//cameraHolder.getRotation().set(Math.toRadians(rotationXRange.getValue()),-Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()));
//camera.lookAt(zero);
//camera.getPosition().set(cameraX, cameraY, cameraZ);
/*
Vector3 newPos=THREE.Vector3(0, 0, 100);
Quaternion prev=GWTThreeUtils.degreeRotationQuaternion(THREE.Vector3(rotationXRange.getValue(),0,0));
Quaternion next=GWTThreeUtils.degreeRotationQuaternion(THREE.Vector3(rotationXRange.getValue(),180,0));
Quaternion result=THREE.Quaternion();
double scale=1.0/360*rotationYRange.getValue() ;
//log("scale:"+scale);
THREE.Quaternion().slerp( prev, next, result, scale);
Matrix4 mx=GWTThreeUtils.rotationToMatrix4(result);
//log("newangle:"+GWTThreeUtils.rotationToDegreeVector3(mx));
mx.multiplyVector3(newPos);
*/
//newPos=GWTThreeUtils.rotationToVector3(result);
//newPos=GWTThreeUtils.degreeToRagiant(newPos);
}
}
private Object3D cameraHolder;
@Override
protected void createCamera(Scene scene,int width,int height){
if(cameraHolder==null){
cameraHolder=THREE.Object3D();
scene.add(cameraHolder);
}
if(camera!=null){
//TODO find update way.
cameraHolder.remove(camera);
camera=null;
}
Camera camera = THREE.PerspectiveCamera(35,(double)width/height,0.1,6000);
//camera.getPosition().set(0, 0, cameraZ);
cameraHolder.add(camera); //some kind of trick.
this.camera=camera;
}
@Override
public void update(WebGLRenderer renderer) {
beforeUpdate(renderer);
camera.getPosition().set(cameraX, cameraY, cameraZ);
//LogUtils.log("camera:"+ThreeLog.get(camera.getPosition()));
renderer.render(scene, camera);
}
@Override
public void resized(int width, int height) {
super.resized(width, height);
leftBottom(bottomPanel);
}
private WebGLRenderer renderer;
public static final String KEY_INDEX="DATA_INDEX";
public static final String KEY_DATA="DATA_VALUE";
public static final String KEY_IMAGE="DATA_IMAGE";
public static final String KEY_HEAD="DATA_HEAD";
public class ContextMenu implements ContextMenuHandler{
@Override
public void onContextMenu(ContextMenuEvent event) {
event.preventDefault();
event.stopPropagation();
showContextMenu(event.getNativeEvent().getClientX(), event.getNativeEvent().getClientY());
}
}
private GWTDragObjectControler dragObjectControler;
public static class Logger {
boolean enabled=false;
public static Logger getLogger(String name){
return new Logger();
}
public void fine(String log){
if(enabled){
LogUtils.log(log);
}
}
public void info(String log) {
if(enabled){
LogUtils.log(log);
}
}
}
private BoneLimit oppositeRL(BoneLimit baseLimit){
BoneLimit limit=new BoneLimit();
limit.setMinXDegit(baseLimit.getMinXDegit());
limit.setMaxXDegit(baseLimit.getMaxXDegit());
limit.setMinYDegit(baseLimit.getMaxYDegit()*-1);
limit.setMaxYDegit(baseLimit.getMinYDegit()*-1);
limit.setMinZDegit(baseLimit.getMaxZDegit()*-1);
limit.setMaxZDegit(baseLimit.getMinZDegit()*-1);
limit.setMinX(Math.toRadians(limit.getMinXDegit()));
limit.setMaxX(Math.toRadians(limit.getMaxXDegit()));
limit.setMinY(Math.toRadians(limit.getMinYDegit()));
limit.setMaxY(Math.toRadians(limit.getMaxYDegit()));
limit.setMinZ(Math.toRadians(limit.getMinZDegit()));
limit.setMaxZ(Math.toRadians(limit.getMaxZDegit()));
return limit;
}
private void createIKAndLimitBone(){
//TODO load from file
//bone limit is very important otherwise ik really slow
//make human1.0 bones
//head ik
//this is for rese pose and not work correctly
/*
ikdatas.add(createIKData(Lists.newArrayList("head","neck","chest","abdomen"),9));
boneLimits.put("abdomen",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("chest",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
boneLimits.put("neck",BoneLimit.createBoneLimit(-34, 34, -34, 34, -34, 34));
//righ-hands,now modifiing
ikdatas.add(createIKData(Lists.newArrayList("rHand","rForeArm","rShldr","rCollar"),9));
boneLimits.put("rForeArm",BoneLimit.createBoneLimit(-30, 60, -60, 90, 0,0));
boneLimits.put("rShldr",BoneLimit.createBoneLimit(-90, 60, -75, 80, -120, 60));
boneLimits.put("rCollar",BoneLimit.createBoneLimit(0,0,-20,0,-40,0));
//left-hand
ikdatas.add(createIKData(Lists.newArrayList("lHand","lForeArm","lShldr","lCollar"),9));
boneLimits.put("lForeArm",oppositeRL(boneLimits.get("rForeArm")));
boneLimits.put("lShldr",oppositeRL(boneLimits.get("rShldr")));
boneLimits.put("lCollar",oppositeRL(boneLimits.get("rCollar")));
//right leg
ikdatas.add(createIKData(Lists.newArrayList("rFoot","rShin","rThigh"),5));
boneLimits.put("rShin",BoneLimit.createBoneLimit(0, 160, 0, 0, -0, 0));
boneLimits.put("rThigh",BoneLimit.createBoneLimit(-90, 90, -30, 30, -60, 45));
ikdatas.add(createIKData(Lists.newArrayList("lFoot","lShin","lThigh"),5));
boneLimits.put("lShin",oppositeRL(boneLimits.get("rShin")));
boneLimits.put("lThigh",oppositeRL(boneLimits.get("rThigh")));
*/
//head
ikdatas.add(createIKData(Lists.newArrayList("head","neck","chest","abdomen"),9));
boneLimits.put("abdomen",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("chest",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));//chest not stable if have more Y
boneLimits.put("neck",BoneLimit.createBoneLimit(-34, 34, -34, 34, -34, 34));
//righ-hand
ikdatas.add(createIKData(Lists.newArrayList("rHand","rForeArm","rShldr","rCollar"),9));
boneLimits.put("rForeArm",BoneLimit.createBoneLimit(0, 0, 0, 140, 0, 0));
boneLimits.put("rShldr",BoneLimit.createBoneLimit(-80, 60, -60, 91, -40, 100));
boneLimits.put("rCollar",BoneLimit.createBoneLimit(0,0,-20,0,-40,0));
//left-hand
ikdatas.add(createIKData(Lists.newArrayList("lHand","lForeArm","lShldr","lCollar"),9));
boneLimits.put("lForeArm",oppositeRL(boneLimits.get("rForeArm")));
boneLimits.put("lShldr",oppositeRL(boneLimits.get("rShldr")));
boneLimits.put("lCollar",oppositeRL(boneLimits.get("rCollar")));
//right leg
ikdatas.add(createIKData(Lists.newArrayList("rFoot","rShin","rThigh"),5));
boneLimits.put("rShin",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 0));
boneLimits.put("rThigh",BoneLimit.createBoneLimit(-120, 60, -35, 5, -80, 40));
ikdatas.add(createIKData(Lists.newArrayList("lFoot","lShin","lThigh"),5));
boneLimits.put("lShin",oppositeRL(boneLimits.get("rShin")));
boneLimits.put("lThigh",oppositeRL(boneLimits.get("rThigh")));
//old datas,right now just catch critibal bug
IKData ikdata3=new IKData("LeftUpLeg-LeftLeg");
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata3.setLastBoneName("LeftFoot");
ikdata3.setBones(new String[]{"LeftLeg","LeftUpLeg"});
ikdata3.setIteration(5);
ikdatas.add(ikdata3);
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-40, 10, 0, 140, -30, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -75, 91, -70, 115));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -140, 0, -10, 30));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 75, -115, 70));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-120, 60, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-120, 60, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-29, 29, -29, 29, -29, 29));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
}
@Override
protected void initializeOthers(WebGLRenderer renderer) {
cameraZ=500/posDivided;
this.renderer=renderer;
canvas.addDomHandler(new ContextMenu(), ContextMenuEvent.getType());
storageControler = new StorageControler();
this.renderer=renderer;
//maybe canvas is transparent
//renderer has already setted 0x333333.this is somekind confirm?
//canvas.setClearColorHex(0x333333);//qustion,what happen if no canvas.
//recently i feel this is good,less flick and
renderer.setClearColor(0, 0);
canvas.getElement().getStyle().setBackgroundColor("#333");
dragObjectControler=new GWTDragObjectControler(scene,projector);
//scene.add(THREE.AmbientLight(0xffffff));
Light pointLight = THREE.DirectionalLight(0xffffff,1);
pointLight.setPosition(0, 10, 300);
scene.add(pointLight);
Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem
pointLight2.setPosition(0, 10, -300);
//scene.add(pointLight2);
root=THREE.Object3D();
scene.add(root);
//background;
//Geometry geo=THREE.PlaneGeometry(1000/posDivided, 1000/posDivided,20,20);
//backgroundMesh = THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0xaaaaaa).wireFrame().build());
//backgroundMesh=THREE.GridHelper(1000/posDivided, 40);
//backgroundMesh.setRotation(Math.toRadians(-90), 0, 0);
int size=1000/posDivided;
int step=size/20;
step=Math.max(1, step);
backgroundGrid = THREE.GridHelper(1000/posDivided, step);
root.add(backgroundGrid);
//line removed,because of flicking
//Object3D xline=GWTGeometryUtils.createLineMesh(THREE.Vector3(-50, 0, 0.001), THREE.Vector3(50, 0, 0.001), 0x880000,3);
//root.add(xline);
//Object3D zline=GWTGeometryUtils.createLineMesh(THREE.Vector3(0, 0, -50), THREE.Vector3(0, 0, 50), 0x008800,3);
//root.add(zline);
double selectionSize=baseBoneCoreSize*2.5/posDivided;
selectionMesh=THREE.Mesh(THREE.CubeGeometry(selectionSize,selectionSize,selectionSize), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
root.add(selectionMesh);
selectionMesh.setVisible(false);
createIKAndLimitBone();
//line flicked think something
//delay make problem
//loadBVH("pose.bvh");//initial bone
/*
IKData ikdata1=new IKData("LowerBack-Neck1");
//ikdata1.setTargetPos(THREE.Vector3(0, 20, 0));
ikdata1.setLastBoneName("Head");
ikdata1.setBones(new String[]{"Neck1","Neck","Spine","LowerBack"});
//ikdata1.setBones(new String[]{"Neck1","Neck","Spine1","Spine","LowerBack"});
ikdata1.setIteration(9);
ikdatas.add(ikdata1);
IKData ikdata0=new IKData("RightArm-RightForeArm");
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata0.setLastBoneName("RightHand");
ikdata0.setBones(new String[]{"RightForeArm","RightArm"});
// ikdata0.setBones(new String[]{"RightForeArm","RightArm","RightShoulder"});
ikdata0.setIteration(7);
ikdatas.add(ikdata0);
//
IKData ikdata=new IKData("RightUpLeg-RightLeg");
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata.setLastBoneName("RightFoot");
ikdata.setBones(new String[]{"RightLeg","RightUpLeg"});
ikdata.setIteration(5);
ikdatas.add(ikdata);
IKData ikdata2=new IKData("LeftArm-LeftForeArm");
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata2.setLastBoneName("LeftHand");
//ikdata2.setBones(new String[]{"LeftForeArm","LeftArm","LeftShoulder"});
ikdata2.setBones(new String[]{"LeftForeArm","LeftArm"});
ikdata2.setIteration(7);
ikdatas.add(ikdata2);
*/
//updateIkLabels();
//calcurate by bvh 80_*
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-118, 0, 0, 60, -170, 0));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-180, 180, -60, 91, -180, 180));
boneLimits.put("RightShoulder",BoneLimit.createBoneLimit(0, 0, 0, 0,0, 0));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -170, 0, 0, 0));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50));
boneLimits.put("LeftShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 91, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-45, 45, -45, 45, -45, 45));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-15, 15, -15, 15, -15, 15));
*/
//there are gimbal lock problem angle must be under 90
/*
* to manual change to joint angle,keep under 90 is better.
but gimbal lock problem happend alreay at IK result converted to eular angle
*/
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-89, 10, 0, 89, -10, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -40, 89, -50,89));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-89, 10, -89.9, 0, -10, 10));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -89, 40, -89, 50));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, 0, 40));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 89, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, -40, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 89, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-35, 35, -35, 35, -35, 35));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
*/
//manual
//for initialize texture
texture=ImageUtils.loadTexture("blondhair_tshirt.png");//initial one //TODO change this.
//generateTexture();
//initial model to avoid async use clientbundle same as "tpose.bvh"
parseInitialBVHAndLoadModels(PoseEditorBundles.INSTANCE.pose().getText());
//model is loaded usually -1 index in modelName.txt on Bundles.
createTabs();
updateDatasPanel();
addShortcuts();
}
private void addShortcuts() {
canvas.addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if(event.getNativeKeyCode()==KeyCodes.KEY_SHIFT || event.getNativeKeyCode()==KeyCodes.KEY_ALT){
return;//ignore them.
}
if(event.getNativeKeyCode()==KeyCodes.KEY_ENTER){
if(bone3D!=null && bone3D.getChildren().length()>0){
selectBone(bone3D.getChildren().get(0),0,0,false);
}
}else if(event.getNativeKeyCode()==KeyCodes.KEY_PAGEUP){
doPrevFrame();
}else if(event.getNativeKeyCode()==KeyCodes.KEY_PAGEDOWN){
doNextFrame();
}else if(event.getNativeKeyCode()==KeyCodes.KEY_HOME){
doFirstFrame();
}else if(event.getNativeKeyCode()==KeyCodes.KEY_TAB){
loopTabSelection(event.isShiftKeyDown());//shift key has problem
}else{
int code=event.getNativeKeyCode();
if(code==45){//Add last
insertFrame(getSelectedPoseEditorData().getPoseFrameDatas().size(),false);
}else if(code==32){//space
touchGroundZero();
}else{
//LogUtils.log(event.getNativeKeyCode());
}
}
}
});
}
/**
* bone mesh's name is same as bone name;
* @param boneName
* @return
*/
private Mesh getBoneMesh(String boneName){
if(bone3D==null){
return null;
}
for(int i=0;i<bone3D.getChildren().length();i++){
if(bone3D.getChildren().get(i).getName().equals(boneName)){
return (Mesh)bone3D.getChildren().get(i);
}
}
return null;
}
protected void loopTabSelection(boolean shiftKeyDown) {
if(isSelectedIk()){
List<IKData> ikLists=Lists.newArrayList(getAvaiableIkdatas());
int index=ikLists.indexOf(getCurrentIkData());
if(index==-1){
LogUtils.log("loopTabSelection() invalid ik selected:"+getCurrentIkData());
return;
}
if(shiftKeyDown){
index
if(index<0){
index=ikLists.size()-1;
}
}else{
index++;
if(index>=ikLists.size()){
index=0;
}
}
Object3D object=getIkObject3D(ikLists.get(index));
selectIk(object, 0, 0,false);
}else if(isSelectedBone()){
int index=boneList.indexOf(selectedBone);
LogUtils.log("loop:"+index);
if(index==-1){
LogUtils.log("loopTabSelection() invalid bone selected:"+selectedBone);
return;
}
if(shiftKeyDown){
index
if(index<0){
index=boneList.size()-1;
}
}else{
index++;
if(index>=boneList.size()){
index=0;
}
}
String newName=boneList.get(index);
Mesh boneMesh=getBoneMesh(newName);
if(boneMesh==null){
LogUtils.log("loopTabSelection() boneMesh not exist:"+newName);
return;
}
selectBone(boneMesh,0,0,false);
//loop bone
}else{
for(IKData ik:getAvaiableIkdatas()){
Object3D object=getIkObject3D(ik);
selectIk(object, 0, 0,false);
break;
}
//List<IKData> iks=Lists.newArrayList(getAvaiableIkdatas());
}
}
private Object3D getIkObject3D(IKData ik){
for(int i=0;i<ik3D.getChildren().length();i++){
Object3D object=ik3D.getChildren().get(i);
if(object.getName().equals("ik:"+ik.getLastBoneName())){
return object;
}
}
return null;
}
private IKData createIKData(List<String> names,int iteration){
List<String> boneNames=Lists.newArrayList(names);
String last=boneNames.remove(0);//something name is strange
IKData mhikdata3=new IKData(Joiner.on("-").join(boneNames));
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
mhikdata3.setLastBoneName(last);
mhikdata3.setBones(boneNames.toArray(new String[0]));//what is this?
mhikdata3.setIteration(iteration);//what is this?
return mhikdata3;
}
private int defaultOffSetY=-40;
private void updateDatasPanel(){
datasPanel.clear();
try{
int index=storageControler.getValue(KEY_INDEX, 0);
for(int i=index;i>=0;i
//String b64=storageControler.getValue(KEY_IMAGE+i,null);
String json=storageControler.getValue(KEY_DATA+i,null);
String head=storageControler.getValue(KEY_HEAD+i,null);
if(json!=null){
DataPanel dp=new DataPanel(i,head,null,json);
//dp.setSize("200px", "200px");
datasPanel.add(dp);
}
}
}catch (StorageException e) {
LogUtils.log("updateDatasPanel faild:"+e.getMessage());
}
}
public class DataPanel extends HorizontalPanel{
private int index;
private String name;
private long cdate;
private String json;
public DataPanel(final int ind,String head,String base64, String text){
this.setSpacing(4);
json=text;
this.index=ind;
//right now stop using image.
Image img=new Image();
if(base64!=null){
img.setUrl(base64);
}else{
img.setVisible(false);
}
this.setVerticalAlignment(ALIGN_MIDDLE);
String name_cdate[]=head.split("\t");
name=name_cdate[0];
cdate=(long)(Double.parseDouble(name_cdate[1]));
String dlabel=dateFormat.format(new Date(cdate));
add(new Label(dlabel));
add(img);
final Label nameLabel=new Label(name);
nameLabel.setWidth("160px");
add(nameLabel);
Button loadBt=new Button("Load");
add(loadBt);
loadBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int loadedIndex=isLoaded(ind);
LogUtils.log("loadedIndex:"+loadedIndex);
if(loadedIndex!=-1){
//if already exist remove from list & alwasy recrete.because possiblly model's bone is alway difference.
poseEditorDatas.remove(loadedIndex);
LogUtils.log("old data is removed");
}
PoseEditorData ped=PoseEditorData.readData(json);
if(ped!=null){
ped.setFileId(ind);
doLoad(ped);
}else{
//TODO error catch
Window.alert("load faild");
}
}
});
Button editBt=new Button("Edit Name");
add(editBt);
editBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
JSONValue jsonValue=JSONParser.parseStrict(json);
JSONObject ped=jsonValue.isObject();
if(ped!=null){
String newName=Window.prompt("Change Name",name);
//ped.setName(newName);
name=newName;
ped.put("name", new JSONString(name));
json=ped.toString();
nameLabel.setText(name);
//JSONObject data=PoseEditorData.writeData(ped);
try{
storageControler.setValue(KEY_DATA+index, json);
storageControler.setValue(KEY_HEAD+index, name+"\t"+cdate);
}catch (StorageException e) {
LogUtils.log("Edit name faild:"+e.getMessage());
}
//rewrite
}else{
//TODO error catch
Window.alert("load faild");
}
}
});
Button removeBt=new Button("Delate");
add(removeBt);
removeBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean ret=Window.confirm("Delete data:"+name);
if(ret){
doRemoveData(index);
}
}
});
Button exportBt=new Button("Export");
add(exportBt);
exportBt.addClickHandler(new ClickHandler() {
private Anchor anchor;
@Override
public void onClick(ClickEvent event) {
PoseEditorData ped=PoseEditorData.readData(json);
String bvhText=convertBVHText(ped);
if(anchor!=null){
anchor.removeFromParent();
}
HTML5Download html5=new HTML5Download();
anchor = html5.generateTextDownloadLink(bvhText, nameLabel.getText()+".bvh", "Click to download",true);
add(anchor);
}
});
Button rawBt=new Button("Raw Json");
//add(rawBt); //this is for debug
rawBt.addClickHandler(new ClickHandler() {
private Anchor anchor;
@Override
public void onClick(ClickEvent event) {
if(anchor!=null){
anchor.removeFromParent();
}
HTML5Download html5=new HTML5Download();
JSONValue jsonValue=JSONParser.parseLenient(json);//possible error if json is invalid
anchor = html5.generateTextDownloadLink(JsonValueUtils.stringify(jsonValue.isObject().getJavaScriptObject()), "raw"+".json", "Click to download",true);
add(anchor);
}
});
}
}
private int isLoaded(int index){
for(int i=0;i<poseEditorDatas.size();i++){
PoseEditorData data=poseEditorDatas.get(i);
if(data.getFileId()==index){
return i;
}
}
return -1;
}
private void doRemoveData(int index){
try{
storageControler.setValue(KEY_DATA+index, null);
storageControler.setValue(KEY_IMAGE+index, null);
storageControler.setValue(KEY_HEAD+index, null);
}catch (StorageException e) {
LogUtils.log("do remove data faild:"+e.getMessage());
}
updateDatasPanel();
}
private void createTabs(){
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
int selection=event.getSelectedItem();
if(selection==0){
stats.setVisible(true);
showControl();
bottomPanel.setVisible(true);
popupPanel.setVisible(true);
}else{
stats.setVisible(false);
bottomPanel.setVisible(false);
hideControl();
popupPanel.setVisible(false);
}
resized(screenWidth,screenHeight);//for some blackout;
}
});
VerticalPanel datasRoot=new VerticalPanel();
tabPanel.add(datasRoot,"Motion & Pose");
HorizontalPanel dataButtons=new HorizontalPanel();
datasRoot.add(dataButtons);
FileUploadForm importBVH=FileUtils.createSingleTextFileUploadForm(new DataURLListener() {
@Override
public void uploaded(File file, String value) {
BVHParser parser=new BVHParser();
int dataIndex;
try {
dataIndex = getNewDataIndex();
} catch (StorageException e1) {
alert("faild getnewdataindex");
return;
}
JSONObject object=null;
try {
BVH bvh=parser.parse(value);
object=new PoseEditorDataConverter().convert(bvh);
} catch (InvalidLineException e) {
alert("invalid bvh:"+file.getFileName());
return;
}
String name=FileNames.getRemovedExtensionName(file.getFileName());
long ctime=System.currentTimeMillis();
object.put("name", new JSONString(name));
object.put("cdate", new JSONNumber(ctime));
try {
storageControler.setValue(KEY_DATA+dataIndex, object.toString());
storageControler.setValue(KEY_HEAD+dataIndex,name+"\t"+ctime);
dataIndex++;
storageControler.setValue(KEY_INDEX, dataIndex);
} catch (StorageException e) {
try {
storageControler.removeValue(KEY_DATA+dataIndex);
storageControler.removeValue(KEY_HEAD+dataIndex);
} catch (StorageException e1) {
}
alert("data store faild:"+e.getMessage());
}
updateDatasPanel();
}
}, true);
importBVH.setAccept(".bvh");
dataButtons.add(new Label("Import BVH"));
dataButtons.add(importBVH);
datasPanel = new VerticalPanel();
//datasPanel.setStyleName("debug");
ScrollPanel scroll=new ScrollPanel(datasPanel);
scroll.setSize("800px", "500px");
datasRoot.add(scroll);
try {
logger.fine("selection:"+storageControler.getValue(PreferenceTabPanel.KEY_MODEL_SELECTION, 0));
} catch (StorageException e) {
e.printStackTrace();
}
//storageControler.setValue(PreferenceTabPanel.KEY_MODEL_SELECTION, 0);
preferencePanel=new PreferenceTabPanel(storageControler,this);
tabPanel.add(preferencePanel,"Model & Texture");
//about
String html="";
html+="<br/>"+"[Howto Move]<br/><b>Select Nothing:</b><br/>Mouse Drag=Cammera Rotatation-XY<br/>Mouse Wheel= Zoom<br/> +ALT Move-XY Camera";
html+="<br/><br/>"+"<b>Select IK(Green Box):</b><br/>Mouse Drag=Move IK-XYZ <br/>Mouse Wheel=Move IK-Z <br/>+ALT=smoth-change <br/>+Shift=Move Only<br/>+ALT+Shift Follow other IK";
html+="<br/><br/>"+"<b>Select Bone(Red Box):</b><br/>Mouse Drag=Rotate-XY<br/>Mouse Wheel=Rotate-Z";
html+="<br/><br/>"+"<b>Select Root(Red Large Box):</b><br/>Mouse Drag=Rotate-XYZ<br/>Mouse Wheel=Rotate-Z +ALT=Follow IK +Shift=Move Position";
html+="<br/><br/>"+"yello box means under Y:0,orange box means near Y:0";
html+="<br/>On IK-Moving switching normal & +Alt(Smooth) is good tactics.";
html+="<br/>"+"<a href='http://webgl.akjava.com'>More info at webgl.akjava.com</a>";
HTML htmlP=new HTML(html);
VerticalPanel aboutRoot=new VerticalPanel();
//TODO credit
aboutRoot.add(htmlP);
tabPanel.add(aboutRoot,"About");
}
PreferenceTabPanel preferencePanel;
public static Map<String,BoneLimit> boneLimits=new HashMap<String,BoneLimit>();
NumberFormat numberFormat= NumberFormat.getFormat("0.0");
private void updateIkPositionLabel(){
//i'm not sure why value x 10 times;
ikPositionLabelX.setText("Ik-X:"+numberFormat.format(getCurrentIkData().getTargetPos().getX()*10));
ikPositionLabelY.setText("Ik-Y:"+numberFormat.format(getCurrentIkData().getTargetPos().getY()*10));
ikPositionLabelZ.setText("Ik-Z:"+numberFormat.format(getCurrentIkData().getTargetPos().getZ()*10));
}
private void updateIkLabels(){
//log(""+boneNamesBox);
boneNamesBox.clear();
if(currentSelectionIkName!=null){
setEnableBoneRanges(false,false,true);//no root
updateIkPositionLabel();
//getCurrentIkData().getTargetPos().getX()
boneNamesBox.addItem("");
for(int i=0;i<getCurrentIkData().getBones().size();i++){
boneNamesBox.addItem(getCurrentIkData().getBones().get(i));
}
boneNamesBox.addItem(getCurrentIkData().getLastBoneName());//need this too
boneNamesBox.setSelectedIndex(0);
}else if(selectedBone!=null){
setEnableBoneRanges(true,true,false);
boneNamesBox.addItem(selectedBone);
boneNamesBox.setSelectedIndex(0);
updateBoneRanges();
}else{
setEnableBoneRanges(false,false,false);//no selection
}
if(boneNamesBox.getItemCount()==0){
rotateAndPosList.setEnabled(false);
boneRotationsPanel.setVisible(false);
bonePositionsPanel.setVisible(false);
}else{
rotateAndPosList.setEnabled(true);
if(rotateAndPosList.getSelectedIndex()==0){
boneRotationsPanel.setVisible(true);
}else{
bonePositionsPanel.setVisible(true);
}
}
}
private void setEnableBoneRanges(boolean rotate,boolean pos,boolean ikPos){
bonePositionsPanel.setVisible(pos);
boneRotationsPanel.setVisible(rotate);
rotationBoneXRange.setEnabled(rotate);
rotationBoneYRange.setEnabled(rotate);
rotationBoneZRange.setEnabled(rotate);
positionXBoneRange.setEnabled(pos);
positionYBoneRange.setEnabled(pos);
positionZBoneRange.setEnabled(pos);
//ik pos
ikPositionsPanel.setVisible(ikPos);
//TODO x,y
}
int ikdataIndex=1;
private List<IKData> ikdatas=new ArrayList<IKData>();
private String currentSelectionIkName;//TODO not use last bone name
Mesh selectionMesh;
final Projector projector=THREE.Projector();
@Override
public void onMouseClick(ClickEvent event) {
//not work correctly on zoom
//Vector3 pos=GWTUtils.toWebGLXY(event.getX(), event.getY(), camera, screenWidth, screenHeight);
// targetPos.setX(pos.getX());
//targetPos.setY(pos.getY());
//doCDDIk();
//doPoseIkk(0);
}
private boolean isSelectedIk(){
return currentSelectionIkName!=null;
}
//here is so slow.
private void switchSelectionIk(String name){
currentSelectionIkName=name;
currentMatrixs=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
if(currentSelectionIkName!=null){
List<List<NameAndVector3>> result=createIKBases(getCurrentIkData());
//log("switchd:"+result.size());
/*for debug
List<NameAndVector3> tmp=result.get(result.size()-1);
for(NameAndVector3 value:tmp){
// log(value.getName()+":"+ThreeLog.get(value.getVector3()));
}
*/
if(candiateAngleAndMatrixs!=null){
candiateAngleAndMatrixs.clear();
}else{
candiateAngleAndMatrixs=new ArrayList<List<AngleAndPosition>>();
}
//must be lower .to keep lower add limit bone inside IK
//LogUtils.log("safe heresome how in danger:"+name);
int index=0;
for(List<NameAndVector3> nv:result){
//log("candiate:"+index);
List<AngleAndPosition> bm=AnimationBonesData.cloneAngleAndMatrix(currentMatrixs);
applyMatrix(bm, nv);
//for debug;
for(String bname:getCurrentIkData().getBones()){
Vector3 angle=bm.get(ab.getBoneIndex(bname)).getAngle();
//log(bname+":"+ThreeLog.get(angle));
}
candiateAngleAndMatrixs.add(bm);
index++;
}
}else{
//LogUtils.log("currentSelectionIkName not selected yet:"+name);
}
/*
LogUtils.log("end switchSelectionIk:"+name);
if(true){
return;
}
*/
updateIkLabels();
}
Map<IKData,List<List<NameAndVector3>>> ikBasesMap=new HashMap<IKData,List<List<NameAndVector3>>>();
public List<List<NameAndVector3>> createIKBases(IKData data){
if(ikBasesMap.get(data)!=null){
return ikBasesMap.get(data);
}
//int angle=30;
int angle=25;//how smooth?
//need change angle step if need more
if(data.getLastBoneName().equals("rShldr") || data.getLastBoneName().equals("lShldr") ){
angle=10; //chest is important?,tried but not so effected.
}
List<List<NameAndVector3>> all=new ArrayList<List<NameAndVector3>>();
List<List<NameAndVector3>> result=new ArrayList<List<NameAndVector3>>();
for(int i=0;i<data.getBones().size();i++){
String name=data.getBones().get(i);
List<NameAndVector3> patterns=createIKBases(name,angle); //90 //60 is slow
all.add(patterns);
//log(name+"-size:"+patterns.size());
}
//log(data.getLastBoneName()+"-joint-size:"+all.size());
addBase(all,result,data.getBones(),0,null,2);
ikBasesMap.put(data,result);//store
if(result.size()>1500){
LogUtils.log("warn many result-size:"+result.size()+" this almost freeze everything. are you forget limit bone.");
}
return result;
}
private static void addBase(List<List<NameAndVector3>> all,
List<List<NameAndVector3>> result, List<String> boneNames, int index,List<NameAndVector3> tmp,int depth) {
if(index>=boneNames.size() || index==depth){
result.add(tmp);
return;
}
if(index==0){
tmp=new ArrayList<NameAndVector3>();
}
for(NameAndVector3 child:all.get(index)){
//copied
List<NameAndVector3> list=new ArrayList<NameAndVector3>();
for(int i=0;i<tmp.size();i++){
list.add(tmp.get(i));
}
list.add(child);
addBase(all,result,boneNames,index+1,list,2);
}
}
private static List<NameAndVector3> createIKBases(String name,int step){
Set<NameAndVector3> patterns=new HashSet<NameAndVector3>();
BoneLimit limit=boneLimits.get(name);
/*
for(int x=-180;x<180;x+=step){
for(int y=-180;y<180;y+=step){
for(int z=-180;z<180;z+=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}*/
//0 - -180
for(int x=0;x>=-180;x-=step){
for(int y=0;y>=-180;y-=step){
for(int z=0;z>=-180;z-=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
// log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}
//step - 179
for(int x=0;x<180;x+=step){
for(int y=0;y<180;y+=step){
for(int z=0;z<180;z+=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
// log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}
if(patterns.size()==0){
logger.fine(name+":use zero base");
patterns.add(new NameAndVector3(name,0,0,0));//empty not allowd
}
return new ArrayList<NameAndVector3>(patterns);
}
PopupPanel contextMenu;
private void showContextMenu(int left,int top){
if(contextMenu==null){
createContextMenu();
}
contextMenu.setPopupPosition(left, top);
updateContextMenu();
contextMenu.show();
}
private List<MenuItem> dynamicMenues=new ArrayList<MenuItem>();
//use enabled ,strange behavior when use visible
private void updateContextMenu() {
//remove old
for(MenuItem item:dynamicMenues){
if(item.getParentMenu()!=null){//usually never possible
item.getParentMenu().removeItem(item);
}
}
dynamicMenues.clear();
if(isSelectedIk()){
dynamicMenues.add(rootBar.addItem("selected Ik",ikSelectedBar));
}else if(isSelectedBone()){
dynamicMenues.add(rootBar.addItem("selected Bone",boneSelecteddBar));
}else{
}
}
private void hideContextMenu(){
if(contextMenu!=null){
contextMenu.hide();
}
}
private Predicate<IKData> existIkPredicate=new Predicate<IKData>() {
@Override
public boolean apply(IKData input) {
return existBone(input.getLastBoneName());
}
};
private Iterable<IKData> getAvaiableIkdatas(){
return Iterables.filter(ikdatas,existIkPredicate);
}
CopiedIk copiedIk;
CopiedBone copiedBone;
private class CopiedBone{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Vector3 getAngle() {
return angle;
}
public void setAngle(Vector3 angle) {
this.angle = angle;
}
public Vector3 getPosition() {
return position;
}
public void setPosition(Vector3 position) {
this.position = position;
}
public CopiedBone(String name, Vector3 angle, Vector3 position) {
super();
this.name = name;
this.angle = angle;
this.position = position;
}
private Vector3 angle;
private Vector3 position;
}
private class CopiedIk{
private String ikName;
public String getIkName() {
return ikName;
}
public void setIkName(String ikName) {
this.ikName = ikName;
}
public List<String> getNames() {
return names;
}
public List<Vector3> getAngles() {
return angles;
}
private List<String> names=new ArrayList<String>();//bone name
private List<Vector3> angles=new ArrayList<Vector3>();
private void clear(){
names.clear();
angles.clear();
}
private void add(String boneName,Vector3 angle){
names.add(boneName);
angles.add(angle.clone());
}
}
private void doPasteIk(){
if(copiedIk==null){
return;
}
boolean needSwap=false;
if(isSelectedIk()){
String ikName=getCurrentIkData().getLastBoneName();//TODO fix handle last bone name;
if(!copiedIk.getIkName().equals(ikName)){
if(copiedIk.getIkName().equals(getMirroredName(ikName))){
needSwap=true;
}else{
Window.alert("not supported paste selection ik selected ="+ikName+" copied "+copiedIk.getIkName());
return;
}
}
}
//do paste
for(int i=0;i<copiedIk.getNames().size();i++){
String targetName;
if(needSwap){
targetName=getMirroredName(copiedIk.getNames().get(i));
}else{
targetName=copiedIk.getNames().get(i);
}
if(targetName==null){
continue;
}
int index=ab.getBoneIndex(targetName);
if(index!=-1 ){
if(needSwap){
rotToBone(targetName, copiedIk.getAngles().get(i).getX(), -copiedIk.getAngles().get(i).getY(), -copiedIk.getAngles().get(i).getZ(),true);
}else{
rotToBone(targetName, copiedIk.getAngles().get(i).getX(), copiedIk.getAngles().get(i).getY(), copiedIk.getAngles().get(i).getZ(),true);
}
}
}
}
private void doPasteBone(){
if(copiedBone==null){
LogUtils.log("not copied bone yet");
return;
}
int srcIndex=ab.getBoneIndex(copiedBone.getName());
if(srcIndex!=-1){
ab.getBoneAngleAndMatrix(srcIndex).getPosition().copy(copiedBone.getPosition());
ab.getBoneAngleAndMatrix(srcIndex).getAngle().copy(copiedBone.getAngle());
ab.getBoneAngleAndMatrix(srcIndex).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
}else{
LogUtils.log("invalid bone selected:"+copiedBone.getName());
}
}
private void doCopyBone(){
if(isSelectedBone()){
String name=getSelectedBoneName();
int srcIndex=ab.getBoneIndex(name);
if(srcIndex!=-1){
Vector3 angle=ab.getBoneAngleAndMatrix(srcIndex).getAngle().clone();
Vector3 pos=ab.getBoneAngleAndMatrix(srcIndex).getPosition().clone();
if(copiedBone==null){
copiedBone=new CopiedBone(name, angle, pos);
}else{
copiedBone.setName(name);
copiedBone.setAngle(angle);
copiedBone.setPosition(pos);
}
}else{
LogUtils.log("invalid bone selected:"+name);
}
}
}
private void doCopyIk(boolean copyLastBone){
if(isSelectedIk()){
if(copiedIk==null){
copiedIk=new CopiedIk();
}else{
copiedIk.clear();
}
IKData ik=getCurrentIkData();
copiedIk.setIkName(ik.getLastBoneName());//TODO fix better ik-name by preset
List<String> boneNames=Lists.newArrayList(ik.getBones());
if(copyLastBone){
boneNames.add(ik.getLastBoneName());
}
for(String name:boneNames){
int srcIndex=ab.getBoneIndex(name);
if(srcIndex!=-1){
Vector3 angle=ab.getBoneAngleAndMatrix(srcIndex).getAngle();
copiedIk.add(name,angle);
}
}
}
}
private void createBoneSelectedMenu(MenuBar parent){
parent.addItem("Copy", new Command(){
@Override
public void execute() {
doCopyBone();
hideContextMenu();
}});
}
private void createIkSelectedMenu(MenuBar parent){
parent.addItem("Copy", new Command(){
@Override
public void execute() {
doCopyIk(false);
hideContextMenu();
}});
parent.addItem("Copy with lastBone", new Command(){
@Override
public void execute() {
doCopyIk(true);
hideContextMenu();
}});
parent.addItem("Paste", new Command(){
@Override
public void execute() {
doPasteIk();
fitIkOnBone();
hideContextMenu();
}});
parent.addItem("Move to Prev Frame Ik-pos", new Command(){
@Override
public void execute() {
if(isSelectedIk() && isCurrentHasPrevFrame()){
String boneName=getCurrentIkData().getLastBoneName();
Vector3 pos=getBonePositionAtFrame(boneName,poseFrameDataIndex-1);
if(pos!=null){
getCurrentIkData().getTargetPos().copy(pos);
syncIkPosition();
}
}
hideContextMenu();
}});
parent.addItem("Move to Current Frame Ik-pos", new Command(){
@Override
public void execute() {
if(isSelectedIk()){
String boneName=getCurrentIkData().getLastBoneName();
Vector3 pos=getBonePositionAtFrame(boneName,poseFrameDataIndex);
if(pos!=null){
getCurrentIkData().getTargetPos().copy(pos);
syncIkPosition();
}
}
hideContextMenu();
}});
parent.addItem("Move to Next Frame Ik-pos", new Command(){
@Override
public void execute() {
if(isSelectedIk() && isCurrentHasNextFrame()){
String boneName=getCurrentIkData().getLastBoneName();
Vector3 pos=getBonePositionAtFrame(boneName,poseFrameDataIndex+1);
if(pos!=null){
getCurrentIkData().getTargetPos().copy(pos);
syncIkPosition();
}
}
hideContextMenu();
}});
parent.addItem("Move to Between Frame Ik-pos", new Command(){
@Override
public void execute() {
if(isSelectedIk() && isCurrentHasNextFrame() && isCurrentHasPrevFrame()){
String boneName=getCurrentIkData().getLastBoneName();
Vector3 pos=getBonePositionAtFrame(boneName,poseFrameDataIndex-1).clone();//to modify to clone
Vector3 next=getBonePositionAtFrame(boneName,poseFrameDataIndex+1);
if(pos!=null && next!=null){
pos.add(next).divideScalar(2);
getCurrentIkData().getTargetPos().copy(pos);
syncIkPosition();
}
}
hideContextMenu();
}});
MenuBar moveToIk=new MenuBar(true);
parent.addItem("Root move to selection IK-Pos", moveToIk);
moveToIk.addItem("Pos-X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().sub(rootPos);
diff.setY(0);
diff.setZ(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.add(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
moveToIk.addItem("Pos-Y", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().sub(rootPos);
diff.setX(0);
diff.setZ(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.add(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
moveToIk.addItem("Pos-Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().sub(rootPos);
diff.setY(0);
diff.setX(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.add(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
moveToIk.addItem("Pos-All", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().sub(rootPos);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.add(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
/*
for(IKData ik:getAvaiableIkdatas()){
ik.getTargetPos().addSelf(diff);
doPoseByMatrix(ab);
hideContextMenu();
}
*/
}});
}
private MenuBar ikSelectedBar,boneSelecteddBar;
private void createContextMenu(){
contextMenu=new PopupPanel();
rootBar = new MenuBar(true);
contextMenu.add(rootBar);
rootBar.setAutoOpen(true);
ikSelectedBar=new MenuBar(true);
createIkSelectedMenu(ikSelectedBar);
boneSelecteddBar=new MenuBar(true);
createBoneSelectedMenu(boneSelecteddBar);
MenuBar ikBar=new MenuBar(true);
rootBar.addItem("Ik",ikBar);
ikBar.addItem("Exec hard", new Command(){
@Override
public void execute() {
execIk();
hideContextMenu();
}});
ikBar.addItem("Exec mild", new Command(){
@Override
public void execute() {
execIk(5,5);
hideContextMenu();
}});
ikBar.addItem("Fit ik on bone", new Command(){
@Override
public void execute() {
if(isSelectedIk()){
//only do selected ik
Vector3 pos=ab.getBonePosition(getCurrentIkData().getLastBoneName());
getCurrentIkData().getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
}else{
fitIkOnBone();//do all
}
doPoseByMatrix(ab);//really need?
hideContextMenu();
}});
ikBar.addItem("Follow target", new Command(){
@Override
public void execute() {
if(isSelectedIk()){
if(existBone(getCurrentIkData().getLastBoneName())){
getCurrentIkData().getTargetPos().copy(getDefaultIkPos(ab.getBoneIndex(getCurrentIkData().getLastBoneName())));
//doPoseByMatrix(ab);
}
}else{
followTarget();//do all
}
doPoseByMatrix(ab);
hideContextMenu();
}});
ikBar.addItem("Paste", new Command(){
@Override
public void execute() {
doPasteIk();
fitIkOnBone();
hideContextMenu();
}});
ikBar.addItem("Y-Zero", new Command(){
@Override
public void execute() {
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setY(0);
doPoseByMatrix(ab);
hideContextMenu();
}
}});
ikBar.addItem("Move to First-IK-XZ", new Command(){
@Override
public void execute() {
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getBones().get(0);
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setX(pos.getX());
ik.getTargetPos().setZ(pos.getZ());
doPoseByMatrix(ab);
hideContextMenu();
}
}});
ikBar.addItem("Move to Last-IK-XZ", new Command(){
@Override
public void execute() {
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getBones().get(ik.getBones().size()-1);
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setX(pos.getX());
ik.getTargetPos().setZ(pos.getZ());
doPoseByMatrix(ab);
hideContextMenu();
}
}});
createContextMenuRoot(rootBar);
MenuBar boneBar=new MenuBar(true);
MenuItem boneLimitMenuItem = new MenuItem("Bone",boneBar);//menu item can change label dynamic
boneBar.addItem("Paste",new Command(){
@Override
public void execute() {
doPasteBone();
updateBoneRanges();
hideContextMenu();
}});
rootBar.addItem(boneLimitMenuItem);
boneBar.addItem("Change bones'limit to none", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.clearY(boneName);
boneLock.clearZ(boneName);
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearY(boneName);
boneLock.clearZ(boneName);
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to Y", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.clearZ(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.clearY(boneName);
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to Y,Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to X,Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearY(boneName);
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneBar.addItem("Change bones'limit to Y,X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearZ(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
}
updateBoneRotationRanges();
hideContextMenu();
}});
//createContextMenuFrames(rootBar);
MenuBar cameraBar=new MenuBar(true);
rootBar.addItem("Camera",cameraBar);
cameraBar.addItem("Front", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(defaultOffSetY);
hideContextMenu();
}});
cameraBar.addItem("Back", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(180);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(defaultOffSetY);
hideContextMenu();
}});
cameraBar.addItem("Quoter", new Command(){
@Override
public void execute() {
rotationXRange.setValue(45);
rotationYRange.setValue(45);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(defaultOffSetY);
hideContextMenu();
}});
cameraBar.addItem("Top", new Command(){
@Override
public void execute() {
rotationXRange.setValue(90);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(0);
hideContextMenu();
}});
cameraBar.addItem("Bottom", new Command(){
@Override
public void execute() {
rotationXRange.setValue(-90);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(0);
hideContextMenu();
}});
cameraBar.addItem("Right", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(90);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(defaultOffSetY);
hideContextMenu();
}});
cameraBar.addItem("Left", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(-90);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(defaultOffSetY);
hideContextMenu();
}});
}
//line has problem,TODO find a way to fix
protected void syncIkPosition() {
for(IKData ik:getAvaiableIkdatas()){
Mesh ikMesh=targetMeshs.get(ik.getLastBoneName());//TODO define ik name,;
if(ikMesh!=null){
ikMesh.setPosition(ik.getTargetPos());
}else{
LogUtils.log("ikMesh not found:"+ik.getLastBoneName());
}
}
if(isSelectedIk()){
selectionMesh.setPosition(getCurrentIkData().getTargetPos());
}
}
/**
*
* @param boneName
* @param frameIndex
* @return origin ,take care of modify
*/
private Vector3 getBonePositionAtFrame(String boneName,int frameIndex){
if(frameIndex<0 || frameIndex>getSelectedPoseEditorData().getPoseFrameDatas().size()-1){
LogUtils.log("getBonePositionAtFrame:out of range frame size= "+getSelectedPoseEditorData().getPoseFrameDatas().size()+" index="+frameIndex);
return null;//out of frame range;
}
if(!existBone(boneName)){
LogUtils.log("getBonePositionAtFrame:bone not found "+boneName);
return null;
}
int boneIndex=ab.getBoneIndex(boneName);
PoseFrameData frameData=getSelectedPoseEditorData().getPoseFrameDatas().get(frameIndex);
AnimationBonesData workingAnimationBoneData=new AnimationBonesData(animationBones, frameData.getAngleAndMatrixs());
return workingAnimationBoneData.getBonePosition(boneIndex);
}
private boolean isCurrentHasPrevFrame() {
return poseFrameDataIndex>0;
}
private boolean isCurrentHasNextFrame() {
return poseFrameDataIndex<getSelectedPoseEditorData().getPoseFrameDatas().size();
}
protected void followTarget() {
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getLastBoneName();
if(existBone(name)){
ik.getTargetPos().copy(getDefaultIkPos(ab.getBoneIndex(name)));
//doPoseByMatrix(ab);
}
}
}
protected void execIk() {
execIk(45,10);
}
protected void execIk(int perLimit,int loop) {
for(IKData ik:getAvaiableIkdatas()){
doPoseIkk(0,false,perLimit,ik,loop);
}
}
private void createContextMenuRoot(MenuBar rootBar){
MenuBar rootBoneBar=new MenuBar(true);
rootBar.addItem("Root",rootBoneBar);
rootBoneBar.addItem("touch ground(Y-0)", new Command(){
@Override
public void execute() {
touchGroundZero();
}});
rootBoneBar.addItem("initial Position", new Command(){
@Override
public void execute() {
JsArrayNumber rootPos=animationBones.get(0).getPos();
double rootX=0;
double rootY=0;
double rootZ=0;
if(rootPos!=null && rootPos.length()==3){
rootX=rootPos.get(0);
rootY=rootPos.get(1);
rootZ=rootPos.get(2);
}
ab.getBoneAngleAndMatrix(0).getPosition().set(rootX, rootY, rootZ);//bone pos
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("initial Pose", new Command(){
@Override
public void execute() {
//store position
Vector3 lastPosition=ab.getBoneAngleAndMatrix(0).getPosition().clone();
List<AngleAndPosition> angleAndPositions=AnimationBonesData.cloneAngleAndMatrix(initialPoseFrameData.getAngleAndMatrixs());
angleAndPositions.get(0).getPosition().copy(lastPosition);
angleAndPositions.get(0).updateMatrix();
selectAnimationDataData(angleAndPositions);
hideContextMenu();
}});
rootBoneBar.addItem("Move to Prev Frame Position", new Command(){
@Override
public void execute() {
if(poseFrameDataIndex<=0){
LogUtils.log("<=0:"+poseFrameDataIndex);
hideContextMenu();
//no frame
return;
}
if(poseFrameDataIndex>=getSelectedPoseEditorData().getPoseFrameDatas().size()){
//something invalid
LogUtils.log("invalid range");
hideContextMenu();
return ;
}
PoseFrameData prevFrameData=getSelectedPoseEditorData().getPoseFrameDatas().get(poseFrameDataIndex-1);
Vector3 prevFramePosition=prevFrameData.getAngleAndMatrixs().get(0).getPosition();
ab.getBoneAngleAndMatrix(0).getPosition().copy(prevFramePosition);
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to Current Frame Position", new Command(){
@Override
public void execute() {
//get not modified position
PoseFrameData prevFrameData=getSelectedPoseEditorData().getPoseFrameDatas().get(poseFrameDataIndex);
Vector3 prevFramePosition=prevFrameData.getAngleAndMatrixs().get(0).getPosition();
ab.getBoneAngleAndMatrix(0).getPosition().copy(prevFramePosition);
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to Next Frame Position", new Command(){
@Override
public void execute() {
if(poseFrameDataIndex<0){
hideContextMenu();
//no frame
return;
}
if(poseFrameDataIndex>=getSelectedPoseEditorData().getPoseFrameDatas().size()){
//something invalid
LogUtils.log("invalid range");
hideContextMenu();
return ;
}
if(poseFrameDataIndex==getSelectedPoseEditorData().getPoseFrameDatas().size()-1){
//at last frame
hideContextMenu();
return;
}
PoseFrameData prevFrameData=getSelectedPoseEditorData().getPoseFrameDatas().get(poseFrameDataIndex+1);
Vector3 prevFramePosition=prevFrameData.getAngleAndMatrixs().get(0).getPosition();
ab.getBoneAngleAndMatrix(0).getPosition().copy(prevFramePosition);
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to between Prev & Next Frame Position", new Command(){
@Override
public void execute() {
if(poseFrameDataIndex<=0){//need prev
hideContextMenu();
//no frame
return;
}
if(poseFrameDataIndex>=getSelectedPoseEditorData().getPoseFrameDatas().size()){
//something invalid
LogUtils.log("invalid range");
hideContextMenu();
return ;
}
if(poseFrameDataIndex==getSelectedPoseEditorData().getPoseFrameDatas().size()-1){
//need next frame
hideContextMenu();
return;
}
PoseFrameData prevFrameData=getSelectedPoseEditorData().getPoseFrameDatas().get(poseFrameDataIndex-1);
Vector3 prevFramePosition=prevFrameData.getAngleAndMatrixs().get(0).getPosition();
PoseFrameData nextFrameData=getSelectedPoseEditorData().getPoseFrameDatas().get(poseFrameDataIndex+1);
Vector3 nextFramePosition=nextFrameData.getAngleAndMatrixs().get(0).getPosition();
Vector3 newPos=prevFramePosition.clone().add(nextFramePosition).divideScalar(2);
ab.getBoneAngleAndMatrix(0).getPosition().copy(newPos);
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Swap all", new Command(){
@Override
public void execute() {
if(bone3D!=null && bone3D.getChildren().length()>0){
//selectBone(bone3D.getChildren().get(0),0,0,false);
//h-flip
//rotationBoneZRange.setValue(-rotationBoneZRange.getValue());
//rotToBone();
List<String> converted=new ArrayList<String>();
//swap all
for(IKData ik:getAvaiableIkdatas()){
List<String> targets=Lists.newArrayList(ik.getBones());
targets.add(ik.getLastBoneName());
for(String name:targets){
if(converted.contains(name)){
continue;
}
String targetName=getMirroredName(name);
if(targetName==null){
continue;
}
int index=ab.getBoneIndex(targetName);
int srcIndex=ab.getBoneIndex(name);
if(index!=-1 && srcIndex!=-1){
Vector3 angle1=ab.getBoneAngleAndMatrix(srcIndex).getAngle();
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(name, angle.getX(), -angle.getY(), -angle.getZ(),false);
rotToBone(targetName, angle1.getX(), -angle1.getY(), -angle1.getZ(),true);
}
converted.add(name);
converted.add(targetName);
}
}
//swap remains
for(String bname:boneList){
if(converted.contains(bname)){
continue;
}
int index=ab.getBoneIndex(bname);
if(index==-1){
LogUtils.log("invalid bone:"+bname);
continue;
}
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(bname, angle.getX(), -angle.getY(), -angle.getZ(),false);
}
doPoseByMatrix(ab);//update all
//TODO check what exactlly doing
updateBoneRanges();
updateIkLabels();
updateIkPositionLabel();
}
}
});
/*
* swap angle maybe need for old range
rootBoneBar.addItem("180 to -180", new Command(){
@Override
public void execute() {
Vector3 angle=ab.getBoneAngleAndMatrix(0).getAngle();
LogUtils.log(ThreeLog.get(angle));
if(angle.getX()==180){
angle.setX(-180);
}else if(angle.getX()==-180){
angle.setX(180);
}
if(angle.getY()==180){
angle.setY(-180);
}else if(angle.getY()==-180){
angle.setY(180);
}
if(angle.getZ()==180){
angle.setZ(-180);
}else if(angle.getZ()==-180){
angle.setZ(180);
}
//ab.getBoneAngleAndMatrix(0).setPosition(getInitialPoseFrameData().getPositions().get(0).clone());
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
updateBoneRotationRanges();
hideContextMenu();
}});
*/
}
protected void touchGroundZero() {
bodyMesh.getGeometry().computeBoundingBox();
LogUtils.log(bodyMesh.getGeometry());
BoundingBox box=bodyMesh.getGeometry().getBoundingBox();
Vector3 currentRoot=ab.getBonePosition(0);
currentRoot.setY(currentRoot.getY()-box.getMin().getY());
logger.fine("min:"+ThreeLog.get(box.getMin()));
logger.fine("max:"+ThreeLog.get(box.getMax()));
ab.getBoneAngleAndMatrix(0).getPosition().setY(currentRoot.getY());
ab.getBoneAngleAndMatrix(0).updateMatrix();
fitIkOnBone();
doPoseByMatrix(ab);
hideContextMenu();
}
//TODO future
private boolean isShowPrevIk;
private void createContextMenuFrames(MenuBar rootBar){
MenuBar framesBar=new MenuBar(true);
contextMenuShowPrevFrame = new MenuItem("Show Prev Iks",true,new Command(){
@Override
public void execute() {
contextMenuShowPrevFrame.setHTML("<b>"+"Show Prev Iks"+"</b>");
contextMenuHidePrefIks.setHTML("Hide Prev Iks");
isShowPrevIk=true;
hideContextMenu();
}});
framesBar.addItem(contextMenuShowPrevFrame);
contextMenuHidePrefIks = new MenuItem("<b>"+"Hide Prev Iks"+"</b>",true,new Command(){
@Override
public void execute() {
contextMenuShowPrevFrame.setHTML(""+"Show Prev Iks"+"");
contextMenuHidePrefIks.setHTML("<b>"+"Hide Prev Iks"+"</b>");
isShowPrevIk=false;
hideContextMenu();
}});
framesBar.addItem(contextMenuHidePrefIks);
rootBar.addItem("Frames",framesBar);
}
private PoseFrameData getInitialPoseFrameData(){
return initialPoseFrameData;
}
private String lastSelectionIkName;
private long lastClicked;
@Override
public void onMouseDown(MouseDownEvent event) {
logger.fine("onMouse down");
if(event.getNativeButton()==NativeEvent.BUTTON_RIGHT){
// showContextMenu(mouseDownX, mouseDownY);
return;
}else{
hideContextMenu();
}
//middle cant select anything
if(event.getNativeButton()==NativeEvent.BUTTON_MIDDLE){
return;
}
long t=System.currentTimeMillis();
boolean doubleclick=t<lastClicked+300;//onDoubleClick called after mouse up,it's hard to use
doMouseDown(event.getX(),event.getY(),doubleclick);
lastClicked=t;
}
private void doMouseDown(int x,int y,boolean selectBoneFirst){
mouseDown=true;
mouseDownX=x;
mouseDownY=y;
//log(mouseDownX+","+mouseDownY+":"+screenWidth+"x"+screenHeight);
/*
log("wpos:"+ThreeLog.get(GWTThreeUtils.toPositionVec(camera.getMatrix())));
log("mpos:"+ThreeLog.get(GWTThreeUtils.toPositionVec(camera.getMatrixWorld())));
log("rpos:"+ThreeLog.get(GWTThreeUtils.toPositionVec(camera.getMatrixRotationWorld())));
log("pos:"+ThreeLog.get(camera.getPosition()));
*/
//log("mouse-click:"+event.getX()+"x"+event.getY());
//TODO only call once for speed up
JsArray<Object3D> targets=(JsArray<Object3D>) JsArray.createArray();
JsArray<Object3D> childs=root.getChildren();
for(int i=0;i<childs.length();i++){
//LogUtils.log(childs.get(i).getName());
targets.push(childs.get(i));
}
JsArray<Object3D> bones=bone3D.getChildren();
for(int i=0;i<bones.length();i++){
//LogUtils.log(bones.get(i).getName());
targets.push(bones.get(i));
}
for(int i=0;i<ik3D.getChildren().length();i++){
//LogUtils.log(bones.get(i).getName());
targets.push(ik3D.getChildren().get(i));
}
JsArray<Intersect> intersects=projector.gwtPickIntersects(x, y, screenWidth, screenHeight,camera,targets);
//log("intersects-length:"+intersects.length());
long t=System.currentTimeMillis();
List<Object3D> selections=convertSelections(intersects);
if(selectBoneFirst){//trying every click change ik and bone if both intersected
//check bone first
Object3D lastIk=null;
for(Object3D selection:selections){
if(selection.getName().startsWith("ik:")){
if(selection.getName().equals(lastSelectionIkName)){
lastIk=selection;
}else{
selectIk(selection,x,y,true);
lastSelectionIkName=selection.getName();
updateBoneRanges();
return;
}
}
}
for(Object3D selection:selections){
if(!selection.getName().isEmpty() && !selection.getName().startsWith("ik:")){
selectBone(selection,x,y,true);
return;
}
}
if(lastIk!=null){//when ik selected,select another ik or bone first
selectIk(lastIk,x,y,true);
lastSelectionIkName=lastIk.getName();
updateBoneRanges();
return;
}
}else{
for(Object3D selection:selections){
if(selection.getName().startsWith("ik:")){
selectIk(selection,x,y,true);
lastSelectionIkName=selection.getName();
updateBoneRanges();
return;
}
if(!selection.getName().isEmpty() && !selection.getName().startsWith("ik:")){
selectBone(selection,x,y,true);
return;
}
}
/*
//ik first
for(Object3D selection:selections){
if(selection.getName().startsWith("ik:")){
selectIk(selection,x,y);
lastSelectionIkName=selection.getName();
updateBoneRanges();
return;
}
}
for(Object3D selection:selections){
if(!selection.getName().isEmpty() && !selection.getName().startsWith("ik:")){
selectBone(selection,x,y);
return;
}
}
*/
}
//log("no-selection");
//not select ik or bone
selectedBone=null;
selectionMesh.setVisible(false);
switchSelectionIk(null);
logger.fine("onMouse down-end1");
}
private String selectedBone;
private List<Object3D> convertSelections(JsArray<Intersect> intersects){
List<Object3D> selections=new ArrayList<Object3D>();
for(int i=0;i<intersects.length();i++){
selections.add(intersects.get(i).getObject());
}
return selections;
}
private void selectBone(Object3D target,int x,int y,boolean needDrag){
//maybe bone or root-bone
selectedBone=target.getName();
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
selectionMesh.getMaterial().gwtGetColor().setHex(0xff0000);
switchSelectionIk(null);
if(needDrag){
dragObjectControler.selectObject(target, x,y, screenWidth, screenHeight, camera);
logger.fine("onMouse down-end2");
}
//i guess set pos
//this is same effect as mouse move
positionXBoneRange.setValue((int) (selectionMesh.getPosition().getX()*100));
positionYBoneRange.setValue((int)(selectionMesh.getPosition().getY()*100));
positionZBoneRange.setValue((int)(selectionMesh.getPosition().getZ()*100));
defereredFocusCanvas();
return;
}
private void defereredFocusCanvas(){
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
tabPanel.selectTab(0);//this work reget focus canvas.
canvas.setFocus(true);
}
});
}
private void selectIk(Object3D target,int x,int y,boolean drag){
String ikBoneName=target.getName().substring(3);//3 is "ik:".length()
for(int j=0;j<ikdatas.size();j++){
if(ikdatas.get(j).getLastBoneName().equals(ikBoneName)){
ikdataIndex=j;//set ikindex here
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
selectionMesh.getMaterial().gwtGetColor().setHex(0x00ff00);
if(!ikBoneName.equals(currentSelectionIkName)){
switchSelectionIk(ikBoneName);
}
selectedBone=null;
if(drag){
dragObjectControler.selectObject(target, x,y, screenWidth, screenHeight, camera);
}
logger.info("onMouse down-end3");
defereredFocusCanvas();
return;//ik selected
}
}
}
@Override
public void onMouseUp(MouseUpEvent event) {
logger.fine("onMouse up");
mouseDown=false;
dragObjectControler.unselectObject();
logger.fine("6 drag");
}
@Override
public void onMouseOut(MouseOutEvent event) {
mouseDown=false;
dragObjectControler.unselectObject();
}
private boolean mouseMoving;
private double lastTime;
private Mesh debugMesh;
//private boolean doSync; never catched
@Override
public void onMouseMove(MouseMoveEvent event) {
if(mouseMoving){
logger.info("conflict-move");
if(lastTime+1000<System.currentTimeMillis()){
logger.info("conflict-move-timeout");//never happen?
}else{
return;
}
}
mouseMoving=true;
lastTime=System.currentTimeMillis();
double diffX=event.getX()-mouseDownX;
double diffY=event.getY()-mouseDownY;
int prevMouseDownX=mouseDownX;
int prevMouseDownY=mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
double mouseMoved=(Math.abs(diffX)+Math.abs(diffY));
if(mouseMoved==0){
mouseMoving=false;
return;
}
if(event.getNativeEvent().getButton()==NativeEvent.BUTTON_MIDDLE){
changeCamera((int)diffX,(int)diffY,event.isShiftKeyDown(),event.isAltKeyDown(),event.isControlKeyDown());
mouseMoving=false;
return;
}
if(mouseDown){
//log(diffX+","+diffY);
logger.fine("mouse move");
/*
* useless
int limit=10;
int limitX=(int) diffX;
int limitY=(int) diffY;
if(diffX>limit){
limitX=limit;
}
if(diffY>limit){
limitY=limit;
}
if(diffX<-limit){
limitX=-limit;
}
if(diffY<-limit){
limitY=-limit;
}
*/
if(isSelectedIk()){
logger.fine("selected ik");
diffX*=0.1;
diffY*=-0.1;
Vector3 old=getCurrentIkData().getTargetPos().clone();
if(dragObjectControler.isSelected()){
//int eventX=prevMouseDownX+limitX;
//int eventY=prevMouseDownY+limitY;
int eventX=event.getX();
int eventY=event.getY();
logger.fine("selected dragObjectControler");
scene.updateMatrixWorld(true);//very important.sometime selectedDraggablekObject.getParent().getMatrixWorld() return 0.
Vector3 newPos=dragObjectControler.moveSelectionPosition(eventX,eventY, screenWidth, screenHeight, camera);
if(newPos==null){
logger.info("newPos-null:"+ThreeLog.get(dragObjectControler.getDraggableOffset()));
mouseMoving=false;
return;
}
double length=newPos.clone().sub(getCurrentIkData().getTargetPos()).length();
/*
if(newPos.getY()<8){
log("error-newPos:"+ThreeLog.get(newPos));
log("error-mouse:"+eventX+","+eventY);
log("error-diff:"+diffX+","+diffY);
log("error-diff-move:"+length+",mouse:"+mouseMoved+",offset:"+ThreeLog.get(dragObjectControler.getDraggableOffset()));
log("error-log:"+dragObjectControler.getLog());
}else{
log("newPos:"+ThreeLog.get(newPos));
log("mouse:"+eventX+","+eventY);
log("diff:"+diffX+","+diffY);
log("diff-move:"+length+",mouse:"+mouseMoved+",offset:"+ThreeLog.get(dragObjectControler.getDraggableOffset()));
log("log:"+dragObjectControler.getLog());
}
*/
if(length<mouseMoved*2 && mouseMoved!=0){
if(length>mouseMoved || length>5){
logger.fine("diff-move:"+length+",mouse:"+mouseMoved+",offset:"+ThreeLog.get(dragObjectControler.getDraggableOffset()));
logger.fine("mouseDown:"+mouseDownX+","+mouseDownY);
}
//getCurrentIkData().getTargetPos().copy(newPos); // iguess
getCurrentIkData().setTargetPos(newPos);
}else{
logger.fine("diff-error:"+length+",mouse:"+mouseMoved+",offset:"+ThreeLog.get(dragObjectControler.getDraggableOffset()));
if(length>mouseMoved*10 && mouseMoved!=0){//invalid
//dragObjectControler.unselectObject();
//dragObjectControler.selectObject(dragObjectControler.getSelectedDraggablekObject(), event.getX(), event.getY(), screenWidth, screenHeight, camera);
}
}
}
//log("diff-moved:"+ThreeLog.get(old.subSelf(getCurrentIkData().getTargetPos())));
/*
getCurrentIkData().getTargetPos().incrementX(diffX);
getCurrentIkData().getTargetPos().incrementY(diffY);
*/
if(event.isAltKeyDown()){//slow
if(event.isShiftKeyDown()){
doPoseIkk(0,false,1,getCurrentIkData(),1);
for(IKData ik:getAvaiableIkdatas()){
//log("ik:"+ik.getName());
if(ik!=getCurrentIkData()){
doPoseIkk(0,false,5,ik,1);
}
}
}else{
//not work correctly
doPoseIkk(0,false,1,getCurrentIkData(),10);
}
}else if(event.isShiftKeyDown()){//move only
//doPoseIkk(0,true,1,getCurrentIkData(),1);
doPoseByMatrix(ab);
//doPoseIkk(0,false,1,getCurrentIkData(),0);
}else{
doPoseIkk(0,true,1,getCurrentIkData(),5);
}
updateIkPositionLabel();
}else if(isSelectedBone()){
logger.info("selected bone");
if(event.isShiftKeyDown()){//move position
int boneIndex=ab.getBoneIndex(selectedBone);
Vector3 pos=null;
if(boneIndex==0){//this version support moving root only
pos=ab.getBonePosition(boneIndex);
}else{
mouseMoving=false;
return;
}
if(dragObjectControler.isSelected()){
Vector3 newPos=dragObjectControler.moveSelectionPosition(event.getX(), event.getY(), screenWidth, screenHeight, camera);
double length=newPos.clone().length();
if(length<mouseMoved*50){
if(length>mouseMoved*10){
logger.fine("diff-move:"+length+",mouse="+mouseMoved);
}
//getCurrentIkData().getTargetPos().copy(newPos);
positionXBoneRange.setValue((int)(newPos.getX()*100));
positionYBoneRange.setValue((int)(newPos.getY()*100));
positionZBoneRange.setValue((int)(newPos.getZ()*100));
logger.fine("moved:"+length+",mouse="+mouseMoved);
}else{
logger.info("diff-error:"+length+",mouse="+mouseMoved);
}
}
//positionXBoneRange.setValue(positionXBoneRange.getValue()+(int)diffX);
//positionYBoneRange.setValue(positionYBoneRange.getValue()-(int)diffY);
positionToBone();
if(event.isAltKeyDown()){//not follow ik
// switchSelectionIk(null);
//effect-ik
for(IKData ik:getAvaiableIkdatas()){
doPoseIkk(0,false,5,ik,1);
}
}else{ //follow ik
if(boneIndex==0){
/*
Vector3 movedPos=ab.getBonePosition(boneIndex);
movedPos.sub(pos);
for(IKData ik:getAvaiableIkdatas()){
ik.getTargetPos().add(movedPos);
}
*/
fitIkOnBone();
doPoseByMatrix(ab);//redraw
}
}
}else{//change angle
Vector3 angle=ab.getBoneAngleAndMatrix(selectedBone).getAngle();
rotationBoneXRange.setValue(getRotationRangeValue(rotationBoneXRange.getValue(),(int)diffY));
rotationBoneYRange.setValue(getRotationRangeValue(rotationBoneYRange.getValue(),(int)diffX));
//rotationBoneXRange.setValue(rotationBoneXRange.getValue()+diffY);
//rotationBoneYRange.setValue(rotationBoneYRange.getValue()+diffX);
rotToBone();
if(event.isAltKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:getAvaiableIkdatas()){
doPoseIkk(0,false,5,ik,1);
}
}else{
//Vector3 rootPos=ab.getBonePosition(0);
Vector3 movedAngle=ab.getBoneAngleAndMatrix(selectedBone).getAngle().clone();
movedAngle.sub(angle);
//log("before:"+ThreeLog.get(angle)+" moved:"+ThreeLog.get(movedAngle));
//Matrix4 mx=GWTThreeUtils.degitRotationToMatrix4(movedAngle);
/*
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getLastBoneName();
//Vector3 pos=ab.getBonePosition(name);
if(existBone(name)){
ik.getTargetPos().copy(getDefaultIkPos(ab.getBoneIndex(name)));
}
//ik.getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
}
*/
fitIkOnBone();
doPoseByMatrix(ab);//redraw
}
}
}
else{//global
logger.fine("global");
changeCamera((int)diffX,(int)diffY,event.isShiftKeyDown(),event.isAltKeyDown(),event.isControlKeyDown());
}
}else{
/*useless
if(!dragObjectControler.isSelected()){
JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight,camera, GWTThreeUtils.toPositionVec(camera.getMatrixWorld()),scene);
//log("intersects-length:"+intersects.length());
for(int i=0;i<intersects.length();i++){
Intersect sect=intersects.get(i);
Object3D target=sect.getObject();
if(!target.getName().isEmpty()){
if(target.getName().startsWith("ik:")){
if(target!=dragObjectControler.getIntersectedDraggablekObject()){
dragObjectControler.setIntersectedDraggablekObject(target);
}
//dragObjectControler.selectObject(target, event.getX(), event.getY(), screenWidth, screenHeight, camera);
}
}
}
}*/
}
mouseMoving=false;
}
private void changeCamera(int diffX,int diffY,boolean shiftKey,boolean AltKey,boolean ctrlKey){
if(shiftKey){
positionXRange.setValue(positionXRange.getValue()+diffX);
positionYRange.setValue(positionYRange.getValue()-diffY);
}else{
rotationXRange.setValue(getRotationRangeValue(rotationXRange.getValue(),diffY));
rotationYRange.setValue(getRotationRangeValue(rotationYRange.getValue(),diffX));
}
}
private int getRotationRangeValue(int oldValue,int diffValue){
int angle=oldValue+diffValue;
if(angle>180){
int over=angle-180;
angle=-180+over;
}
if(angle<-180){
int under=angle+180;
angle=180+under;
}
return angle;
}
private boolean isSelectedBone(){
return !isSelectedIk() && selectedBone!=null;
}
private IKData getCurrentIkData(){
return ikdatas.get(ikdataIndex);
}
@Override
public void onMouseWheel(MouseWheelEvent event) {
if(isSelectedIk()){
double dy=event.getDeltaY()*2.0/posDivided;
getCurrentIkData().getTargetPos().gwtIncrementZ(dy);
if(event.isAltKeyDown()){
if(event.isShiftKeyDown()){//IK selected with ALT+Shift on mouseWheel,? bugs
doPoseIkk(0,false,1,getCurrentIkData(),1);
for(IKData ik:getAvaiableIkdatas()){
if(ik!=getCurrentIkData()){
doPoseIkk(0,false,5,ik,1);
}
}
}else{//IK selected with ALT on mouseWheel,Do move bones mildly.
doPoseIkk(0,false,1,getCurrentIkData(),10);
}
}else if(event.isShiftKeyDown()){//IK selected with Shift on mouseWheel,Do move IK only
//doPoseIkk(0,true,1,getCurrentIkData(),1);
//LogUtils.log("shift-key");
doPoseByMatrix(ab);
}else{
doPoseIkk(0,true,1,getCurrentIkData(),5);
}
updateIkPositionLabel();
}else if(isSelectedBone()){
if(event.isShiftKeyDown()){//move
int diff=event.getDeltaY();
int boneIndex=ab.getBoneIndex(selectedBone);
Vector3 pos=null;
if(boneIndex==0){//this version support moving root only
pos=ab.getBonePosition(boneIndex);
}
positionZBoneRange.setValue(positionZBoneRange.getValue()+diff);
positionToBone();
if(event.isAltKeyDown()){
//switchSelectionIk(null);
//effect-ik
execIk(5, 1);
/*
for(IKData ik:getAvaiableIkdatas()){
if(ik!=getCurrentIkData()){//no need re-ik root?
doPoseIkk(0,false,5,ik,1);
}
}*/
}else{//ik-follow
if(boneIndex==0){
Vector3 moved=ab.getBonePosition(boneIndex);
moved.sub(pos);
for(IKData ik:getAvaiableIkdatas()){
ik.getTargetPos().add(moved);
}
}
}
}else{
int diff=event.getDeltaY();
Vector3 angle=ab.getBoneAngleAndMatrix(selectedBone).getAngle();
rotationBoneZRange.setValue(getRotationRangeValue(rotationBoneZRange.getValue(),diff));
//rotationBoneZRange.setValue(rotationBoneZRange.getValue()+diff);
rotToBone();
if(event.isAltKeyDown()){
// switchSelectionIk(null);
//effect-ik
/*
for(IKData ik:getAvaiableIkdatas()){
doPoseIkk(0,false,5,ik,1);
}
*/
execIk(5, 1);
}else{
//Vector3 rootPos=ab.getBonePosition(0);
Vector3 movedAngle=ab.getBoneAngleAndMatrix(selectedBone).getAngle().clone();
movedAngle.sub(angle);
//logger.fine("before:"+ThreeLog.get(angle)+" moved:"+ThreeLog.get(movedAngle));
//Matrix4 mx=GWTThreeUtils.degitRotationToMatrix4(movedAngle);
//move green-ik-indicator
//--this is keep green ik-bone position
/*
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getLastBoneName();
//Vector3 pos=ab.getBonePosition(name);
//ik.getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
//LogUtils.log("ik:"+name);
//some difference bone call this
if(existBone(name)){//duplicate?
ik.getTargetPos().copy(getDefaultIkPos(ab.getBoneIndex(name)));
}
}
*/
fitIkOnBone();
doPoseByMatrix(ab);//redraw
}
}
}
else{//use small version
double tzoom=5.0/posDivided;
//TODO make class
long t=System.currentTimeMillis();
if(mouseLast+100>t){
czoom*=2;
}else{
czoom=tzoom;
}
//GWT.log("wheel:"+event.getDeltaY());
double tmp=cameraZ+event.getDeltaY()*czoom;
tmp=Math.max(20.0/posDivided, tmp);
tmp=Math.min(4000, tmp);
cameraZ=(double)tmp;
mouseLast=t;
}
}
private double czoom;
private InputRangeWidget positionXRange;
private InputRangeWidget positionYRange;
private InputRangeWidget positionZRange;
//private InputRangeWidget frameRange;
private InputRangeWidget rotationXRange;
private InputRangeWidget rotationYRange;
private InputRangeWidget rotationZRange;
private InputRangeWidget rotationBoneXRange;
private InputRangeWidget rotationBoneYRange;
private InputRangeWidget rotationBoneZRange;
private PopupPanel bottomPanel;
private InputRangeWidget currentFrameRange;
private Label currentFrameLabel;
private InputRangeWidget positionXBoneRange;
private InputRangeWidget positionYBoneRange;
private InputRangeWidget positionZBoneRange;
private CheckBox ylockCheck;
private CheckBox xlockCheck;
private List<String> ikLocks=new ArrayList<String>();
private CheckBox showBonesCheck,showIkCheck,smallCheck;
private int posDivided=10; //how small 10 or 100
private CheckBox showTileCheck;
private VerticalPanel ikPositionsPanel;
private Label ikPositionLabelY;
private Label ikPositionLabelZ;
@Override
public void createControl(DropVerticalPanelBase parent) {
HorizontalPanel h1=new HorizontalPanel();
rotationXRange = InputRangeWidget.createInputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationXRange));
parent.add(h1);
h1.add(rotationXRange);
Button reset=new Button("Reset");
reset.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationXRange.setValue(0);
}
});
h1.add(reset);
HorizontalPanel h2=new HorizontalPanel();
rotationYRange = InputRangeWidget.createInputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange));
parent.add(h2);
h2.add(rotationYRange);
Button reset2=new Button("Reset");
reset2.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationYRange.setValue(0);
}
});
h2.add(reset2);
HorizontalPanel h3=new HorizontalPanel();
rotationZRange = InputRangeWidget.createInputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange));
parent.add(h3);
h3.add(rotationZRange);
Button reset3=new Button("Reset");
reset3.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationZRange.setValue(0);
}
});
h3.add(reset3);
HorizontalPanel h4=new HorizontalPanel();
positionXRange = InputRangeWidget.createInputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange,posDivided));
parent.add(h4);
h4.add(positionXRange);
Button reset4=new Button("Reset");
reset4.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXRange.setValue(0);
}
});
h4.add(reset4);
HorizontalPanel h5=new HorizontalPanel();
positionYRange = InputRangeWidget.createInputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange,posDivided));
parent.add(h5);
h5.add(positionYRange);
Button reset5=new Button("Reset");
reset5.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYRange.setValue(0);
}
});
h5.add(reset5);
//maybe z no need,there are whell-zoom
HorizontalPanel h6=new HorizontalPanel();
positionZRange = InputRangeWidget.createInputRange(-300,300,0);
//parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange,10));
//parent.add(h6);
h6.add(positionZRange);
Button reset6=new Button("Reset");
reset6.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZRange.setValue(0);
}
});
h6.add(reset6);
HorizontalPanel vPanel=new HorizontalPanel();
parent.add(vPanel);
transparentCheck = new CheckBox();
vPanel.add(transparentCheck);
transparentCheck.setText("transparent");
transparentCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
transparentCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
try {
storageControler.setValue(KEY_TRANSPARENT, ""+event.getValue());
} catch (StorageException e) {
//not important
LogUtils.log("storage error:"+e.getMessage());
}
}
});
try {
transparentCheck.setValue(ValuesUtils.toBoolean(storageControler.getValue(KEY_TRANSPARENT, "false"),false));
} catch (StorageException e) {
LogUtils.log("storage error:"+e.getMessage());
}
basicMaterialCheck = new CheckBox();
vPanel.add(basicMaterialCheck);
basicMaterialCheck.setText("BasicMaterial");
basicMaterialCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
try {
basicMaterialCheck.setValue(ValuesUtils.toBoolean(storageControler.getValue(KEY_BASIC_MATERIAL, "false"),false));
} catch (StorageException e) {
LogUtils.log("storage error:"+e.getMessage());
}
basicMaterialCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
try {
storageControler.setValue(KEY_BASIC_MATERIAL, ""+event.getValue());
} catch (StorageException e) {
//not important
LogUtils.log("storage error:"+e.getMessage());
}
}
});
/*
* i tried but behavior totally wrong.i should learn cdd ik again.
HorizontalPanel optionPanel=new HorizontalPanel();
parent.add(optionPanel);
CheckBox useEndsite=new CheckBox("use end-site");
optionPanel.add(useEndsite);
useEndsite.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
isIkTargetEndSite=event.getValue();
fitIkOnBone();
}
});
*/
HorizontalPanel shows=new HorizontalPanel();
parent.add(shows);
showBonesCheck = new CheckBox();
shows.add(showBonesCheck);
showBonesCheck.setText("Show Bones");
showBonesCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateBonesVisible();
}
});
showBonesCheck.setValue(true);
smallCheck = new CheckBox();
shows.add(smallCheck);
smallCheck.setText("small");
smallCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateBonesSize();
}
});
smallCheck.setValue(false);
showIkCheck = new CheckBox();
shows.add(showIkCheck);
showIkCheck.setText("Iks");
showIkCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateIKVisible();
}
});
showIkCheck.setValue(true);
showTileCheck = new CheckBox("Tile");
shows.add(showTileCheck);
showTileCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Object3DUtils.setVisibleAll(backgroundGrid,showTileCheck.getValue());
//backgroundGrid.setVisible(showTileCheck.getValue());
}
});
showTileCheck.setValue(true);
//dont need now
/*
HorizontalPanel frames=new HorizontalPanel();
frameRange = InputRangeWidget.createInputRange(0,1,0);
parent.add(HTML5Builder.createRangeLabel("Frame:", frameRange));
//parent.add(frames);
frames.add(frameRange);
*/
/*
frameRange.addListener(InputRangeWidget.createInputRangeListener() {
@Override
public void changed(int newValue) {
doPose(frameRange.getValue());
}
});
*/
HorizontalPanel boneInfo=new HorizontalPanel();
boneInfo.setWidth("250px");
parent.add(boneInfo);
boneInfo.add(new Label("Bone"));
rotateAndPosList = new ListBox();
boneInfo.add(rotateAndPosList);
rotateAndPosList.addItem("Rotation");
rotateAndPosList.addItem("Position");
rotateAndPosList.setSelectedIndex(0);
rotateAndPosList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
switchRotateAndPosList();
}
});
HorizontalPanel boneNames=new HorizontalPanel();
parent.add(boneNames);
boneNamesBox = new ListBox();
boneNamesBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
updateBoneRanges();
}
});
boneNames.add(boneNamesBox);
ikLockCheck = new CheckBox("ik-lock");
boneNames.add(ikLockCheck);
ikLockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//String name=boneNameBox.get
if(ikLockCheck.getValue()){
ikLocks.add(getSelectedBoneName());
}else{
ikLocks.remove(getSelectedBoneName());
}
}
});
//mirror
HorizontalPanel mButtons=new HorizontalPanel();
parent.add(mButtons);
//because it' natural from front-view
Button rightToLeft=new Button("R > L");
rightToLeft.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doMirror(true);
}
});
mButtons.add(rightToLeft);
Button mirror=new Button("L > R");
mirror.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doMirror(false);
}
});
mButtons.add(mirror);
Button swap=new Button("do Swap");
swap.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSwap();
}
});
mButtons.add(swap);
bonePostionAndRotationContainer = new VerticalPanel();
bonePostionAndRotationContainer.setSize("210px", "150px");
bonePostionAndRotationContainer.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE);
parent.add(bonePostionAndRotationContainer);
//ikspos
ikPositionsPanel = new VerticalPanel();
bonePostionAndRotationContainer.add(ikPositionsPanel);
ikPositionsPanel.setVisible(false);
ikPositionLabelX = new Label();
ikPositionsPanel.add(ikPositionLabelX);
ikPositionLabelY = new Label();
ikPositionsPanel.add(ikPositionLabelY);
ikPositionLabelZ = new Label();
ikPositionsPanel.add(ikPositionLabelZ);
//positions
bonePositionsPanel = new VerticalPanel();
bonePostionAndRotationContainer.add(bonePositionsPanel);
bonePositionsPanel.setVisible(true);
HorizontalPanel h1bpos=new HorizontalPanel();
positionXBoneRange = InputRangeWidget.createInputRange(-60000/posDivided,60000/posDivided,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("X-Pos:", positionXBoneRange,10));
bonePositionsPanel.add(h1bpos);
h1bpos.add(positionXBoneRange);
createPosRangeControlers(positionXBoneRange,h1bpos);
positionXBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
HorizontalPanel h2bpos=new HorizontalPanel();
positionYBoneRange = InputRangeWidget.createInputRange(-60000/posDivided,60000/posDivided,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Y-Pos:", positionYBoneRange,10));
bonePositionsPanel.add(h2bpos);
h2bpos.add(positionYBoneRange);
createPosRangeControlers(positionYBoneRange,h2bpos);
positionYBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
HorizontalPanel h3bpos=new HorizontalPanel();
positionZBoneRange = InputRangeWidget.createInputRange(-60000/posDivided,60000/posDivided,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Z-Pos:", positionZBoneRange,10));
bonePositionsPanel.add(h3bpos);
h3bpos.add(positionZBoneRange);
createPosRangeControlers(positionZBoneRange,h3bpos);
/*
Button reset3bpos=new Button("Reset");
reset3bpos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZBoneRange.setValue(0);
positionToBone();
}
});
h3bpos.add(reset3bpos);
*/
positionZBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
boneRotationsPanel = new VerticalPanel();
bonePostionAndRotationContainer.add(boneRotationsPanel);
HorizontalPanel rotButtons=new HorizontalPanel();
rotButtons.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
boneRotationsPanel.add(rotButtons);
Button resetAll=new Button("Reset All Rotation",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneXRange.setValue(0);
rotationBoneYRange.setValue(0);
rotationBoneZRange.setValue(0);
rotToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
rotButtons.add(resetAll);
//flip angle controler
rotButtons.add(new Label("Flip"));
final ListBox flipBox=new ListBox();
flipBox.addItem("");
flipBox.addItem("X");
flipBox.addItem("Y");
flipBox.addItem("Z");
rotButtons.add(flipBox);
flipBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int index=flipBox.getSelectedIndex();
if(index==0){
return;
}
if(index==1){
rotationBoneXRange.setValue(-rotationBoneXRange.getValue());
flipBox.setSelectedIndex(0);
}
else if(index==2){
rotationBoneYRange.setValue(-rotationBoneYRange.getValue());
flipBox.setSelectedIndex(0);
}
else if(index==3){
rotationBoneZRange.setValue(-rotationBoneZRange.getValue());
flipBox.setSelectedIndex(0);
}
rotToBone();
}
});
HorizontalPanel h1b=new HorizontalPanel();
xlockCheck = new CheckBox();
h1b.add(xlockCheck);
xlockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(xlockCheck.getValue()){
boneLock.setX(getSelectedBoneName(), rotationBoneXRange.getValue());
rotationBoneXRange.setEnabled(false);
}else{
boneLock.clearX(getSelectedBoneName());
rotationBoneXRange.setEnabled(true);
}
}
});
xlockCheck.setTitle("lock this axis");
rotationBoneXRange = InputRangeWidget.createInputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationBoneXRange));
boneRotationsPanel.add(h1b);
h1b.add(rotationBoneXRange);
createRotRangeControlers(rotationBoneXRange,h1b);
rotationBoneXRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
}
});
HorizontalPanel h2b=new HorizontalPanel();
ylockCheck = new CheckBox();
h2b.add(ylockCheck);
ylockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(ylockCheck.getValue()){
boneLock.setY(getSelectedBoneName(), rotationBoneYRange.getValue());
rotationBoneYRange.setEnabled(false);
}else{
boneLock.clearY(getSelectedBoneName());
rotationBoneYRange.setEnabled(true);
}
}
});
ylockCheck.setTitle("lock this axis");
rotationBoneYRange = InputRangeWidget.createInputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationBoneYRange));
boneRotationsPanel.add(h2b);
h2b.add(rotationBoneYRange);
createRotRangeControlers(rotationBoneYRange,h2b);
rotationBoneYRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
}
});
HorizontalPanel h3b=new HorizontalPanel();
zlockCheck = new CheckBox();
h3b.add(zlockCheck);
zlockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(zlockCheck.getValue()){
boneLock.setZ(getSelectedBoneName(), rotationBoneZRange.getValue());
rotationBoneZRange.setEnabled(false);
}else{
boneLock.clearZ(getSelectedBoneName());
rotationBoneZRange.setEnabled(true);
}
}
});
zlockCheck.setTitle("lock this axis");
rotationBoneZRange = InputRangeWidget.createInputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationBoneZRange));
boneRotationsPanel.add(h3b);
h3b.add(rotationBoneZRange);
createRotRangeControlers(rotationBoneZRange,h3b);
rotationBoneZRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
if(event.isAltKeyDown()){
execIk();
}
}
});
/*
Button test=new Button("image",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String url=canvas.getRenderer().gwtPngDataUrl();//can'i snap shot with it.
Window.open(url, "test", null);
}
});
parent.add(test);
*/
/*
* crash so oftern if you use don't forget add
* THREE.WebGLRenderer(GWTRenderObject.create().preserveDrawingBuffer());
*
Button test=new Button("screen-shot");
parent.add(test);
test.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//better screen shot
//Keep before setting
//change setting if
//re render
//back to setting
String url=renderer.gwtPngDataUrl();
//log(url);
//String text="<img style='position:absolute;top:0;left:0' src='"+url+"'>";
//ExportUtils.openTabHtml(text, "screenshot"+screenShotIndex);
ExportUtils.openTabImage(url, "screenshot"+screenShotIndex);
screenShotIndex++;
//Window.open(url, "newwin"+screenShotIndex, null); sometime crash and kill owner
screenShotIndex++;
}
});
*/
/*
parent.add(new Label("Texture Image"));
final FileUploadForm textureUpload=new FileUploadForm();
parent.add(textureUpload);
textureUpload.getFileUpload().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
JsArray<File> files = FileUtils.toFile(event.getNativeEvent());
final FileReader reader=FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
@Override
public void onLoad() {
//log("load:"+Benchmark.end("load"));
//GWT.log(reader.getResultAsString());
textureUrl=reader.getResultAsString();
updateMaterial();
}
});
reader.readAsDataURL(files.get(0));
textureUpload.reset();
}
});
*/
/*
CheckBox do1small=new CheckBox("x 0.1");
do1small.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
onTotalSizeChanged(event.getValue());
}
});
parent.add(do1small);
*/
positionYRange.setValue(defaultOffSetY);//for test
updateIkLabels();
createBottomPanel();
showControl();
}
/*
int upscale=1;
protected void onTotalSizeChanged(Boolean value) {
if(value){
upscale=10;
}else{
upscale=1;
}
List<Mesh> meshs=Lists.newArrayList();
//meshs.add(selectionMesh);
meshs.addAll(vertexMeshs);
meshs.addAll(boneJointMeshs);
meshs.addAll(boneCoreMeshs);
meshs.addAll(endPointMeshs);
if(selectionPointIndicateMesh!=null){
meshs.add(selectionPointIndicateMesh);
}
if(boneSelectionMesh!=null){
meshs.add(boneSelectionMesh);
}
//redo-bone and vertex
for(Mesh mesh:meshs){
double scale=(1.0/upscale);
mesh.getScale().set(scale,scale,scale);
}
}
*/
boolean isIkTargetEndSite;
private void createPosRangeControlers(final InputRangeWidget range,HorizontalPanel parent){
Button minus3b=new Button("-");
minus3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()-10);
positionToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(minus3b);
Button minus=new Button("-.");
minus.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()-1);
positionToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(minus);
Button zero=new Button("0");
zero.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(0);
positionToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(zero);
Button plus3b=new Button("+.");
plus3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()+1);
positionToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(plus3b);
Button plus=new Button("+");
plus.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()+10);
positionToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(plus);
}
private void createRotRangeControlers(final InputRangeWidget range,HorizontalPanel parent){
Button minus3b=new Button("-");
minus3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()-1);
rotToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(minus3b);
List<Integer> angles=Lists.newArrayList(-180,-135,-90,-60,-45,0,45,60,90,135,180);
final ValueListBox<Integer> vlist=new ValueListBox<Integer>(new Renderer<Integer>() {
@Override
public String render(Integer object) {
if(object==null){
return "";
}
return String.valueOf(object);
}
@Override
public void render(Integer object, Appendable appendable) throws IOException {
// TODO Auto-generated method stub
}
});
vlist.setValue(null);
vlist.setAcceptableValues(angles);
vlist.addValueChangeHandler(new ValueChangeHandler<Integer>() {
@Override
public void onValueChange(ValueChangeEvent<Integer> event) {
if(event.getValue()==null){
return;
}
range.setValue(event.getValue());
rotToBone();
vlist.setValue(null);//reset to
/*
if(event.isAltKeyDown()){
execIk();
}
*/
}
});
parent.add(vlist);
Button plus3b=new Button("+");
plus3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
range.setValue(range.getValue()+1);
rotToBone();
if(event.isAltKeyDown()){
execIk(5,1);
}
}
});
parent.add(plus3b);
}
protected void doSwap() {
List<AngleAndPosition> lastAAP=cloneAngleAndPositions(ab.getBonesAngleAndMatrixs());
if(isSelectedIk() && getSelectedBoneName().isEmpty()){
IKData ik=getCurrentIkData();
for(String name:ik.getBones()){
String targetName=getMirroredName(name);
if(targetName==null){
continue;
}
int index=ab.getBoneIndex(targetName);
int srcIndex=ab.getBoneIndex(name);
if(index!=-1 && srcIndex!=-1){
Vector3 angle1=ab.getBoneAngleAndMatrix(srcIndex).getAngle();
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(name, angle.getX(), -angle.getY(), -angle.getZ(),false);
rotToBone(targetName, angle1.getX(), -angle1.getY(), -angle1.getZ(),true);
}
}
//move ik pos
IKData targetIk=getIk(getMirroredName(ik.getName()));
if(targetIk!=null){
Vector3 root=ab.getBonePosition(0);
Vector3 targetPos=targetIk.getTargetPos().clone().sub(root);
targetPos.setX(targetPos.getX()*-1);
targetPos.add(root);
Vector3 srcPos=ik.getTargetPos().clone().sub(root);
srcPos.setX(srcPos.getX()*-1);
srcPos.add(root);
ik.getTargetPos().set(targetPos.getX(),targetPos.getY(),targetPos.getZ());
targetIk.getTargetPos().set(srcPos.getX(),srcPos.getY(),srcPos.getZ());
doPoseByMatrix(ab);
}
}else{
String name=getSelectedBoneName();
if(name==null){
return;
}
//h mirror
String targetName=getMirroredName(name);
if(targetName==null){
return;
}
int index=ab.getBoneIndex(targetName);
if(index!=-1){
Vector3 targetAngle=ab.getBoneAngleAndMatrix(index).getAngle();
double x=rotationBoneXRange.getValue();
double y=rotationBoneYRange.getValue()*-1;
double z=rotationBoneZRange.getValue()*-1;
rotationBoneXRange.setValue((int) targetAngle.getX());
rotationBoneYRange.setValue((int) targetAngle.getY()*-1);
rotationBoneZRange.setValue((int) targetAngle.getZ()*-1);
rotToBone(targetName,x,y,z,false);
rotToBone();
}
}
List<AngleAndPosition> newAAP=cloneAngleAndPositions(ab.getBonesAngleAndMatrixs());
AngleAndPositionsCommand command=new AngleAndPositionsCommand(newAAP, lastAAP);
undoControler.addCommand(command);
}
private IKData getIk(String name){
for(IKData ik:ikdatas){
if(ik.getName().equals(name)){
return ik;
}
}
return null;
}
protected void doMirror(boolean rightToLeft) {
List<AngleAndPosition> lastAAP=cloneAngleAndPositions(ab.getBonesAngleAndMatrixs());
if(isSelectedIk() && getSelectedBoneName().isEmpty()){
IKData ik=getCurrentIkData();
for(String name:ik.getBones()){
String targetName=getMirroredName(name);
if(targetName==null){
continue;
}
String srcBoneName;
String destBoneName;
if(isRightBone(name)){
if(rightToLeft){
srcBoneName=name;
destBoneName=targetName;
}else{
srcBoneName=targetName;
destBoneName=name;
}
}else{
if(rightToLeft){
srcBoneName=targetName;
destBoneName=name;
}else{
srcBoneName=name;
destBoneName=targetName;
}
}
int index=ab.getBoneIndex(srcBoneName);
if(index!=-1){
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(destBoneName, angle.getX(), -angle.getY(), -angle.getZ(),false);
}
}
//Vector3 lastPosition=ik.getTargetPos().clone();
//invoke not call
fitIkOnBone();
doPoseByMatrix(ab);//do it only once
switchSelectionIk(ik.getLastBoneName());//recreate ik pose otherwise use old pose
updateBoneRanges();//possible changed
//ik.getTargetPos().copy(lastPosition);//restore position,usually user continue editing.but i change my mind ,when set opposite selection current ik pos make bad effect
}else{//single selected bone
String name=getSelectedBoneName();
if(name==null){
//somehow not selected
return;
}
String targetName=getMirroredName(name);
LogUtils.log("mirror:"+targetName);
if(targetName==null){
return;
}
int targetBoneIndex=ab.getBoneIndex(targetName);
if(targetBoneIndex!=-1){
if(isRightBone(name)){
if(rightToLeft){
rotToBone(targetName, rotationBoneXRange.getValue(),-rotationBoneYRange.getValue(),-rotationBoneZRange.getValue(),true);
}else{
//copy from left
Vector3 angle=ab.getBoneAngleAndMatrix(targetBoneIndex).getAngle();
rotationBoneXRange.setValue((int) angle.getX());
rotationBoneYRange.setValue((int) angle.getY()*-1);
rotationBoneZRange.setValue((int) angle.getZ()*-1);
rotToBone();
}
}else{//left bone
if(rightToLeft){
Vector3 angle=ab.getBoneAngleAndMatrix(targetBoneIndex).getAngle();
rotationBoneXRange.setValue((int) angle.getX());
rotationBoneYRange.setValue((int) angle.getY()*-1);
rotationBoneZRange.setValue((int) angle.getZ()*-1);
rotToBone();
}else{
rotToBone(targetName, rotationBoneXRange.getValue(),-rotationBoneYRange.getValue(),-rotationBoneZRange.getValue(),true);
}
}
}
}
List<AngleAndPosition> newAAP=cloneAngleAndPositions(ab.getBonesAngleAndMatrixs());
AngleAndPositionsCommand command=new AngleAndPositionsCommand(newAAP, lastAAP);
undoControler.addCommand(command);
//no need invoke;
}
protected void updateBonesVisible() {
if(bone3D!=null){
Object3DUtils.setVisibleAll(bone3D, showBonesCheck.getValue());
}
}
protected void updateBonesSize() {
if(bone3D!=null){
doPoseByMatrix(ab);//re-create
}
}
protected void updateIKVisible() {
if(ik3D!=null){
Object3DUtils.setVisibleAll(ik3D, showIkCheck.getValue());
}
}
protected String getMirroredName(String name) {
if(name.indexOf("Right")!=-1){
return name.replace("Right", "Left");
}
if(name.indexOf("right")!=-1){
return name.replace("right", "left");
}
if(name.indexOf("Left")!=-1){
return name.replace("Left", "Right");
}
if(name.indexOf("left")!=-1){
return name.replace("left", "right");
}
//makehuman 19 bones
if(name.startsWith("r")){
return "l"+name.substring(1);
}
else if(name.startsWith("l")){
return "r"+name.substring(1);
}
return null;
}
private boolean isRightBone(String name){
if(name.indexOf("Right")!=-1){
return true;
}
if(name.indexOf("right")!=-1){
return true;
}
//makehuman 19 bones
if(name.startsWith("r")){
return true;
}
return false;
}
private JsArray<Material> loadedMaterials;
JSONModelFile lastLoadedModel;
private void fixGeometryWeight(Geometry geometry){
for(int i=0;i<geometry.getSkinWeight().length();i++){
Vector4 vec4=geometry.getSkinWeight().get(i);
double x=vec4.getX();
double y=vec4.getY();
//seems somehow 1.0 weight make problem?
if(x==1){
geometry.getSkinIndices().get(i).setY(geometry.getSkinIndices().get(i).getX());
}else if(y==1){
geometry.getSkinIndices().get(i).setX(geometry.getSkinIndices().get(i).getY());
}else{//total value is under 1.0 bone usually make problem
double total=x+y;
if(total>1){
// LogUtils.log("invalid:"+total);
}
double remain=(1.0-total);
double nx=(x/total)*remain+x;
double ny=1.0-nx;
vec4.setX(nx);
vec4.setY(ny);
//must be 1.0 ?
}
}
}
private void LoadJsonModel(String jsonText){
try {
JSONModelFile model=GWTThreeUtils.parseJsonObject(jsonText);
lastLoadedModel=model;
GWTThreeUtils.loadJsonModel(lastLoadedModel,new JSONLoadHandler() {
@Override
public void loaded(Geometry geometry,JsArray<Material> materials) {
if(bodyMesh!=null){
root.remove(bodyMesh);//for initialzie
bodyMesh=null;
}
//LogUtils.log("material?");
loadedMaterials=materials;
ab=null;//for remake matrix.
LogUtils.log("loadJsonModel:");
LogUtils.log(geometry);
//fix geometry weight,otherwise broken model
fixGeometryWeight(geometry);//TODO retest really need?
baseGeometry=geometry;//change body mesh
LogUtils.log(baseGeometry.getBones());
if(baseGeometry.getBones()!=null && baseGeometry.getBones().length()>0){
LogUtils.log("create-bone from geometry:size="+baseGeometry.getBones().length());
setBone(baseGeometry.getBones()); //possible broken bone.TODO test geometry bone
/*
logger.fine("testly use bone from bvh");//TODO move back
AnimationBoneConverter converter=new AnimationBoneConverter();
setBone(converter.convertJsonBone(bvh));
*/
}else{
Window.alert("your loaded model has not contain bone,\nand use default bone.but this make many problem.\nplease export your model with bone");
logger.fine("bvh:"+bvh);
LogUtils.log("use bvh bone:maybe this is problem");
//initialize default bone
AnimationBoneConverter converter=new AnimationBoneConverter();
setBone(converter.convertJsonBone(bvh));
}
//log(""+(baseGeometry.getBones()!=null));
//log(baseGeometry.getBones());
doRePose(0);
//log("snapped");
if(poseEditorDatas.size()==0){//initial new list
initialPoseFrameData=snapCurrentFrameData();//get invalid pose
updateMaterial();
doNewFile();
}
//update texture
if(texture!=null){
if(lastLoadedModel.getMetaData().getFormatVersion()==3){
LogUtils.log("model-format is 3.0 and set flipY=false");
texture.setFlipY(false);
}else{
texture.setFlipY(true);
}
}
}
});//texture tested.
} catch (InvalidModelFormatException e) {
LogUtils.log("LoadJsonModel:"+e.getMessage());
}
}
private String getSelectedBoneName(){
if(boneNamesBox.getSelectedIndex()==-1){
return "";
}
return boneNamesBox.getValue(boneNamesBox.getSelectedIndex());
}
protected void positionToBone() {
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int index=ab.getBoneIndex(name);
if(index!=0){
//limit root only
//TODO limit by bvh channel
return;
}
Vector3 pos=THREE.Vector3(positionXBoneRange.getValue(),
positionYBoneRange.getValue()
, positionZBoneRange.getValue()).multiplyScalar(0.01);
/*
Vector3 angles=GWTThreeUtils.rotationToVector3(ab.getBoneAngleAndMatrix(index).getMatrix());
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
*/
ab.getBoneAngleAndMatrix(index).setPosition(pos);
ab.getBoneAngleAndMatrix(index).updateMatrix();
doPoseByMatrix(ab);
if( isSelectedBone()){
selectionMesh.setPosition(pos);
}
}
protected void switchRotateAndPosList() {
int index=rotateAndPosList.getSelectedIndex();
if(index==0){
bonePositionsPanel.setVisible(false);
boneRotationsPanel.setVisible(true);
}else{
bonePositionsPanel.setVisible(true);
boneRotationsPanel.setVisible(false);
}
}
private String getNewName(){
return "Untitled"+(fileIndex);
}
private int fileIndex;
private Button redoButton;
private void createBottomPanel(){
bottomPanel = new PopupPanel();
bottomPanel.setVisible(true);
bottomPanel.setSize("650px", "96px");
VerticalPanel main=new VerticalPanel();
bottomPanel.add(main);
HorizontalPanel trueTop=new HorizontalPanel();
trueTop.setWidth("100%");
main.add(trueTop);
//upper
HorizontalPanel topPanel=new HorizontalPanel();
trueTop.add(topPanel);
pedSelectionListBox=new ValueListBox<PoseEditorData>(new Renderer<PoseEditorData>() {
@Override
public String render(PoseEditorData object) {
if(object==null){
return "";
}
return object.getName();
}
@Override
public void render(PoseEditorData object, Appendable appendable) throws IOException {
// TODO Auto-generated method stub
}
});
pedSelectionListBox.addValueChangeHandler(new ValueChangeHandler<PoseEditorData>() {
@Override
public void onValueChange(ValueChangeEvent<PoseEditorData> event) {
event.getValue().updateMatrix(ab);//need bone data
updatePoseEditorDatas();
}
});
topPanel.add(pedSelectionListBox);
Button newFile=new Button("New");
topPanel.add(newFile);
newFile.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doNewFile();
}
});
saveButton = new Button("Save");
topPanel.add(saveButton);
saveButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSaveFile();
}
});
Button saveAsButton = new Button("SaveAs");
topPanel.add(saveAsButton);
saveAsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSaveAsFile(getSelectedPoseEditorData());
}
});
undoButton = new Button("Undo");
topPanel.add(undoButton);
undoButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
undoControler.undo();
}
});
undoButton.setEnabled(false);
redoButton = new Button("Redo");
topPanel.add(redoButton);
redoButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
undoControler.redo();
}
});
redoButton.setEnabled(false);
HorizontalPanel rightSide=new HorizontalPanel();
rightSide.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
rightSide.setWidth("100%");
trueTop.add(rightSide);
Button imageBt=new Button("Screenshot",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doScreenShot();
}
});
rightSide.add(imageBt);
Button gifAnimeBt=new Button("GifAnime",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doGifAnime();
}
});
rightSide.add(gifAnimeBt);
imageLinkContainer = new VerticalPanel();
imageLinkContainer.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
imageLinkContainer.setWidth("100px");
rightSide.add(imageLinkContainer);
HorizontalPanel upperPanel=new HorizontalPanel();
upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
main.add(upperPanel);
Button snap=new Button("Add");//TODO before,after
upperPanel.add(snap);
snap.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(getSelectedPoseEditorData().getPoseFrameDatas().size(),false);
}
});
Button replace=new Button("Replace");//TODO before,after
upperPanel.add(replace);
replace.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(currentFrameRange.getValue(),true);
}
});
/*
*should think system
Button cut=new Button("Cut");
upperPanel.add(cut);
cut.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doCut();
}
});
*/
final Button pasteBefore=new Button("Paste Before");
final Button pasteAfter=new Button("Paste After");
pasteBefore.setEnabled(false);
pasteAfter.setEnabled(false);
Button copy=new Button("Copy");
upperPanel.add(copy);
copy.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doCopy();
pasteBefore.setEnabled(true);
pasteAfter.setEnabled(true);
}
});
upperPanel.add(pasteBefore);
pasteBefore.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doPasteBefore();
getSelectedPoseEditorData().setModified(true);
updateSaveButtons();
}
});
upperPanel.add(pasteAfter);
pasteAfter.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doPasteAfter();
getSelectedPoseEditorData().setModified(true);
updateSaveButtons();
}
});
Button remove=new Button("Remove");
upperPanel.add(remove);
remove.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
getSelectedPoseEditorData().getPoseFrameDatas().remove(poseFrameDataIndex);
getSelectedPoseEditorData().setModified(true);
updatePoseIndex(Math.max(0,poseFrameDataIndex-1));
updateSaveButtons();
}
});
HorizontalPanel pPanel=new HorizontalPanel();
main.add(pPanel);
pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
currentFrameRange = InputRangeWidget.createInputRange(0,0,0);
currentFrameRange.setWidth(420);
pPanel.add(currentFrameRange);
currentFrameRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
updatePoseIndex(currentFrameRange.getValue());
}
});
Button prev=new Button("Prev");
pPanel.add(prev);
prev.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doPrevFrame();
}
});
Button next=new Button("Next");
pPanel.add(next);
next.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doNextFrame();
}
});
currentFrameLabel = new Label("1/1");//usually this style
currentFrameLabel.setWidth("40px");
pPanel.add(currentFrameLabel);
Button first=new Button("First");
pPanel.add(first);
first.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doFirstFrame();
}
});
bottomPanel.show();
super.leftBottom(bottomPanel);
}
protected void doGifAnime() {
// TODO Auto-generated method stub
}
private SimpleUndoControler undoControler=new SimpleUndoControler();
private class SimpleUndoControler{
private ICommand currentCommand;
public void undo(){
if(currentCommand!=null){
currentCommand.undo();
}
undoButton.setEnabled(false);
redoButton.setEnabled(true);
}
public void redo(){
if(currentCommand!=null){
currentCommand.redo();
}
undoButton.setEnabled(true);
redoButton.setEnabled(false);
}
public void addCommand(ICommand command){
currentCommand=command;
undoButton.setEnabled(true);
redoButton.setEnabled(false);
}
}
private List<AngleAndPosition> cloneAngleAndPositions(List<AngleAndPosition> datas){
return AnimationBonesData.cloneAngleAndMatrix(datas);
}
private class AngleAndPositionsCommand implements ICommand{
public AngleAndPositionsCommand(List<AngleAndPosition> newBoneData, List<AngleAndPosition> lastBoneData) {
super();
this.newBoneData = newBoneData;
this.lastBoneData = lastBoneData;
}
private List<AngleAndPosition> newBoneData;
private List<AngleAndPosition> lastBoneData;
@Override
public void invoke() {
selectAnimationDataData(cloneAngleAndPositions(newBoneData));
}
@Override
public void undo() {
selectAnimationDataData(cloneAngleAndPositions(lastBoneData));
}
@Override
public void redo() {
selectAnimationDataData(cloneAngleAndPositions(newBoneData));
}
}
private class FrameMoveCommand implements ICommand{
public FrameMoveCommand(int index,List<AngleAndPosition> boneData){
this.frameIndex=index;
this.boneData=boneData;
this.lastIndex=currentFrameRange.getValue();
}
private int lastIndex;
private int frameIndex;
private List<AngleAndPosition> boneData;
@Override
public void invoke() {
currentFrameRange.setValue(frameIndex);
updatePoseIndex(frameIndex);
}
@Override
public void undo() {
currentFrameRange.setValue(lastIndex);
updatePoseIndex(lastIndex);
selectAnimationDataData(AnimationBonesData.cloneAngleAndMatrix(boneData));
}
@Override
public void redo() {
currentFrameRange.setValue(frameIndex);
updatePoseIndex(frameIndex);
}
}
protected void doScreenShot() {
String url=canvas.getRenderer().gwtPngDataUrl();
Anchor anchor=HTML5Download.get().generateBase64DownloadLink(url, "image/png", "poseeditor.png", "Download", true);
imageLinkContainer.clear();
imageLinkContainer.add(anchor);
}
private void doFirstFrame() {
FrameMoveCommand command=new FrameMoveCommand(0,AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs()));
command.invoke();
undoControler.addCommand(command);
}
private void doPrevFrame(){
int value=currentFrameRange.getValue();
if(value>0){
value
FrameMoveCommand command=new FrameMoveCommand(value,AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs()));
command.invoke();
undoControler.addCommand(command);
}
}
private void doNextFrame(){
int value=currentFrameRange.getValue();
if(value<getSelectedPoseEditorData().getPoseFrameDatas().size()-1){
value++;
FrameMoveCommand command=new FrameMoveCommand(value,AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs()));
command.invoke();
undoControler.addCommand(command);
}
}
private int getNewDataIndex() throws StorageException{
int dataIndex=0;
dataIndex = storageControler.getValue(KEY_INDEX, 0);
return dataIndex;
}
protected void doSaveAsFile(PoseEditorData pdata) {
String result=Window.prompt("Save File", pdata.getName());
if(result!=null){
pdata.setName(result);
JSONObject data=PoseEditorData.writeData(pdata);
updateListBox();
//fileNames.setItemText(poseEditorDataSelection, result);
//TODO
if(!storageControler.isAvailable()){
//TODO just export
Window.alert("not saved because your browser not supoort HTML5 storage");
return;
}
// Window.alert("hello");
//save database
int dataIndex=0;
try {
dataIndex = getNewDataIndex();
} catch (StorageException e) {
alert("save faild:"+e.getMessage());
return;
}
//TODO method?
//Canvas canvas=Canvas.createIfSupported();
/*
int thumbW=32;
int thumbH=32;
canvas.setSize(thumbW+"px", thumbH+"px");
canvas.setCoordinateSpaceWidth(thumbW);
canvas.setCoordinateSpaceHeight(thumbH);
//log(renderer.gwtCanvas());
//now stop write image.
//canvas.getContext2d().drawImage(renderer.gwtCanvas(),0,0,screenWidth,screenHeight,0,0,thumbW,thumbH);
String thumbnail=canvas.toDataUrl();
LogUtils.log(thumbnail);
*/
// Window.alert("hello1");
//Window.alert("hello1");
//Window.open(thumbnail, "tmp", null);
try{
storageControler.setValue(KEY_DATA+dataIndex, data.toString());
// Window.alert("hello2");
//storageControler.setValue(KEY_IMAGE+dataIndex, thumbnail);
storageControler.setValue(KEY_HEAD+dataIndex, pdata.getName()+"\t"+pdata.getCdate());
// Window.alert("hello3:"+dataIndex);
pdata.setFileId(dataIndex);
//increment
dataIndex++;
storageControler.setValue(KEY_INDEX, dataIndex);
pdata.setModified(false);
updateSaveButtons();
updateDatasPanel();
tabPanel.selectTab(1);//datas
}catch(Exception e){
try {
//remove no need values
storageControler.removeValue(KEY_DATA+dataIndex);
storageControler.removeValue(KEY_HEAD+dataIndex);
} catch (StorageException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
alert(e.getMessage());
}
}
}
//TODO more info
public static void alert(String message){
logger.fine(message);
if(message.indexOf("(QUOTA_EXCEEDED_ERR)")!=-1 || message.indexOf("(QuotaExceededError)")!=-1){
String title="QUOTA EXCEEDED_ERR\n";
title+="maybe load texture is succeed.but store data is faild.so this data can't load again.\nbecause over internal HTML5 storage capacity.\n";
title+="please remove unused textures or models from Preference Tab\n";
Window.alert(title);
}else{
Window.alert("Error:"+message);
}
}
protected void doSaveFile() {
PoseEditorData pdata=getSelectedPoseEditorData();
int fileId=pdata.getFileId();
if(fileId!=-1){
JSONObject data=PoseEditorData.writeData(pdata);
try{
storageControler.setValue(KEY_DATA+fileId, data.toString());
pdata.setModified(false);
updateSaveButtons();
updateDatasPanel();
}catch(Exception e){
alert(e.getMessage());
}
}else{
doSaveAsFile(pdata);
}
//log(data.toString());
/*
//test
PoseEditorData readData=PoseEditorData.readData(data.toString());
readData.updateMatrix(ab);
readData.setName("tmp1");
doLoad(readData);
*/
}
//private int poseEditorDataSelection;
List<PoseEditorData> poseEditorDatas=new ArrayList<PoseEditorData>();
public void updatePoseEditorDatas(){
//poseEditorDataSelection=index;
updatePoseIndex(0);
updateSaveButtons();
}
private PoseEditorData getSelectedPoseEditorData(){
return pedSelectionListBox.getValue();
}
protected void doNewFile() {
fileIndex++;
String newName=getNewName();
PoseEditorData ped=new PoseEditorData();
ped.setModified(true);//new always
ped.setName(newName);
ped.setCdate(System.currentTimeMillis());
List<PoseFrameData> pfList=new ArrayList<PoseFrameData>();
ped.setPoseFrameDatas(pfList);
pfList.add(initialPoseFrameData.clone());
ped.setBones(boneList);
poseEditorDatas.add(ped);
pedSelectionListBox.setValue(ped);
//when new file 0 is natural
updatePoseIndex(0);
//updatePoseIndex(Math.max(0,poseFrameDataIndex-1));//new label
updateSaveButtons();
}
private void updateListBox(){//refresh list
pedSelectionListBox.setAcceptableValues(poseEditorDatas);
}
/**
* load frame data
* @param ped
*/
public void doLoad(PoseEditorData ped){
//add to list
poseEditorDatas.add(ped);
updateListBox();
pedSelectionListBox.setValue(ped);//select
ped.updateMatrix(ab);//need bone data
tabPanel.selectTab(0);//datas
updatePoseEditorDatas();
}
protected void doPasteBefore() {
if(clipboard!=null){
int index=Math.max(0, poseFrameDataIndex);//same means insert before
getSelectedPoseEditorData().getPoseFrameDatas().add(index,clipboard.clone());
updatePoseIndex(index);
}
}
protected void doPasteAfter() {
if(clipboard!=null){
getSelectedPoseEditorData().getPoseFrameDatas().add(currentFrameRange.getValue()+1,clipboard.clone());
updatePoseIndex(currentFrameRange.getValue()+1);
}
}
protected void doCut() {
// TODO Auto-generated method stub
}
PoseFrameData clipboard;
private boolean availIk(IKData ik){
if(ab.getBoneIndex(ik.getLastBoneName())==-1){
return false;
}
for(String name:ik.getBones()){
if(ab.getBoneIndex(name)==-1){
return false;
}
}
return true;
}
protected void doCopy() {
// TODO Auto-generated method stub
clipboard=snapCurrentFrameData();
}
private PoseFrameData initialPoseFrameData;
private PoseFrameData snapCurrentFrameData(){
List<AngleAndPosition> matrixs=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
List<Vector3> angles=new ArrayList<Vector3>();
List<Vector3> positions=new ArrayList<Vector3>();
for(int i=0;i<matrixs.size();i++){
Vector3 angle=matrixs.get(i).getAngle().clone();
angles.add(angle);
Vector3 position=ab.getMatrixPosition(i);//TODO getPosition()?
position.sub(ab.getBaseBoneRelativePosition(i));
positions.add(position);
// log(ab.getBoneName(i)+" pos="+ThreeLog.get(position)+",base="+ThreeLog.get(ab.getBaseBoneRelativePosition(i)));
}
List<Vector3> targets=new ArrayList<Vector3>();
List<String> names=new ArrayList<String>();
Map<String,Vector3> ikDataMap=new LinkedHashMap<String,Vector3>();
for(IKData ikdata:ikdatas){
if(!availIk(ikdata)){//check ik
continue;
}
//some how not work correctly
Vector3 pos=getDefaultIkPos(ab.getBoneIndex(ikdata.getLastBoneName()));
pos.sub(ab.getBonePosition(ikdata.getLastBoneName()));//relative path
//Vector3 pos=
ikDataMap.put(ikdata.getName(), pos);
}
PoseFrameData ps=new PoseFrameData(matrixs, ikDataMap);
ps.setAngles(angles);
ps.setPositions(positions);
return ps;
}
private void insertFrame(int index,boolean overwrite){
if(index<0){
index=0;
}
PoseFrameData ps=snapCurrentFrameData();
if(overwrite){
getSelectedPoseEditorData().getPoseFrameDatas().set(index,ps);
updatePoseIndex(index,false);
}else{
getSelectedPoseEditorData().getPoseFrameDatas().add(index,ps);
updatePoseIndex(getSelectedPoseEditorData().getPoseFrameDatas().size()-1,false);
}
getSelectedPoseEditorData().setModified(true);
updateSaveButtons();
}
private void updateSaveButtons() {
if(getSelectedPoseEditorData().isModified()){
saveButton.setEnabled(true);
}else{
saveButton.setEnabled(false);
}
}
protected String convertBVHText(PoseEditorData ped) {
ped.updateMatrix(ab);//current-bone
BVH exportBVH=new BVH();
BVHConverter converter=new BVHConverter();
BVHNode node=converter.convertBVHNode(animationBones);
exportBVH.setHiearchy(node);
converter.setChannels(node,0,"XYZ"); //TODO support other order
BVHMotion motion=new BVHMotion();
motion.setFrameTime(.25);
//TODO post issue
//this is temporaly fix,first frame contain root pos and must sub position
JsArrayNumber rootPos=animationBones.get(0).getPos();
double rootX=0;
double rootY=0;
double rootZ=0;
if(rootPos!=null && rootPos.length()==3){
rootX=rootPos.get(0);
rootY=rootPos.get(1);
rootZ=rootPos.get(2);
}
//somehow this pos value don't care bone position.
for(PoseFrameData pose:ped.getPoseFrameDatas()){
double[] values=converter.angleAndMatrixsToMotion(pose.getAngleAndMatrixs(),BVHConverter.ROOT_POSITION_ROTATE_ONLY,"XYZ");
//TODO update pos based on channel,but now has no channel data
values[0]=values[0]-rootX;
values[1]=values[1]-rootY;
values[2]=values[2]-rootZ;
motion.add(values);
}
motion.setFrames(motion.getMotions().size());
exportBVH.setMotion(motion);
//log("frames:"+exportBVH.getFrames());
BVHWriter writer=new BVHWriter();
String bvhText=writer.writeToString(exportBVH);
return bvhText;
/*
//log(bvhText);
ExportUtils.exportTextAsDownloadDataUrl(bvhText, "UTF-8", "poseeditor"+exportIndex);
//ExportUtils.openTabTextChrome(bvhText,"poseeditor"+exportIndex);//
exportIndex++;
*/
}
private int exportIndex=0;
private int poseFrameDataIndex=0;
//private List<PoseFrameData> poseFrameDatas=new ArrayList<PoseFrameData>();
private void updatePoseIndex(int index){
updatePoseIndex(index,true);
}
private void updatePoseIndex(int index,boolean needSelect){
if(index==-1){
currentFrameRange.setMax(0);
currentFrameRange.setValue(0);
currentFrameLabel.setText("");
}else{
//poseIndex=index;
currentFrameRange.setMax(Math.max(0,getSelectedPoseEditorData().getPoseFrameDatas().size()-1));
if(currentFrameRange.getValue()==index){
currentFrameRange.setValue(currentFrameRange.getMin());//on paste before not value change,index
//need change value to update range widget;
}
currentFrameRange.setValue(index);
currentFrameLabel.setText((index+1)+"/"+getSelectedPoseEditorData().getPoseFrameDatas().size());
//currentFrameRange.setFocus(true);
//LogUtils.log(currentFrameRange.getMin()+"/"+currentFrameRange.getMax()+" v="+currentFrameRange.getValue());
if(!needSelect){
poseFrameDataIndex=index; //need set poseFrameDataIndex,
return;//no need select maybe still add or replacing
}
//check in range
if(index<=currentFrameRange.getMax() && getSelectedPoseEditorData().getPoseFrameDatas().size()!=0){//0 is empty no need to set
selectFrameData(index);
}else{
LogUtils.log("call small index:"+index+" of "+currentFrameRange.getMax());
}
}
}
private void selectFrameData(int index) {
poseFrameDataIndex=index;
PoseFrameData pfd=getSelectedPoseEditorData().getPoseFrameDatas().get(index);
if(pfd.getAngleAndMatrixs().size()!=animationBones.length()){
Window.alert("difference- bone.not compatiple this frame.\nso push new button.");
return;
}
selectAnimationDataData(AnimationBonesData.cloneAngleAndMatrix(pfd.getAngleAndMatrixs()));
}
private void selectAnimationDataData(List<AngleAndPosition> angleAndPositions) {
currentMatrixs=angleAndPositions;
ab.setBonesAngleAndMatrixs(currentMatrixs);
//update
fitIkOnBone();
//followTarget();//use initial pos,TODO follow or fit
/*
for(int i=0;i<ikdatas.size();i++){
if(!availIk(ikdatas.get(i))){
continue;
}
int boneIndex=ab.getBoneIndex(ikdatas.get(i).getLastBoneName());
ab.getBonePosition(boneIndex);
//this is load form ikdatas
String ikName=ikdatas.get(i).getName();
Vector3 vec=pfd.getIkTargetPosition(ikName);
if(vec!=null){
vec=vec.clone();
vec.add(ab.getBonePosition(ikdatas.get(i).getLastBoneName()));//relative path
LogUtils.log("ignore ikpos");
ikdatas.get(i).getTargetPos().set(vec.getX(), vec.getY(), vec.getZ());
}
}
*/
if(isSelectedIk()){
switchSelectionIk(getCurrentIkData().getLastBoneName());
}
doPoseByMatrix(ab);
updateBoneRanges();
}
/**
* ik position is same on last ik bone.
* this style usually not so moved when root-bone rotateds
*
* call doPoseByMatrix or syncIkPosition to sync 3d model position
*/
private void fitIkOnBone() {
for(IKData ik:getAvaiableIkdatas()){
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name,isIkTargetEndSite);//try get endsite
ik.getTargetPos().copy(pos);
}
}
private void rotToBone(String name,double x,double y,double z,boolean doPoseByMatrix){
int index=ab.getBoneIndex(name);
if(index==-1){
LogUtils.log("rotToBone:invalid bone called name="+name);
return ;
}
//Matrix4 mx=ab.getBoneMatrix(name);
Vector3 degAngles=THREE.Vector3(x,y,z);
Vector3 angles=GWTThreeUtils.degreeToRagiant(degAngles);
//log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
//mx.setRotationFromEuler(angles, "XYZ");
Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(index).getMatrix());
//log("pos:"+ThreeLog.get(pos));
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiplyMatrices(posMx,rotMx);
//log("bone-pos:"+ThreeLog.get(bones.get(index).getPos()));
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
ab.getBoneAngleAndMatrix(index).setAngle(degAngles);
if(doPoseByMatrix){
doPoseByMatrix(ab);
}
}
//update current selection angles
private void rotToBone(){
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
rotToBone(name,rotationBoneXRange.getValue(),rotationBoneYRange.getValue(),rotationBoneZRange.getValue(),true);
}
/*
private void rotToBone(String boneName,Vector3 degAngles,boolean doPoseByMatrix){
int index=ab.getBoneIndex(boneName);
if(index==-1){
LogUtils.log("rotToBone:invalid bone called name="+boneName);
return ;
}
Vector3 angles=GWTThreeUtils.degreeToRagiant(degAngles);
//log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
//mx.setRotationFromEuler(angles, "XYZ");
Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(index).getMatrix());
//log("pos:"+ThreeLog.get(pos));
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiplyMatrices(posMx,rotMx);
//log("bone-pos:"+ThreeLog.get(bones.get(index).getPos()));
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
ab.getBoneAngleAndMatrix(index).setAngle(degAngles);
//log("set angle:"+ThreeLog.get(degAngles));
if(doPoseByMatrix){
doPoseByMatrix(ab);
}
}
*/
private void updateBoneRanges(){
updateBoneRotationRanges();
updateBonePositionRanges();
}
private void updateBoneRotationRanges(){
if(isSelectEmptyBoneListBox()){
setEnableBoneRanges(false,false,true);
return;
}else{
setEnableBoneRanges(true,true,false);
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
if(ikLocks.contains(name)){
ikLockCheck.setValue(true);
}else{
ikLockCheck.setValue(false);
}
int boneIndex=ab.getBoneIndex(name);
if(boneIndex!=0){//only root has position
rotateAndPosList.setSelectedIndex(0);
switchRotateAndPosList();
}
//Quaternion q=GWTThreeUtils.jsArrayToQuaternion(bones.get(boneIndex).getRotq());
//log("bone:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(q))));
Vector3 mAngles=GWTThreeUtils.toDegreeAngle(ab.getBoneAngleAndMatrix(name).getMatrix());
//log("updateBoneRotationRanges():"+ThreeLog.get(mAngles));
Vector3 angles=ab.getBoneAngleAndMatrix(name).getAngle();
int x=(int) angles.getX();
rotationBoneXRange.setValue(x);
if(boneLock.hasX(name)){
xlockCheck.setValue(true);
rotationBoneXRange.setEnabled(false);
}else{
xlockCheck.setValue(false);
rotationBoneXRange.setEnabled(true);
}
int y=(int) angles.getY();
rotationBoneYRange.setValue(y);
if(boneLock.hasY(name)){
ylockCheck.setValue(true);
rotationBoneYRange.setEnabled(false);
}else{
ylockCheck.setValue(false);
rotationBoneYRange.setEnabled(true);
}
int z=(int) angles.getZ();
rotationBoneZRange.setValue(z);
if(boneLock.hasZ(name)){
zlockCheck.setValue(true);
rotationBoneZRange.setEnabled(false);
}else{
zlockCheck.setValue(false);
rotationBoneZRange.setEnabled(true);
}
}
private boolean isSelectEmptyBoneListBox(){
return boneNamesBox.getSelectedIndex()==-1 || boneNamesBox.getItemText(boneNamesBox.getSelectedIndex()).isEmpty();
}
private void updateBonePositionRanges(){
if(isSelectEmptyBoneListBox()){
return;
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
Vector3 values=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(name).getMatrix());
values.multiplyScalar(100);
int x=(int) values.getX();
positionXBoneRange.setValue(x);
int y=(int) values.getY();
positionYBoneRange.setValue(y);
int z=(int) values.getZ();
positionZBoneRange.setValue(z);
}
private Material bodyMaterial;
private String textureUrl="female001_texture1.jpg";//default
private Texture texture;
protected void updateMaterial() {
if(lastLoadedModel!=null){
if(lastLoadedModel.getMetaData().getFormatVersion()==3){
texture.setFlipY(false);
}else{
texture.setFlipY(true);
}
}
Material material=null;
boolean transparent=transparentCheck.getValue();
double opacity=1;
if(transparent){
opacity=0.75;
}
JSParameter parameter=MeshBasicMaterialParameter.create().map(texture).transparent(true).opacity(opacity);
if(texture==null){//some case happend
material=THREE.MeshBasicMaterial(MeshBasicMaterialParameter.create().transparent(true).opacity(opacity));
//only initial happend,if you set invalid texture
}else{
if(basicMaterialCheck.getValue()){
material=THREE.MeshBasicMaterial(parameter);
}else{
material=THREE.MeshLambertMaterial(parameter);
}
}
bodyMaterial=material;
if(basicMaterialCheck.getValue()){
if(bodyMesh!=null){
bodyMesh.setMaterial(material);//somehow now works.
}else{
LogUtils.log("materical update called,but body mesh is null");
}
}else{
//not basic material need recreate-model
doPoseByMatrix(ab);
}
//test loaded material
/* i have no idea how to set it.
if(loadedMaterials!=null){
MeshFaceMaterial faceMaterial=THREE.MeshFaceMaterial(loadedMaterials);
LogUtils.log(faceMaterial);
bodyMesh.setMaterial(faceMaterial);
}
*/
}
//TODO use for load bvh
private void loadBVH(String path){
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path));
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
String bvhText=response.getText();
parseInitialBVHAndLoadModels(bvhText);
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("load faild:");
}
});
} catch (RequestException e) {
LogUtils.log(e.getMessage());
e.printStackTrace();
}
}
private Geometry baseGeometry;
private List<String> boneList=new ArrayList<String>();
protected void parseInitialBVHAndLoadModels(String bvhText) {
final BVHParser parser=new BVHParser();
parser.parseAsync(bvhText, new ParserListener() {
@Override
public void onFaild(String message) {
LogUtils.log(message);
}
@Override
public void onSuccess(BVH bv) {
bvh=bv;
//createBonesFromBVH
AnimationBoneConverter converter=new AnimationBoneConverter();
setBone(converter.convertJsonBone(bvh));
if(preferencePanel!=null){
LogUtils.log("load from preference");
preferencePanel.loadSelectionModel();
preferencePanel.loadSelectionTexture();
}
//frameRange.setMax(animationData.getHierarchy().get(0).getKeys().length());
/*
JSONLoader loader=THREE.JSONLoader();
loader.load("men3menb.js", new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
baseGeometry=geometry;
//doPose(0);
doPose(0);//bug i have no idea,need call twice to better initial pose
initialPoseFrameData=snapCurrentFrameData();
doNewFile();
//insertFrame(getSelectedPoseEditorData().getPoseFrameDatas().size(),false);//initial pose-frame
}
});
*/
}
});
}
private void setBone(JsArray<AnimationBone> bo){
animationBones=bo;
AnimationDataConverter dataConverter=new AnimationDataConverter();
dataConverter.setSkipFirst(false);
animationData = dataConverter.convertJsonAnimation(animationBones,bvh);//use for first pose
boneList.clear();
for(int i=0;i<animationBones.length();i++){
boneList.add(animationBones.get(i).getName()); //TODO should i trim?
//log(bones.get(i).getName()+","+ThreeLog.get(GWTThreeUtils.jsArrayToVector3(bones.get(i).getPos())));
}
}
/**
* simple check bone-name;
* @param name
* @return
*/
private boolean existBone(String name){
return boneList.contains(name);
}
public static class MatrixAndVector3{
public MatrixAndVector3(){}
private Vector3 position;
public Vector3 getPosition() {
return position;
}
public void setPosition(Vector3 position) {
this.position = position;
}
private Vector3 absolutePosition;
public Vector3 getAbsolutePosition() {
return absolutePosition;
}
public void setAbsolutePosition(Vector3 absolutePosition) {
this.absolutePosition = absolutePosition;
}
public Matrix4 getMatrix() {
return matrix;
}
public void setMatrix(Matrix4 matrix) {
this.matrix = matrix;
}
private Matrix4 matrix;
}
private List<MatrixAndVector3> boneMatrix;
/*
private Vector3 calculateBonedPos(Vector3 pos,AnimationBone bone,int animationIndex){
}
*/
public static List<MatrixAndVector3> boneToBoneMatrix(JsArray<AnimationBone> bones,AnimationData animationData,int index){
List<MatrixAndVector3> boneMatrix=new ArrayList<MatrixAndVector3>();
//analyze bone matrix
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
AnimationHierarchyItem item=animationData.getHierarchy().get(i);
AnimationKey motion=item.getKeys().get(index);
//log(bone.getName());
Matrix4 mx=THREE.Matrix4().makeRotationFromQuaternion(GWTThreeUtils.jsArrayToQuaternion(motion.getRot()));
Vector3 motionPos=GWTThreeUtils.jsArrayToVector3(motion.getPos());
//seems same as bone
// LogUtils.log(motionPos);
mx.setPosition(motionPos);
//mx.setRotationFromQuaternion();
/*
Matrix4 mx2=THREE.Matrix4();
mx2.setRotationFromQuaternion(motion.getRot());
mx.multiplySelf(mx2);
*/
/*
Vector3 tmpRot=THREE.Vector3();
tmpRot.setRotationFromMatrix(mx);
Vector3 tmpPos=THREE.Vector3();
tmpPos.setPositionFromMatrix(mx);
*/
//LogUtils.log(tmpPos.getX()+","+tmpPos.getY()+","+tmpPos.getZ());
//LogUtils.log(Math.toDegrees(tmpRot.))
MatrixAndVector3 mv=new MatrixAndVector3();
Vector3 bpos=AnimationBone.jsArrayToVector3(bone.getPos());
mv.setPosition(bpos);//not effected self matrix
mv.setMatrix(mx);
if(bone.getParent()!=-1){
MatrixAndVector3 parentMv=boneMatrix.get(bone.getParent());
Vector3 apos=bpos.clone();
apos.add(parentMv.getAbsolutePosition());
mv.setAbsolutePosition(apos);
}else{
//root
mv.setAbsolutePosition(bpos.clone());
}
boneMatrix.add(mv);
}
return boneMatrix;
}
private List<List<Integer>> bonePath;
private boolean hasChild(List<List<Integer>> paths,int target){
boolean ret=false;
for(List<Integer> path:paths){
for(int i=0;i<path.size()-1;i++){//exclude last
if(path.get(i)==target){
return true;
}
}
}
return ret;
}
public static List<List<Integer>> boneToPath(JsArray<AnimationBone> bones){
List<List<Integer>> data=new ArrayList<List<Integer>>();
for(int i=0;i<bones.length();i++){
List<Integer> path=new ArrayList<Integer>();
AnimationBone bone=bones.get(i);
path.add(i);
data.add(path);
while(bone.getParent()!=-1){
//path.add(bone.getParent());
path.add(0,bone.getParent());
bone=bones.get(bone.getParent());
}
}
return data;
}
private JsArray<Vector4> bodyIndices;
private JsArray<Vector4> bodyWeight;
Mesh bodyMesh;
Object3D root;
Object3D bone3D;
Object3D ik3D;
private CheckBox transparentCheck;
private CheckBox basicMaterialCheck;
/**
* called after load
* @param index
*/
/*
* trying to fix leg problem
Vector3 rootOffset=GWTThreeUtils.jsArrayToVector3(animationData.getHierarchy().get(0).getKeys().get(index).getPos());
//initial pose is base for motions
baseGeometry=GeometryUtils.clone(bodyMesh.getGeometry());
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex vertex=baseGeometry.vertices().get(i);
vertex.getPosition().subSelf(rootOffset);
}
*/
//for after loading
private void doRePose(int index){
//initializeBodyMesh();
initializeAnimationData(index,true);
//stepCDDIk();
doPoseByMatrix(ab);
updateBoneRanges();
LogUtils.log("update-bone-range");
}
AnimationBonesData ab;
List<AngleAndPosition> baseMatrixs;
private void applyMatrix(List<AngleAndPosition> matrix,List<NameAndVector3> samples){
for(NameAndVector3 nv:samples){
int boneIndex=ab.getBoneIndex(nv.getName());
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(boneIndex).getMatrix()));
Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(nv.getVector3());
newMatrix.multiplyMatrices(translates,newMatrix);
//log("apply-matrix");
matrix.get(boneIndex).setAngle(GWTThreeUtils.radiantToDegree(nv.getVector3()));
matrix.get(boneIndex).setMatrix(newMatrix);
}
}
List<List<AngleAndPosition>> candiateAngleAndMatrixs;
/*
private void initializeBodyMesh(){
//initializeBodyMesh
if(bodyMesh==null){//initial Indices & weight,be careful bodyMesh create in doPoseByMatrix
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
//geometry initialized 0 indices & weights
if(baseGeometry.getSkinIndices().length()!=0 && baseGeometry.getSkinWeight().length()!=0){
log("auto-weight from geometry:");
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight);
}else{
//WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}
//WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearAgressive, bodyIndices, bodyWeight);
log("initialized-weight:"+bodyIndices.length());
for(int i=0;i<bodyIndices.length();i++){
log(bodyIndices.get(i).getX()+" x "+bodyIndices.get(i).getY());
}
}else{
root.remove(bodyMesh);
}
}
*/
List<AngleAndPosition> currentMatrixs;
private void initializeAnimationData(int index,boolean resetMatrix){
//initialize AnimationBone
if(ab==null){
baseMatrixs=AnimationBonesData.boneToAngleAndMatrix(animationBones, animationData, index);
ab=new AnimationBonesData(animationBones,AnimationBonesData.cloneAngleAndMatrix(baseMatrixs) );
currentMatrixs=null;
for(int i=0;i<animationBones.length();i++){
// log(bones.get(i).getName()+":"+ThreeLog.get(baseMatrixs.get(i).getPosition()));
}
}
//TODO make automatic
//this is find base matrix ,because sometime cdd-ik faild from some position
//nearMatrix=new ArrayList<List<Matrix4>>();
//nearMatrix.add(AnimationBonesData.cloneMatrix(baseMatrixs));
/*
* for foot
List<NameAndVector3> sample=new ArrayList<NameAndVector3>();
sample.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(90, 0, 0)), 0));
sample.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(-90, 0, 0)), 0));
List<Matrix4> bm=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm, sample);
nearMatrix.add(bm);
List<NameAndVector3> sample1=new ArrayList<NameAndVector3>();
sample1.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 0)), 0));
sample1.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 45)), 0));
List<Matrix4> bm1=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm1, sample);
//ab.setBonesMatrixs(findStartMatrix("RightFoot",getCurrentIkData().getTargetPos()));//
*/
if(currentMatrixs!=null && resetMatrix){
if(candiateAngleAndMatrixs!=null){
//need bone limit
ab.setBonesAngleAndMatrixs(AnimationBonesData.cloneAngleAndMatrix(findStartMatrix(getCurrentIkData().getLastBoneName(),getCurrentIkData().getTargetPos())));
}else{
ab.setBonesAngleAndMatrixs(AnimationBonesData.cloneAngleAndMatrix(currentMatrixs));
}
//TODO only need?
}else{
}
}
private BoneLockControler boneLock=new BoneLockControler();
//this new position base ikk faild
private Vector3 findNextStep(int boneIndex,int lastBoneIndex,Vector3 targetPos){
Vector3 lastTrans=ab.getMatrixPosition(lastBoneIndex);
List<Integer> path=ab.getBonePath(lastBoneIndex);
Matrix4 matrix=THREE.Matrix4();
for(int i=0;i<path.size()-1;i++){
int bindex=path.get(i);
AngleAndPosition am=ab.getBoneAngleAndMatrix(bindex);
matrix.multiply(am.getMatrix());
}
Vector3 base=THREE.Vector3(0,0,0);
Vector3 pos=matrix.multiplyVector3(lastTrans.clone());
double length=pos.sub(targetPos).length();
//log("length:"+length+","+0+"x"+0+"x"+0);
Vector3 tmpVec=THREE.Vector3();
for(int x=-1;x<=1;x++){
for(int y=-1;y<=1;y++){
for(int z=-1;z<=1;z++){
if(x==0 && y==0 && z==0){
continue;
}
tmpVec.set(x*5, y*5, z*5);
matrix=THREE.Matrix4();
for(int i=0;i<path.size()-1;i++){
int bindex=path.get(i);
AngleAndPosition am=ab.getBoneAngleAndMatrix(bindex);
Matrix4 m=am.getMatrix();
if(bindex==boneIndex){
Vector3 newAngle=am.getAngle().clone().add(tmpVec);
Vector3 pv=GWTThreeUtils.toPositionVec(m);
m=THREE.Matrix4();
m.setPosition(pv);
m.setRotationFromEuler(newAngle, "XYZ");
}
matrix.multiply(m);
}
pos=matrix.multiplyVector3(lastTrans.clone());
double tmpl=pos.sub(targetPos).length();
//log("length:"+tmpl+","+x+"x"+y+"x"+z);
if(tmpl<length){
base.set(x*5,y*5,z*5);
length=tmpl;
}
}
}
}
//log("mutch:"+ThreeLog.get(base));
return base.add(ab.getBoneAngleAndMatrix(boneIndex).getAngle());
}
private boolean doLimit=true;
private boolean ignorePerLimit=false;
private void stepCDDIk(int perLimit,IKData ikData,int cddLoop){
//do CDDIK
//doCDDIk();
currentIkJointIndex=0;
List<AngleAndPosition> minMatrix=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
double minLength=ab.getBonePosition(ikData.getLastBoneName(),isIkTargetEndSite).clone().sub(ikData.getTargetPos()).length();
for(int i=0;i<ikData.getIteration()*cddLoop;i++){
String targetBoneName=ikData.getBones().get(currentIkJointIndex);
if(ikLocks.contains(targetBoneName)){
currentIkJointIndex++;
if(currentIkJointIndex>=ikData.getBones().size()){
currentIkJointIndex=0;
}
//LogUtils.log("skipped-ik:"+targetBoneName);
continue;
}
//LogUtils.log("do-ik:"+targetBoneName);
int boneIndex=ab.getBoneIndex(targetBoneName);
Vector3 ikkedAngle=null;
Matrix4 jointRot=ab.getBoneAngleAndMatrix(targetBoneName).getMatrix();
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(jointRot));
Vector3 currentAngle=ab.getBoneAngleAndMatrix(targetBoneName).getAngle().clone();
//log("current:"+ThreeLog.get(currentAngle));
String beforeAngleLog="";
if(perLimit>0){
Vector3 lastJointPos=ab.getBonePosition(ikData.getLastBoneName(),isIkTargetEndSite);
//Vector3 jointPos=ab.getParentPosition(targetName);
Vector3 jointPos=ab.getBonePosition(targetBoneName);
//Vector3 beforeAngles=GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(jointRot));
//Vector3 beforeAngle=ab.getBoneAngleAndMatrix(targetBoneName).getAngle().clone();
//Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, ikData.getTargetPos());
//TODO add parent bone angles
//AngleAndPosition root=ab.getBoneAngleAndMatrix(0);
Vector3 parentAngle=ab.getParentAngles(boneIndex);
Matrix4 newMatrix=cddIk.getStepAngleMatrix(parentAngle,lastJointPos, jointPos, jointRot, ikData.getTargetPos());
beforeAngleLog=targetBoneName+","+"parent:"+ThreeLog.get(parentAngle)+",joint:"+ThreeLog.get(currentAngle);
if(newMatrix==null){//invalid value
if(debug){
LogUtils.log("null matrix");
}
continue;
}
//limit per angles
/*
* if angle value over 90 usually value is invalid.
* but i dont know how to detect or fix it.
*/
ikkedAngle=GWTThreeUtils.rotationToVector3(newMatrix);
//Vector3 diffAngles=GWTThreeUtils.radiantToDegree(ikkedAngle).subSelf(currentAngle);
Vector3 diffAngles=GWTThreeUtils.radiantToDegree(ikkedAngle);
if(perLimit==1){
//diffAngles.normalize();
}
//diffAngles.normalize().addScalar(perLimit);//miss choice
//log("diff:"+ThreeLog.get(diffAngles));
if(!ignorePerLimit){
if(Math.abs(diffAngles.getX())>perLimit){
double diff=perLimit;
if(diffAngles.getX()<0){
diff*=-1;
}
diffAngles.setX(diff);
}
if(Math.abs(diffAngles.getY())>perLimit){
double diff=perLimit;
if(diffAngles.getY()<0){
diff*=-1;
}
diffAngles.setY(diff);
}
if(Math.abs(diffAngles.getZ())>perLimit){
double diff=perLimit;
if(diffAngles.getZ()<0){
diff*=-1;
}
diffAngles.setZ(diff);
}
}
currentAngle.add(diffAngles);
//log("added:"+ThreeLog.get(currentAngle));
//currentAngle.setX(0);//keep x
ikkedAngle=GWTThreeUtils.degreeToRagiant(currentAngle);
}else{
//faild TODO fix it
Vector3 angle=findNextStep(boneIndex, ab.getBoneIndex(ikData.getLastBoneName()), ikData.getTargetPos());
//log(targetBoneName+" before:"+ThreeLog.get(ab.getBoneAngleAndMatrix(boneIndex).getAngle())+" after:"+ThreeLog.get(angle));
ikkedAngle=GWTThreeUtils.degreeToRagiant(angle);
}
//log("before:"+ThreeLog.get(beforeAngle)+" after:"+ThreeLog.get(currentAngle));
//limit max
BoneLimit blimit=boneLimits.get(targetBoneName);
//log(targetBoneName);
//log("before-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
if(blimit!=null && doLimit){
blimit.apply(ikkedAngle);
}
//invalid ignore
if("NaN".equals(""+ikkedAngle.getX())){
continue;
}
if("NaN".equals(""+ikkedAngle.getY())){
continue;
}
if("NaN".equals(""+ikkedAngle.getZ())){
continue;
}
if(boneLock.hasX(targetBoneName)){
ikkedAngle.setX(Math.toRadians(boneLock.getX(targetBoneName)));
}
if(boneLock.hasY(targetBoneName)){
ikkedAngle.setY(Math.toRadians(boneLock.getY(targetBoneName)));
}
if(boneLock.hasZ(targetBoneName)){
ikkedAngle.setZ(Math.toRadians(boneLock.getZ(targetBoneName)));
}
//String afterAngleLog=("after-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(ikkedAngle)));
Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(ikkedAngle);
newMatrix.multiplyMatrices(translates,newMatrix);
ab.getBoneAngleAndMatrix(boneIndex).setMatrix(newMatrix);
ab.getBoneAngleAndMatrix(boneIndex).setAngle(GWTThreeUtils.radiantToDegree(ikkedAngle));
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
Vector3 diffPos=ab.getBonePosition(ikData.getLastBoneName()).clone().subSelf(ikData.getTargetPos());
/*
if(diffPos.length()>2){
//usually ivalid
log(i+","+"length="+diffPos.length()+" diff:"+ThreeLog.get(diffPos));
log(beforeAngleLog);
log(afterAngleLog);
}*/
if(diffPos.length()<minLength){
minMatrix=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
}
currentIkJointIndex++;
if(currentIkJointIndex>=ikData.getBones().size()){
currentIkJointIndex=0;
}
if(diffPos.length()<0.02){
break;
}
//tmp1=lastJointPos;
//tmp2=jointPos;
}
ab.setBonesAngleAndMatrixs(minMatrix);//use min
}
private void doPoseIkk(int index,boolean resetMatrix,int perLimit,IKData ikdata,int cddLoop){
if(!existBone(ikdata.getLastBoneName())){
return;//some non exist bone.
}
//initializeBodyMesh();
initializeAnimationData(index,resetMatrix);
stepCDDIk(perLimit,ikdata,cddLoop);
doPoseByMatrix(ab);
updateBoneRanges();
}
private List<AngleAndPosition> findStartMatrix(String boneName,Vector3 targetPos) {
List<AngleAndPosition> retMatrix=candiateAngleAndMatrixs.get(0);
ab.setBonesAngleAndMatrixs(retMatrix);//TODO without set
Vector3 tpos=ab.getBonePosition(boneName);
double minlength=targetPos.clone().sub(tpos).length();
for(int i=1;i<candiateAngleAndMatrixs.size();i++){
List<AngleAndPosition> mxs=candiateAngleAndMatrixs.get(i);
ab.setBonesAngleAndMatrixs(mxs);//TODO change
Vector3 tmpPos=ab.getBonePosition(boneName);
double tmpLength=targetPos.clone().sub(tmpPos).length();
if(tmpLength<minlength){
minlength=tmpLength;
retMatrix=mxs;
}
}
for(String name:getCurrentIkData().getBones()){
//Matrix4 mx=retMatrix.get(ab.getBoneIndex(name));
// log(name+":"+ThreeLog.get(GWTThreeUtils.rotationToVector3(mx)));
// log(name+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx)));
}
return retMatrix;
}
/*
private void doCDDIk(){
String targetName=getCurrentIkData().getBones().get(currentIkJointIndex);
int boneIndex=ab.getBoneIndex(targetName);
Vector3 lastJointPos=ab.getPosition("RightFoot");
Vector3 jointPos=ab.getParentPosition(targetName);
Matrix4 jointRot=ab.getBoneMatrix(targetName);
Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, getCurrentIkData().getTargetPos());
ab.setBoneMatrix(boneIndex, newMatrix);
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
currentIkJointIndex++;
if(currentIkJointIndex>=getCurrentIkData().getBones().size()){
currentIkJointIndex=0;
}
doPoseByMatrix(ab);
}
*/
CDDIK cddIk=new CDDIK();
int currentIkJointIndex=0;
//private String[] ikTestNames={"RightLeg","RightUpLeg"};
//Vector3 targetPos=THREE.Vector3(-10, -3, 0);
private ListBox boneNamesBox;
private double baseBoneCoreSize=7;
private double baseIkLength=13;
private void doPoseByMatrix(AnimationBonesData animationBonesData){
if(animationBonesData==null){
return;
}
if(isSelectedBone()){
selectionMesh.setPosition(ab.getBonePosition(selectedBone));
}
List<AngleAndPosition> boneMatrix=animationBonesData.getBonesAngleAndMatrixs();
bonePath=boneToPath(animationBones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
if(ik3D!=null){
root.remove(ik3D);
}
ik3D=THREE.Object3D();
root.add(ik3D);
//selection
//test ikk
/*
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(1.5, 1.5, 1.5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
*/
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<animationBones.length();i++){
Matrix4 mv=boneMatrix.get(i).getMatrix();
double bsize=baseBoneCoreSize;
if(i==0){//root is better
bsize=baseBoneCoreSize*2;
}
bsize/=posDivided;
if(smallCheck.getValue()){
bsize/=2;
}
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(bsize,bsize, bsize),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=THREE.Vector3();
pos.setFromMatrixPosition(mv);
//Vector3 rot=GWTThreeUtils.rotationToVector3(GWTThreeUtils.jsArrayToQuaternion(bones.get(i).getRotq()));
Vector3 rot=GWTThreeUtils.degreeToRagiant(ab.getBoneAngleAndMatrix(i).getAngle());
List<Integer> path=bonePath.get(i);
String boneName=animationBones.get(i).getName();
//log(boneName);
mesh.setName(boneName);
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself,no need for bone-pos
Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix();
matrix.multiplyMatrices(matrix, mx);
}
pos.applyProjection(matrix);//set pos before last bone matrixed.
//matrix.multiplyVector3(pos);
//but need for transform
matrix.multiplyMatrices(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one
moveMatrix.add(matrix);
//maybe this position use for end-sites.
if(animationBones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(animationBones.get(i).getParent());
//pos.addSelf(ppos);
//log(boneName+":"+ThreeLog.get(pos)+","+ThreeLog.get(ppos));
Object3D line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
//cylinder
/* better bone faild
Vector3 halfPos=pos.clone().subSelf(ppos).multiplyScalar(0.5).addSelf(ppos);
Mesh boneMesh=THREE.Mesh(THREE.CylinderGeometry(.1,.1,.2,6), THREE.MeshLambertMaterial().color(0xffffff).build());
boneMesh.setPosition(halfPos);
boneMesh.setName(boneName);
bone3D.add(boneMesh);
BoxData data=boxDatas.get(boneName);
if(data!=null){
boneMesh.setScale(data.getScaleX(), data.getScaleY(), data.getScaleZ());
boneMesh.getRotation().setZ(Math.toRadians(data.getRotateZ()));
}
*/
for(IKData ik:getAvaiableIkdatas()){
if(ik.getLastBoneName().equals(boneName)){//valid ik
Mesh ikMesh=targetMeshs.get(boneName);
if(ikMesh==null){//at first call this from non-ik stepped.
//log("xxx");
//initial
double ikLength=baseIkLength/posDivided;
if(!hasChild(bonePath,i)){
ikLength=baseIkLength*2/posDivided;
}
double ikCoreSize=baseBoneCoreSize*2/posDivided;
Vector3 ikpos=pos.clone().subSelf(ppos).multiplyScalar(ikLength).addSelf(ppos);
//ikpos=pos.clone();
//trying transparent
ikMesh=THREE.Mesh(THREE.CubeGeometry(ikCoreSize, ikCoreSize, ikCoreSize),THREE.MeshLambertMaterial(MeshLambertMaterialParameter.create().color(0x00ff00).transparent(true).opacity(0.5)));
ikMesh.setPosition(ikpos);
ikMesh.setName("ik:"+boneName);
// log(boneName+":"+ThreeLog.get(ikpos));
//log(ThreeLog.get(pos));
ik.getTargetPos().set(ikpos.getX(), ikpos.getY(), ikpos.getZ());
targetMeshs.put(boneName, ikMesh);
}else{
ikMesh.getParent().remove(ikMesh);
}
ik3D.add(ikMesh);
ikMesh.setPosition(ik.getTargetPos());
Line ikline=GWTGeometryUtils.createLineMesh(pos, ik.getTargetPos(), 0xffffff);
ik3D.add(ikline);
}
}
}
mesh.setRotation(rot);
mesh.setPosition(pos);
//mesh color
if(pos.getY()<0){
mesh.getMaterial().gwtGetColor().set(0xffee00);//over color
}else if(pos.getY()<10.0/posDivided){
mesh.getMaterial().gwtGetColor().set(0xff8800);//near
}
bonePositions.add(pos);
}
//dont work
Object3DUtils.setVisibleAll(bone3D, showBonesCheck.getValue());
Object3DUtils.setVisibleAll(ik3D, showIkCheck.getValue());
//bone3D.setVisible(showBonesCheck.getValue());
//Geometry geo=GeometryUtils.clone(baseGeometry);
//initialize AutoWeight
if(bodyMesh==null){//initial
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
//geometry initialized 0 indices & weights
if(baseGeometry.getSkinIndices().length()!=0 && baseGeometry.getSkinWeight().length()!=0){
//LogUtils.log(bones);
LogUtils.log("use geometry bone");
//test
/*
LogUtils.log("testlly use root all geometry");
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_ROOT_ALL, bodyIndices, bodyWeight);
*/
WeightBuilder.autoWeight(baseGeometry, animationBones, WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight);
/*
List<String> lines=new ArrayList<String>();
for(int i=0;i<bodyWeight.length();i++){
lines.add(i+get(bodyWeight.get(i)));
}
LogUtils.log("after");
LogUtils.log(Joiner.on("\n").join(lines));
*/
}else{
LogUtils.log("auto-weight :sometime this broke models.you can use ModelWeight Apps");
WeightBuilder.autoWeight(baseGeometry, animationBones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}
}else{
root.remove(bodyMesh);
}
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
//log("bi-length:"+bodyIndices.length());
for(int i=0;i<baseGeometry.vertices().length();i++){
Vector3 baseVertex=baseGeometry.vertices().get(i);
Vector3 vertexPosition=baseVertex.clone();
Vector3 targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
String name=animationBonesData.getBoneName(boneIndex1);
//log(boneIndex1+"x"+boneIndex2);
/*
*
if(name.equals("RightLeg")){//test parent base
Vector3 parentPos=animationBonesData.getBaseParentBonePosition(boneIndex1);
Matrix4 tmpMatrix=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 20)));
vertexPosition.subSelf(parentPos);
tmpMatrix.multiplyVector3(vertexPosition);
vertexPosition.addSelf(parentPos);
boneIndex2=boneIndex1; //dont work without this
}*/
Vector3 bonePos=animationBonesData.getBaseBonePosition(boneIndex1);
Vector3 relatePos=bonePos.clone();
relatePos.subVectors(vertexPosition,bonePos);
//double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
/*
if(name.equals("RightLeg")){
Vector3 parentPos=animationBonesData.getParentPosition(boneIndex1);
relatePos.subSelf(parentPos);
Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
tmpMatrix2.multiplyVector3(relatePos);
relatePos.addSelf(parentPos);
}*/
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
//what is this?
Vector3 bonePos2=animationBonesData.getBaseBonePosition(boneIndex2);
Vector3 relatePos2=bonePos2.clone();
relatePos2.subVectors(baseVertex,bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.add(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
/*//why need this?,anyway this crash models.
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.subVectors(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.add(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
//LogUtils.log("length2<1:"+i);
}
*/
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}else{
if(name.equals("RightLeg")){
// Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
// tmpMatrix2.multiplyVector3(relatePos);
}
}
targetVertex.set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
//selection
//selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
if(isSelectedIk()){
selectionMesh.setPosition(getCurrentIkData().getTargetPos());
}
//bone3D.add(selectionMesh);
//selectionMesh.setVisible(false);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
//TODO move to three.js
public static String get(Vector4 vec){
if(vec==null){
return "Null";
}
String ret="x:"+vec.getX();
ret+=",y:"+vec.getY();
ret+=",z:"+vec.getZ();
ret+=",w:"+vec.getW();
return ret;
}
private Vector3 getDefaultIkPos(int index){
Vector3 pos=ab.getBonePosition(index);
Vector3 ppos=ab.getParentPosition(index);
double ikLength=1.5;
if(!hasChild(bonePath,index)){
ikLength=2.5;
}
return pos.clone().sub(ppos).multiplyScalar(ikLength).add(ppos);
}
private Map<String,Mesh> targetMeshs=new HashMap<String,Mesh>();
private ListBox rotateAndPosList;
private VerticalPanel bonePositionsPanel;
private VerticalPanel boneRotationsPanel;
private CheckBox zlockCheck;
private CheckBox ikLockCheck;
//private ListBox fileNames;
private ValueListBox<PoseEditorData> pedSelectionListBox;
private IStorageControler storageControler;
private VerticalPanel datasPanel;
private Button saveButton;
private VerticalPanel bonePostionAndRotationContainer;
private MenuItem contextMenuShowPrevFrame;
private MenuItem contextMenuHidePrefIks;
private GridHelper backgroundGrid;
private Label ikPositionLabelX;
private MenuBar rootBar;
private VerticalPanel imageLinkContainer;
private Button undoButton;
;
/**
* @deprecated
*/
private void doPose(List<MatrixAndVector3> boneMatrix){
bonePath=boneToPath(animationBones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
//test ikk
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<animationBones.length();i++){
MatrixAndVector3 mv=boneMatrix.get(i);
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=mv.getPosition().clone();
List<Integer> path=bonePath.get(i);
String boneName=animationBones.get(i).getName();
//log(boneName);
Matrix4 tmpmx=boneMatrix.get(path.get(path.size()-1)).getMatrix();
Vector3 tmpp=THREE.Vector3();
tmpp.setFromMatrixPosition(tmpmx);
//log(pos.getX()+","+pos.getY()+","+pos.getZ()+":"+tmpp.getX()+","+tmpp.getY()+","+tmpp.getZ());
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself
// log(""+path.get(j));
Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix();
matrix.multiplyMatrices(matrix, mx);
}
matrix.multiplyVector3(pos);
matrix.multiplyMatrices(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one
moveMatrix.add(matrix);
if(animationBones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(animationBones.get(i).getParent());
//pos.addSelf(ppos);
Line line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
}else{
//root action
Matrix4 mx=boneMatrix.get(0).getMatrix();
mx.multiplyVector3(pos);
}
mesh.setPosition(pos);
bonePositions.add(pos);
}
//Geometry geo=GeometryUtils.clone(baseGeometry);
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
for(int i=0;i<baseGeometry.vertices().length();i++){
Vector3 baseVertex=baseGeometry.vertices().get(i);
Vector3 targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
Vector3 bonePos=boneMatrix.get(boneIndex1).getAbsolutePosition();
Vector3 relatePos=bonePos.clone();
relatePos.sub(baseVertex,bonePos);
double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
Vector3 bonePos2=boneMatrix.get(boneIndex2).getAbsolutePosition();
Vector3 relatePos2=bonePos2.clone();
relatePos2.sub(baseVertex,bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.add(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.add(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}
targetVertex.set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
@Override
public String getHtml(){
String html="Pose Editor ver."+version+" "+super.getHtml()+" 3D-Models created by <a href='http://makehuman.org'>Makehuman</a>";
return html;
}
@Override
public String getTabTitle() {
return "Editor";
}
@Override
public void modelChanged(SimpleTextData model) {
//log("model-load:"+model.getData());
LoadJsonModel(model.getData());
//refresh matrix for new bone-model
pedSelectionListBox.getValue().updateMatrix(ab);
//new model need new initial pose
initialPoseFrameData=snapCurrentFrameData();
try{
//now catch error
selectFrameData(currentFrameRange.getValue());//re pose
}catch (Exception e) {
Window.alert("maybe difference bone model loaded.\nreload app");
}
}
@Override
public void textureChanged(SimpleTextData textureValue) {
textureUrl=textureValue.getData();
generateTexture();
}
private void generateTexture(){
final Image img=new Image(textureUrl);
img.setVisible(false);
RootPanel.get().add(img);
img.addLoadHandler(new com.google.gwt.event.dom.client.LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
Canvas canvas=Canvas.createIfSupported();
canvas.setCoordinateSpaceWidth(img.getWidth());
canvas.setCoordinateSpaceHeight(img.getHeight());
canvas.getContext2d().drawImage(ImageElement.as(img.getElement()),0,0);
texture=THREE.Texture(canvas.getCanvasElement());
texture.setNeedsUpdate(true);
img.removeFromParent();
//LogUtils.log("generate-texture");
updateMaterial();
}
});
}
//this called after mouse up and it's hard to use
@Override
public void onDoubleClick(DoubleClickEvent event) {
//usually called after onMouseDown?
//doMouseDown(event.getX(),event.getY(),true);
}
} |
package ru.tsibrovskii.examples.Bot;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ClientTest {
private static final String LN = System.getProperty("line.separator");
@Test
public void whenGiveInputStreamShouldReturnInputStream() throws IOException {
String inputString = Joiner.on(LN).join("hello", "exit");
Socket socket = mock(Socket.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(inputString.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
when(socket.getOutputStream()).thenReturn(out);
when(socket.getInputStream()).thenReturn(in);
Client client = new Client(socket);
String test = reader.readLine();
String str;
while ((str = reader.readLine()) != null) {
test = String.format("%s%s%s", test, LN, str);
}
assertThat(test, is(inputString));
}
} |
package com.axelby.podax;
import java.io.File;
import java.util.Vector;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActiveDownloadListActivity extends ListActivity {
Runnable refresher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Runnable refresher = new Runnable() {
public void run() {
setListAdapter(new ActiveDownloadAdapter());
new Handler().postDelayed(this, 1000);
}
};
setContentView(R.layout.downloads_list);
refresher.run();
PlayerActivity.injectPlayerFooter(this);
}
public class ActiveDownloadAdapter extends BaseAdapter {
Podcast _active = null;
Vector<Podcast> _waiting = new Vector<Podcast>();
LayoutInflater _layoutInflater;
public ActiveDownloadAdapter() {
super();
_layoutInflater = LayoutInflater.from(ActiveDownloadListActivity.this);
DBAdapter dbAdapter = DBAdapter.getInstance(ActiveDownloadListActivity.this);
Integer activeId = dbAdapter.getActiveDownloadId();
Vector<Podcast> toProcess = dbAdapter.getQueue();
for (Podcast podcast : toProcess) {
if (!podcast.needsDownload())
continue;
if (activeId != null && podcast.getId() == activeId) {
_active = podcast;
}
_waiting.add(podcast);
}
}
public int getCount() {
return _waiting.size();
}
public Object getItem(int position) {
return _waiting.get(position);
}
public long getItemId(int position) {
return ((Podcast)getItem(position)).getId();
}
public View getView(int position, View convertView, ViewGroup parent) {
Podcast podcast = (Podcast)getItem(position);
LinearLayout view;
if (convertView == null) {
view = (LinearLayout)_layoutInflater.inflate(R.layout.downloads_list_item, null);
}
else {
view = (LinearLayout)convertView;
}
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(podcast.getTitle());
TextView subscription = (TextView)view.findViewById(R.id.subscription);
subscription.setText(podcast.getSubscription().getDisplayTitle());
// TODO: figure out when this is null
if (podcast != null && podcast == _active)
{
int max = podcast.getFileSize();
int downloaded = (int) new File(podcast.getFilename()).length();
View extras = _layoutInflater.inflate(R.layout.downloads_list_active_item, null);
view.addView(extras);
ProgressBar progressBar = (ProgressBar)extras.findViewById(R.id.progressBar);
progressBar.setMax(max);
progressBar.setProgress(downloaded);
TextView progressText = (TextView)extras.findViewById(R.id.progressText);
progressText.setText(Math.round(100.0f * downloaded / max) + "% done");
}
else
{
View extras = view.findViewById(R.id.active);
if (extras != null)
view.removeView(extras);
}
return view;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Restart Downloader");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
UpdateService.downloadPodcasts(this);
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
} |
package com.artifex.mupdf;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;
class SearchTaskResult {
public final int pageNumber;
public final RectF searchBoxes[];
SearchTaskResult(int _pageNumber, RectF _searchBoxes[]) {
pageNumber = _pageNumber;
searchBoxes = _searchBoxes;
}
}
class ProgressDialogX extends ProgressDialog {
public ProgressDialogX(Context context) {
super(context);
}
private boolean mCancelled = false;
public boolean isCancelled() {
return mCancelled;
}
@Override
public void cancel() {
mCancelled = true;
super.cancel();
}
}
public class MuPDFActivity extends Activity
{
/* The core rendering instance */
private enum LinkState {DEFAULT, HIGHLIGHT, INHIBIT};
private final int TAP_PAGE_MARGIN = 5;
private static final int SEARCH_PROGRESS_DELAY = 200;
private MuPDFCore core;
private String mFileName;
private ReaderView mDocView;
private View mButtonsView;
private boolean mButtonsVisible;
private EditText mPasswordView;
private TextView mFilenameView;
private SeekBar mPageSlider;
private TextView mPageNumberView;
private ImageButton mSearchButton;
private ImageButton mCancelButton;
private ImageButton mOutlineButton;
private ViewSwitcher mTopBarSwitcher;
// XXX private ImageButton mLinkButton;
private boolean mTopBarIsSearch;
private ImageButton mSearchBack;
private ImageButton mSearchFwd;
private EditText mSearchText;
private AsyncTask<Integer,Integer,SearchTaskResult> mSearchTask;
private SearchTaskResult mSearchTaskResult;
private AlertDialog.Builder mAlertBuilder;
private LinkState mLinkState = LinkState.DEFAULT;
private final Handler mHandler = new Handler();
private MuPDFCore openFile(String path)
{
int lastSlashPos = path.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1
? path
: path.substring(lastSlashPos+1));
System.out.println("Trying to open "+path);
try
{
core = new MuPDFCore(path);
// New file: drop the old outline data
OutlineActivityData.set(null);
}
catch (Exception e)
{
System.out.println(e);
return null;
}
return core;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAlertBuilder = new AlertDialog.Builder(this);
if (core == null) {
core = (MuPDFCore)getLastNonConfigurationInstance();
if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
mFileName = savedInstanceState.getString("FileName");
}
}
if (core == null) {
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri.toString().startsWith("content://media/external/file")) {
// Handle view requests from the Transformer Prime's file manager
// Hopefully other file managers will use this same scheme, if not
// using explicit paths.
Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
if (cursor.moveToFirst()) {
uri = Uri.parse(cursor.getString(0));
}
}
core = openFile(Uri.decode(uri.getEncodedPath()));
}
if (core != null && core.needsPassword()) {
requestPassword(savedInstanceState);
return;
}
}
if (core == null)
{
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.open_failed);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
createUI(savedInstanceState);
}
public void requestPassword(final Bundle savedInstanceState) {
mPasswordView = new EditText(this);
mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
mPasswordView.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.enter_password);
alert.setView(mPasswordView);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (core.authenticatePassword(mPasswordView.getText().toString())) {
createUI(savedInstanceState);
} else {
requestPassword(savedInstanceState);
}
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
public void createUI(Bundle savedInstanceState) {
if (core == null)
return;
// Now create the UI.
// First create the document view making use of the ReaderView's internal
// gesture recognition
mDocView = new ReaderView(this) {
private boolean showButtonsDisabled;
public boolean onSingleTapUp(MotionEvent e) {
if (e.getX() < super.getWidth()/TAP_PAGE_MARGIN) {
super.moveToPrevious();
} else if (e.getX() > super.getWidth()*(TAP_PAGE_MARGIN-1)/TAP_PAGE_MARGIN) {
super.moveToNext();
} else if (!showButtonsDisabled) {
int linkPage = -1;
if (mLinkState != LinkState.INHIBIT) {
MuPDFPageView pageView = (MuPDFPageView) mDocView.getDisplayedView();
if (pageView != null) {
// XXX linkPage = pageView.hitLinkPage(e.getX(), e.getY());
}
}
if (linkPage != -1) {
mDocView.setDisplayedViewIndex(linkPage);
} else {
if (!mButtonsVisible) {
showButtons();
} else {
hideButtons();
}
}
}
return super.onSingleTapUp(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!showButtonsDisabled)
hideButtons();
return super.onScroll(e1, e2, distanceX, distanceY);
}
public boolean onScaleBegin(ScaleGestureDetector d) {
// Disabled showing the buttons until next touch.
// Not sure why this is needed, but without it
// pinch zoom can make the buttons appear
showButtonsDisabled = true;
return super.onScaleBegin(d);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
showButtonsDisabled = false;
return super.onTouchEvent(event);
}
protected void onChildSetup(int i, View v) {
if (mSearchTaskResult != null && mSearchTaskResult.pageNumber == i)
((PageView)v).setSearchBoxes(mSearchTaskResult.searchBoxes);
else
((PageView)v).setSearchBoxes(null);
((PageView)v).setLinkHighlighting(mLinkState == LinkState.HIGHLIGHT);
}
protected void onMoveToChild(int i) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d/%d", i+1, core.countPages()));
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(i);
if (mSearchTaskResult != null && mSearchTaskResult.pageNumber != i) {
mSearchTaskResult = null;
mDocView.resetupChildren();
}
}
protected void onSettle(View v) {
// When the layout has settled ask the page to render
// in HQ
((PageView)v).addHq();
}
protected void onUnsettle(View v) {
// When something changes making the previous settled view
// no longer appropriate, tell the page to remove HQ
((PageView)v).removeHq();
}
};
mDocView.setAdapter(new MuPDFPageAdapter(this, core));
// Make the buttons overlay, and store all its
// controls in variables
makeButtonsView();
// Set the file-name text
mFilenameView.setText(mFileName);
// Activate the seekbar
mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
mDocView.setDisplayedViewIndex(seekBar.getProgress());
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePageNumView(progress);
}
});
// Activate the search-preparing button
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOn();
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOff();
}
});
// Search invoking buttons are disabled while there is no text specified
mSearchBack.setEnabled(false);
mSearchFwd.setEnabled(false);
// React to interaction with the text widget
mSearchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
boolean haveText = s.toString().length() > 0;
mSearchBack.setEnabled(haveText);
mSearchFwd.setEnabled(haveText);
// Remove any previous search results
if (mSearchTaskResult != null) {
mSearchTaskResult = null;
mDocView.resetupChildren();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
//React to Done button on keyboard
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
search(1);
return false;
}
});
mSearchText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
search(1);
return false;
}
});
// Activate search invoking buttons
mSearchBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(-1);
}
});
mSearchFwd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(1);
}
});
/* XXX
mLinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(mLinkState) {
case DEFAULT:
mLinkState = LinkState.HIGHLIGHT;
mLinkButton.setImageResource(R.drawable.ic_hl_link);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case HIGHLIGHT:
mLinkState = LinkState.INHIBIT;
mLinkButton.setImageResource(R.drawable.ic_nolink);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case INHIBIT:
mLinkState = LinkState.DEFAULT;
mLinkButton.setImageResource(R.drawable.ic_link);
break;
}
}
});
*/
if (core.hasOutline()) {
mOutlineButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OutlineItem outline[] = core.getOutline();
if (outline != null) {
OutlineActivityData.get().items = outline;
Intent intent = new Intent(MuPDFActivity.this, OutlineActivity.class);
startActivityForResult(intent, 0);
}
}
});
} else {
mOutlineButton.setVisibility(View.GONE);
}
// Reenstate last state if it was recorded
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
mDocView.setDisplayedViewIndex(prefs.getInt("page"+mFileName, 0));
if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
showButtons();
if(savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false))
searchModeOn();
// Stick the document view and the buttons overlay into a parent view
RelativeLayout layout = new RelativeLayout(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode >= 0)
mDocView.setDisplayedViewIndex(resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
public Object onRetainNonConfigurationInstance()
{
MuPDFCore mycore = core;
core = null;
return mycore;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFileName != null && mDocView != null) {
outState.putString("FileName", mFileName);
// Store current page in the prefs against the file name,
// so that we can pick it up each time the file is loaded
// Other info is needed only for screen-orientation change,
// so it can go in the bundle
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
if (!mButtonsVisible)
outState.putBoolean("ButtonsHidden", true);
if (mTopBarIsSearch)
outState.putBoolean("SearchMode", true);
}
@Override
protected void onPause() {
super.onPause();
killSearch();
if (mFileName != null && mDocView != null) {
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
}
public void onDestroy()
{
if (core != null)
core.onDestroy();
core = null;
super.onDestroy();
}
void showButtons() {
if (core == null)
return;
if (!mButtonsVisible) {
mButtonsVisible = true;
// Update page number text and slider
int index = mDocView.getDisplayedViewIndex();
updatePageNumView(index);
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(index);
if (mTopBarIsSearch) {
mSearchText.requestFocus();
showKeyboard();
}
Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mTopBarSwitcher.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageSlider.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageNumberView.setVisibility(View.VISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void hideButtons() {
if (mButtonsVisible) {
mButtonsVisible = false;
hideKeyboard();
Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mTopBarSwitcher.setVisibility(View.INVISIBLE);
}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageNumberView.setVisibility(View.INVISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageSlider.setVisibility(View.INVISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void searchModeOn() {
mTopBarIsSearch = true;
//Focus on EditTextWidget
mSearchText.requestFocus();
showKeyboard();
mTopBarSwitcher.showNext();
}
void searchModeOff() {
mTopBarIsSearch = false;
hideKeyboard();
mTopBarSwitcher.showPrevious();
mSearchTaskResult = null;
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
void updatePageNumView(int index) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d/%d", index+1, core.countPages()));
}
void makeButtonsView() {
mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null);
mFilenameView = (TextView)mButtonsView.findViewById(R.id.docNameText);
mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider);
mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber);
mSearchButton = (ImageButton)mButtonsView.findViewById(R.id.searchButton);
mCancelButton = (ImageButton)mButtonsView.findViewById(R.id.cancel);
mOutlineButton = (ImageButton)mButtonsView.findViewById(R.id.outlineButton);
mTopBarSwitcher = (ViewSwitcher)mButtonsView.findViewById(R.id.switcher);
mSearchBack = (ImageButton)mButtonsView.findViewById(R.id.searchBack);
mSearchFwd = (ImageButton)mButtonsView.findViewById(R.id.searchForward);
mSearchText = (EditText)mButtonsView.findViewById(R.id.searchText);
// XXX mLinkButton = (ImageButton)mButtonsView.findViewById(R.id.linkButton);
mTopBarSwitcher.setVisibility(View.INVISIBLE);
mPageNumberView.setVisibility(View.INVISIBLE);
mPageSlider.setVisibility(View.INVISIBLE);
}
void showKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(mSearchText, 0);
}
void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
}
void killSearch() {
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
}
void search(int direction) {
hideKeyboard();
if (core == null)
return;
killSearch();
final ProgressDialogX progressDialog = new ProgressDialogX(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle(getString(R.string.searching_));
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
killSearch();
}
});
progressDialog.setMax(core.countPages());
mSearchTask = new AsyncTask<Integer,Integer,SearchTaskResult>() {
@Override
protected SearchTaskResult doInBackground(Integer... params) {
int index;
if (mSearchTaskResult == null)
index = mDocView.getDisplayedViewIndex();
else
index = mSearchTaskResult.pageNumber + params[0].intValue();
while (0 <= index && index < core.countPages() && !isCancelled()) {
publishProgress(index);
RectF searchHits[] = core.searchPage(index, mSearchText.getText().toString());
if (searchHits != null && searchHits.length > 0)
return new SearchTaskResult(index, searchHits);
index += params[0].intValue();
}
return null;
}
@Override
protected void onPostExecute(SearchTaskResult result) {
progressDialog.cancel();
if (result != null) {
// Ask the ReaderView to move to the resulting page
mDocView.setDisplayedViewIndex(result.pageNumber);
mSearchTaskResult = result;
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
} else {
mAlertBuilder.setTitle(R.string.text_not_found);
AlertDialog alert = mAlertBuilder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
(DialogInterface.OnClickListener)null);
alert.show();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.cancel();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0].intValue());
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mHandler.postDelayed(new Runnable() {
public void run() {
if (!progressDialog.isCancelled())
progressDialog.show();
}
}, SEARCH_PROGRESS_DELAY);
}
};
mSearchTask.execute(new Integer(direction));
}
} |
package com.castlefrog.agl.domains.hex;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;
import com.castlefrog.agl.Simulator;
import com.castlefrog.agl.AbstractSimulator;
import com.castlefrog.agl.IllegalActionException;
import com.castlefrog.agl.TurnType;
public final class HexSimulator extends AbstractSimulator<HexState, HexAction> {
public static final int N_AGENTS = 2;
public static final int MIN_BOARD_SIZE = 1;
public static final int MAX_BOARD_SIZE = 26;
private static int boardSize_;
/**
* Create a hex simulator.
* Defaults to an initial board state.
* @param size
* size of board
* @param turnType
* indicates how turns are handled
*/
public HexSimulator(int boardSize,
TurnType turnType) {
nAgents_ = N_AGENTS;
if (boardSize < MIN_BOARD_SIZE || boardSize > MAX_BOARD_SIZE)
throw new IllegalArgumentException("Invalid board size: (" + boardSize + ") " +
MIN_BOARD_SIZE + " <= boardSize <= " + MAX_BOARD_SIZE);
boardSize_ = boardSize;
turnType_ = turnType;
state_ = getInitialState();
rewards_ = new int[nAgents_];
legalActions_ = new ArrayList<HashSet<HexAction>>();
legalActions_.add(new HashSet<HexAction>());
legalActions_.add(new HashSet<HexAction>());
computeLegalActions(null);
}
/**
* Contructor is used by the copy method.
*/
private HexSimulator(HexState state,
List<HashSet<HexAction>> legalActions,
int[] rewards) {
state_ = state.clone();
legalActions_ = new ArrayList<HashSet<HexAction>>();
for (HashSet<HexAction> actions: legalActions) {
HashSet<HexAction> temp = new HashSet<HexAction>();
for (HexAction action: actions)
temp.add(action);
legalActions_.add(temp);
}
rewards_ = new int[nAgents_];
for (int i = 0; i < nAgents_; i += 1)
rewards_[i] = rewards[i];
}
@Override
public Simulator<HexState, HexAction> clone() {
return new HexSimulator(state_, legalActions_, rewards_);
}
public void setState(HexState state) {
state_ = state.clone();
computeRewards();
computeLegalActions(null);
}
public void stateTransition(List<HexAction> actions) {
HexAction action = actions.get(state_.getAgentTurn());
if (!legalActions_.get(state_.getAgentTurn()).contains(action))
throw new IllegalActionException(action,state_);
int x = action.getX();
int y = action.getY();
if (state_.getLocation(x,y) == 0)
state_.setLocation(x,y,state_.getAgentTurn() + 1);
else {
state_.setLocation(x,y,0);
state_.setLocation(y,x,state_.getAgentTurn() + 1);
}
state_.switchAgentTurn();
computeRewards(action);
computeLegalActions(action);
}
private void computeLegalActions(HexAction prevAction) {
if (rewards_[0] == 0) {
int agentTurn = state_.getAgentTurn();
int otherTurn = (agentTurn + 1) % 2;
legalActions_.set(agentTurn, legalActions_.get(otherTurn));
legalActions_.set(otherTurn, new HashSet<HexAction>());
HashSet<HexAction> legalActions = legalActions_.get(agentTurn);
if (prevAction != null && state_.getNPieces() > 2) {
legalActions.remove(prevAction);
} else {
legalActions.clear();
if (state_.getNPieces() == 1 && state_.getAgentTurn() == 1) {
for (int i = 0; i < boardSize_; i += 1)
for (int j = 0; j < boardSize_; j += 1)
legalActions.add(HexAction.valueOf(i,j));
} else {
for (int i = 0; i < boardSize_; i += 1)
for (int j = 0; j < boardSize_; j += 1)
if (state_.getLocation(i,j) == 0)
legalActions.add(HexAction.valueOf(i,j));
}
}
} else
for (HashSet<HexAction> legalActions: legalActions_)
legalActions.clear();
}
private void computeRewards() {
if (state_.getNPieces() > 2 * boardSize_ - 2) {
byte[][] locations = state_.getLocations();
boolean[][] visited = new boolean[boardSize_][boardSize_];
for (int i = 0; i < boardSize_; i += 1) {
if (locations[0][i] == 1 && visited[0][i] == false) {
if ((dfsSides(0, i, locations, visited) & 3) == 3) {
rewards_[0] = 1;
rewards_[1] = -1;
return;
}
} else if (locations[i][0] == 2 && visited[i][0] == false) {
if ((dfsSides(i, 0, locations, visited) & 12) == 12) {
rewards_[0] = -1;
rewards_[1] = 1;
return;
}
}
}
}
rewards_[0] = rewards_[1] = 0;
}
private void computeRewards(HexAction action) {
byte[][] locations = state_.getLocations();
boolean[][] visited = new boolean[boardSize_][boardSize_];
int x = action.getX();
int y = action.getY();
int value = dfsSides(x,y,locations,visited);
if (locations[x][y] == 1 && (value & 3) == 3) {
rewards_[0] = 1;
rewards_[1] = -1;
} else if (locations[x][y] == 2 && (value & 12) == 12) {
rewards_[0] = -1;
rewards_[1] = 1;
} else
rewards_[0] = rewards_[1] = 0;
}
private int dfsSides(int x0,
int y0,
byte[][] locations,
boolean[][] visited) {
int value = 0;
Stack<HexAction> stack = new Stack<HexAction>();
stack.push(HexAction.valueOf(x0,y0));
visited[x0][y0] = true;
while (!stack.empty()) {
HexAction v = stack.pop();
int x = v.getX();
int y = v.getY();
value |= getLocationMask(x,y);
for (int i = -1; i <= 1; i += 1) {
for (int j = -1; j <= 1; j += 1) {
int xi = x + i;
int yi = y + j;
if (i + j != 0 && xi >= 0 && yi >= 0 &&
xi < boardSize_ && yi < boardSize_) {
if (!visited[xi][yi] &&
locations[xi][yi] == locations[x][y]) {
stack.push(HexAction.valueOf(xi, yi));
visited[xi][yi] = true;
}
}
}
}
}
return value;
}
private List<HexAction> dfsWin(int x0,
int y0,
byte[][] locations,
boolean[][] visited) {
int value = 0;
List<HexAction> connection = new ArrayList<HexAction>();
Stack<HexAction> stack = new Stack<HexAction>();
stack.push(HexAction.valueOf(x0,y0));
connection.add(HexAction.valueOf(x0,y0));
visited[x0][y0] = true;
while (!stack.empty()) {
HexAction v = stack.pop();
int x = v.getX();
int y = v.getY();
value |= getLocationMask(x,y);
for (int i = -1; i <= 1; i += 1) {
for (int j = -1; j <= 1; j += 1) {
int xi = x + i;
int yi = y + j;
if (i + j != 0 && xi >= 0 && yi >= 0 &&
xi < boardSize_ && yi < boardSize_) {
if (!visited[xi][yi] &&
locations[xi][yi] == locations[x][y]) {
stack.push(HexAction.valueOf(xi,yi));
connection.add(HexAction.valueOf(xi,yi));
visited[xi][yi] = true;
}
}
}
}
}
if (value != 3 && value != 12)
connection.clear();
return connection;
}
private int getLocationMask(int x, int y) {
int side = 0;
if (x == 0)
side |= 1;
else if (x == boardSize_ - 1)
side |= 2;
if (y == 0)
side |= 4;
else if (y == boardSize_ - 1)
side |= 8;
return side;
}
public int[][] getWinningConnection() {
int[][] connection = new int[boardSize_][boardSize_];
if (rewards_[0] != 0) {
Simulator<HexState,HexAction> simulator = new HexSimulator(boardSize_, TurnType.SEQUENTIAL);
HexState state = state_.clone();
for (int i = 0; i < boardSize_; i += 1) {
for (int j = 0; j < boardSize_; j += 1) {
int location = state.getLocation(i,j);
if (!state.isLocationEmpty(i,j) &&
location != state.getAgentTurn() + 1) {
state.setLocation(i,j,HexState.Location.EMPTY);
simulator.setState(state);
if (!simulator.isTerminalState()) {
connection[i][j] = 1;
state.setLocation(i,j,location);
}
}
}
}
}
return connection;
}
public HexState getInitialState() {
return new HexState(new byte[boardSize_][boardSize_], 0);
}
public HexState getState() {
return state_.clone();
}
public int getBoardSize() {
return boardSize_;
}
} |
package com.ecyrd.jspwiki.auth.modules;
import com.ecyrd.jspwiki.auth.*;
import com.ecyrd.jspwiki.*;
import java.util.*;
import java.security.Principal;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.filters.BasicPageFilter;
import com.ecyrd.jspwiki.providers.ProviderException;
/**
* This default UserDatabase implementation provides user profiles
* and groups to JSPWiki.
*
* <p>UserProfiles are simply created upon request, and cached
* locally. More intricate providers might look up profiles in
* a remote DB, provide an unauthenticatable object for unknown
* users, etc.
*
* <p>The authentication of a user is done elsewhere (see
* WikiAuthenticator); newly created profiles should have
* login status UserProfile.NONE.
*
* <p>Groups are based on WikiPages.
* The name of the page determines the group name (as a convention,
* we suggest the name of the page ends in Group, e.g. EditorGroup).
* By setting attribute 'members' on the page, the named members are
* added to the group:
*
* <pre>
* [{SET members fee fie foe foo}]
* </pre>
*
* <p>The list of members can be separated by commas or spaces.
*
* <p>TODO: are 'named members' supposed to be usernames, or are
* group names allowed? (Suggestion: both)
*/
public class WikiDatabase
implements UserDatabase
{
private WikiEngine m_engine;
static Category log = Category.getInstance( WikiDatabase.class );
private HashMap m_groupPrincipals = new HashMap();
private HashMap m_userPrincipals = new HashMap();
/**
* The attribute to set on a page - [{SET members ...}] - to define
* members of the group named by that page.
*/
public static final String ATTR_MEMBERLIST = "members";
public void initialize( WikiEngine engine, Properties props )
{
m_engine = engine;
m_engine.getFilterManager().addPageFilter( new SaveFilter(), 1000000 );
initUserDatabase();
}
// This class must contain a large cache for user databases.
// FIXME: Needs to cache this somehow; this is far too slow!
public List getGroupsForPrincipal( Principal p )
throws NoSuchPrincipalException
{
List memberList = new ArrayList();
log.debug("Finding groups for "+p.getName());
for( Iterator i = m_groupPrincipals.values().iterator(); i.hasNext(); )
{
Object o = i.next();
if( o instanceof WikiGroup )
{
log.debug(" Checking group: "+o);
if( ((WikiGroup)o).isMember( p ) )
{
log.debug(" Is member");
memberList.add( o );
}
}
else
{
log.debug(" Found strange object: "+o.getClass());
}
}
return memberList;
}
/**
* List contains a bunch of Strings to denote members of this group.
*/
protected void updateGroup( String groupName, List memberList )
{
WikiGroup group = (WikiGroup)m_groupPrincipals.get( groupName );
if( group == null && memberList == null )
{
return;
}
if( group == null && memberList != null )
{
log.debug("Adding new group: "+groupName);
group = new WikiGroup();
group.setName( groupName );
}
if( group != null && memberList == null )
{
log.debug("Detected removed group: "+groupName);
m_groupPrincipals.remove( groupName );
return;
}
for( Iterator j = memberList.iterator(); j.hasNext(); )
{
Principal udp = new UndefinedPrincipal( (String)j.next() );
group.addMember( udp );
log.debug("** Added member: "+udp.getName());
}
m_groupPrincipals.put( groupName, group );
}
protected void initUserDatabase()
{
log.info( "Initializing user database group information from wiki pages..." );
try
{
Collection allPages = m_engine.getPageManager().getAllPages();
m_groupPrincipals.clear();
for( Iterator i = allPages.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage) i.next();
// FIX: if the pages haven't been scanned yet, no attributes.
// If the default perms are restrictive, the user can never save
// -> groups will not be updated on postSave(), either.
// Requires either changed initialization order, or, since this
// will fail with lazy-init-systems, something more elaborate..
List memberList = (List) p.getAttribute(ATTR_MEMBERLIST);
if( memberList != null )
{
updateGroup( p.getName(), memberList );
}
}
}
catch( ProviderException e )
{
log.fatal("Cannot start database",e );
}
}
/**
* Stores a UserProfile with expiry information.
*/
private void storeUserProfile( String name, UserProfile p )
{
m_userPrincipals.put( name, new TimeStampWrapper( p, 24*3600*1000 ) );
}
/**
* Returns a stored UserProfile, taking expiry into account.
*/
private UserProfile getUserProfile( String name )
{
TimeStampWrapper w = (TimeStampWrapper)m_userPrincipals.get( name );
if( w != null && w.expires() < System.currentTimeMillis() )
{
w = null;
m_userPrincipals.remove( name );
}
if( w != null )
{
return( (UserProfile)w.getContent() );
}
return( null );
}
/**
* Returns a principal; UserPrincipal storage is scanned
* first, then WikiGroup storage. If neither contains the
* requested principal, a new (empty) UserPrincipal is
* returned.
*/
public WikiPrincipal getPrincipal( String name )
{
// FIX: requests for non-existent users can now override groups.
WikiPrincipal rval = (WikiPrincipal)getUserProfile( name );
if( rval == null )
{
rval = (WikiPrincipal) m_groupPrincipals.get( name );
}
if( rval == null )
{
rval = new UserProfile();
rval.setName( name );
// Store, to reduce creation overhead. Expire in one day.
storeUserProfile( name, (UserProfile)rval );
}
return( rval );
}
/**
* This special filter class is used to refresh the database
* after a page has been changed.
*/
// FIXME: JSPWiki should really take care of itself that any metadata
// relevant to a page is refreshed.
public class SaveFilter
extends BasicPageFilter
{
/**
* Parses through the member list of a page.
*/
private List parseMemberList( String memberLine )
{
if( memberLine == null ) return null;
log.debug("Parsing member list: "+memberLine);
StringTokenizer tok = new StringTokenizer( memberLine, ", " );
ArrayList members = new ArrayList();
while( tok.hasMoreTokens() )
{
String uid = tok.nextToken();
log.debug(" Adding member: "+uid);
members.add( uid );
}
return members;
}
public void postSave( WikiContext context, String content )
{
WikiPage p = context.getPage();
log.debug("Skimming through page "+p.getName()+" to see if there are new users...");
m_engine.textToHTML( context, content );
String members = (String) p.getAttribute(ATTR_MEMBERLIST);
updateGroup( p.getName(), parseMemberList( members ) );
}
}
public class TimeStampWrapper
{
private Object contained = null;
private long expirationTime = -1;
public TimeStampWrapper( Object item, long expiresIn )
{
contained = item;
expirationTime = System.currentTimeMillis() + expiresIn;
}
public Object getContent()
{
return( contained );
}
public long expires()
{
return( expirationTime );
}
}
} |
package com.master.thesis;
import com.sun.org.apache.xpath.internal.SourceTree;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.DBSCAN;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Normalize;
import java.util.Map;
import java.util.TreeMap;
public class DBScanImbalancedAlgorithm implements ImbalancedAlgorithm {
private Instances data;
public DBScanImbalancedAlgorithm() {
}
/**
* Not implemented yet.
*
* @param options
*/
public DBScanImbalancedAlgorithm(String[] options) {
//setParameters(options);
}
@Override
public void setParameters() {
}
@Override
public void getParameters() {
}
@Override
public void start() throws Exception {
if (data.classIndex() == -1) {
data.setClassIndex(data.numAttributes() - 1);
}
System.out.println("=====================================");
System.out.println(String.format("%-20s %s", " ", "Count"));
System.out.println("
System.out.println(String.format("%-20s %s", "Instances", data.numInstances()));
System.out.println(String.format("%-20s %s", "Atrributes", data.numAttributes()));
System.out.println(String.format("%-20s %s", "Distinct Values", data.numDistinctValues(data.classAttribute())));
Instances minorityInstances = new Instances(data);
Instances majorityInstances = new Instances(data);
separateDecisionClasses(data, minorityInstances, majorityInstances);
System.out.println(String.format("%-20s %s", "Minority Class", minorityInstances.numInstances()));
System.out.println(String.format("%-20s %s", "Majority Class", majorityInstances.numInstances()));
System.out.println(String.format("%-20s %.2f %%", "Balance", 100.0 * minorityInstances.numInstances() / data.numInstances()));
System.out.println("=====================================");
System.out.println();
// Ustaw opcje DBScan'a
DBSCAN dbScan = new DBSCAN();
dbScan.setDatabase_Type("weka.clusterers.forOPTICSAndDBScan.Databases.SequentialDatabase");
dbScan.setDatabase_distanceType("weka.clusterers.forOPTICSAndDBScan.DataObjects.EuclideanDataObject");
dbScan.setEpsilon(0.5);
dbScan.setMinPoints(4);
weka.filters.unsupervised.attribute.Remove filter = new weka.filters.unsupervised.attribute.Remove();
filter.setAttributeIndices("" + (minorityInstances.classIndex() + 1));
filter.setInputFormat(minorityInstances);
Instances minorityInstancesNoClass = Filter.useFilter(minorityInstances, filter);
dbScan.buildClusterer(minorityInstancesNoClass);
ClusterEvaluation evaluation = new ClusterEvaluation();
evaluation.setClusterer(dbScan);
evaluation.evaluateClusterer(minorityInstancesNoClass);
System.out.println(evaluation.clusterResultsToString());
double[] minorityClusterAssignments = evaluation.getClusterAssignments();
Map<Integer, Integer> minorityHistogram = new TreeMap<Integer, Integer>();
for (double val : minorityClusterAssignments) {
minorityHistogram.put((int) val, minorityHistogram.containsKey((int) val) ? minorityHistogram.get((int) val) + 1 : 1);
}
Map<Integer, Integer> majorityHistogram = new TreeMap<Integer, Integer>();
for (int i = 0; i < majorityInstances.numInstances(); i++) {
Instance currInst = majorityInstances.instance(i);
try {
int cluster = dbScan.clusterInstance(currInst);
majorityHistogram.put(cluster, majorityHistogram.containsKey(cluster) ? majorityHistogram.get(cluster) + 1 : 1);
//System.out.println(dbScan.clusterInstance(currInst));
} catch (Exception e) {
//System.out.println("NOISE -> Cannot be clustered");
majorityHistogram.put(-1, majorityHistogram.containsKey(-1) ? majorityHistogram.get(-1) + 1 : 1);
}
}
System.out.println();
System.out.println("Majority's objects");
for (Map.Entry<Integer, Integer> entry : majorityHistogram.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
System.out.println("Balance in clusters");
double averageBalance = 0;
for (Map.Entry<Integer, Integer> entry : majorityHistogram.entrySet()) {
int cluster = entry.getKey();
int majorityCount = entry.getValue();
int minorityCount = minorityHistogram.get(entry.getKey());
double balance = 100.0*minorityCount/(minorityCount+majorityCount);
averageBalance += balance;
System.out.print(cluster + ": " + majorityCount + ", " + minorityCount + " ");
System.out.println(String.format("\t\t%.2f %%", balance));
}
averageBalance /= majorityHistogram.size();
System.out.println(String.format("Average balance: %.2f %%", averageBalance));
}
@Override
public Instances loadDataFile(String filename) {
String path = System.getProperty("user.dir") + "\\resources\\datasets\\";
path = path.concat(filename);
System.out.println("Path:\t\t" + path);
System.out.println("Dataset:\t" + filename);
DataSource source;
try {
source = new DataSource(path);
data = source.getDataSet();
System.out.println(filename + " -> Data loaded.");
Normalize filterNorm = new Normalize();
filterNorm.setInputFormat(data) ;
data = Filter.useFilter(data, filterNorm);
System.out.println("Data Normalized");
System.out.println();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public double getMinorityValue(Instances instances) throws Exception {
int numInstances = instances.numInstances();
if (numInstances < 1) {
throw new Exception("Empty Instances");
}
Map<String, Integer> mapValues = new TreeMap<String, Integer>();
for (int i = 0; i < numInstances; i++) {
Instance instance = instances.instance(i);
String key = String.valueOf(instance.value(instance.classAttribute()));
if (mapValues.containsKey(key)) {
mapValues.put(String.valueOf(key), (mapValues.get(key) + 1));
} else {
mapValues.put(String.valueOf(key), 1);
}
}
mapValues = MapUtil.sortByValue(mapValues);
for (Map.Entry<String, Integer> entry : mapValues.entrySet()) {
//System.out.println(entry.getKey() + " " + entry.getValue());
return Double.valueOf(entry.getKey());
}
return -1.0;
}
public void separateDecisionClasses(Instances instances, Instances minorityInstances, Instances majorityInstances) throws Exception {
Double minorityValue = getMinorityValue(instances);
minorityInstances.delete();
majorityInstances.delete();
int numInstances = instances.numInstances();
for (int i = 0; i < numInstances; i++) {
Instance instance = instances.instance(i);
if (instance.value(instance.classAttribute()) == minorityValue) {
minorityInstances.add(instance);
} else {
majorityInstances.add(instance);
}
}
}
} |
#parse("main/Header.vm")
package com.nativelibs4java.opencl;
import com.nativelibs4java.util.EnumValue;
import com.nativelibs4java.util.EnumValues;
import com.nativelibs4java.opencl.library.OpenCLLibrary;
import com.nativelibs4java.util.IOUtils;
import com.nativelibs4java.util.NIOUtils;
import static com.nativelibs4java.opencl.library.OpenCLLibrary.*;
import static com.nativelibs4java.opencl.library.IOpenCLLibrary.*;
import org.bridj.*;
import static org.bridj.Pointer.*;
import java.io.IOException;
import java.nio.*;
import static com.nativelibs4java.opencl.JavaCL.*;
import static com.nativelibs4java.util.NIOUtils.*;
import java.util.*;
import static com.nativelibs4java.opencl.CLException.*;
import com.nativelibs4java.util.ValuedEnum;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* OpenCL device (CPU, GPU...).<br/>
* Devices are retrieved from a CLPlatform through
* {@link CLPlatform#listDevices(java.util.EnumSet, boolean) },
* {@link CLPlatform#listAllDevices(boolean) },
* {@link CLPlatform#listCPUDevices(boolean) },
* {@link CLPlatform#listGPUDevices(boolean) }
*/
@SuppressWarnings("unused")
public class CLDevice extends CLAbstractEntity {
#declareInfosGetter("infos", "CL.clGetDeviceInfo")
private volatile CLPlatform platform;
private final boolean needsRelease;
CLDevice(CLPlatform platform, long device) {
this(platform, device, false);
}
CLDevice(CLPlatform platform, long device, boolean needsRelease) {
super(device);
this.platform = platform;
this.needsRelease = needsRelease;
}
public synchronized CLPlatform getPlatform() {
if (platform == null) {
Pointer pplat = infos.getPointer(getEntity(), CL_DEVICE_PLATFORM);
platform = new CLPlatform(getPeer(pplat));
}
return platform;
}
@Override
protected void clear() {
if (needsRelease)
error(CL.clReleaseDevice(getEntity()));
}
public String createSignature() {
return getName() + "|" + getVendor() + "|" + getDriverVersion() + "|" + getProfile();
}
public static Map<String, List<CLDevice>> getDevicesBySignature(List<CLDevice> devices) {
Map<String, List<CLDevice>> ret = new HashMap<String, List<CLDevice>>();
for (CLDevice device : devices) {
String signature = device.createSignature();
List<CLDevice> list = ret.get(signature);
if (list == null)
ret.put(signature, list = new ArrayList<CLDevice>());
list.add(device);
}
return ret;
}
private volatile ByteOrder byteOrder;
public ByteOrder getByteOrder() {
if (byteOrder == null)
byteOrder = isEndianLittle() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
return byteOrder;
}
private volatile ByteOrder kernelsDefaultByteOrder;
/**
* @deprecated Use {@link CLDevice#getByteOrder()}
*/
@Deprecated
public synchronized ByteOrder getKernelsDefaultByteOrder() {
if (kernelsDefaultByteOrder == null) {
kernelsDefaultByteOrder = ByteOrderHack.guessByteOrderNeededForBuffers(this);
}
return kernelsDefaultByteOrder;
}
/** Bit values for CL_DEVICE_EXECUTION_CAPABILITIES */
public enum ExecutionCapability implements com.nativelibs4java.util.ValuedEnum {
Kernel(CL_EXEC_KERNEL),
NativeKernel(CL_EXEC_NATIVE_KERNEL);
ExecutionCapability(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static long getValue(EnumSet<ExecutionCapability> set) {
return EnumValues.getValue(set);
}
public static EnumSet<ExecutionCapability> getEnumSet(long v) {
return EnumValues.getEnumSet(v, ExecutionCapability.class);
}
}
/**
* Describes the execution capabilities of the device.<br/>
* The mandated minimum capability is: Kernel.
*/
@InfoName("CL_DEVICE_EXECUTION_CAPABILITIES")
public EnumSet<ExecutionCapability> getExecutionCapabilities() {
return ExecutionCapability.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_EXECUTION_CAPABILITIES));
}
/** Bit values for CL_DEVICE_TYPE */
public enum Type implements com.nativelibs4java.util.ValuedEnum {
CPU(CL_DEVICE_TYPE_CPU),
GPU(CL_DEVICE_TYPE_GPU),
Accelerator(CL_DEVICE_TYPE_ACCELERATOR),
Default(CL_DEVICE_TYPE_DEFAULT),
All(CL_DEVICE_TYPE_ALL);
Type(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static long getValue(EnumSet<Type> set) {
return EnumValues.getValue(set);
}
public static EnumSet<Type> getEnumSet(long v) {
return EnumValues.getEnumSet(v, Type.class);
}
}
/**
* The OpenCL device type.
*/
@InfoName("CL_DEVICE_TYPE")
public EnumSet<Type> getType() {
return Type.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_TYPE));
}
/**
* A unique device vendor identifier. <br/>
* An example of a unique device identifier could be the PCIe ID.
*/
@InfoName("CL_DEVICE_VENDOR_ID")
public int getVendorId() {
return infos.getInt(getEntity(), CL_DEVICE_VENDOR_ID);
}
/**
* The number of parallel compute cores on the OpenCL device. <br/>
* The minimum value is 1.
*/
@InfoName("CL_DEVICE_MAX_COMPUTE_UNITS")
public int getMaxComputeUnits() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_COMPUTE_UNITS);
}
/**
* Maximum dimensions that specify the global and local work-item IDs used by the data parallel execution model. <br/>
* (Refer to clEnqueueNDRangeKernel).
* <br/>The minimum value is 3.
*/
@InfoName("CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS")
public int getMaxWorkItemDimensions() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS);
}
/**
* Maximum number of work-items that can be specified in each dimension of the work-group to clEnqueueNDRangeKernel.
*/
@InfoName("CL_DEVICE_MAX_WORK_ITEM_SIZES")
public long[] getMaxWorkItemSizes() {
long sizes[] = infos.getNativeSizes(getEntity(), CL_DEVICE_MAX_WORK_ITEM_SIZES, getMaxWorkItemDimensions());
for (int i = 0, n = sizes.length; i < n; i++) {
long size = sizes[i];
if ((size & 0xffffffff00000000L) == 0xcccccccc00000000L)
sizes[i] = size & 0xffffffffL;
}
return sizes;
}
/**
* Maximum number of work-items in a work-group executing a kernel using the data parallel execution model.
* (Refer to clEnqueueNDRangeKernel). <br/>
* The minimum value is 1.
*/
@InfoName("CL_DEVICE_MAX_WORK_GROUP_SIZE")
public long getMaxWorkGroupSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_WORK_GROUP_SIZE);
}
/**
* Maximum configured clock frequency of the device in MHz.
*/
@InfoName("CL_DEVICE_MAX_CLOCK_FREQUENCY")
public int getMaxClockFrequency() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_CLOCK_FREQUENCY);
}
/**
* The default compute device address space size specified as an unsigned integer value in bits. Currently supported values are 32 or 64 bits..<br>
* Size of size_t type in OpenCL kernels can be obtained with getAddressBits() / 8.
*/
@InfoName("CL_DEVICE_ADDRESS_BITS")
public int getAddressBits() {
return infos.getInt(getEntity(), CL_DEVICE_ADDRESS_BITS);
}
/**
* Max size of memory object allocation in bytes. The minimum value is max (1/4th of CL_DEVICE_GLOBAL_MEM_SIZE , 128*1024*1024)
*/
@InfoName("CL_DEVICE_MAX_MEM_ALLOC_SIZE")
public long getMaxMemAllocSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_MEM_ALLOC_SIZE);
}
/**
* Is CL_TRUE if images are supported by the OpenCL device and CL_FALSE otherwise.
*/
@InfoName("CL_DEVICE_IMAGE_SUPPORT")
public boolean hasImageSupport() {
return infos.getBool(getEntity(), CL_DEVICE_IMAGE_SUPPORT);
}
/**
* Max number of simultaneous image objects that can be read by a kernel. <br/>
* The minimum value is 128 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()).
*/
@InfoName("CL_DEVICE_MAX_READ_IMAGE_ARGS")
public int getMaxReadImageArgs() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_READ_IMAGE_ARGS);
}
/**
* Max number of simultaneous image objects that can be written to by a kernel. <br/>
* The minimum value is 8 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE (@see hasImageSupport()).
*/
@InfoName("CL_DEVICE_MAX_WRITE_IMAGE_ARGS")
public int getMaxWriteImageArgs() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_WRITE_IMAGE_ARGS);
}
@Override
public String toString() {
return getName() + " (" + getPlatform().getName() + ")";
}
/**
#documentCallsFunction("clCreateCommandQueue")
* Create an OpenCL execution queue on this device for the specified context.
* @param context context of the queue to create
* @return new OpenCL queue object
*/
@SuppressWarnings("deprecation")
public CLQueue createQueue(CLContext context, QueueProperties... queueProperties) {
#declareReusablePtrsAndPErr()
long flags = 0;
for (QueueProperties prop : queueProperties)
flags |= prop.value();
long queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), flags, getPeer(pErr));
#checkPErr()
return new CLQueue(context, queue, this);
}
/**
#documentCallsFunction("clCreateCommandQueue")
*/
@Deprecated
public CLQueue createQueue(EnumSet<QueueProperties> queueProperties, CLContext context) {
#declareReusablePtrsAndPErr()
long queue = CL.clCreateCommandQueue(context.getEntity(), getEntity(), QueueProperties.getValue(queueProperties), getPeer(pErr));
#checkPErr()
return new CLQueue(context, queue, this);
}
public CLQueue createOutOfOrderQueue(CLContext context) {
return createQueue(EnumSet.of(QueueProperties.OutOfOrderExecModeEnable), context);
}
public CLQueue createProfilingQueue(CLContext context) {
return createQueue(EnumSet.of(QueueProperties.ProfilingEnable), context);
}
/**
* Max width of 2D image in pixels. <br/>
* The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_IMAGE2D_MAX_WIDTH")
public long getImage2DMaxWidth() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_WIDTH);
}
/**
* Max height of 2D image in pixels. <br/>
* The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_IMAGE2D_MAX_HEIGHT")
public long getImage2DMaxHeight() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE2D_MAX_HEIGHT);
}
/**
* Max width of 3D image in pixels. <br/>
* The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_IMAGE3D_MAX_WIDTH")
public long getImage3DMaxWidth() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_WIDTH);
}
/**
* Max height of 3D image in pixels. <br/>
* The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_IMAGE3D_MAX_HEIGHT")
public long getImage3DMaxHeight() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_HEIGHT);
}
/**
* Max depth of 3D image in pixels. <br/>
* The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_IMAGE3D_MAX_DEPTH")
public long getImage3DMaxDepth() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_IMAGE3D_MAX_DEPTH);
}
/**
* Maximum number of samplers that can be used in a kernel. <br/>
* Refer to section 6.11.8 for a detailed description on samplers. <br/>
* The minimum value is 16 if CL_DEVICE_IMAGE_SUPPORT is CL_TRUE.
*/
@InfoName("CL_DEVICE_MAX_SAMPLERS")
public int getMaxSamplers() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_SAMPLERS);
}
/**
* Max size in bytes of the arguments that can be passed to a kernel. <br/>
* The minimum value is 256.
*/
@InfoName("CL_DEVICE_MAX_PARAMETER_SIZE")
public long getMaxParameterSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_PARAMETER_SIZE);
}
/**
* Describes the alignment in bits of the base address of any allocated memory object.
*/
@InfoName("CL_DEVICE_MEM_BASE_ADDR_ALIGN")
public int getMemBaseAddrAlign() {
return infos.getInt(getEntity(), CL_DEVICE_MEM_BASE_ADDR_ALIGN);
}
/**
* The smallest alignment in bytes which can be used for any data type.
*/
@InfoName("CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE")
public int getMinDataTypeAlign() {
return infos.getInt(getEntity(), CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE);
}
/** Bit values for CL_DEVICE_SINGLE_FP_CONFIG */
public enum SingleFPConfig implements com.nativelibs4java.util.ValuedEnum {
/** denorms are supported */
Denorm(CL_FP_DENORM),
/** INF and quiet NaNs are supported. */
InfNaN(CL_FP_INF_NAN),
/** round to nearest even rounding mode supported */
RoundToNearest(CL_FP_ROUND_TO_NEAREST),
/** round to zero rounding mode supported */
RoundToZero(CL_FP_ROUND_TO_ZERO),
/** round to +ve and -ve infinity rounding modes supported */
RoundToInf(CL_FP_ROUND_TO_INF),
/** IEEE754-2008 fused multiply-add is supported. */
FMA(CL_FP_FMA);
SingleFPConfig(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static long getValue(EnumSet<SingleFPConfig> set) {
return EnumValues.getValue(set);
}
public static EnumSet<SingleFPConfig> getEnumSet(long v) {
return EnumValues.getEnumSet(v, SingleFPConfig.class);
}
}
/**
* Describes single precision floating- point capability of the device.<br/>
* The mandated minimum floating-point capability is: RoundToNearest and InfNaN.
*/
@InfoName("CL_DEVICE_SINGLE_FP_CONFIG")
public EnumSet<SingleFPConfig> getSingleFPConfig() {
return SingleFPConfig.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_SINGLE_FP_CONFIG));
}
/** Values for CL_DEVICE_GLOBAL_MEM_CACHE_TYPE */
public enum GlobalMemCacheType implements com.nativelibs4java.util.ValuedEnum {
None(CL_NONE),
ReadOnlyCache(CL_READ_ONLY_CACHE),
ReadWriteCache(CL_READ_WRITE_CACHE);
GlobalMemCacheType(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static GlobalMemCacheType getEnum(long v) {
return EnumValues.getEnum(v, GlobalMemCacheType.class);
}
}
/**
* Type of global memory cache supported.
*/
@InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_TYPE")
public GlobalMemCacheType getGlobalMemCacheType() {
return GlobalMemCacheType.getEnum(infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_TYPE));
}
/**
* Size of global memory cache line in bytes.
*/
@InfoName("CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE")
public int getGlobalMemCachelineSize() {
return infos.getInt(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE);
}
/**
* Size of global memory cache in bytes.
*/
@InfoName("CL_DEVICE_GLOBAL_MEM_CACHE_SIZE")
public long getGlobalMemCacheSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_CACHE_SIZE);
}
/**
* Size of global device memory in bytes.
*/
@InfoName("CL_DEVICE_GLOBAL_MEM_SIZE")
public long getGlobalMemSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_GLOBAL_MEM_SIZE);
}
/**
* Max size in bytes of a constant buffer allocation. <br/>
* The minimum value is 64 KB.
*/
@InfoName("CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE")
public long getMaxConstantBufferSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE);
}
/**
* Max number of arguments declared with the __constant qualifier in a kernel. <br/>
* The minimum value is 8.
*/
@InfoName("CL_DEVICE_MAX_CONSTANT_ARGS")
public int getMaxConstantArgs() {
return infos.getInt(getEntity(), CL_DEVICE_MAX_CONSTANT_ARGS);
}
/** Values for CL_DEVICE_LOCAL_MEM_TYPE */
public enum LocalMemType implements com.nativelibs4java.util.ValuedEnum {
/** implying dedicated local memory storage such as SRAM */
Local(CL_LOCAL),
Global(CL_GLOBAL);
LocalMemType(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static LocalMemType getEnum(long v) {
return EnumValues.getEnum(v, LocalMemType.class);
}
}
/**
* Type of local memory supported. <br/>
*/
@InfoName("CL_DEVICE_LOCAL_MEM_TYPE")
public LocalMemType getLocalMemType() {
return LocalMemType.getEnum(infos.getInt(getEntity(), CL_DEVICE_LOCAL_MEM_TYPE));
}
/**
* Size of local memory arena in bytes. <br/>
* The minimum value is 16 KB.
*/
@InfoName("CL_DEVICE_LOCAL_MEM_SIZE")
public long getLocalMemSize() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_LOCAL_MEM_SIZE);
}
/**
* Is CL_TRUE if the device implements error correction for the memories, caches, registers etc. in the device. <br/>
* Is CL_FALSE if the device does not implement error correction. <br/>
* This can be a requirement for certain clients of OpenCL.
*/
@InfoName("CL_DEVICE_ERROR_CORRECTION_SUPPORT")
public boolean hasErrorCorrectionSupport() {
return infos.getBool(getEntity(), CL_DEVICE_ERROR_CORRECTION_SUPPORT);
}
@InfoName("Out of order queues support")
public boolean hasOutOfOrderQueueSupport() {
CLContext context = getPlatform().createContext(null, this);
CLQueue queue = null;
try {
queue = createOutOfOrderQueue(context);
return true;
} catch (CLException ex) {
return false;
} finally {
if (queue != null)
queue.release();
context.release();
}
}
/**
* Describes the resolution of device timer. <br/>
* This is measured in nanoseconds. <br/>
* Refer to section 5.9 for details.
*/
@InfoName("CL_DEVICE_PROFILING_TIMER_RESOLUTION")
public long getProfilingTimerResolution() {
return infos.getIntOrLong(getEntity(), CL_DEVICE_PROFILING_TIMER_RESOLUTION);
}
/**
* Is CL_TRUE if the OpenCL device is a little endian device and CL_FALSE otherwise.
*/
@InfoName("CL_DEVICE_ENDIAN_LITTLE")
public boolean isEndianLittle() {
return infos.getBool(getEntity(), CL_DEVICE_ENDIAN_LITTLE);
}
/**
* Is CL_TRUE if the device is available and CL_FALSE if the device is not available.
*/
@InfoName("CL_DEVICE_AVAILABLE")
public boolean isAvailable() {
return infos.getBool(getEntity(), CL_DEVICE_AVAILABLE);
}
/**
* Is CL_FALSE if the implementation does not have a compiler available to compile the program source. <br/>
* Is CL_TRUE if the compiler is available.<br/>
* This can be CL_FALSE for the embededed platform profile only.
*/
@InfoName("CL_DEVICE_COMPILER_AVAILABLE")
public boolean isCompilerAvailable() {
return infos.getBool(getEntity(), CL_DEVICE_COMPILER_AVAILABLE);
}
/**
Device name string.
*/
@InfoName("CL_DEVICE_NAME")
public String getName() {
return infos.getString(getEntity(), CL_DEVICE_NAME);
}
/**
* OpenCL C version string. <br/>
* Returns the highest OpenCL C version supported by the compiler for this device. <br/>
* This version string has the following format:<br/>
* OpenCL<space>C<space><major_version.minor_version><space><vendor-specific information><br/>
* The major_version.minor_version value returned must be 1.1 if CL_DEVICE_VERSION is OpenCL 1.1.<br/>
* The major_version.minor_version value returned can be 1.0 or 1.1 if CL_DEVICE_VERSION is OpenCL 1.0. <br/>
* If OpenCL C 1.1 is returned, this implies that the language feature set defined in section 6 of the OpenCL 1.1 specification is supported by the OpenCL 1.0 device.
* @since OpenCL 1.1
*/
@InfoName("CL_DEVICE_OPENCL_C_VERSION")
public String getOpenCLCVersion() {
try {
return infos.getString(getEntity(), CL_DEVICE_OPENCL_C_VERSION);
} catch (Throwable th) {
// TODO throw if supposed to handle OpenCL 1.1
return "OpenCL C 1.0";
}
}
/**
* @deprecated Legacy typo, use getOpenCLCVersion() instead.
*/
@Deprecated
public String getOpenCLVersion() {
return getOpenCLCVersion();
}
/**
Vendor name string.
*/
@InfoName("CL_DEVICE_VENDOR")
public String getVendor() {
return infos.getString(getEntity(), CL_DEVICE_VENDOR);
}
/**
OpenCL software driver version string in the form major_number.minor_number.
*/
@InfoName("CL_DRIVER_VERSION")
public String getDriverVersion() {
return infos.getString(getEntity(), CL_DRIVER_VERSION);
}
/**
* OpenCL profile string. <br/>
* Returns the profile name supported by the device. <br/>
* The profile name returned can be one of the following strings:
* <ul>
* <li>FULL_PROFILE if the device supports the OpenCL specification (functionality defined as part of the core specification and does not require any extensions to be supported).</li>
* <li>EMBEDDED_PROFILE if the device supports the OpenCL embedded profile.</li>
* </ul>
*/
@InfoName("CL_DEVICE_PROFILE")
public String getProfile() {
return infos.getString(getEntity(), CL_DEVICE_PROFILE);
}
/**
* Whether the device and the host have a unified memory subsystem.
* @since OpenCL 1.1
*/
@InfoName("CL_DEVICE_HOST_UNIFIED_MEMORY")
public boolean isHostUnifiedMemory() {
try {
return infos.getBool(getEntity(), CL_DEVICE_HOST_UNIFIED_MEMORY);
} catch (Throwable th) {
// TODO throw if supposed to handle OpenCL 1.1
return false;
}
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR")
public int getPreferredVectorWidthChar() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR);
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT")
public int getPreferredVectorWidthShort() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT);
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT")
public int getPreferredVectorWidthInt() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT);
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG")
public int getPreferredVectorWidthLong() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG);
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT")
public int getPreferredVectorWidthFloat() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT);
}
/**
* Preferred native vector width size for built-in scalar types that can be put into vectors. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_PREFERRED_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE")
public int getPreferredVectorWidthDouble() {
return infos.getInt(getEntity(), CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR")
public int getNativeVectorWidthChar() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT")
public int getNativeVectorWidthShort() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_INT")
public int getNativeVectorWidthInt() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_INT);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG")
public int getNativeVectorWidthLong() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT")
public int getNativeVectorWidthFloat() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT);
}
/**
* Returns the native ISA vector width. <br/>
* The vector width is defined as the number of scalar elements that can be stored in the vector. <br/>
* If the cl_khr_fp64 extension is not supported, CL_DEVICE_NATIVE_VECTOR_WID TH_DOUBLE must return 0.
*/
@InfoName("CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE")
public int getNativeVectorWidthDouble() {
return infos.getOptionalFeatureInt(getEntity(), CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE);
}
/**
* OpenCL version string. <br/>
* Returns the OpenCL version supported by the device.<br/>
* This version string has the following format:
* <code>
* OpenCL<space><major_version.min or_version><space><vendor-specific information>
* </code>
* The major_version.minor_version value returned will be 1.0.
*/
@InfoName("CL_DEVICE_VERSION")
public String getVersion() {
return infos.getString(getEntity(), CL_DEVICE_VERSION);
}
/**
Returns a space separated list of extension names (the extension names themselves do not contain any spaces). The list of extension names returned currently can include one or more of
*/
@InfoName("CL_DEVICE_EXTENSIONS")
public String[] getExtensions() {
if (extensions == null) {
extensions = infos.getString(getEntity(), CL_DEVICE_EXTENSIONS).split("\\s+");
}
return extensions;
}
private String[] extensions;
public boolean hasExtension(String name) {
name = name.trim();
for (String x : getExtensions()) {
if (name.equals(x.trim())) {
return true;
}
}
return false;
}
public boolean isDoubleSupported() {
return isDoubleSupportedKHR() || isDoubleSupportedAMD();
}
public boolean isDoubleSupportedKHR() {
return hasExtension("cl_khr_fp64");
}
public boolean isDoubleSupportedAMD() {
return hasExtension("cl_amd_fp64");
}
/**
* If this device supports the extension cl_amd_fp64 but not cl_khr_fp64, replace any OpenCL source code pragma of the style <code>#pragma OPENCL EXTENSION cl_khr_fp64 : enable</code> by <code>#pragma OPENCL EXTENSION cl_amd_fp64 : enable</code>.<br>
* Also works the other way around (if the KHR extension is available but the source code refers to the AMD extension).<br>
* This method is called automatically by CLProgram unless the javacl.adjustDoubleExtension property is set to false or the JAVACL_ADJUST_DOUBLE_EXTENSION is set to 0.
*/
public String replaceDoubleExtensionByExtensionActuallyAvailable(String kernelSource) {
boolean hasKHR = isDoubleSupportedKHR(), hasAMD = isDoubleSupportedAMD();
if (hasAMD && !hasKHR)
kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_khr_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_amd_fp64 : enable");
else if (!hasAMD && hasKHR)
kernelSource = kernelSource.replaceAll("#pragma\\s+OPENCL\\s+EXTENSION\\s+cl_amd_fp64\\s*:\\s*enable", "#pragma OPENCL EXTENSION cl_khr_fp64 : enable");
return kernelSource;
}
public boolean isHalfSupported() {
return hasExtension("cl_khr_fp16");
}
public boolean isByteAddressableStoreSupported() {
return hasExtension("cl_khr_byte_addressable_store");
}
public boolean isGLSharingSupported() {
return hasExtension("cl_khr_gl_sharing") || hasExtension("cl_APPLE_gl_sharing");
}
public boolean isGlobalInt32BaseAtomicsSupported() {
return hasExtension("cl_khr_global_int32_base_atomics");
}
public boolean isGlobalInt32ExtendedAtomicsSupported() {
return hasExtension("cl_khr_global_int32_extended_atomics");
}
public boolean isLocalInt32BaseAtomicsSupported() {
return hasExtension("cl_khr_local_int32_base_atomics");
}
public boolean isLocalInt32ExtendedAtomicsSupported() {
return hasExtension("cl_khr_local_int32_extended_atomics");
}
/** Bit values for CL_DEVICE_QUEUE_PROPERTIES */
public static enum QueueProperties implements com.nativelibs4java.util.ValuedEnum {
OutOfOrderExecModeEnable(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE),
ProfilingEnable(CL_QUEUE_PROFILING_ENABLE);
QueueProperties(long value) { this.value = value; }
long value;
@Override
public long value() { return value; }
public static long getValue(EnumSet<QueueProperties> set) {
return EnumValues.getValue(set);
}
public static EnumSet<QueueProperties> getEnumSet(long v) {
return EnumValues.getEnumSet(v, QueueProperties.class);
}
}
/**
* Describes the command-queue properties supported by the device.<br/>
* These properties are described in table 5.1.<br/>
* The mandated minimum capability is: ProfilingEnable.
*/
@InfoName("CL_DEVICE_QUEUE_PROPERTIES")
public EnumSet<QueueProperties> getQueueProperties() {
return QueueProperties.getEnumSet(infos.getIntOrLong(getEntity(), CL_DEVICE_QUEUE_PROPERTIES));
}
} |
package com.vaadin.terminal.gwt.client;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ui.UnknownComponentConnector;
import com.vaadin.terminal.gwt.client.ui.window.VWindow;
/**
* TODO Rename to something more Vaadin7-ish?
*/
public class VUIDLBrowser extends SimpleTree {
private static final String HELP = "Shift click handle to open recursively. Click components to hightlight them on client side. Shift click components to highlight them also on the server side.";
private ApplicationConfiguration conf;
private String highlightedPid;
/**
* TODO Should probably take ApplicationConnection instead of
* ApplicationConfiguration
*/
public VUIDLBrowser(final UIDL uidl, ApplicationConfiguration conf) {
this.conf = conf;
final UIDLItem root = new UIDLItem(uidl, conf);
add(root);
}
public VUIDLBrowser(ValueMap u, ApplicationConfiguration conf) {
this.conf = conf;
ValueMap valueMap = u.getValueMap("meta");
if (valueMap.containsKey("hl")) {
highlightedPid = valueMap.getString("hl");
}
Set<String> keySet = u.getKeySet();
for (String key : keySet) {
if (key.equals("state")) {
ValueMap stateJson = u.getValueMap(key);
SimpleTree stateChanges = new SimpleTree("Shared state");
for (String stateKey : stateJson.getKeySet()) {
stateChanges.add(new SharedStateItem(stateKey, stateJson
.getValueMap(stateKey)));
}
add(stateChanges);
} else if (key.equals("changes")) {
JsArray<UIDL> jsValueMapArray = u.getJSValueMapArray(key)
.cast();
for (int i = 0; i < jsValueMapArray.length(); i++) {
UIDL uidl = jsValueMapArray.get(i);
UIDLItem change = new UIDLItem(uidl, conf);
change.setTitle("change " + i);
add(change);
}
} else if (key.equals("meta")) {
} else {
// TODO consider pretty printing other request data
// addItem(key + " : " + u.getAsString(key));
}
}
open(highlightedPid != null);
setTitle(HELP);
}
/**
* A debug view of a server-originated component state change.
*/
abstract class StateChangeItem extends SimpleTree {
protected StateChangeItem() {
setTitle(HELP);
addDomHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
deHiglight();
}
}, MouseOutEvent.getType());
}
@Override
protected void select(ClickEvent event) {
ComponentConnector connector = getConnector();
highlight(connector);
if (event != null && event.getNativeEvent().getShiftKey()) {
connector.getConnection().highlightComponent(connector);
}
super.select(event);
}
/**
* Returns the Connector associated with this state change.
*/
protected ComponentConnector getConnector() {
List<ApplicationConnection> runningApplications = ApplicationConfiguration
.getRunningApplications();
// TODO this does not work properly with multiple application on
// same host page
for (ApplicationConnection applicationConnection : runningApplications) {
ServerConnector connector = ConnectorMap.get(
applicationConnection).getConnector(getConnectorId());
if (connector instanceof ComponentConnector) {
return (ComponentConnector) connector;
}
}
return new UnknownComponentConnector();
}
protected abstract String getConnectorId();
}
/**
* A debug view of a Vaadin 7 style shared state change.
*/
class SharedStateItem extends StateChangeItem {
private String connectorId;
SharedStateItem(String connectorId, ValueMap stateChanges) {
this.connectorId = connectorId;
setText(connectorId);
dir(new JSONObject(stateChanges), this);
}
@Override
protected String getConnectorId() {
return connectorId;
}
private void dir(String key, JSONValue value, SimpleTree tree) {
if (value.isObject() != null) {
SimpleTree subtree = new SimpleTree(key + "=object");
tree.add(subtree);
dir(value.isObject(), subtree);
} else if (value.isArray() != null) {
SimpleTree subtree = new SimpleTree(key + "=array");
dir(value.isArray(), subtree);
tree.add(subtree);
} else {
tree.add(new HTML(key + "=" + value));
}
}
private void dir(JSONObject state, SimpleTree tree) {
for (String key : state.keySet()) {
dir(key, state.get(key), tree);
}
}
private void dir(JSONArray array, SimpleTree tree) {
for (int i = 0; i < array.size(); ++i) {
dir("" + i, array.get(i), tree);
}
}
}
/**
* A debug view of a Vaadin 6 style hierarchical component state change.
*/
class UIDLItem extends StateChangeItem {
private UIDL uidl;
UIDLItem(UIDL uidl, ApplicationConfiguration conf) {
this.uidl = uidl;
try {
String name = uidl.getTag();
try {
name = getNodeName(uidl, conf, Integer.parseInt(name));
} catch (Exception e) {
// NOP
}
setText(name);
addItem("LOADING");
} catch (Exception e) {
setText(uidl.toString());
}
}
@Override
protected String getConnectorId() {
return uidl.getId();
}
private String getNodeName(UIDL uidl, ApplicationConfiguration conf,
int tag) {
Class<? extends ServerConnector> widgetClassByDecodedTag = conf
.getConnectorClassByEncodedTag(tag);
if (widgetClassByDecodedTag == UnknownComponentConnector.class) {
return conf.getUnknownServerClassNameByTag(tag)
+ "(NO CLIENT IMPLEMENTATION FOUND)";
} else {
return widgetClassByDecodedTag.getName();
}
}
@Override
public void open(boolean recursive) {
if (getWidgetCount() == 1
&& getWidget(0).getElement().getInnerText()
.equals("LOADING")) {
dir();
}
super.open(recursive);
}
public void dir() {
remove(0);
String nodeName = uidl.getTag();
try {
nodeName = getNodeName(uidl, conf, Integer.parseInt(nodeName));
} catch (Exception e) {
// NOP
}
Set<String> attributeNames = uidl.getAttributeNames();
for (String name : attributeNames) {
if (uidl.isMapAttribute(name)) {
try {
ValueMap map = uidl.getMapAttribute(name);
JsArrayString keyArray = map.getKeyArray();
nodeName += " " + name + "=" + "{";
for (int i = 0; i < keyArray.length(); i++) {
nodeName += keyArray.get(i) + ":"
+ map.getAsString(keyArray.get(i)) + ",";
}
nodeName += "}";
} catch (Exception e) {
}
} else {
final String value = uidl.getAttribute(name);
nodeName += " " + name + "=" + value;
}
}
setText(nodeName);
try {
SimpleTree tmp = null;
Set<String> variableNames = uidl.getVariableNames();
for (String name : variableNames) {
String value = "";
try {
value = uidl.getVariable(name);
} catch (final Exception e) {
try {
String[] stringArrayAttribute = uidl
.getStringArrayAttribute(name);
value = stringArrayAttribute.toString();
} catch (final Exception e2) {
try {
final int intVal = uidl.getIntVariable(name);
value = String.valueOf(intVal);
} catch (final Exception e3) {
value = "unknown";
}
}
}
if (tmp == null) {
tmp = new SimpleTree("variables");
}
tmp.addItem(name + "=" + value);
}
if (tmp != null) {
add(tmp);
}
} catch (final Exception e) {
// Ignored, no variables
}
final Iterator<Object> i = uidl.getChildIterator();
while (i.hasNext()) {
final Object child = i.next();
try {
final UIDL c = (UIDL) child;
final UIDLItem childItem = new UIDLItem(c, conf);
add(childItem);
} catch (final Exception e) {
addItem(child.toString());
}
}
if (highlightedPid != null && highlightedPid.equals(uidl.getId())) {
getElement().getStyle().setBackgroundColor("#fdd");
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
getElement().scrollIntoView();
}
});
}
}
}
static Element highlight = Document.get().createDivElement();
static {
Style style = highlight.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setZIndex(VWindow.Z_INDEX + 1000);
style.setBackgroundColor("red");
style.setOpacity(0.2);
if (BrowserInfo.get().isIE()) {
style.setProperty("filter", "alpha(opacity=20)");
}
}
static void highlight(ComponentConnector paintable) {
if (paintable != null) {
Widget w = paintable.getWidget();
Style style = highlight.getStyle();
style.setTop(w.getAbsoluteTop(), Unit.PX);
style.setLeft(w.getAbsoluteLeft(), Unit.PX);
style.setWidth(w.getOffsetWidth(), Unit.PX);
style.setHeight(w.getOffsetHeight(), Unit.PX);
RootPanel.getBodyElement().appendChild(highlight);
}
}
static void deHiglight() {
if (highlight.getParentElement() != null) {
highlight.getParentElement().removeChild(highlight);
}
}
} |
package com.vaadin.terminal.gwt.client.ui;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableElement;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasBlurHandlers;
import com.google.gwt.event.dom.client.HasFocusHandlers;
import com.google.gwt.event.dom.client.HasKeyDownHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.impl.FocusImpl;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.EventId;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderInformation;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VCaption;
public class VTabsheet extends VTabsheetBase implements Focusable,
FocusHandler, BlurHandler, KeyDownHandler {
private static class VCloseEvent {
private Tab tab;
VCloseEvent(Tab tab) {
this.tab = tab;
}
public Tab getTab() {
return tab;
}
}
private interface VCloseHandler {
public void onClose(VCloseEvent event);
}
/**
* Representation of a single "tab" shown in the TabBar
*
*/
private static class Tab extends SimplePanel implements HasFocusHandlers,
HasBlurHandlers, HasKeyDownHandlers {
private static final String TD_CLASSNAME = CLASSNAME + "-tabitemcell";
private static final String TD_FIRST_CLASSNAME = TD_CLASSNAME
+ "-first";
private static final String TD_SELECTED_CLASSNAME = TD_CLASSNAME
+ "-selected";
private static final String TD_SELECTED_FIRST_CLASSNAME = TD_SELECTED_CLASSNAME
+ "-first";
private static final String TD_DISABLED_CLASSNAME = TD_CLASSNAME
+ "-disabled";
private static final String DIV_CLASSNAME = CLASSNAME + "-tabitem";
private static final String DIV_SELECTED_CLASSNAME = DIV_CLASSNAME
+ "-selected";
private TabCaption tabCaption;
Element td = getElement();
private VCloseHandler closeHandler;
private boolean enabledOnServer = true;
private Element div;
private TabBar tabBar;
private boolean hiddenOnServer = false;
private String styleName;
private Tab(TabBar tabBar) {
super(DOM.createTD());
this.tabBar = tabBar;
setStyleName(td, TD_CLASSNAME);
div = DOM.createDiv();
focusImpl.setTabIndex(td, -1);
setStyleName(div, DIV_CLASSNAME);
DOM.appendChild(td, div);
tabCaption = new TabCaption(this, getTabsheet()
.getApplicationConnection());
add(tabCaption);
addFocusHandler(getTabsheet());
addBlurHandler(getTabsheet());
addKeyDownHandler(getTabsheet());
}
public boolean isHiddenOnServer() {
return hiddenOnServer;
}
public void setHiddenOnServer(boolean hiddenOnServer) {
this.hiddenOnServer = hiddenOnServer;
}
@Override
protected Element getContainerElement() {
// Attach caption element to div, not td
return div;
}
public boolean isEnabledOnServer() {
return enabledOnServer;
}
public void setEnabledOnServer(boolean enabled) {
enabledOnServer = enabled;
setStyleName(td, TD_DISABLED_CLASSNAME, !enabled);
if (!enabled) {
focusImpl.setTabIndex(td, -1);
}
}
public void addClickHandler(ClickHandler handler) {
tabCaption.addClickHandler(handler);
}
public void setCloseHandler(VCloseHandler closeHandler) {
this.closeHandler = closeHandler;
}
/**
* Toggles the style names for the Tab
*
* @param selected
* true if the Tab is selected
* @param first
* true if the Tab is the first visible Tab
*/
public void setStyleNames(boolean selected, boolean first) {
setStyleName(td, TD_FIRST_CLASSNAME, first);
setStyleName(td, TD_SELECTED_CLASSNAME, selected);
setStyleName(td, TD_SELECTED_FIRST_CLASSNAME, selected && first);
setStyleName(div, DIV_SELECTED_CLASSNAME, selected);
}
public void setTabulatorIndex(int tabIndex) {
focusImpl.setTabIndex(td, tabIndex);
}
public boolean isClosable() {
return tabCaption.isClosable();
}
public void onClose() {
closeHandler.onClose(new VCloseEvent(this));
}
public VTabsheet getTabsheet() {
return tabBar.getTabsheet();
}
public void updateFromUIDL(UIDL tabUidl) {
tabCaption.updateCaption(tabUidl);
// Apply the styleName set for the tab
String newStyleName = tabUidl.getStringAttribute(TAB_STYLE_NAME);
// Find the nth td element
if (newStyleName != null && newStyleName.length() != 0) {
if (!newStyleName.equals(styleName)) {
// If we have a new style name
if (styleName != null && styleName.length() != 0) {
// Remove old style name if present
td.removeClassName(TD_CLASSNAME + "-" + styleName);
}
// Set new style name
td.addClassName(TD_CLASSNAME + "-" + newStyleName);
styleName = newStyleName;
}
} else if (styleName != null) {
// Remove the set stylename if no stylename is present in the
// uidl
td.removeClassName(TD_CLASSNAME + "-" + styleName);
styleName = null;
}
}
public void recalculateCaptionWidth() {
tabCaption.setWidth(tabCaption.getRequiredWidth() + "px");
}
public HandlerRegistration addFocusHandler(FocusHandler handler) {
return addDomHandler(handler, FocusEvent.getType());
}
public HandlerRegistration addBlurHandler(BlurHandler handler) {
return addDomHandler(handler, BlurEvent.getType());
}
public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
return addDomHandler(handler, KeyDownEvent.getType());
}
public void focus() {
focusImpl.focus(td);
}
public void blur() {
focusImpl.blur(td);
}
}
private static class TabCaption extends VCaption {
private boolean closable = false;
private Element closeButton;
private Tab tab;
private ApplicationConnection client;
TabCaption(Tab tab, ApplicationConnection client) {
super(null, client);
this.client = client;
this.tab = tab;
}
@Override
public boolean updateCaption(UIDL uidl) {
if (uidl.hasAttribute(ATTRIBUTE_DESCRIPTION)
|| uidl.hasAttribute(ATTRIBUTE_ERROR)) {
TooltipInfo tooltipInfo = new TooltipInfo();
tooltipInfo.setTitle(uidl
.getStringAttribute(ATTRIBUTE_DESCRIPTION));
if (uidl.hasAttribute(ATTRIBUTE_ERROR)) {
tooltipInfo.setErrorUidl(uidl.getErrors());
}
client.registerTooltip(getTabsheet(), getElement(), tooltipInfo);
} else {
client.registerTooltip(getTabsheet(), getElement(), null);
}
boolean ret = super.updateCaption(uidl);
setClosable(uidl.hasAttribute("closable"));
return ret;
}
private VTabsheet getTabsheet() {
return tab.getTabsheet();
}
@Override
public void onBrowserEvent(Event event) {
if (closable && event.getTypeInt() == Event.ONCLICK
&& event.getEventTarget().cast() == closeButton) {
tab.onClose();
event.stopPropagation();
event.preventDefault();
}
super.onBrowserEvent(event);
if (event.getTypeInt() == Event.ONLOAD) {
getTabsheet().tabSizeMightHaveChanged(getTab());
}
client.handleTooltipEvent(event, getTabsheet(), getElement());
}
public Tab getTab() {
return tab;
}
@Override
public void setWidth(String width) {
super.setWidth(width);
if (BrowserInfo.get().isIE7()) {
/*
* IE7 apparently has problems with calculating width for
* floated elements inside a DIV with padding. Set the width
* explicitly for the caption.
*/
fixTextWidth();
}
}
private void fixTextWidth() {
Element captionText = getTextElement();
if (captionText == null) {
return;
}
int captionWidth = Util.getRequiredWidth(captionText);
int scrollWidth = captionText.getScrollWidth();
if (scrollWidth > captionWidth) {
captionWidth = scrollWidth;
}
captionText.getStyle().setPropertyPx("width", captionWidth);
}
public void setClosable(boolean closable) {
this.closable = closable;
if (closable && closeButton == null) {
closeButton = DOM.createSpan();
closeButton.setInnerHTML("×");
closeButton
.setClassName(VTabsheet.CLASSNAME + "-caption-close");
getElement().insertBefore(closeButton,
getElement().getLastChild());
} else if (!closable && closeButton != null) {
getElement().removeChild(closeButton);
closeButton = null;
}
if (closable) {
addStyleDependentName("closable");
} else {
removeStyleDependentName("closable");
}
}
public boolean isClosable() {
return closable;
}
@Override
public int getRequiredWidth() {
int width = super.getRequiredWidth();
if (closeButton != null) {
width += Util.getRequiredWidth(closeButton);
}
return width;
}
}
static class TabBar extends ComplexPanel implements ClickHandler,
VCloseHandler {
private final Element tr = DOM.createTR();
private final Element spacerTd = DOM.createTD();
private Tab selected;
private VTabsheet tabsheet;
TabBar(VTabsheet tabsheet) {
this.tabsheet = tabsheet;
Element el = DOM.createTable();
Element tbody = DOM.createTBody();
DOM.appendChild(el, tbody);
DOM.appendChild(tbody, tr);
setStyleName(spacerTd, CLASSNAME + "-spacertd");
DOM.appendChild(tr, spacerTd);
DOM.appendChild(spacerTd, DOM.createDiv());
setElement(el);
}
public void onClose(VCloseEvent event) {
Tab tab = event.getTab();
if (!tab.isEnabledOnServer()) {
return;
}
int tabIndex = getWidgetIndex(tab);
getTabsheet().sendTabClosedEvent(tabIndex);
}
protected Element getContainerElement() {
return tr;
}
public int getTabCount() {
return getWidgetCount();
}
public Tab addTab() {
Tab t = new Tab(this);
int tabIndex = getTabCount();
// Logical attach
insert(t, tr, tabIndex, true);
if (tabIndex == 0) {
// Set the "first" style
t.setStyleNames(false, true);
t.setTabulatorIndex(-1);
}
t.addClickHandler(this);
t.setCloseHandler(this);
return t;
}
public void onClick(ClickEvent event) {
Widget caption = (Widget) event.getSource();
int index = getWidgetIndex(caption.getParent());
getTabsheet().onTabSelected(index);
}
public VTabsheet getTabsheet() {
return tabsheet;
}
public Tab getTab(int index) {
if (index < 0 || index >= getTabCount()) {
return null;
}
return (Tab) super.getWidget(index);
}
public void selectTab(int index) {
final Tab newSelected = getTab(index);
final Tab oldSelected = selected;
newSelected.setStyleNames(true, isFirstVisibleTab(index));
newSelected.setTabulatorIndex(getTabsheet().tabulatorIndex);
if (oldSelected != null && oldSelected != newSelected) {
oldSelected.setStyleNames(false,
isFirstVisibleTab(getWidgetIndex(oldSelected)));
oldSelected.setTabulatorIndex(-1);
}
// Update the field holding the currently selected tab
selected = newSelected;
// The selected tab might need more (or less) space
newSelected.recalculateCaptionWidth();
getTab(tabsheet.activeTabIndex).recalculateCaptionWidth();
}
public void removeTab(int i) {
Tab tab = getTab(i);
if (tab == null) {
return;
}
remove(tab);
/*
* If this widget was selected we need to unmark it as the last
* selected
*/
if (tab == selected) {
selected = null;
}
// FIXME: Shouldn't something be selected instead?
}
private boolean isFirstVisibleTab(int index) {
return getFirstVisibleTab() == index;
}
/**
* Returns the index of the first visible tab
*
* @return
*/
private int getFirstVisibleTab() {
return getNextVisibleTab(-1);
}
/**
* Find the next visible tab. Returns -1 if none is found.
*
* @param i
* @return
*/
private int getNextVisibleTab(int i) {
int tabs = getTabCount();
do {
i++;
} while (i < tabs && getTab(i).isHiddenOnServer());
if (i == tabs) {
return -1;
} else {
return i;
}
}
/**
* Find the previous visible tab. Returns -1 if none is found.
*
* @param i
* @return
*/
private int getPreviousVisibleTab(int i) {
do {
i
} while (i >= 0 && getTab(i).isHiddenOnServer());
return i;
}
public int scrollLeft(int currentFirstVisible) {
int prevVisible = getPreviousVisibleTab(currentFirstVisible);
if (prevVisible == -1) {
return -1;
}
Tab newFirst = getTab(prevVisible);
newFirst.setVisible(true);
newFirst.recalculateCaptionWidth();
return prevVisible;
}
public int scrollRight(int currentFirstVisible) {
int nextVisible = getNextVisibleTab(currentFirstVisible);
if (nextVisible == -1) {
return -1;
}
Tab currentFirst = getTab(currentFirstVisible);
currentFirst.setVisible(false);
currentFirst.recalculateCaptionWidth();
return nextVisible;
}
}
public static final String CLASSNAME = "v-tabsheet";
public static final String TABS_CLASSNAME = "v-tabsheet-tabcontainer";
public static final String SCROLLER_CLASSNAME = "v-tabsheet-scroller";
// Can't use "style" as it's already in use
public static final String TAB_STYLE_NAME = "tabstyle";
private static final FocusImpl focusImpl = FocusImpl.getFocusImplForPanel();
private final Element tabs; // tabbar and 'scroller' container
private final Element scroller; // tab-scroller element
private final Element scrollerNext; // tab-scroller next button element
private final Element scrollerPrev; // tab-scroller prev button element
private Tab focusedTab;
/**
* The tabindex property (position in the browser's focus cycle.) Named like
* this to avoid confusion with activeTabIndex.
*/
private int tabulatorIndex = 0;
/**
* The index of the first visible tab (when scrolled)
*/
private int scrollerIndex = 0;
private final TabBar tb = new TabBar(this);
private final VTabsheetPanel tp = new VTabsheetPanel();
private final Element contentNode, deco;
private String height;
private String width;
private boolean waitingForResponse;
private final RenderInformation renderInformation = new RenderInformation();
/**
* Previous visible widget is set invisible with CSS (not display: none, but
* visibility: hidden), to avoid flickering during render process. Normal
* visibility must be returned later when new widget is rendered.
*/
private Widget previousVisibleWidget;
private boolean rendering = false;
private String currentStyle;
/**
* @return Whether the tab could be selected or not.
*/
private boolean onTabSelected(final int tabIndex) {
if (disabled || waitingForResponse) {
return false;
}
final Object tabKey = tabKeys.get(tabIndex);
if (disabledTabKeys.contains(tabKey)) {
return false;
}
if (client != null && activeTabIndex != tabIndex) {
tb.selectTab(tabIndex);
if (focusedTab != null) {
focusedTab = tb.getTab(tabIndex);
}
addStyleDependentName("loading");
// run updating variables in deferred command to bypass some FF
// optimization issues
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
previousVisibleWidget = tp.getWidget(tp.getVisibleWidget());
DOM.setStyleAttribute(
DOM.getParent(previousVisibleWidget.getElement()),
"visibility", "hidden");
client.updateVariable(id, "selected", tabKeys.get(tabIndex)
.toString(), true);
}
});
waitingForResponse = true;
return true;
}
return false;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
public void tabSizeMightHaveChanged(Tab tab) {
// icon onloads may change total width of tabsheet
if (isDynamicWidth()) {
updateDynamicWidth();
}
updateTabScroller();
}
void sendTabClosedEvent(int tabIndex) {
client.updateVariable(id, "close", tabKeys.get(tabIndex), true);
}
private boolean isDynamicWidth() {
return width == null || width.equals("");
}
private boolean isDynamicHeight() {
return height == null || height.equals("");
}
public VTabsheet() {
super(CLASSNAME);
addHandler(this, FocusEvent.getType());
addHandler(this, BlurEvent.getType());
// Tab scrolling
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
tabs = DOM.createDiv();
DOM.setElementProperty(tabs, "className", TABS_CLASSNAME);
scroller = DOM.createDiv();
DOM.setElementProperty(scroller, "className", SCROLLER_CLASSNAME);
scrollerPrev = DOM.createButton();
DOM.setElementProperty(scrollerPrev, "className", SCROLLER_CLASSNAME
+ "Prev");
DOM.sinkEvents(scrollerPrev, Event.ONCLICK);
scrollerNext = DOM.createButton();
DOM.setElementProperty(scrollerNext, "className", SCROLLER_CLASSNAME
+ "Next");
DOM.sinkEvents(scrollerNext, Event.ONCLICK);
DOM.appendChild(getElement(), tabs);
// Tabs
tp.setStyleName(CLASSNAME + "-tabsheetpanel");
contentNode = DOM.createDiv();
deco = DOM.createDiv();
addStyleDependentName("loading"); // Indicate initial progress
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(contentNode, "className", CLASSNAME + "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
add(tb, tabs);
DOM.appendChild(scroller, scrollerPrev);
DOM.appendChild(scroller, scrollerNext);
DOM.appendChild(getElement(), contentNode);
add(tp, contentNode);
DOM.appendChild(getElement(), deco);
DOM.appendChild(tabs, scroller);
// TODO Use for Safari only. Fix annoying 1px first cell in TabBar.
// DOM.setStyleAttribute(DOM.getFirstChild(DOM.getFirstChild(DOM
// .getFirstChild(tb.getElement()))), "display", "none");
}
@Override
public void onBrowserEvent(Event event) {
// Tab scrolling
if (isScrolledTabs() && DOM.eventGetTarget(event) == scrollerPrev) {
int newFirstIndex = tb.scrollLeft(scrollerIndex);
if (newFirstIndex != -1) {
scrollerIndex = newFirstIndex;
updateTabScroller();
}
} else if (isClippedTabs() && DOM.eventGetTarget(event) == scrollerNext) {
int newFirstIndex = tb.scrollRight(scrollerIndex);
if (newFirstIndex != -1) {
scrollerIndex = newFirstIndex;
updateTabScroller();
}
} else {
super.onBrowserEvent(event);
}
}
/**
* Checks if the tab with the selected index has been scrolled out of the
* view (on the left side).
*
* @param index
* @return
*/
private boolean scrolledOutOfView(int index) {
return scrollerIndex > index;
}
@Override
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
if (!uidl.getBooleanAttribute("cached")) {
// Handle stylename changes before generics (might affect size
// calculations)
handleStyleNames(uidl);
}
super.updateFromUIDL(uidl, client);
if (cachedUpdate) {
rendering = false;
return;
}
// tabs; push or not
if (!isDynamicWidth()) {
// FIXME: This makes tab sheet tabs go to 1px width on every update
// and then back to original width
// update width later, in updateTabScroller();
DOM.setStyleAttribute(tabs, "width", "1px");
DOM.setStyleAttribute(tabs, "overflow", "hidden");
} else {
showAllTabs();
DOM.setStyleAttribute(tabs, "width", "");
DOM.setStyleAttribute(tabs, "overflow", "visible");
updateDynamicWidth();
}
if (!isDynamicHeight()) {
// Must update height after the styles have been set
updateContentNodeHeight();
updateOpenTabSize();
}
if (uidl.hasAttribute("tabindex")) {
tabulatorIndex = uidl.getIntAttribute("tabindex");
if (tabulatorIndex == -1) {
blur();
}
}
// If a tab was focused before, focus the new active tab
if (focusedTab != null && tb.getTabCount() > 0 && tabulatorIndex != -1) {
focus();
}
iLayout();
// Re run relative size update to ensure optimal scrollbars
// TODO isolate to situation that visible tab has undefined height
try {
client.handleComponentRelativeSize(tp.getWidget(tp
.getVisibleWidget()));
} catch (Exception e) {
// Ignore, most likely empty tabsheet
}
renderInformation.updateSize(getElement());
waitingForResponse = false;
rendering = false;
}
private void handleStyleNames(UIDL uidl) {
// Add proper stylenames for all elements (easier to prevent unwanted
// style inheritance)
if (uidl.hasAttribute("style")) {
final String style = uidl.getStringAttribute("style");
if (currentStyle != style) {
currentStyle = style;
final String[] styles = style.split(" ");
final String tabsBaseClass = TABS_CLASSNAME;
String tabsClass = tabsBaseClass;
final String contentBaseClass = CLASSNAME + "-content";
String contentClass = contentBaseClass;
final String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
tb.addStyleDependentName(styles[i]);
tabsClass += " " + tabsBaseClass + "-" + styles[i];
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(tabs, "className", tabsClass);
DOM.setElementProperty(contentNode, "className", contentClass);
DOM.setElementProperty(deco, "className", decoClass);
borderW = -1;
}
} else {
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(tabs, "className", TABS_CLASSNAME);
DOM.setElementProperty(contentNode, "className", CLASSNAME
+ "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
}
if (uidl.hasAttribute("hidetabs")) {
tb.setVisible(false);
addStyleName(CLASSNAME + "-hidetabs");
} else {
tb.setVisible(true);
removeStyleName(CLASSNAME + "-hidetabs");
}
}
private void updateDynamicWidth() {
// Find width consumed by tabs
TableCellElement spacerCell = ((TableElement) tb.getElement().cast())
.getRows().getItem(0).getCells().getItem(tb.getTabCount());
int spacerWidth = spacerCell.getOffsetWidth();
DivElement div = (DivElement) spacerCell.getFirstChildElement();
int spacerMinWidth = spacerCell.getOffsetWidth() - div.getOffsetWidth();
int tabsWidth = tb.getOffsetWidth() - spacerWidth + spacerMinWidth;
// Find content width
Style style = tp.getElement().getStyle();
String overflow = style.getProperty("overflow");
style.setProperty("overflow", "hidden");
style.setPropertyPx("width", tabsWidth);
boolean hasTabs = tp.getWidgetCount() > 0;
Style wrapperstyle = null;
if (hasTabs) {
wrapperstyle = tp.getWidget(tp.getVisibleWidget()).getElement()
.getParentElement().getStyle();
wrapperstyle.setPropertyPx("width", tabsWidth);
}
// Get content width from actual widget
int contentWidth = 0;
if (hasTabs) {
contentWidth = tp.getWidget(tp.getVisibleWidget()).getOffsetWidth();
}
style.setProperty("overflow", overflow);
// Set widths to max(tabs,content)
if (tabsWidth < contentWidth) {
tabsWidth = contentWidth;
}
int outerWidth = tabsWidth + getContentAreaBorderWidth();
tabs.getStyle().setPropertyPx("width", outerWidth);
style.setPropertyPx("width", tabsWidth);
if (hasTabs) {
wrapperstyle.setPropertyPx("width", tabsWidth);
}
contentNode.getStyle().setPropertyPx("width", tabsWidth);
super.setWidth(outerWidth + "px");
updateOpenTabSize();
}
@Override
protected void renderTab(final UIDL tabUidl, int index, boolean selected,
boolean hidden) {
Tab tab = tb.getTab(index);
if (tab == null) {
tab = tb.addTab();
}
tab.updateFromUIDL(tabUidl);
tab.setEnabledOnServer((!disabledTabKeys.contains(tabKeys.get(index))));
tab.setHiddenOnServer(hidden);
if (scrolledOutOfView(index)) {
// Should not set tabs visible if they are scrolled out of view
hidden = true;
}
// Set the current visibility of the tab (in the browser)
tab.setVisible(!hidden);
/*
* Force the width of the caption container so the content will not wrap
* and tabs won't be too narrow in certain browsers
*/
tab.recalculateCaptionWidth();
UIDL tabContentUIDL = null;
Paintable tabContent = null;
if (tabUidl.getChildCount() > 0) {
tabContentUIDL = tabUidl.getChildUIDL(0);
tabContent = client.getPaintable(tabContentUIDL);
}
if (tabContent != null) {
/* This is a tab with content information */
int oldIndex = tp.getWidgetIndex((Widget) tabContent);
if (oldIndex != -1 && oldIndex != index) {
/*
* The tab has previously been rendered in another position so
* we must move the cached content to correct position
*/
tp.insert((Widget) tabContent, index);
}
} else {
/* A tab whose content has not yet been loaded */
/*
* Make sure there is a corresponding empty tab in tp. The same
* operation as the moving above but for not-loaded tabs.
*/
if (index < tp.getWidgetCount()) {
Widget oldWidget = tp.getWidget(index);
if (!(oldWidget instanceof PlaceHolder)) {
tp.insert(new PlaceHolder(), index);
}
}
}
if (selected) {
renderContent(tabContentUIDL);
tb.selectTab(index);
} else {
if (tabContentUIDL != null) {
// updating a drawn child on hidden tab
if (tp.getWidgetIndex((Widget) tabContent) < 0) {
tp.insert((Widget) tabContent, index);
}
tabContent.updateFromUIDL(tabContentUIDL, client);
} else if (tp.getWidgetCount() <= index) {
tp.add(new PlaceHolder());
}
}
}
public class PlaceHolder extends VLabel {
public PlaceHolder() {
super("");
}
}
@Override
protected void selectTab(int index, final UIDL contentUidl) {
if (index != activeTabIndex) {
activeTabIndex = index;
tb.selectTab(activeTabIndex);
}
renderContent(contentUidl);
}
private void renderContent(final UIDL contentUIDL) {
final Paintable content = client.getPaintable(contentUIDL);
if (tp.getWidgetCount() > activeTabIndex) {
Widget old = tp.getWidget(activeTabIndex);
if (old != content) {
tp.remove(activeTabIndex);
if (old instanceof Paintable) {
client.unregisterPaintable((Paintable) old);
}
tp.insert((Widget) content, activeTabIndex);
}
} else {
tp.add((Widget) content);
}
tp.showWidget(activeTabIndex);
VTabsheet.this.iLayout();
(content).updateFromUIDL(contentUIDL, client);
/*
* The size of a cached, relative sized component must be updated to
* report correct size to updateOpenTabSize().
*/
if (contentUIDL.getBooleanAttribute("cached")) {
client.handleComponentRelativeSize((Widget) content);
}
updateOpenTabSize();
VTabsheet.this.removeStyleDependentName("loading");
if (previousVisibleWidget != null) {
DOM.setStyleAttribute(
DOM.getParent(previousVisibleWidget.getElement()),
"visibility", "");
previousVisibleWidget = null;
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
this.height = height;
updateContentNodeHeight();
if (!rendering) {
updateOpenTabSize();
iLayout();
// TODO Check if this is needed
client.runDescendentsLayout(this);
}
}
private void updateContentNodeHeight() {
if (height != null && !"".equals(height)) {
int contentHeight = getOffsetHeight();
contentHeight -= DOM.getElementPropertyInt(deco, "offsetHeight");
contentHeight -= tb.getOffsetHeight();
if (contentHeight < 0) {
contentHeight = 0;
}
// Set proper values for content element
DOM.setStyleAttribute(contentNode, "height", contentHeight + "px");
renderSpace.setHeight(contentHeight);
} else {
DOM.setStyleAttribute(contentNode, "height", "");
renderSpace.setHeight(0);
}
}
@Override
public void setWidth(String width) {
if ((this.width == null && width.equals(""))
|| (this.width != null && this.width.equals(width))) {
return;
}
super.setWidth(width);
if (width.equals("")) {
width = null;
}
this.width = width;
if (width == null) {
renderSpace.setWidth(0);
contentNode.getStyle().setProperty("width", "");
} else {
int contentWidth = getOffsetWidth() - getContentAreaBorderWidth();
if (contentWidth < 0) {
contentWidth = 0;
}
contentNode.getStyle().setProperty("width", contentWidth + "px");
renderSpace.setWidth(contentWidth);
}
if (!rendering) {
if (isDynamicHeight()) {
Util.updateRelativeChildrenAndSendSizeUpdateEvent(client, tp,
this);
}
updateOpenTabSize();
iLayout();
// TODO Check if this is needed
client.runDescendentsLayout(this);
}
}
public void iLayout() {
updateTabScroller();
tp.runWebkitOverflowAutoFix();
}
/**
* Sets the size of the visible tab (component). As the tab is set to
* position: absolute (to work around a firefox flickering bug) we must keep
* this up-to-date by hand.
*/
private void updateOpenTabSize() {
/*
* The overflow=auto element must have a height specified, otherwise it
* will be just as high as the contents and no scrollbars will appear
*/
int height = -1;
int width = -1;
int minWidth = 0;
if (!isDynamicHeight()) {
height = renderSpace.getHeight();
}
if (!isDynamicWidth()) {
width = renderSpace.getWidth();
} else {
/*
* If the tabbar is wider than the content we need to use the tabbar
* width as minimum width so scrollbars get placed correctly (at the
* right edge).
*/
minWidth = tb.getOffsetWidth() - getContentAreaBorderWidth();
}
tp.fixVisibleTabSize(width, height, minWidth);
}
/**
* Layouts the tab-scroller elements, and applies styles.
*/
private void updateTabScroller() {
if (width != null) {
DOM.setStyleAttribute(tabs, "width", width);
}
// Make sure scrollerIndex is valid
if (scrollerIndex < 0 || scrollerIndex > tb.getTabCount()) {
scrollerIndex = tb.getFirstVisibleTab();
} else if (tb.getTabCount() > 0
&& tb.getTab(scrollerIndex).isHiddenOnServer()) {
scrollerIndex = tb.getNextVisibleTab(scrollerIndex);
}
boolean scrolled = isScrolledTabs();
boolean clipped = isClippedTabs();
if (tb.getTabCount() > 0 && tb.isVisible() && (scrolled || clipped)) {
DOM.setStyleAttribute(scroller, "display", "");
DOM.setElementProperty(scrollerPrev, "className",
SCROLLER_CLASSNAME + (scrolled ? "Prev" : "Prev-disabled"));
DOM.setElementProperty(scrollerNext, "className",
SCROLLER_CLASSNAME + (clipped ? "Next" : "Next-disabled"));
} else {
DOM.setStyleAttribute(scroller, "display", "none");
}
if (BrowserInfo.get().isSafari()) {
// fix tab height for safari, bugs sometimes if tabs contain icons
String property = tabs.getStyle().getProperty("height");
if (property == null || property.equals("")) {
tabs.getStyle().setPropertyPx("height", tb.getOffsetHeight());
}
/*
* another hack for webkits. tabscroller sometimes drops without
* "shaking it" reproducable in
* com.vaadin.tests.components.tabsheet.TabSheetIcons
*/
final Style style = scroller.getStyle();
style.setProperty("whiteSpace", "normal");
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
style.setProperty("whiteSpace", "");
}
});
}
}
private void showAllTabs() {
scrollerIndex = tb.getFirstVisibleTab();
for (int i = 0; i < tb.getTabCount(); i++) {
Tab t = tb.getTab(i);
if (!t.isHiddenOnServer()) {
t.setVisible(true);
}
}
}
private boolean isScrolledTabs() {
return scrollerIndex > tb.getFirstVisibleTab();
}
private boolean isClippedTabs() {
return (tb.getOffsetWidth() - DOM.getElementPropertyInt((Element) tb
.getContainerElement().getLastChild().cast(), "offsetWidth")) > getOffsetWidth()
- (isScrolledTabs() ? scroller.getOffsetWidth() : 0);
}
@Override
protected void clearPaintables() {
int i = tb.getTabCount();
while (i > 0) {
tb.removeTab(--i);
}
tp.clear();
}
@Override
protected Iterator getPaintableIterator() {
return tp.iterator();
}
public boolean hasChildComponent(Widget component) {
if (tp.getWidgetIndex(component) < 0) {
return false;
} else {
return true;
}
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
tp.replaceComponent(oldComponent, newComponent);
}
public void updateCaption(Paintable component, UIDL uidl) {
/* Tabsheet does not render its children's captions */
}
public boolean requestLayout(Set<Paintable> child) {
if (!isDynamicHeight() && !isDynamicWidth()) {
/*
* If the height and width has been specified for this container the
* child components cannot make the size of the layout change
*/
// layout size change may affect its available space (scrollbars)
for (Paintable paintable : child) {
client.handleComponentRelativeSize((Widget) paintable);
}
return true;
}
updateOpenTabSize();
if (renderInformation.updateSize(getElement())) {
/*
* Size has changed so we let the child components know about the
* new size.
*/
iLayout();
client.runDescendentsLayout(this);
return false;
} else {
/*
* Size has not changed so we do not need to propagate the event
* further
*/
return true;
}
}
private int borderW = -1;
private int getContentAreaBorderWidth() {
if (borderW < 0) {
borderW = Util.measureHorizontalBorder(contentNode);
}
return borderW;
}
private final RenderSpace renderSpace = new RenderSpace(0, 0, true);
public RenderSpace getAllocatedSpace(Widget child) {
// All tabs have equal amount of space allocated
return renderSpace;
}
@Override
protected int getTabCount() {
return tb.getTabCount();
}
@Override
protected Paintable getTab(int index) {
if (tp.getWidgetCount() > index) {
return (Paintable) tp.getWidget(index);
}
return null;
}
@Override
protected void removeTab(int index) {
tb.removeTab(index);
/*
* This must be checked because renderTab automatically removes the
* active tab content when it changes
*/
if (tp.getWidgetCount() > index) {
tp.remove(index);
}
}
public void onBlur(BlurEvent event) {
if (focusedTab != null && event.getSource() instanceof Tab) {
focusedTab = null;
if (client.hasEventListeners(this, EventId.BLUR)) {
client.updateVariable(id, EventId.BLUR, "", true);
}
}
}
public void onFocus(FocusEvent event) {
if (focusedTab == null && event.getSource() instanceof Tab) {
focusedTab = (Tab) event.getSource();
if (client.hasEventListeners(this, EventId.FOCUS)) {
client.updateVariable(id, EventId.FOCUS, "", true);
}
}
}
public void focus() {
tb.getTab(activeTabIndex).focus();
}
public void blur() {
tb.getTab(activeTabIndex).blur();
}
public void onKeyDown(KeyDownEvent event) {
if (event.getSource() instanceof Tab) {
int keycode = event.getNativeEvent().getKeyCode();
if (keycode == getPreviousTabKey()) {
int newTabIndex = activeTabIndex;
// Find the previous non-disabled tab with wraparound.
do {
newTabIndex = (newTabIndex != 0) ? newTabIndex - 1 : tb
.getTabCount() - 1;
} while (newTabIndex != activeTabIndex
&& !onTabSelected(newTabIndex));
activeTabIndex = newTabIndex;
// Tab scrolling
if (isScrolledTabs()) {
int newFirstIndex = tb.scrollLeft(scrollerIndex);
if (newFirstIndex != -1) {
scrollerIndex = newFirstIndex;
updateTabScroller();
}
}
} else if (keycode == getNextTabKey()) {
int newTabIndex = activeTabIndex;
// Find the next non-disabled tab with wraparound.
do {
newTabIndex = (newTabIndex + 1) % tb.getTabCount();
} while (newTabIndex != activeTabIndex
&& !onTabSelected(newTabIndex));
activeTabIndex = newTabIndex;
if (isClippedTabs()) {
int newFirstIndex = tb.scrollRight(scrollerIndex);
if (newFirstIndex != -1) {
scrollerIndex = newFirstIndex;
updateTabScroller();
}
}
} else if (keycode == getCloseTabKey()) {
Tab tab = tb.getTab(activeTabIndex);
if (tab.isClosable()) {
tab.onClose();
removeTab(activeTabIndex);
}
}
}
}
protected int getPreviousTabKey() {
return KeyCodes.KEY_LEFT;
}
protected int getNextTabKey() {
return KeyCodes.KEY_RIGHT;
}
protected int getCloseTabKey() {
return KeyCodes.KEY_DELETE;
}
} |
package edu.wpi.first.wpilibj.templates;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import edu.wpi.first.wpilibj.Joystick;
/**
*
* @author Ben
*/
public class FancyJoystick extends Joystick {
/** Primary Driver Controller Port Number. */
private static final int PRIMARY_DRIVER = 1;
/** Secondary Driver Controller Port Number. */
private static final int SECONDARY_DRIVER = 2;
/** Axis values below this threshold will be ignored. */
public static final double DEFAULT_DEAD_ZONE = 0.3;
/** XBOX 360 South Face Button */
public static final int BUTTON_A = 1;
/** XBOX 360 East Face Button */
public static final int BUTTON_B = 2;
/** XBOX 360 West Face Button */
public static final int BUTTON_X = 3;
/** XBOX 360 North Face Button */
public static final int BUTTON_Y = 4;
/** XBOX 360 Left Bumper (Top) */
public static final int BUTTON_LB = 5;
/** XBOX 360 Right Bumper (Top) */
public static final int BUTTON_RB = 6;
/** XBOX 360 Back Button */
public static final int BUTTON_BACK = 7;
/** XBOX 360 Start Button */
public static final int BUTTON_START = 8;
/** XBOX 360 Left Joystick Button (Press Down) */
public static final int BUTTON_LEFTJOY = 9;
/** XBOX 360 Right Joystick Button (Press Down) */
public static final int BUTTON_RIGHTJOY = 10;
/** XBOX 360 Left Horizontal Axis (Left=-1, Right=1) */
public static final int AXIS_LEFT_X = 1;
/** XBOX 360 Left Vertical Axis (Up=-1, Down=1) */
public static final int AXIS_LEFT_Y = 2;
/** XBOX 360 Trigger Axis (?) */
public static final int AXIS_TRIGGERS = 3;
/** XBOX 360 Right Horizontal Axis (Left=-1, Right=1) */
public static final int AXIS_RIGHT_X = 4;
/** XBOX 360 Right Vertical Axis (Up=-1, Down=1) */
public static final int AXIS_RIGHT_Y = 5;
/** The number of axes on a standard XBOX 360 controller. */
public static final int XBOX_AXES = 6;
/** The number of buttons on a standard XBOX 360 controller. */
public static final int XBOX_BUTTONS = 10;
/** Internal dead zone value. */
private double _deadZone = 0;
/** The "live zone" is always equal to (1-_deadZone). */
private double _liveZone = 1;
public static FancyJoystick primary = new FancyJoystick(PRIMARY_DRIVER,.15);
public static FancyJoystick secondary = new FancyJoystick(SECONDARY_DRIVER,.15);
/**
* Creates a new FancyJoystick instance configured for use with an XBOX 360
* controller.
* @param port The joystick port number.
*/
public FancyJoystick(int port){
super(port, XBOX_BUTTONS, XBOX_AXES);
setDeadZone(DEFAULT_DEAD_ZONE);
}
/**
* Creates a new FancyJoystick instance configured for use with an XBOX 360
* controller.
* @param port The joystick port number.
* @param deadZone Specifies a dead zone threshold, between zero and one.
* Axis values below this threshold will be ignored, and zero will be
* returned.
*/
public FancyJoystick(int port, double deadZone){
super(port, XBOX_BUTTONS, XBOX_AXES);
setDeadZone(deadZone);
}
/**
* Creates a new FancyJoystick instance. You must specify the number of
* channels and buttons for this joystick.
* @param port The joystick port number.
* @param numChannels The maximum number of channels of input provided by
* this joystick.
* @param numAxes The maximum number of axes given by this joystick.
*/
public FancyJoystick(int port, int numChannels, int numAxes){
super(port, numChannels, numAxes);
setDeadZone(DEFAULT_DEAD_ZONE);
}
/**
* Creates a new FancyJoystick instance. You must specify the number of
* channels and buttons for this joystick.
* @param port The joystick port number.
* @param numChannels The maximum number of channels of input provided by
* this joystick.
* @param numAxes The maximum number of axes given by this joystick.
* @param deadZone Specifies a dead zone threshold, between zero and one.
* Axis values below this threshold will be ignored, and zero will be
* returned.
*/
public FancyJoystick(int port, int numChannels, int numAxes, double deadZone){
super(port, numChannels, numAxes);
setDeadZone(deadZone);
}
/**
* Returns the value of the specified axis, after being subjected to dead
* zone constraints. Only values above the dead zone are reported.
* @param axis The axis number.
* @return The specified axis value, after dead zones.
* @see FancyJoystick#setDeadZone(double)
*/
public double getDeadAxis(int axis){
return getDeadAxis(axis, _deadZone);
}
/**
* Returns the value of the specified axis, after being subjected to dead
* zone constraints. Only values above the dead zone are reported.
* @param axis The axis number.
* @param deadZone The dead zone value to use. (does not change the
* internal dead zone value of this instance.)
* @return The specified axis value, after dead zones.
* @see FancyJoystick#setDeadZone(double)
*/
public double getDeadAxis(int axis, double deadZone){
double liveZone = 1 - deadZone;
double value = this.getRawAxis(axis);
if(Math.abs(value) > deadZone){
return (value - (deadZone * MathUtils.sign(value))) / liveZone;
} else {
return 0.0;
}
}
/**
* Set the default dead zone threshold for this instance.
* @param value A value in the range [0-1]
*/
public void setDeadZone(double value){
_deadZone = Math.min(1.0, Math.max(0.0, value));
_liveZone = 1 - _deadZone;
}
/**
*
* @return The dead zone threshold for this FancyJoystick instance.
* @see FancyJoystick#setDeadZone(double)
*/
public double getDeadZone(){
return _deadZone;
}
} |
package com.valkryst.VTerminal.builder;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.component.Screen;
import com.valkryst.VTerminal.font.Font;
import lombok.Getter;
import javax.swing.*;
public class PanelBuilder {
/** The width of the panel, in characters. */
@Getter private int widthInCharacters = 80;
/** The height of the panel, in characters. */
@Getter private int heightInCharacters = 24;
/** The font to draw with. */
@Getter private Font font;
/** The screen being displayed on the panel. */
@Getter private Screen screen;
/** The frame in which the panel is to be placed. */
@Getter private JFrame frame;
public Panel build() throws IllegalStateException {
checkState();
final Panel panel = new Panel(this);
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
panel.setIgnoreRepaint(true);
panel.setFocusable(true);
return panel;
}
private void checkState() throws IllegalStateException {
if (font == null) {
throw new NullPointerException("The panel must have an AsciiFont to draw with.");
}
if (screen == null) {
screen = new Screen(0, 0, widthInCharacters, heightInCharacters);
}
if (frame == null) {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
/** Resets the builder to it's default state. */
public void reset() {
widthInCharacters = 80;
heightInCharacters = 24;
font = null;
screen = null;
frame = null;
}
/**
* Sets the frame.
*
* @param frame
* The new frame.
*
* @return
* This.
*/
public PanelBuilder setJFrame(final JFrame frame) {
this.frame = frame;
return this;
}
/**
* Sets the width in characters.
*
* @param widthInCharacters
* The new width in characters.
*
* @return
* This.
*/
public PanelBuilder setWidthInCharacters(final int widthInCharacters) {
if (widthInCharacters < 1) {
this.widthInCharacters = 1;
} else {
this.widthInCharacters = widthInCharacters;
}
return this;
}
/**
* Sets the height in characters.
*
* @param heightInCharacters
* The new height in characters.
*
* @return
* This.
*/
public PanelBuilder setHeightInCharacters(final int heightInCharacters) {
if (heightInCharacters < 1) {
this.heightInCharacters = 1;
} else {
this.heightInCharacters = heightInCharacters;
}
return this;
}
/**
* Sets the font.
*
* @param asciiFont
* The new font.
*
* @return
* This.
*/
public PanelBuilder setFont(final Font asciiFont) {
if (asciiFont != null) {
this.font = asciiFont;
}
return this;
}
/**
* Sets the screen.
*
* @param screen
* The new screen.
*
* @return
* This.
*/
public PanelBuilder setScreen(final Screen screen) {
this.screen = screen;
return this;
}
} |
package net.patowen.hyperbolicspace;
import javax.media.opengl.GL3;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLException;
import javax.media.opengl.GLProfile;
import javax.swing.JOptionPane;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import com.jogamp.opengl.util.glsl.ShaderState;
/**
* {@code Controller} acts as a context in which all other classes can access shared
* data without having to pass things around arbitrary.
* @author Patrick Owen
*/
public class Controller
{
private FPSAnimator anim;
private MatrixHandler matrixHandler;
private InputHandler inputHandler;
private GLWindow win;
private TextureBank textureBank;
/** A renderable scene node */
public SceneNodeType dodecahedron, building, horosphere, plane;
/**
* Constructs all meshes
*/
public void init()
{
dodecahedron = new Dodecahedron(this);
building = new Building(this);
horosphere = new Horosphere(this);
plane = new Plane(this);
}
/**
* Initializes all textures and prepares all meshes for rendering
* @param gl
*/
public void renderInit(GL3 gl)
{
textureBank = new TextureBank();
textureBank.initTextures(gl);
dodecahedron.renderInit(gl);
building.renderInit(gl);
horosphere.renderInit(gl);
plane.renderInit(gl);
}
/**
* Gracefully quits the application
*/
public void exit()
{
anim.stop();
}
/**
* Begins the render loop
*/
public void startAnimation()
{
anim = new FPSAnimator(win, 30);
anim.start();
}
/**
* Toggles whether the window is fullscreen
*/
public void toggleFullscreen()
{
win.setFullscreen(!win.isFullscreen());
}
/**
* Initializes OpenGL and creates a window with the OpenGL3 context
*/
public void createWindow()
{
GLCapabilities caps;
try
{
caps = new GLCapabilities(GLProfile.get("GL3"));
}
catch (GLException e)
{
JOptionPane.showMessageDialog(null, "Your video card does not support OpenGL3, which is required to run this application.",
"OpenGL3 not supported", JOptionPane.ERROR_MESSAGE);
return;
}
caps.setDepthBits(24);
win = GLWindow.create(caps);
}
/**
* Initializes the listener for input
*/
public void createInputHandler()
{
inputHandler = new InputHandler(this);
}
/**
* Loads the shader resources and compiles all the shaders
* @param gl
*/
public void initShaders(GL3 gl)
{
ShaderProgram prog = new ShaderProgram();
prog.init(gl);
ShaderCode vsCode = ShaderHandler.getShaderCode(GL3.GL_VERTEX_SHADER, "hyperbolic_vs");
vsCode.compile(gl);
prog.add(vsCode);
ShaderCode gsCode = ShaderHandler.getShaderCode(GL3.GL_GEOMETRY_SHADER, "hyperbolic_gs");
gsCode.compile(gl);
prog.add(gsCode);
ShaderCode fsCode = ShaderHandler.getShaderCode(GL3.GL_FRAGMENT_SHADER, "hyperbolic_fs");
fsCode.compile(gl);
prog.add(fsCode);
ShaderState shaderState = new ShaderState();
matrixHandler = new MatrixHandler(shaderState);
shaderState.attachShaderProgram(gl, prog, false);
shaderState.bindAttribLocation(gl, 0, "vertex_position");
shaderState.bindAttribLocation(gl, 1, "normal_position");
shaderState.bindAttribLocation(gl, 2, "tex_coord_in");
prog.link(gl, System.err);
prog.validateProgram(gl, System.err);
shaderState.useProgram(gl, true);
}
/**
* Returns the main {@code MatrixHandler} object
* @return a reference to the main {@code MatrixHandler} object
*/
public MatrixHandler getMatrixHandler()
{
return matrixHandler;
}
/**
* Returns the main {@code InputHandler} object
* @return a reference to the main {@code InputHandler} object
*/
public InputHandler getInputHandler()
{
return inputHandler;
}
/**
* Returns the main window
* @return a reference to the main window
*/
public GLWindow getWindow()
{
return win;
}
/**
* Returns the main {@code TextureBank} object
* @return a reference to the main {@code TextureBank} object
*/
public TextureBank getTextureBank()
{
return textureBank;
}
} |
package fr.openwide.core.jpa.more.business.file.model;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.more.business.file.model.util.ImageThumbnailFormat;
public class ImageGalleryFileStoreImpl extends SimpleFileStoreImpl {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageGalleryFileStoreImpl.class);
private static final int IMAGE_MAGICK_CONVERT_TIMEOUT = 5000;
private File imageMagickConvertBinary;
private List<ImageThumbnailFormat> thumbnailFormats;
public ImageGalleryFileStoreImpl(String key, String rootDirectoryPath, List<ImageThumbnailFormat> thumbnailFormats,
File imageMagickConvertBinaryCandidate) {
super(key, rootDirectoryPath, true);
this.thumbnailFormats = thumbnailFormats;
this.imageMagickConvertBinary = getImageMagickConvertBinary(imageMagickConvertBinaryCandidate);
}
@Override
public void addFile(File file, String fileKey, String extension) throws ServiceException, SecurityServiceException {
super.addFile(file, fileKey, extension);
generateThumbnails(fileKey, extension);
}
@Override
public void addFile(InputStream inputStream, String fileKey, String extension) throws ServiceException, SecurityServiceException {
super.addFile(inputStream, fileKey, extension);
generateThumbnails(fileKey, extension);
}
protected void generateThumbnails(String fileKey, String extension) throws ServiceException, SecurityServiceException {
for (ImageThumbnailFormat thumbnailFormat : thumbnailFormats) {
if (isImageMagickConvertAvailable()) {
generateThumbnailWithImageMagickConvert(getFile(fileKey, extension), fileKey, extension, thumbnailFormat);
} else {
generateThumbnailWithJava(getFile(fileKey, extension), fileKey, extension, thumbnailFormat);
}
}
}
@Override
public void removeFile(String fileKey, String extension) {
for (ImageThumbnailFormat thumbnailFormat : thumbnailFormats) {
if (!getThumbnailFile(fileKey, extension, thumbnailFormat).delete()) {
LOGGER.error("Error removing thumbnail file " + fileKey + " " + extension + " " + thumbnailFormat);
}
}
super.removeFile(fileKey, extension);
}
private File getImageMagickConvertBinary(File imageMagickConvertBinaryCandidate) {
if (imageMagickConvertBinaryCandidate == null) {
LOGGER.warn("ImageMagick's convert binary is not configured. Using Java to scale images.");
return null;
}
if (!imageMagickConvertBinaryCandidate.exists()) {
LOGGER.warn("ImageMagick's convert binary {} does not exist. Using Java to scale images.",
imageMagickConvertBinaryCandidate.getAbsolutePath());
return null;
}
if (!imageMagickConvertBinaryCandidate.isFile()) {
LOGGER.warn("ImageMagick's convert binary {} is not a file. Using Java to scale images.",
imageMagickConvertBinaryCandidate.getAbsolutePath());
return null;
}
if (!imageMagickConvertBinaryCandidate.canExecute()) {
LOGGER.warn("ImageMagick's convert binary {} is not executable. Using Java to scale images.",
imageMagickConvertBinaryCandidate.getAbsolutePath());
return null;
}
return imageMagickConvertBinaryCandidate;
}
private boolean isImageMagickConvertAvailable() {
if (imageMagickConvertBinary != null) {
return true;
} else {
return false;
}
}
private void generateThumbnailWithImageMagickConvert(File file, String fileKey, String extension, ImageThumbnailFormat thumbnailFormat)
throws ServiceException, SecurityServiceException {
try {
CommandLine commandLine = new CommandLine(imageMagickConvertBinary);
commandLine.addArgument("-resize");
if (thumbnailFormat.isAllowEnlarge()) {
commandLine.addArgument("${width}x${height}");
} else {
commandLine.addArgument("${width}x${height}>");
}
commandLine.addArgument("-quality");
commandLine.addArgument("${quality}");
commandLine.addArgument("${originalFilePath}");
commandLine.addArgument("${targetFilePath}");
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("width", String.valueOf(thumbnailFormat.getWidth()));
parameters.put("height", String.valueOf(thumbnailFormat.getHeight()));
parameters.put("quality", String.valueOf(thumbnailFormat.getQuality()));
parameters.put("originalFilePath", file.getAbsolutePath());
parameters.put("targetFilePath", getThumbnailFilePath(fileKey, extension, thumbnailFormat));
commandLine.setSubstitutionMap(parameters);
DefaultExecutor executor = new DefaultExecutor();
ExecuteWatchdog watchdog = new ExecuteWatchdog(IMAGE_MAGICK_CONVERT_TIMEOUT);
executor.setWatchdog(watchdog);
executor.execute(commandLine);
} catch (Exception e) {
throw new ServiceException(e);
}
}
private void generateThumbnailWithJava(File file, String fileKey, String extension, ImageThumbnailFormat thumbnailFormat)
throws ServiceException, SecurityServiceException {
try {
BufferedImage originalImage = ImageIO.read(file);
if (originalImage == null) {
throw new ServiceException("Image cannot be read.");
}
int type = (originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());
int originalImageWidth = originalImage.getWidth();
int originalImageHeight = originalImage.getHeight();
double widthRatio = (double) thumbnailFormat.getWidth() / (double) originalImageWidth;
double heightRatio = (double) thumbnailFormat.getHeight() /(double) originalImageHeight;
if (widthRatio < 1.0d || heightRatio < 1.0d) {
double ratio = Math.min(widthRatio, heightRatio);
int resizedImageWidth = (int) (ratio * originalImageWidth);
int resizedImageHeight = (int) (ratio * originalImageHeight);
BufferedImage resizedImage = new BufferedImage(resizedImageWidth, resizedImageHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
AffineTransform tx = new AffineTransform();
tx.scale(ratio, ratio);
g.drawImage(originalImage, 0, 0, resizedImageWidth, resizedImageHeight, null);
g.dispose();
FileImageOutputStream outputStream = null;
try {
Iterator<ImageWriter> imageWritersIterator = ImageIO.getImageWritersByFormatName(thumbnailFormat.getJavaFormatName());
ImageWriter writer = imageWritersIterator.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
if (iwp.canWriteCompressed()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(thumbnailFormat.getQuality() / 100f);
}
outputStream = new FileImageOutputStream(getThumbnailFile(fileKey, extension, thumbnailFormat));
writer.setOutput(outputStream);
IIOImage image = new IIOImage(resizedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
} catch (Exception e) {
throw new ServiceException(e);
} finally {
if (outputStream != null) {
outputStream.close();
}
}
} else {
FileUtils.copyFile(getFile(fileKey, extension), getThumbnailFile(fileKey, extension, thumbnailFormat));
}
} catch (Exception e) {
throw new ServiceException(e);
}
}
public File getThumbnailFile(String fileKey, String extension, ImageThumbnailFormat thumbnailFormat) {
return new File(getThumbnailFilePath(fileKey, extension, thumbnailFormat));
}
protected String getThumbnailFilePath(String fileKey, String extension, ImageThumbnailFormat thumbnailFormat) {
StringBuilder fileName = new StringBuilder();
fileName.append(fileKey);
fileName.append("-");
fileName.append(thumbnailFormat.getName());
fileName.append(".");
fileName.append(thumbnailFormat.getExtension());
return FilenameUtils.concat(getRootDirectoryPath(), fileName.toString());
}
} |
/*
* generated by Xtext
*/
package org.muml.psm.allocation.language.xtext.validation;
import org.eclipse.ocl.pivot.Type;
import org.eclipse.ocl.pivot.internal.utilities.EnvironmentFactoryInternal;
import org.eclipse.ocl.pivot.utilities.PivotUtil;
import org.eclipse.ocl.xtext.essentialoclcs.ContextCS;
import org.eclipse.xtext.validation.Check;
import org.muml.psm.allocation.language.as.EvaluableElement;
import org.muml.psm.allocation.language.cs.BoundCS;
import org.muml.psm.allocation.language.cs.BoundWeightTupleDescriptorCS;
import org.muml.psm.allocation.language.cs.CoherenceConstraintCS;
import org.muml.psm.allocation.language.cs.CsPackage;
import org.muml.psm.allocation.language.cs.EvaluableElementCS;
import org.muml.psm.allocation.language.cs.ImplicationConstraintCS;
import org.muml.psm.allocation.language.cs.ImplicationConstraintTupleDescriptorCS;
import org.muml.psm.allocation.language.cs.LocationConstraintCS;
import org.muml.psm.allocation.language.cs.QoSDimensionCS;
import org.muml.psm.allocation.language.cs.RelationCS;
import org.muml.psm.allocation.language.cs.ResourceConstraintCS;
import org.muml.psm.allocation.language.cs.TupleDescriptorCS;
import org.muml.psm.allocation.language.cs.WeightTupleDescriptorCS;
import org.muml.psm.allocation.language.xtext.typing.TypesUtil;
public class AllocationSpecificationLanguageJavaValidator extends org.muml.psm.allocation.language.xtext.validation.AbstractAllocationSpecificationLanguageJavaValidator {
private static final String typeMismatch = "Type mismatch: expected %s but got %s";
private static final String noPivotElement = "Unable to retrieve pivot element for object %s";
@Check
public void checkRelationCS(RelationCS relationCS) {
TupleDescriptorCS tupleDescriptorCS = relationCS.getTupleDescriptor();
BoundCS lowerBoundCS = relationCS.getLowerBound();
BoundCS upperBoundCS = relationCS.getUpperBound();
ContextCS oclExpression = relationCS.getExpression();
if (tupleDescriptorCS == null || oclExpression == null
|| lowerBoundCS == null || upperBoundCS == null) {
// in this case a different error is displayed
return;
}
checkTypes(relationCS);
}
@Check
public void checkBoundCS(BoundCS boundCS) {
if (boundCS.getExpression() == null) {
// in this case a different error is displayed
return;
}
checkTypes(boundCS);
}
@Check
public void checkCoherenceConstraintCS(CoherenceConstraintCS constraintCS) {
TupleDescriptorCS tupleDescriptorCS = constraintCS.getTupleDescriptor();
ContextCS oclExpression = constraintCS.getExpression();
if (tupleDescriptorCS == null || oclExpression == null) {
// in this case a different error is displayed
return;
}
checkTypes(constraintCS);
}
@Check
public void checkLocationConstraintCS(LocationConstraintCS constraintCS) {
TupleDescriptorCS tupleDescriptorCS = constraintCS.getTupleDescriptor();
ContextCS oclExpression = constraintCS.getExpression();
if (tupleDescriptorCS == null || oclExpression == null) {
// in this case a different error is displayed
return;
}
checkTypes(constraintCS);
}
@Check
public void checkResourceConstraintCS(ResourceConstraintCS constraintCS) {
BoundWeightTupleDescriptorCS tupleDescriptorCS = constraintCS.getTupleDescriptor();
ContextCS oclExpression = constraintCS.getExpression();
if (tupleDescriptorCS == null || tupleDescriptorCS.getWeight() == null
|| tupleDescriptorCS.getBound() == null || oclExpression == null) {
// parser/ui will display an error
return;
}
checkTypes(constraintCS);
}
@Check
public void checkImplicationConstraintCS(ImplicationConstraintCS constraintCS) {
ImplicationConstraintTupleDescriptorCS tupleDescriptor = constraintCS.getTupleDescriptor();
ContextCS oclExpression = constraintCS.getExpression();
if (tupleDescriptor == null || tupleDescriptor.getPremise() == null
|| tupleDescriptor.getConclusion() == null
|| oclExpression == null) {
return;
}
checkTypes(constraintCS);
}
@Check
public void checkQoSDimensionCS(QoSDimensionCS qosDimensionCS) {
WeightTupleDescriptorCS tupleDescriptorCS = qosDimensionCS.getTupleDescriptor();
ContextCS oclExpression = qosDimensionCS.getExpression();
if (tupleDescriptorCS == null || tupleDescriptorCS.getWeight() == null
|| oclExpression == null) {
return;
}
checkTypes(qosDimensionCS);
}
private void checkTypes(EvaluableElementCS elementCS) {
EvaluableElement element = PivotUtil.getPivot(EvaluableElement.class, elementCS);
if (element == null) {
// this is no "error(...)" but an exceptional situation
throw new IllegalStateException(String.format(noPivotElement,
elementCS));
}
EnvironmentFactoryInternal envFactory = TypesUtil.getEnvironmentFactory(element);
Type expectedType = TypesUtil.createType(element);
Type actualType = element.getExpression().getType();
boolean conformsTo = TypesUtil.conformsTo(envFactory, actualType, expectedType);
if (!conformsTo) {
error(String.format(typeMismatch, expectedType, actualType),
CsPackage.Literals.EVALUABLE_ELEMENT_CS__EXPRESSION);
}
}
} |
package org.xwiki.component.annotation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.descriptor.DefaultComponentDescriptor;
import org.xwiki.component.internal.RoleHint;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.component.util.ReflectionUtils;
/**
* Dynamically loads all components defined using Annotations and declared in META-INF/components.txt files.
*
* @version $Id$
* @since 1.8.1
*/
public class ComponentAnnotationLoader
{
/**
* Location in the classloader of the file defining the list of component implementation class to parser for
* annotations.
*/
public static final String COMPONENT_LIST = "META-INF/components.txt";
/**
* Location in the classloader of the file specifying which component implementation to use when several components
* with the same role/hint are found.
*
* @deprecated starting with 3.3M1 use the notion of priorities instead (see {@link ComponentDeclaration}).
*/
@Deprecated
public static final String COMPONENT_OVERRIDE_LIST = "META-INF/component-overrides.txt";
/**
* The encoding used to parse component list files.
*/
private static final String COMPONENT_LIST_ENCODING = "UTF-8";
/**
* Logger to use for logging...
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ComponentAnnotationLoader.class);
/**
* Factory to create a Component Descriptor from an annotated class.
*/
private ComponentDescriptorFactory factory = new ComponentDescriptorFactory();
/**
* Loads all components defined using annotations.
*
* @param manager the component manager to use to dynamically register components
* @param classLoader the classloader to use to look for the Component list declaration file (
* {@code META-INF/components.txt})
*/
public void initialize(ComponentManager manager, ClassLoader classLoader)
{
try {
// Find all declared components by retrieving the list defined in COMPONENT_LIST.
List<ComponentDeclaration> componentDeclarations = getDeclaredComponents(classLoader, COMPONENT_LIST);
// Find all the Component overrides and adds them to the bottom of the list as component declarations with
// the highest priority of 0. This is purely for backward compatibility since the override files is now
// deprecated.
List<ComponentDeclaration> componentOverrideDeclarations =
getDeclaredComponents(classLoader, COMPONENT_OVERRIDE_LIST);
for (ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations) {
// Since the old way to declare an override was to define it in both a component.txt and a
// component-overrides.txt file we first need to remove the override component declaration stored in
// componentDeclarations.
componentDeclarations.remove(componentOverrideDeclaration);
// Add it to the end of the list with the highest priority.
componentDeclarations.add(new ComponentDeclaration(componentOverrideDeclaration
.getImplementationClassName(), 0));
}
initialize(manager, classLoader, componentDeclarations);
} catch (Exception e) {
// Make sure we make the calling code fail in order to fail fast and prevent the application to start
// if something is amiss.
throw new RuntimeException("Failed to get the list of components to load", e);
}
}
/**
* @param manager the component manager to use to dynamically register components
* @param classLoader the classloader to use to look for the Component list declaration file (
* {@code META-INF/components.txt})
* @param componentDeclarations the declarations of components to register
* @since 3.3M1
*/
public void initialize(ComponentManager manager, ClassLoader classLoader,
List<ComponentDeclaration> componentDeclarations)
{
register(manager, classLoader, componentDeclarations);
}
/**
* @param manager the component manager to use to dynamically register components
* @param classLoader the classloader to use to look for the Component list declaration file (
* {@code META-INF/components.txt})
* @param componentDeclarations the declarations of components to register
* @since 4.0M1
*/
public void register(ComponentManager manager, ClassLoader classLoader,
List<ComponentDeclaration> componentDeclarations)
{
try {
// 2) For each component class name found, load its class and use introspection to find the necessary
// annotations required to create a Component Descriptor.
Map<RoleHint<?>, ComponentDescriptor<?>> descriptorMap =
new HashMap<RoleHint<?>, ComponentDescriptor<?>>();
Map<RoleHint<?>, Integer> priorityMap = new HashMap<RoleHint<?>, Integer>();
for (ComponentDeclaration componentDeclaration : componentDeclarations) {
Class<?> componentClass;
try {
componentClass = classLoader.loadClass(componentDeclaration.getImplementationClassName());
} catch (Exception e) {
throw new RuntimeException(
String.format("Failed to load component class [%s] for annotation parsing",
componentDeclaration.getImplementationClassName()), e);
}
// Look for ComponentRole annotations and register one component per ComponentRole found
for (Type componentRoleType : findComponentRoleTypes(componentClass)) {
for (ComponentDescriptor<?> componentDescriptor : this.factory.createComponentDescriptors(
componentClass, componentRoleType)) {
// If there's already a existing role/hint in the list of descriptors then decide which one
// to keep by looking at their priorities. Highest priority wins (i.e. lowest integer value).
RoleHint<?> roleHint =
new RoleHint(componentDescriptor.getRoleType(), componentDescriptor.getRoleHint());
addComponent(descriptorMap, priorityMap, roleHint, componentDescriptor, componentDeclaration,
true);
}
}
}
// 3) Activate all component descriptors
for (ComponentDescriptor<?> descriptor : descriptorMap.values()) {
manager.registerComponent(descriptor);
}
} catch (Exception e) {
// Make sure we make the calling code fail in order to fail fast and prevent the application to start
// if something is amiss.
throw new RuntimeException("Failed to dynamically load components with annotations", e);
}
}
private void addComponent(Map<RoleHint<?>, ComponentDescriptor<?>> descriptorMap,
Map<RoleHint<?>, Integer> priorityMap, RoleHint<?> roleHint, ComponentDescriptor<?> componentDescriptor,
ComponentDeclaration componentDeclaration, boolean warn)
{
if (descriptorMap.containsKey(roleHint)) {
// Compare priorities
int currentPriority = priorityMap.get(roleHint);
if (componentDeclaration.getPriority() < currentPriority) {
// Override!
descriptorMap.put(roleHint, componentDescriptor);
priorityMap.put(roleHint, componentDeclaration.getPriority());
} else if (componentDeclaration.getPriority() == currentPriority) {
if (warn) {
// Warning that we're not overwriting since they have the same priorities
getLogger().warn(
"Component [{}] which implements [{}] tried to overwrite component "
+ "[{}]. However, no action was taken since both components have the same priority "
+ "level of [{}].",
new Object[] { componentDeclaration.getImplementationClassName(), roleHint,
descriptorMap.get(roleHint).getImplementation().getName(), currentPriority });
}
} else {
getLogger().debug(
"Ignored component [{}] since its priority level of [{}] is lower "
+ "than the currently registered component [{}] which has a priority of [{}]",
new Object[] { componentDeclaration.getImplementationClassName(),
componentDeclaration.getPriority(), currentPriority });
}
} else {
descriptorMap.put(roleHint, componentDescriptor);
priorityMap.put(roleHint, componentDeclaration.getPriority());
}
}
/**
* @param manager the component manager to use to dynamically register components
* @param classLoader the classloader to use to look for the Component list declaration file (
* {@code META-INF/components.txt})
* @param componentDeclarations the declarations of components to register
* @since 4.0M1
*/
public void unregister(ComponentManager manager, ClassLoader classLoader,
List<ComponentDeclaration> componentDeclarations)
{
for (ComponentDeclaration componentDeclaration : componentDeclarations) {
Class<?> componentClass = null;
try {
componentClass = classLoader.loadClass(componentDeclaration.getImplementationClassName());
} catch (ClassNotFoundException e) {
getLogger().warn("Can't find any existing component with class [{}]. Ignoring it.",
componentDeclaration.getImplementationClassName());
} catch (Exception e) {
getLogger().warn("Fail to load component implementation class [{}]. Ignoring it.",
componentDeclaration.getImplementationClassName(), e);
}
if (componentClass != null) {
for (ComponentDescriptor<?> componentDescriptor : getComponentsDescriptors(componentClass)) {
manager.unregisterComponent(componentDescriptor);
if (componentDescriptor.getRoleType() instanceof ParameterizedType) {
Class roleClass = ReflectionUtils.getTypeClass(componentDescriptor.getRoleType());
DefaultComponentDescriptor<?> classComponentDescriptor =
new DefaultComponentDescriptor(componentDescriptor);
classComponentDescriptor.setRoleType(roleClass);
manager.unregisterComponent(classComponentDescriptor);
}
}
}
}
}
public List<ComponentDescriptor> getComponentsDescriptors(Class<?> componentClass)
{
List<ComponentDescriptor> descriptors = new ArrayList<ComponentDescriptor>();
// Look for ComponentRole annotations and register one component per ComponentRole found
for (Type componentRoleType : findComponentRoleTypes(componentClass)) {
descriptors.addAll(this.factory.createComponentDescriptors(componentClass, componentRoleType));
}
return descriptors;
}
public Set<Type> findComponentRoleTypes(Class<?> componentClass)
{
return findComponentRoleTypes(componentClass, null);
}
public Set<Type> findComponentRoleTypes(Class<?> componentClass, Type[] parameters)
{
// Note: We use a Set to ensure that we don't register duplicate roles.
Set<Type> types = new LinkedHashSet<Type>();
Component component = componentClass.getAnnotation(Component.class);
// If the roles are specified by the user then don't auto-discover roles!
if (component != null && component.roles().length > 0) {
types.addAll(Arrays.asList(component.roles()));
} else {
// Auto-discover roles by looking for a @Role annotation or a @Provider one in both the superclass
// and implemented interfaces.
for (Type interfaceType : getGenericInterfaces(componentClass)) {
Class<?> interfaceClass;
Type[] interfaceParameters;
if (interfaceType instanceof ParameterizedType) {
ParameterizedType interfaceParameterizedType = (ParameterizedType) interfaceType;
interfaceClass = ReflectionUtils.getTypeClass(interfaceType);
Type[] variableParameters = interfaceParameterizedType.getActualTypeArguments();
interfaceParameters =
ReflectionUtils.resolveSuperArguments(variableParameters, componentClass, parameters);
if (interfaceParameters == null) {
interfaceType = interfaceClass;
} else if (interfaceParameters != variableParameters) {
interfaceType =
new DefaultParameterizedType(interfaceParameterizedType.getOwnerType(), interfaceClass,
interfaceParameters);
}
} else if (interfaceType instanceof Class) {
interfaceClass = (Class<?>) interfaceType;
interfaceParameters = null;
} else {
continue;
}
// Handle superclass of interfaces
types.addAll(findComponentRoleTypes(interfaceClass, interfaceParameters));
// Handle interfaces directly declared in the passed component class
if (ReflectionUtils.getDirectAnnotation(Role.class, interfaceClass) != null) {
types.add(interfaceType);
}
// Handle javax.inject.Provider
if (Provider.class.isAssignableFrom(interfaceClass)) {
types.add(interfaceType);
}
// Handle ComponentRole (retro-compatibility since 4.0M1)
if (ReflectionUtils.getDirectAnnotation(ComponentRole.class, interfaceClass) != null) {
types.add(interfaceClass);
}
}
// Note that we need to look into the superclass since the super class can itself implements an interface
// that has the @Role annotation.
Type superType = componentClass.getGenericSuperclass();
if (superType != null && superType != Object.class) {
if (superType instanceof ParameterizedType) {
ParameterizedType superParameterizedType = (ParameterizedType) superType;
types.addAll(findComponentRoleTypes((Class) superParameterizedType.getRawType(), ReflectionUtils
.resolveSuperArguments(superParameterizedType.getActualTypeArguments(), componentClass,
parameters)));
} else if (superType instanceof Class) {
types.addAll(findComponentRoleTypes((Class) superType, null));
}
}
}
return types;
}
/**
* Helper method that generate a {@link RuntimeException} in case of a reflection error.
*
* @param componentClass the component for which to return the interface types
* @return the Types representing the interfaces directly implemented by the class or interface represented by this
* object
* @throws RuntimeException in case of a reflection error such as
* {@link java.lang.reflect.MalformedParameterizedTypeException}
*/
private Type[] getGenericInterfaces(Class<?> componentClass)
{
Type[] interfaceTypes;
try {
interfaceTypes = componentClass.getGenericInterfaces();
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to get interface for [%s]", componentClass.getName()), e);
}
return interfaceTypes;
}
/**
* Finds the interfaces that implement component roles by looking recursively in all interfaces of the passed
* component implementation class. If the roles annotation value is specified then use the specified list instead of
* doing auto-discovery. Also note that we support component classes implementing JSR 330's
* {@link javax.inject.Provider} (and thus without a component role annotation).
*
* @param componentClass the component implementation class for which to find the component roles it implements
* @return the list of component role classes implemented
* @deprecated since 4.0M1 use {@link #findComponentRoleTypes(Class)} instead
*/
@Deprecated
public Set<Class<?>> findComponentRoleClasses(Class<?> componentClass)
{
// Note: We use a Set to ensure that we don't register duplicate roles.
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
Component component = componentClass.getAnnotation(Component.class);
if (component != null && component.roles().length > 0) {
classes.addAll(Arrays.asList(component.roles()));
} else {
// Look in both superclass and interfaces for @Role or javax.inject.Provider
for (Class<?> interfaceClass : componentClass.getInterfaces()) {
// Handle superclass of interfaces
classes.addAll(findComponentRoleClasses(interfaceClass));
// Handle interfaces directly declared in the passed component class
for (Annotation annotation : interfaceClass.getDeclaredAnnotations()) {
if (annotation.annotationType() == ComponentRole.class) {
classes.add(interfaceClass);
}
}
// Handle javax.inject.Provider
if (Provider.class.isAssignableFrom(interfaceClass)) {
classes.add(interfaceClass);
}
}
// Note that we need to look into the superclass since the super class can itself implements an interface
// that has the @Role annotation.
Class<?> superClass = componentClass.getSuperclass();
if (superClass != null && superClass != Object.class) {
classes.addAll(findComponentRoleClasses(superClass));
}
}
return classes;
}
/**
* Get all components listed in the passed resource file.
*
* @param classLoader the classloader to use to find the resources
* @param location the name of the resources to look for
* @return the list of component implementation class names
* @throws IOException in case of an error loading the component list resource
* @since 3.3M1
*/
private List<ComponentDeclaration> getDeclaredComponents(ClassLoader classLoader, String location)
throws IOException
{
List<ComponentDeclaration> annotatedClassNames = new ArrayList<ComponentDeclaration>();
Enumeration<URL> urls = classLoader.getResources(location);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
LOGGER.debug("Loading declared component definitions from [{}]", url);
InputStream componentListStream = url.openStream();
try {
annotatedClassNames.addAll(getDeclaredComponents(componentListStream));
} finally {
componentListStream.close();
}
}
return annotatedClassNames;
}
/**
* Get all components listed in the passed resource stream. The format is:
* {@code (priority level):(fully qualified component implementation name)}.
*
* @param componentListStream the stream to parse
* @return the list of component declaration (implementation class names and priorities)
* @throws IOException in case of an error loading the component list resource
* @since 3.3M1
*/
public List<ComponentDeclaration> getDeclaredComponents(InputStream componentListStream) throws IOException
{
List<ComponentDeclaration> annotatedClassNames = new ArrayList<ComponentDeclaration>();
// Read all components definition from the URL
// Always force UTF-8 as the encoding, since these files are read from the official jars, and those are
// generated on an 8-bit system.
BufferedReader in = new BufferedReader(new InputStreamReader(componentListStream, COMPONENT_LIST_ENCODING));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Make sure we don't add empty lines
if (inputLine.trim().length() > 0) {
try {
String[] chunks = inputLine.split(":");
ComponentDeclaration componentDeclaration;
if (chunks.length > 1) {
componentDeclaration = new ComponentDeclaration(chunks[1], Integer.parseInt(chunks[0]));
} else {
componentDeclaration = new ComponentDeclaration(chunks[0]);
}
LOGGER.debug(" - Adding component definition [{}] with priority [{}]",
componentDeclaration.getImplementationClassName(), componentDeclaration.getPriority());
annotatedClassNames.add(componentDeclaration);
} catch (Exception e) {
getLogger().error("Failed to parse component declaration from [{}]", inputLine, e);
}
}
}
return annotatedClassNames;
}
/**
* Get all components listed in a JAR file.
*
* @param jarFile the JAR file to parse
* @return the list of component declaration (implementation class names and priorities)
* @throws IOException in case of an error loading the component list resource
*/
public List<ComponentDeclaration> getDeclaredComponentsFromJAR(InputStream jarFile) throws IOException
{
ZipInputStream zis = new ZipInputStream(jarFile);
List<ComponentDeclaration> componentDeclarations = null;
List<ComponentDeclaration> componentOverrideDeclarations = null;
for (ZipEntry entry = zis.getNextEntry(); entry != null
&& (componentDeclarations == null || componentOverrideDeclarations == null); entry = zis.getNextEntry()) {
if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_LIST)) {
componentDeclarations = getDeclaredComponents(zis);
} else if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_OVERRIDE_LIST)) {
componentOverrideDeclarations = getDeclaredComponents(zis);
}
}
// Merge all overrides found with a priority of 0. This is purely for backward compatibility since the
// override files is now deprecated.
if (componentOverrideDeclarations != null) {
if (componentDeclarations == null) {
componentDeclarations = new ArrayList<ComponentDeclaration>();
}
for (ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations) {
componentDeclarations.add(new ComponentDeclaration(componentOverrideDeclaration
.getImplementationClassName(), 0));
}
}
return componentDeclarations;
}
/**
* Useful for unit tests that need to capture logs; they can return a mock logger instead of the real logger and
* thus assert what's been logged.
*
* @return the Logger instance to use to log
*/
protected Logger getLogger()
{
return LOGGER;
}
} |
package org.apereo.cas.authentication.trigger;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.MultifactorAuthenticationProvider;
import org.apereo.cas.authentication.MultifactorAuthenticationProviderResolver;
import org.apereo.cas.authentication.MultifactorAuthenticationTrigger;
import org.apereo.cas.authentication.MultifactorAuthenticationUtils;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.spring.ApplicationContextProvider;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import static org.springframework.util.StringUtils.commaDelimitedListToSet;
/**
* This is {@link PrincipalAttributeMultifactorAuthenticationTrigger}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Getter
@Setter
@Slf4j
@RequiredArgsConstructor
public class PrincipalAttributeMultifactorAuthenticationTrigger implements MultifactorAuthenticationTrigger {
private final CasConfigurationProperties casProperties;
private final MultifactorAuthenticationProviderResolver multifactorAuthenticationProviderResolver;
private int order = Ordered.LOWEST_PRECEDENCE;
@Override
public Optional<MultifactorAuthenticationProvider> isActivated(final Authentication authentication,
final RegisteredService registeredService,
final HttpServletRequest httpServletRequest, final Service service) {
if (authentication == null) {
LOGGER.debug("No authentication is available to determine event for principal");
return Optional.empty();
}
val principal = getPrincipalForMultifactorAuthentication(authentication);
val result = resolveMultifactorAuthenticationProvider(Optional.empty(), registeredService, principal);
if (result != null && !result.isEmpty()) {
val id = CollectionUtils.firstElement(result);
return MultifactorAuthenticationUtils.getMultifactorAuthenticationProviderById(id.get().toString(), ApplicationContextProvider.getApplicationContext());
}
return Optional.empty();
}
/**
* Gets principal attributes for multifactor authentication.
*
* @param authentication the authentication
* @return the principal attributes for multifactor authentication
*/
protected Principal getPrincipalForMultifactorAuthentication(final Authentication authentication) {
return authentication.getPrincipal();
}
/**
* Resolve multifactor authentication provider set.
*
* @param context the context
* @param service the service
* @param principal the principal
* @return the set
*/
protected Set<Event> resolveMultifactorAuthenticationProvider(final Optional<RequestContext> context,
final RegisteredService service,
final Principal principal) {
val globalPrincipalAttributeValueRegex = casProperties.getAuthn().getMfa().getGlobalPrincipalAttributeValueRegex();
val providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(ApplicationContextProvider.getApplicationContext());
val providers = providerMap.values();
if (providers.size() == 1 && StringUtils.isNotBlank(globalPrincipalAttributeValueRegex)) {
return resolveSingleMultifactorProvider(context, service, principal, providers);
}
return resolveMultifactorProviderViaPredicate(context, service, principal, providers);
}
/**
* Resolve multifactor provider by regex predicate set.
*
* @param context the context
* @param service the service
* @param principal the principal
* @param providers the providers
* @return the set
*/
protected Set<Event> resolveMultifactorProviderViaPredicate(final Optional<RequestContext> context,
final RegisteredService service,
final Principal principal,
final Collection<MultifactorAuthenticationProvider> providers) {
val attributeNames = commaDelimitedListToSet(casProperties.getAuthn().getMfa().getGlobalPrincipalAttributeNameTriggers());
return multifactorAuthenticationProviderResolver.resolveEventViaPrincipalAttribute(principal, attributeNames, service, context, providers,
input -> providers.stream().anyMatch(provider -> input != null && provider.matches(input)));
}
/**
* Resolve single multifactor provider set.
*
* @param context the context
* @param service the service
* @param principal the principal
* @param providers the providers
* @return the set
*/
protected Set<Event> resolveSingleMultifactorProvider(final Optional<RequestContext> context, final RegisteredService service,
final Principal principal,
final Collection<MultifactorAuthenticationProvider> providers) {
val globalPrincipalAttributeValueRegex = casProperties.getAuthn().getMfa().getGlobalPrincipalAttributeValueRegex();
val provider = providers.iterator().next();
LOGGER.trace("Found a single multifactor provider [{}] in the application context", provider);
val attributeNames = commaDelimitedListToSet(casProperties.getAuthn().getMfa().getGlobalPrincipalAttributeNameTriggers());
return multifactorAuthenticationProviderResolver.resolveEventViaPrincipalAttribute(principal, attributeNames, service, context, providers,
input -> input != null && input.matches(globalPrincipalAttributeValueRegex));
}
} |
package org.innovateuk.ifs.management.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.application.resource.ApplicationSummaryPageResource;
import org.innovateuk.ifs.application.resource.ApplicationSummaryResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.management.model.ManagePanelApplicationsModelPopulator;
import org.innovateuk.ifs.management.viewmodel.ManagePanelApplicationsViewModel;
import org.innovateuk.ifs.management.viewmodel.PaginationViewModel;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import java.util.List;
import java.util.Optional;
import static org.innovateuk.ifs.application.builder.ApplicationSummaryResourceBuilder.newApplicationSummaryResource;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.competition.resource.CompetitionStatus.IN_ASSESSMENT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class AssessmentPanelManageApplicationsControllerTest extends BaseControllerMockMVCTest<AssessmentPanelManageApplicationsController> {
@InjectMocks
@Spy
private ManagePanelApplicationsModelPopulator managePanelApplicationsPopulator;
@Override
protected AssessmentPanelManageApplicationsController supplyControllerUnderTest() {
return new AssessmentPanelManageApplicationsController();
}
@Test
public void manageApplications() throws Exception {
CompetitionResource competitionResource = newCompetitionResource()
.withId(1L)
.withName("name")
.withCompetitionStatus(IN_ASSESSMENT)
.build();
List<ApplicationSummaryResource> summaryResources = newApplicationSummaryResource()
.withId(1L, 2L)
.withName("one", "two")
.withLead("Lead 1", "Lead 2")
.withInnovationArea("Digital manufacturing")
.build(2);
ApplicationSummaryPageResource expectedPageResource = new ApplicationSummaryPageResource(41, 3, summaryResources, 1, 20);
when(competitionRestService.getCompetitionById(competitionResource.getId()))
.thenReturn(restSuccess(competitionResource));
when(applicationSummaryRestService.getSubmittedApplications(competitionResource.getId(), "",1,20, Optional.of("filter"), Optional.empty()))
.thenReturn(restSuccess(expectedPageResource));
ManagePanelApplicationsViewModel model = (ManagePanelApplicationsViewModel) mockMvc
.perform(get("/assessment/panel/competition/{competitionId}/manage-applications?page=1&filterSearch=filter", competitionResource.getId()))
.andExpect(status().isOk())
.andExpect(view().name("competition/manage-applications-panel"))
.andExpect(model().attributeExists("model"))
.andReturn().getModelAndView().getModel().get("model");
assertEquals((long) competitionResource.getId(), model.getCompetitionId());
assertEquals(competitionResource.getName(), model.getCompetitionName());
assertEquals(competitionResource.getCompetitionStatus().getDisplayName(), model.getCompetitionStatus());
assertEquals(2, model.getApplications().size());
assertEquals("Lead 1", model.getApplications().get(0).getLeadOrganisation());
assertEquals("Lead 2", model.getApplications().get(1).getLeadOrganisation());
PaginationViewModel actualPagination = model.getPagination();
assertEquals(1, actualPagination.getCurrentPage());
assertEquals(20,actualPagination.getPageSize());
assertEquals(3, actualPagination.getTotalPages());
assertEquals("1 to 20", actualPagination.getPageNames().get(0).getTitle());
assertEquals("21 to 40", actualPagination.getPageNames().get(1).getTitle());
assertEquals("41 to 41", actualPagination.getPageNames().get(2).getTitle());
assertEquals("?origin=MANAGE_APPLICATIONS_PANEL&filterSearch=filter&page=2", actualPagination.getPageNames().get(2).getPath());
}
} |
package wikt.stat;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import wikokit.base.wikipedia.language.LanguageType;
import wikokit.base.wikipedia.sql.Connect;
import wikokit.base.wikipedia.sql.Statistics;
import wikokit.base.wikt.api.WTMeaning;
import wikokit.base.wikt.constant.Label;
import wikokit.base.wikt.constant.LabelCategory;
import wikokit.base.wikt.constant.LabelCategoryLocal;
import wikokit.base.wikt.constant.POS;
import wikokit.base.wikt.multi.en.name.LabelEn;
import wikokit.base.wikt.multi.ru.name.LabelCategoryRu;
import wikokit.base.wikt.multi.ru.name.LabelRu;
import wikokit.base.wikt.sql.TLang;
import wikokit.base.wikt.sql.TLangPOS;
import wikokit.base.wikt.sql.TMeaning;
import wikokit.base.wikt.sql.TPOS;
import wikokit.base.wikt.sql.TPage;
import wikokit.base.wikt.sql.label.TLabel;
import wikokit.base.wikt.sql.label.TLabelCategory;
import wikokit.base.wikt.sql.label.TLabelMeaning;
import wikt.stat.printer.CommonPrinter;
/** Context labels statistics in the database of the parsed Wiktionary. */
public class LabelTableAll {
private static final boolean DEBUG = true;
/** Number of labels per language. */
private static Map<LanguageType, Integer> m_lang_n = new HashMap<LanguageType, Integer>();
/** Number of meanings for each label: <label, example_words and counter). */
private static Map<Label, ObjectWithWords> m_label_n = new HashMap<Label, ObjectWithWords>();
private static int MAX_EXAMPLE_WORDS = 3;
/** Inner class which contains an object with a (small, example) list of words using this object.
* An object is a label with several words with this label
*/
private static class ObjectWithWords {
ObjectWithWords(Label _label) {
label = _label;
example_words = new ArrayList<String>();
counter = 0;
}
/** Object's name, e.g. labels in meanings, or labels in relations, or labels in translations. */
public Label label;
/** Example of several entries which use this label. */
public List<String> example_words;
/** Counter of using this label in Wiktionary entries. */
public int counter;
/** Adds new label to the map m;
* if there is space (< MAX_EXAMPLE_WORDS), then add example word for this object.
*/
private static void add(String page_title,
Label _label,
Map<Label, ObjectWithWords> m)
{
if(null == _label) { // 0 == _object_name.length()) {
System.out.println("Warning (LabelTableAll.ObjectWithWords.add()): page=" +page_title+ " with empty _object_name!");
return;
}
ObjectWithWords s_w = m.get(_label);
if(null == s_w) {
s_w = new ObjectWithWords(_label);
s_w.counter = 1;
s_w.example_words = new ArrayList<String>();
if(!s_w.example_words.contains(page_title))
s_w.example_words.add(page_title);
m.put(_label, s_w);
} else {
s_w.counter += 1;
if(s_w.example_words.size() < MAX_EXAMPLE_WORDS) {
if(!s_w.example_words.contains(page_title))
s_w.example_words.add(page_title);
}
}
}
} // eo class ObjectWithWords
/** Counts number of labels, category_labels (m_category_n),...
* by selecting all records from the table 'quote' from the database of the parsed Wiktionary.<br><br>
* SELECT * FROM quote;
*
* @param connect connection to the database of the parsed Wiktionary
* @return map from the language into a number of translation boxes
* which contain synonyms, antonyms, etc. in English (etc.)
*/
public static Map<LanguageType, Integer> countLabels (Connect wikt_parsed_conn) {
// label_meaning -> meaning -> lang_pos -> lang -> count
Statement s = null;
ResultSet rs= null;
long t_start;
int n_unknown_lang_pos = 0; // translations into unknown languages
int n_total = Statistics.Count(wikt_parsed_conn, "label");
t_start = System.currentTimeMillis();
Map<Integer, Label> id2label = TLabel.getAllID2Labels();
// System.out.println("id2label size=" + id2label.size());
/*for (Map.Entry<Integer, Label> entry : id2label.entrySet()) {
Integer _label_id = entry.getKey();
Label _label = entry.getValue();
}*/
// SELECT label_id, meaning_id FROM label_meaning
// select * from label where category_id IS NULL and counter>0
// SELECT label_id, meaning_id FROM label_meaning, label WHERE id=label_id AND category_id IS NULL and counter>0 LIMIT 3;
try {
s = wikt_parsed_conn.conn.createStatement();
StringBuilder str_sql = new StringBuilder();
if(DEBUG)
str_sql.append("SELECT label_id, meaning_id FROM label_meaning LIMIT 5000"); // 10000 37000
//str_sql.append("SELECT label_id, meaning_id FROM label_meaning WHERE label_id=465");
else
str_sql.append("SELECT label_id, meaning_id FROM label_meaning");
s.executeQuery (str_sql.toString());
rs = s.getResultSet ();
int n_cur = 0;
while (rs.next ())
{
n_cur ++;
int label_id = rs.getInt("label_id");
Label label = id2label.get( label_id );
TMeaning m = TMeaning.getByID(wikt_parsed_conn, rs.getInt("meaning_id"));
TLangPOS lang_pos = m.getLangPOS(wikt_parsed_conn);
TLang tlang = lang_pos.getLang();
LanguageType lang = tlang.getLanguage();
if(m_lang_n.containsKey(lang) ) {
int n = m_lang_n.get(lang);
m_lang_n.put(lang, n + 1);
} else
m_lang_n.put(lang, 1);
if(null == m) {
System.out.println("Warning (LabelTableAll.countLabels()): there is label with label_id=" +label_id+ " with NULL meaning_id!");
continue;
}
if(null != lang_pos) {
TPage tpage = lang_pos.getPage();
String page_title = tpage.getPageTitle();
if(null != label) {
ObjectWithWords.add(page_title, label, m_label_n);
}
if(DEBUG && 0 == n_cur % 1000) { // % 100
//if(n_cur > 333)
// break;
long t_cur, t_remain;
t_cur = System.currentTimeMillis() - t_start;
t_remain = (long)((n_total - n_cur) * t_cur/(60f*1000f*(float)(n_cur)));
// where time for 1 page = t_cur / n_cur
// in min, since /(60*1000)
t_cur = (long)(t_cur/(60f*1000f));
//t_cur = t_cur/(60f*1000f));
if(null != tpage) {
System.out.println(n_cur + ": " + tpage.getPageTitle() +
", duration: " + t_cur + // t_cur/(60f*1000f) +
" min, remain: " + t_remain +
" min");
}
}
} else
n_unknown_lang_pos ++;
}
} catch(SQLException ex) {
System.out.println("SQLException (LabelTableAll.countLabels()): " + ex.getMessage());
} finally {
if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } rs = null; }
if (s != null) { try { s.close(); } catch (SQLException sqlEx) { } s = null; }
}
//long t_end;
//float t_work;
//t_end = System.currentTimeMillis();
//t_work = (t_end - t_start)/1000f; // in sec
int n_labels_by_hand = TLabel.countLabelsAddedByHand (wikt_parsed_conn);
int n_labels_found_by_parser = TLabel.countLabelsFoundByParser(wikt_parsed_conn);
System.out.println(//"\nTime sec:" + t_work +
"\nTotal unique labels: " + n_total +
"\n\nUnique labels added by hand: " + n_labels_by_hand +
"\n\nUnique labels found by parser: " + n_labels_found_by_parser +
// "\n\nTotal meanings with labels: " + n_total_with_authors +
// "\n\nTotal meanings : " + n_total_with_authors +
"\n\nThere are labels for words in " + m_lang_n.size() + " languages." +
"\n\nUnknown<ref>'''Unknown''' - number of words with labels (but language code and POS are unknown)</ref>: "
+ n_unknown_lang_pos);
return m_lang_n;
}
/** Prints statistics about context labels added by hand.
*/
private static void printLabelsAddedByHand (
Map<Label, ObjectWithWords> m_source_n)
{
System.out.println("\n=== Labels added by hand ===");
//System.out.println("\n'''Number of entries''' is a number of (Language & POS level) entries per language. E.g. the Wiktionary article \"[[:en:rook|rook]]\" contains three English and two Dutch entries of Part Of Speech level.");
//System.out.println("\n'''Total''' is a total number of relations, i.e. synonyms + antonyms + etc...\n");
/** Number of quotes for each source: <source name, example_words and counter). */
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.println("! English !! Template !! Short name !! Name !! Category !! Counter !! words");
// print values
for(Label _label : m_source_n.keySet()) {
ObjectWithWords s_w = m_source_n.get(_label);
if(LabelEn.isLabelFoundByParser( _label.getLinkedLabelEn()))
continue;
// _label added by hand, so != null
LabelEn linked_label_en = _label.getLinkedLabelEn();
LabelCategory label_category = linked_label_en.getCategory();
/*
LabelEn linked_label_en = _label.getLinkedLabelEn();
if(null == linked_label_en)
continue;
LabelCategory label_category = linked_label_en.getCategory();
if(LabelEn.isLabelFoundByParser( label_category))
continue;*/
System.out.println("|-");
System.out.print(
"|" + _label.getShortNameEnglish() +
"||{{" + _label.getShortName() +
"}}||" + _label.getShortName() +
"||" + _label.getName() +
"||" + label_category.getName() +
"||" + s_w.counter + "||" );
StringBuilder sb = new StringBuilder();
List<String> words = s_w.example_words;
for(String w : words)
sb.append("[[").append(w).append("]], ");
if(sb.length() > 3)
sb.delete(sb.length()-2, sb.length());
System.out.println( sb.toString() );
}
System.out.println("|}");
}
/** Prints statistics about context labels found by parser.
*/
private static void printLabelsFoundByParser (
Map<Label, ObjectWithWords> m_source_n)
{
System.out.println("\n=== Labels found by parser ===");
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.println("! Short name !! Length !! Counter !! words");
// print values
for(Label _label : m_source_n.keySet()) {
ObjectWithWords s_w = m_source_n.get(_label);
if(!LabelEn.isLabelFoundByParser( _label.getLinkedLabelEn()))
continue;
/*LabelEn linked_label_en = _label.getLinkedLabelEn();
if(null != linked_label_en && !isLabelFoundByParser( linked_label_en.getCategory() )) // label was added by hand
continue;
*/
// replace since there are problems in wiki tables
String short_name = _label.getShortName().replace("+", "<nowiki>+</nowiki>");
System.out.println("|-");
System.out.print(
"|" + short_name +
"||" + _label.getShortName().length() +
"||" + s_w.counter + "||" );
StringBuilder sb = new StringBuilder();
List<String> words = s_w.example_words;
for(String w : words)
sb.append("[[").append(w).append("]], ");
if(sb.length() > 3)
sb.delete(sb.length()-2, sb.length());
System.out.println( sb.toString() );
}
System.out.println("|}");
}
/** Prints statistics about only
* (1) regional context labels added by hand (LabelCategory = regional) and
* (2) regional context labels found by parser (LabelCategory = "regional automatic").
*/
private static void printRegionalLabels (
Map<Label, ObjectWithWords> m_source_n)
{
System.out.println("\n=== Regional labels ===");
System.out.println("\nRegional labels added by hand, category = \"regional\".");
System.out.println("\nRegional labels found by parser, category = \"regional automatic\".");
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.println("! Short name !! Category !! Counter !! words");
// print values
int counter = 0;
int total = 0;
for(Label _label : m_source_n.keySet()) {
ObjectWithWords s_w = m_source_n.get(_label);
LabelCategory lc = _label.getCategory();
/*LabelEn linked_label_en = _label.getLinkedLabelEn();
if(null == linked_label_en)
continue;
LabelCategory label_category = linked_label_en.getCategory();
*/
// print only regional labels
if(lc != LabelCategory.regional &&
lc != LabelCategory.regional_automatic)
continue;
// at this line: label_category != null;
counter ++;
total = total + s_w.counter;
// replace since there are problems in wiki tables
String short_name = _label.getShortName().replace("+", "<nowiki>+</nowiki>");
System.out.println("|-");
System.out.print(
"|" + short_name +
"||" + lc +
"||" + s_w.counter + "||" );
StringBuilder sb = new StringBuilder();
List<String> words = s_w.example_words;
for(String w : words)
sb.append("[[").append(w).append("]], ");
if(sb.length() > 3)
sb.delete(sb.length()-2, sb.length());
System.out.println( sb.toString() );
}
System.out.println("|}");
counter --; // Unique regional labels without [empty 'regional' label, i.e. whithout regions]
System.out.println("\nUnique regional labels used in definitions: " + counter );
System.out.println("\nTotal regional labels used in definitions: " + total );
}
/** Calculates number of categories of labels (only added by hand), read data from m_source_n,
* prints result to table "Label categories"
*/
private static void calcAndPrintAddedByHandLabelCategories (
Map<Label, ObjectWithWords> m_source_n,
LanguageType wikt_lang)
{
/** Total number of label categories: <label category, total number). */
Map<LabelCategory, Integer> m_category_n = new HashMap<LabelCategory, Integer>();
// 1. sum labels for each category
for(Label _label : m_source_n.keySet()) {
ObjectWithWords s_w = m_source_n.get(_label);
LabelCategory lc = _label.getCategory();
if(null == lc)
continue;
/*if(null == lc) {
// all except: |regional automatic||regional automatic||regional||182
LabelEn linked_label_en = _label.getLinkedLabelEn();
if(null == linked_label_en)
continue;
lc = linked_label_en.getCategory();
if(null == lc)
continue;
}*/
/* case 3: empty list
LabelCategory lc = LabelEn.getCategoryByLabel(_label);
if(null == lc)
continue;*/
if(m_category_n.containsKey(lc) ) {
int n = m_category_n.get(lc);
m_category_n.put(lc, n + s_w.counter);
} else
m_category_n.put(lc, s_w.counter);
}
// 2. print table
System.out.println("\n=== Label categories ===");
System.out.println("\nNumber of labels for each label's category.");
System.out.println("\nThese labels were added by hand only, since labels added automatically don't have categories (except \"regional automatic\" labels in Russian Wiktionary).\n");
// + translation of label category into Russian
String add_header = "";
if(wikt_lang == LanguageType.ru)
add_header = "! in Russian !";
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.println(add_header+"! Category !! Parent category !! Number");
int total = 0;
for(LabelCategory _cat : m_category_n.keySet()) {
int n = m_category_n.get( _cat );
String add_translation = "";
if(wikt_lang == LanguageType.ru)
add_translation = "|"+LabelCategoryRu.getName(_cat)+"|";
System.out.println("|-");
System.out.println(
add_translation +
"|" + _cat.getName() +
"||" + _cat.getParent().getName() +
"||" + n );
total += n;
}
System.out.println("|}");
System.out.println("\nTotal labels added by hand (with categories): " + total );
}
/** Maximum number of meanings in one article (language - POS level) */
static final int MAX_MEANINGS = 100;
private static String[][] ar_labels_meanings_words = new String[MAX_MEANINGS][MAX_MEANINGS];
/** Counts number of meanings with labels, writes result to two-dimensional array,
* fills by example words array ar_labels_meanings_words.<br><br>
*
* @param connect connection to the database of the parsed Wiktionary
* @param only_pos only this POS words will be counted,
* if only_pos is NULL then all words will be counted
* @param only_lang only this language words will be counted,
* if only_lang is NULL then words of all languages will be counted
* @return integer two-dimensional array, where [X][Y] = Z means that
* X - number of meanings with labels;
* Y - total number of meanings;
* Z - number of words with Y meanings, where X meanings have one or more labels (X <= Y)
*/
public static int[][] countNumberOfMeaningsWithLabels ( Connect wikt_parsed_conn,
LanguageType only_lang,
POS only_pos) {
// lang_pos -> meaning -> label_meaning
int[][] ar_labels_meanings = new int[MAX_MEANINGS][MAX_MEANINGS];
Statement s = null;
ResultSet rs= null;
long t_start;
int n_total = Statistics.Count(wikt_parsed_conn, "lang_pos");
t_start = System.currentTimeMillis();
try {
s = wikt_parsed_conn.conn.createStatement ();
s.executeQuery ("SELECT id FROM lang_pos");
rs = s.getResultSet ();
int n_cur = 0;
while (rs.next ())
{
n_cur ++;
int id = rs.getInt("id");
TLangPOS lang_pos_not_recursive = TLangPOS.getByID (wikt_parsed_conn, id);// fields are not filled recursively
if(null == lang_pos_not_recursive)
continue;
LanguageType lang = lang_pos_not_recursive.getLang().getLanguage();
if(null != only_lang && only_lang != lang) // this is not our language :)
continue;
TPage tpage = lang_pos_not_recursive.getPage();
String page_title = tpage.getPageTitle();
int n_meaning = WTMeaning.countMeanings(wikt_parsed_conn, lang_pos_not_recursive);
if(0 == n_meaning)
continue; // only meanings with nonempty definitions
POS p = lang_pos_not_recursive.getPOS().getPOS();
if(null != only_pos && only_pos != p) // only our POS should be counted :)
continue;
if(DEBUG)
System.out.print("\n" + page_title + ", meanings:" + n_meaning);
//System.out.print(", pos:" + p.toString());
int meanings_with_labels = 0;
TMeaning[] mm = TMeaning.get(wikt_parsed_conn, lang_pos_not_recursive);
for(TMeaning m : mm) {
String meaning_text = m.getWikiTextString();
if(0 == meaning_text.length())
continue;
if(DEBUG)
System.out.print("\n def: " + meaning_text);
Label[] labels = TLabelMeaning.get(wikt_parsed_conn, m);
if(null != labels && labels.length > 0)
meanings_with_labels ++;
}
ar_labels_meanings [meanings_with_labels] [n_meaning] ++;
ar_labels_meanings_words [meanings_with_labels] [n_meaning] = page_title;
if(0 == n_cur % 1000) { // % 100
if(DEBUG && n_cur > 1999)
break;
long t_cur, t_remain;
t_cur = System.currentTimeMillis() - t_start;
t_remain = (long)((n_total - n_cur) * t_cur/(60f*1000f*(float)(n_cur)));
t_cur = (long)(t_cur/(60f*1000f));
System.out.println(n_cur + ": " +
", duration: " + t_cur + // t_cur/(60f*1000f) +
" min, remain: " + t_remain +
" min");
}
} // eo while
} catch(SQLException ex) {
System.err.println("SQLException (LabelTableAll.countLabelsForEachLangPOS()): " + ex.getMessage());
} finally {
if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } rs = null; }
if (s != null) { try { s.close(); } catch (SQLException sqlEx) { } s = null; }
}
return ar_labels_meanings;
}
/** Prints number of meanings with labels in form of table.<br><br>
*/
private static void printNumberOfMeaningsWithLabels (
int[][] ar_labels_meanings,
LanguageType only_lang,
POS only_pos)
{
// 1. Calculate maximum number of meanings,
// i.e. calculate maximum array index N with non-zero value in ar_labels_meanings [N][N]
int max_non_zero_meaning = 0;
int max_non_zero_labels = 0;
for(int i=0; i<MAX_MEANINGS; i++) {
for(int j=0; j<MAX_MEANINGS; j++) {
if(ar_labels_meanings[i][j] > 0 && j > max_non_zero_meaning)
max_non_zero_meaning = j;
if(ar_labels_meanings[i][j] > 0 && i > max_non_zero_labels)
max_non_zero_labels = i;
}
}
int MAX = max_non_zero_meaning;
// 2. print table
System.out.println("\n=== Number of meanings with labels ===");
if(null != only_lang)
System.out.println("\nOnly "+only_lang.toString()+" words were taken into account.");
if(null != only_pos)
System.out.println("\nOnly one POS were taken into account: "+only_pos.toString()+".");
System.out.println("\nTable contains two-dimensional integer array, where [X][Y] = Z means that \n"
+ ":: X (horizontal) - total number of meanings; \n" +
":: Y (vertical) - number of meanings with labels; \n" +
":: Z (value in cell) - number of words with Y meanings, where X meanings have one or more labels (X <= Y)");
System.out.println("E.g. \"[[:ru:abdomen
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.print("! Y \\ X "); // top-left cell
// print horizontal header - number of meanings of words
for(int i=0; i<MAX+1; i++)
System.out.print("!!" + i);
System.out.println("");
int total = 0;
for(int i=0; i<MAX+1; i++) {
// print vertical header - number of meanings with labels
System.out.println("|-");
System.out.print( "|" + i);
for(int j=0; j<MAX+1; j++) {
System.out.print(
"||" + ar_labels_meanings[i][j] );
total += ar_labels_meanings[i][j];
}
System.out.println("");
}
System.out.println("|}");
System.out.println("\nTotal number of meanings with labels: " + total );
System.out.println("\nMaximum number of meanings (with labels): "+MAX);
System.out.println("\nMaximum number of meanings marked by labels: "+max_non_zero_labels);
// part 2.
System.out.println("\n\nThe same table with example words: ");
System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
System.out.print("! Y \\ X "); // top-left cell
// print horizontal header - number of meanings of words
for(int i=0; i<MAX+1; i++)
System.out.print("!!" + i);
System.out.println("");
for(int i=0; i<MAX+1; i++) {
// print vertical header - number of meanings with labels
System.out.println("|-");
System.out.print( "|" + i);
for(int j=0; j<MAX+1; j++) {
String s = ar_labels_meanings_words[i][j];
s = null == s ? "" : "[[" + s + "]]" ;
System.out.print("||" + s);
}
System.out.println("");
}
System.out.println("|}");
}
public static void main(String[] args) {
// Connect to wikt_parsed database
Connect wikt_parsed_conn = new Connect();
// Russian
LanguageType native_lang = LanguageType.ru;
wikt_parsed_conn.Open(Connect.RUWIKT_HOST, Connect.RUWIKT_PARSED_DB, Connect.RUWIKT_USER, Connect.RUWIKT_PASS, LanguageType.ru);
// English
//LanguageType native_lang = LanguageType.en;
//wikt_parsed_conn.Open(Connect.ENWIKT_HOST, Connect.ENWIKT_PARSED_DB, Connect.ENWIKT_USER, Connect.ENWIKT_PASS, LanguageType.en);
TLang.createFastMaps(wikt_parsed_conn);
TPOS.createFastMaps(wikt_parsed_conn);
// ? TRelationType.createFastMaps(wikt_parsed_conn);
LabelCategoryLocal temp0 = LabelCategoryRu.computing; // let's initialize maps in LabelCategoryRu class
TLabelCategory.createFastMaps(wikt_parsed_conn);
Label temp1 = LabelEn.Acadia; // let's initialize maps in LabelEn class
Label temp2 = LabelRu.Yoruba; // ... in LabelRu class
TLabel.createFastMaps(wikt_parsed_conn, native_lang);
String db_name = wikt_parsed_conn.getDBName();
System.out.println("\n== Statistics of context labels in the Wiktionary parsed database ==");
System.out.println("\n''Last updated: summer 2013.''");
CommonPrinter.printHeader (db_name);
int n_label_meaning = Statistics.Count(wikt_parsed_conn, "label_meaning");
System.out.println("\nTotal labels used in definitions (meanings): " + n_label_meaning );
int n_meaning = Statistics.countDistinct(wikt_parsed_conn, "label_meaning", "meaning_id");
System.out.println("\nTotal definitions with labels: " + n_meaning );
// Map<LanguageType, Integer> m = LabelTableAll.countLabels(wikt_parsed_conn);
// ar_labels_meanings [X][Y] = Z
// X - number of meanings with labels; Y - total number of meanings; Z - number of words with Y meanings, where X meanings have one or more labels (X <= Y)
//LanguageType only_lang = null;
LanguageType only_lang = LanguageType.ru;
//POS only_pos = null;
POS only_pos = POS.verb;
int[][] ar_labels_meanings = LabelTableAll.countNumberOfMeaningsWithLabels(wikt_parsed_conn, only_lang, only_pos);
// int[][] ar_labels_meanings = LabelTableAll.countLabelsForEachLangPOS(wikt_parsed_conn, POS.noun);
LabelTableAll.printNumberOfMeaningsWithLabels(ar_labels_meanings, only_lang, only_pos);
wikt_parsed_conn.Close();
System.out.println();
// CommonPrinter.printSomethingPerLanguage(native_lang, m);
/** Number of using labels in meanings (definitions) */
/* LabelTableAll.printLabelsAddedByHand(m_label_n);
LabelTableAll.printLabelsFoundByParser(m_label_n);
LabelTableAll.printRegionalLabels(m_label_n);
LabelTableAll.calcAndPrintAddedByHandLabelCategories(m_label_n, native_lang);
*/
//System.out.println("\nThere are quotes in " + m.size() + " languages.");
CommonPrinter.printFooter();
}
} |
package crystal.client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashSet;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import org.junit.Assert;
import crystal.Constants;
import crystal.client.ClientPreferences.DuplicateProjectNameException;
import crystal.model.DataSource;
/**
* The GUI that allows editing of the Crystal configuration.
* Basically, PreferencesGUIEditorFrame lets you edit a ClientPreferences object by adding,
* removing, and augmenting projects, and changing other attributes.
*
* @author brun
*/
public class PreferencesGUIEditorFrame extends JFrame {
private static final long serialVersionUID = 4574346360968958312L;
// The singleton instance of this frame.
private static PreferencesGUIEditorFrame editorFrame;
/**
* @return the singleton instance of this frame. If a frame already exists, just returns that one.
* otherwise, it creates a new one with the specified prefs configuration.
* @param prefs: the configuration to use if no frame exists yet.
*/
public static PreferencesGUIEditorFrame getPreferencesGUIEditorFrame(ClientPreferences prefs) {
if (editorFrame == null)
editorFrame = new PreferencesGUIEditorFrame(prefs);
editorFrame.setVisible(true);
return editorFrame;
}
/**
* @return the singleton instance of this frame.
*/
public static PreferencesGUIEditorFrame getPreferencesGUIEditorFrame() {
if (editorFrame != null)
editorFrame.setVisible(true);
return editorFrame;
}
/**
* A private constructor to create a new editor frame based on the specified prefs configuration.
* @param prefs: the configuration to use.
*/
private PreferencesGUIEditorFrame(final ClientPreferences prefs) {
super("Crystal Configuration Editor");
Assert.assertNotNull(prefs);
final JFrame frame = this;
frame.setIconImage((new ImageIcon(Constants.class.getResource("/crystal/client/images/crystal-ball_blue_128.jpg"))).getImage());
if (prefs.getProjectPreference().isEmpty()) {
// ClientPreferences client = new ClientPreferences("/usr/bin/hg/", "/tmp/crystalClient/");
ProjectPreferences newGuy = new ProjectPreferences(new DataSource("", "", DataSource.RepoKind.HG, false, null), prefs);
try {
prefs.addProjectPreferences(newGuy);
prefs.setChanged(true);
} catch (DuplicateProjectNameException e) {
// Just ignore the duplicate project name
}
}
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
getContentPane().add(new JLabel("Closing this window will save the configuraion settings."));
// JPanel hgPanel = new JPanel();
// hgPanel.setLayout(new BoxLayout(hgPanel, BoxLayout.X_AXIS));
// hgPanel.add(new JLabel("Path to hg executable:"));
// final JTextField hgPath = new JTextField(prefs.getHgPath());
// hgPath.setSize(hgPath.getWidth(), 16);
// hgPanel.add(hgPath);
// hgPath.addKeyListener(new KeyListener() {
// public void keyPressed(KeyEvent arg0) {
// public void keyTyped(KeyEvent arg0) {
// public void keyReleased(KeyEvent arg0) {
// prefs.setHgPath(hgPath.getText());
// prefs.setChanged(true);
// frame.pack();
// JButton hgButton = new JButton("find");
// hgPanel.add(hgButton);
// hgButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// new MyPathChooser("Path to hg executable", hgPath, JFileChooser.FILES_ONLY);
// prefs.setChanged(true);
// getContentPane().add(hgPanel);
JPanel tempPanel = new JPanel();
tempPanel.setLayout(new BoxLayout(tempPanel, BoxLayout.X_AXIS));
tempPanel.add(new JLabel("Path to scratch space:"));
final JTextField tempPath = new JTextField(prefs.getTempDirectory());
tempPanel.add(tempPath);
tempPath.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
prefs.setTempDirectory(tempPath.getText());
prefs.setChanged(true);
frame.pack();
}
});
JButton tempButton = new JButton("find");
tempPanel.add(tempButton);
tempButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new MyPathChooser("Path to scratch directory", tempPath, JFileChooser.DIRECTORIES_ONLY);
prefs.setChanged(true);
}
});
getContentPane().add(tempPanel);
final JTabbedPane projectsTabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
/*
* projectsTabs.addChangeListener(new ChangeListener() {
*
* @Override public void stateChanged(ChangeEvent e) { frame.pack(); System.out.println("Tabs changed"); } });
*/
for (ProjectPreferences pref : prefs.getProjectPreference()) {
ProjectPanel current = new ProjectPanel(pref, prefs, frame, projectsTabs);
projectsTabs.addTab(current.getName(), current);
// projectsTabs.setTitleAt(projectsTabs.getTabCount() - 1, current.getName());
}
final JButton newProjectButton = new JButton("Add New Project");
final JButton deleteProjectButton = new JButton("Delete This Project");
newProjectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteProjectButton.setEnabled(true);
HashSet<String> shortNameLookup = new HashSet<String>();
for (ProjectPreferences current : prefs.getProjectPreference()) {
shortNameLookup.add(current.getEnvironment().getShortName());
}
int count = 1;
while (shortNameLookup.contains("New Project " + count++))
;
ProjectPreferences newGuy = new ProjectPreferences(new DataSource("New Project " + --count, "", DataSource.RepoKind.HG, false, null), prefs);
try {
prefs.addProjectPreferences(newGuy);
} catch (DuplicateProjectNameException e1) {
// This should never happen because we just found a clean project name to use.
throw new RuntimeException("When I tried to create a new project, I found a nice, clean, unused name:\n" +
"New Project " + count + "\nbut then the preferences told me that name was in use. \n" +
"This should never happen!");
}
ProjectPanel newGuyPanel = new ProjectPanel(newGuy, prefs, frame, projectsTabs);
projectsTabs.addTab("New Project " + count, newGuyPanel);
prefs.setChanged(true);
frame.pack();
}
});
deleteProjectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int current = projectsTabs.getSelectedIndex();
prefs.removeProjectPreferencesAtIndex(current);
projectsTabs.remove(current);
if (prefs.getProjectPreference().isEmpty())
deleteProjectButton.setEnabled(false);
prefs.setChanged(true);
frame.pack();
}
});
getContentPane().add(newProjectButton);
getContentPane().add(projectsTabs);
getContentPane().add(deleteProjectButton);
addWindowListener(new WindowListener() {
public void windowClosing(WindowEvent arg0) {
if (prefs.hasChanged()) {
ClientPreferences.savePreferencesToDefaultXML(prefs);
prefs.setChanged(false);
}
}
public void windowActivated(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowOpened(WindowEvent arg0) {
}
});
pack();
setVisible(true);
}
/**
* A file chooser to select paths
* @author brun
*/
private static class MyPathChooser extends JFrame {
private static final long serialVersionUID = 4078764196578702307L;
MyPathChooser(String name, final JTextField path, int fileSelectionMode) {
super(name);
final JFrame chooserFrame = this;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
final JFileChooser chooser = new JFileChooser(path.getText());
chooser.setFileSelectionMode(fileSelectionMode);
getContentPane().add(chooser);
pack();
setVisible(true);
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
path.setText(chooser.getSelectedFile().getAbsolutePath());
// and pretend like you typed a key:
path.getKeyListeners()[0].keyTyped(new KeyEvent(path, 0, 0, 0, 0, ' '));
chooserFrame.setVisible(false);
}
});
}
}
/**
* An execution point used only for testing.
*/
public static void main(String[] args) {
ClientPreferences client = new ClientPreferences("temp", "hgPath", Constants.DEFAULT_REFRESH);
ProjectPreferences one = new ProjectPreferences(new DataSource("first project", "~brun\\firstrepo", DataSource.RepoKind.HG, false, null), client);
DataSource oneOther = new DataSource("Mike's copy", "~mernst\\repo", DataSource.RepoKind.HG, false, null);
DataSource twoOther = new DataSource("Reid's copy", "~rtholmes\\repo", DataSource.RepoKind.HG, false, null);
DataSource threeOther = new DataSource("David's copy", "~notkin\\repo", DataSource.RepoKind.HG, false, null);
one.addDataSource(oneOther);
one.addDataSource(twoOther);
ProjectPreferences two = new ProjectPreferences(new DataSource("second project", "~brun\\secondrepo", DataSource.RepoKind.HG, false, null), client);
two.addDataSource(threeOther);
two.addDataSource(oneOther);
try {
client.addProjectPreferences(one);
client.addProjectPreferences(two);
} catch (DuplicateProjectNameException e) {
// This should really never happen because we're dealing with an empty set of preferences.
throw new RuntimeException("When I was creating some nice fresh preferences with two projects, one and two, I got this error:\n" +
e.getMessage());
}
getPreferencesGUIEditorFrame(client);
// int i = 0;
// while(true) {
// i = (i + 1) % 1000000;
// if (i == 0)
// System.out.println(mine.getEnvironment().getShortName());
}
} |
package de.dlichti.base64tool.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import de.dlichti.base64tool.Base64Coder;
import de.dlichti.base64tool.Base64CoderMIME;
import de.dlichti.base64tool.Base64Encoding;
import de.dlichti.base64tool.Base64Exception;
import de.dlichti.base64tool.Radix64Coder;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.ButtonGroup;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Base64Translate {
// Some important UI components
private JFrame mainFrame;
private final ButtonGroup encodingButtonGroup = new ButtonGroup();
private final InputArea txtrClearText = new InputArea("Clear Text");
private final InputArea txtrEncodedText = new InputArea("Encoded Text");
private JRadioButton defaultButton;
// Actions to change encoding
private final SelectCoderAction selectBase64Action = new SelectCoderAction(new Base64Coder());
private final SelectCoderAction selectBase64UrlAction = new SelectCoderAction(new Base64Coder(Base64Encoding.BASE_64_URL));
private final SelectCoderAction selectBase64XmlAction = new SelectCoderAction(new Base64Coder(Base64Encoding.BASE_64_XML_NAME));
private final SelectCoderAction selectBase64MIMEAction = new SelectCoderAction(new Base64CoderMIME());
private final SelectCoderAction selectRadix64Action = new SelectCoderAction(new Radix64Coder());
/**
* The currently enabled encoder class
*/
protected Base64Coder encoder;
/**
* Reflects the current usage mode.
* Set {@code true} if the program should encode clear text.
* Set {@code false} if the program should decode encoded text.
*/
protected boolean encode;
/**
* Launch the application.
*/
public static void main (String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run () {
try {
Base64Translate window = new Base64Translate();
window.mainFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Base64Translate () {
initialize();
this.encode = true;
this.encodingButtonGroup.setSelected(this.defaultButton.getModel(), true);
this.selectBase64Action.actionPerformed(null);
}
/**
* Initialize the contents of the frame.
*/
private void initialize () {
mainFrame = new JFrame();
mainFrame.setTitle("Base64Code");
mainFrame.setBounds(100, 100, 507, 376);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel optionsPanel = new JPanel();
mainFrame.getContentPane().add(optionsPanel, BorderLayout.NORTH);
GridBagLayout gbl_optionsPanel = new GridBagLayout();
gbl_optionsPanel.columnWidths = new int[]{0, 0, 0, 0, 0, 0};
gbl_optionsPanel.rowHeights = new int[]{0, 0};
gbl_optionsPanel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_optionsPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
optionsPanel.setLayout(gbl_optionsPanel);
int gridx = 0;
defaultButton = addEncodingButton(selectBase64Action, optionsPanel, gridx++, 0);
addEncodingButton(selectBase64MIMEAction, optionsPanel, gridx++, 0);
addEncodingButton(selectRadix64Action, optionsPanel, gridx++, 0);
addEncodingButton(selectBase64UrlAction, optionsPanel, gridx++, 0);
addEncodingButton(selectBase64XmlAction, optionsPanel, gridx++, 0);
JPanel contentPanel = new JPanel();
mainFrame.getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new GridLayout(0, 2, 0, 0));
this.txtrClearText.setWrapStyleWord(true);
contentPanel.add(this.txtrClearText);
this.txtrClearText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
Base64Translate.this.encode = true;
Base64Translate.this.updateText();
}
});
contentPanel.add(this.txtrEncodedText);
txtrEncodedText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
Base64Translate.this.encode = false;
Base64Translate.this.updateText();
}
});
}
protected JRadioButton addEncodingButton (SelectCoderAction action, JPanel panel, int gridx, int gridy) {
JRadioButton button = new JRadioButton();
button.setAction(action);
encodingButtonGroup.add(button);
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(0, 0, 0, 5);
constraints.gridx = gridx;
constraints.gridy = gridy;
panel.add(button, constraints);
return button;
}
protected void updateText () {
System.out.println("Updating text field contents");
if (this.encode) this.updateEncoded();
else this.updateDecoded();
}
private void updateEncoded () {
final String clearText = this.txtrClearText.getText();
final String encodedText = this.encoder.encode(clearText.getBytes());
this.txtrEncodedText.setText(encodedText);
this.txtrEncodedText.setState(InputArea.VALID);
}
private void updateDecoded () {
final String encodedText = this.txtrEncodedText.getText();
try {
String clearText = new String(this.encoder.decode(encodedText));
this.txtrClearText.setText(clearText);
this.txtrEncodedText.setState(InputArea.VALID);
} catch (Base64Exception e) {
e.printStackTrace();
this.txtrClearText.setText(e.getMessage());
this.txtrEncodedText.setState(InputArea.INVALID);
}
}
private class SelectCoderAction extends AbstractSelectCoderAction {
private static final long serialVersionUID = 1L;
public SelectCoderAction (Base64Coder coder) {
super (coder);
putValue(NAME, this.coder.getName());
putValue(SHORT_DESCRIPTION, String.format("Use %s encoding", this.coder.getName()));
}
public void actionPerformed(ActionEvent e) {
Base64Translate.this.encoder = this.coder;
System.out.println(String.format("Set encoding to %s.", this.coder.getName()));
Base64Translate.this.updateText();
}
}
} |
//package com.nandaka.bakareaderclone;
package com.erakk.lnreader;
//import java.io.IOException;
//import java.net.URL;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.erakk.lnreader.dao.NovelsDao;
import com.erakk.lnreader.helper.AsyncTaskResult;
import com.erakk.lnreader.model.PageModel;
//import org.jsoup.nodes.Document;
//import org.jsoup.nodes.Element;
//nadaka.bakareaderclone original
//import com.erakk.lnreader.helper.DownloadPageTask;
//import android.app.Activity;
//import android.widget.ListView;
public class DisplayLightNovelsActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.erakk.lnreader.NOVEL";
public final static String EXTRA_PAGE = "com.erakk.lnreader.page";
public static final String EXTRA_TITLE = "com.erakk.lnreader.title";
ArrayList<PageModel> listItems=new ArrayList<PageModel>();
ArrayAdapter<PageModel> adapter;
NovelsDao dao = new NovelsDao(this);
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_light_novels);
getActionBar().setDisplayHomeAsUpEnabled(true);
try {
adapter=new ArrayAdapter<PageModel>(this,
android.R.layout.simple_list_item_1,
listItems);
// adapter=new ArrayAdapter<PageModel>(this,
// R.layout.novel_list_item,
// listItems);
// listItems = new LoadNovelsTask().execute(adapter).get().getResult();
new LoadNovelsTask().execute(new Void[] {});
setListAdapter(adapter);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast t = Toast.makeText(this, e.getClass().toString() +": " + e.getMessage(), Toast.LENGTH_SHORT);
t.show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
PageModel o = adapter.getItem(position);
String novel = o.toString();
//Create new intent
Intent intent = new Intent(this, LightNovelChaptersActivity.class);
intent.putExtra(EXTRA_MESSAGE, novel);
intent.putExtra(EXTRA_PAGE, o.getPage());
intent.putExtra(EXTRA_TITLE, o.getTitle());
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_display_light_novels, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent launchNewIntent = new Intent(this, DisplaySettingsActivity.class);
startActivity(launchNewIntent);
return true;
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==android.R.layout.activity_list_item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("Quick Menu");
String[] menuItems = getResources().getStringArray(R.array.novel_context_menu);
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
public class LoadNovelsTask extends AsyncTask<Void, ProgressBar, AsyncTaskResult<ArrayList<PageModel>>> {
@SuppressLint("NewApi")
@Override
protected AsyncTaskResult<ArrayList<PageModel>> doInBackground(Void... arg0) {
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar2);
pb.setIndeterminate(true);
pb.setActivated(true);
pb.animate();
try {
listItems = dao.getNovels();
return new AsyncTaskResult<ArrayList<PageModel>>(listItems);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast t = Toast.makeText(getApplicationContext(), e.getClass().toString() + ": " + e.getMessage(), Toast.LENGTH_SHORT);
t.show();
e.printStackTrace();
return new AsyncTaskResult<ArrayList<PageModel>>(e);
}
}
@SuppressLint("NewApi")
protected void onPostExecute(AsyncTaskResult<ArrayList<PageModel>> result) {
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar2);
TextView tv = (TextView) findViewById(R.id.loading);
tv.setVisibility(TextView.GONE);
pb.setActivated(false);
pb.setVisibility(ProgressBar.GONE);
ArrayList<PageModel> list = result.getResult();
if(list != null) adapter.addAll(list);
}
}
} |
package dk.itu.jglyph.features;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import dk.itu.jglyph.Edge;
import dk.itu.jglyph.JGlyph;
import dk.itu.jglyph.Node;
public class FeatureExtractors
{
private static FeatureExtractors instance = null;
private List<IFeatureExtractor> extractors;
private List<String> descriptions;
private FeatureExtractors()
{
extractors = new ArrayList<>();
descriptions = new ArrayList<>();
addExtractor((JGlyph g) -> minAngle(g), "Minimum angle.");
addExtractor((JGlyph g) -> avgAngle(g), "Average angle.");
addExtractor((JGlyph g) -> maxAngle(g), "Maximum angle.");
addExtractor((JGlyph g) -> minDistanceToCenter(g), "Minimum distance to center.");
addExtractor((JGlyph g) -> avgDistanceToCenter(g), "Average distance to center");
addExtractor((JGlyph g) -> maxDistanceToCenter(g), "Maximum distance to center.");
addExtractor((JGlyph g) -> minEdgeLength(g), "Minimum edge length.");
addExtractor((JGlyph g) -> avgEdgeLength(g), "Average edge length.");
addExtractor((JGlyph g) -> maxEdgeLength(g), "Maximum edge length.");
addExtractor((JGlyph g) -> avgStrokeEndsX(g), "Average stroke ends X.");
addExtractor((JGlyph g) -> avgStrokeEndsY(g), "Average stroke ends Y.");
addExtractor((JGlyph g) -> unitCount(g), "Unit count.");
addExtractor((JGlyph g) -> edgeCount(g), "Edge count.");
addExtractor((JGlyph g) -> strokeEstimate(g), "Stroke count estimate.");
}
private void addExtractor(IFeatureExtractor extractor, String description)
{
extractors.add(extractor);
descriptions.add(description);
}
public IFeatureExtractor getExtractor(int index)
{
return extractors.get(index);
}
public String getDescription(int index)
{
return descriptions.get(index);
}
public int count()
{
return extractors.size();
}
public static FeatureExtractors getInstance()
{
if(instance == null)
{
instance = new FeatureExtractors();
}
return(instance);
}
public static double minAngle(JGlyph glyph)
{
List<Double> angles = getAngles(glyph);
if (angles.size() == 0) return Math.PI;
double min = Double.MAX_VALUE;
for (Double d : angles) {
if (d < min && d != 0) min = d; // TODO do we need to use epsilon for the last comparison?
}
return min;
}
public static double avgAngle(JGlyph glyph)
{
List<Double> angles = getAngles(glyph);
if (angles.size() == 0) return Math.PI;
double sum = 0;
System.out.println(angles);
for (Double d : angles) {
sum += d;
}
return sum / angles.size();
}
public static double maxAngle(JGlyph glyph)
{
List<Double> angles = getAngles(glyph);
if (angles.size() == 0) return Math.PI;
double max = Double.MIN_VALUE;
for (Double d : angles) {
if (d > max) max = d;
}
return max;
}
private static List<Double> getAngles(JGlyph g) {
List<Double> result = new ArrayList<Double>();
for (Node node : g.getNodes()) {
// TODO x/y cannot be double with our current creation scheme
int id = g.getNodeId((int)node.x, (int)node.y);
List<Edge> edges = g.getEdges(id);
for (int i = 0; i < edges.size(); i++) {
for (int j = i+1; j < edges.size(); j++) {
Edge e1 = edges.get(i);
Edge e2 = edges.get(j);
Node n1 = node.equals(e1.from) ? e1.to : e1.from;
Node n2 = node.equals(e2.from) ? e2.to : e2.from;
//Skip dots
if (node.equals(n1) || node.equals(n2)) continue;
// TODO 0/180 could be sorted our here but we might need that for other metrics
result.add(getAngle(node, n1, n2));
}
}
}
return result;
}
private static Double getAngle(Node center, Node n1, Node n2) {
double x1 = n1.x - center.x;
double x2 = n2.x - center.x;
double y1 = n1.y - center.y;
double y2 = n2.y - center.y;
double dot = x1*x2 + y1*y2;
double l1 = Math.sqrt(x1*x1 + y1*y1);
double l2 = Math.sqrt(x2*x2 + y2*y2);
return Math.acos(dot/(l1*l2));
}
/** Minimum distance from center for stroke start/end */
public static double minDistanceToCenter(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
if(ends.isEmpty())
{
return(0);
}
Node centroid = glyph.getCentroid();
double minSq = Double.MAX_VALUE;
for(Node end : glyph.getEndsOfStrokes())
{
double distSq = end.distanceSq(centroid);
if(distSq < minSq)
{
minSq = distSq;
}
}
double min = Math.sqrt(minSq);
return(min);
}
/** Average distance from center for stroke start/end */
public static double avgDistanceToCenter(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
int count = ends.size();
if(count == 0)
{
return(0);
}
Node centroid = glyph.getCentroid();
double sum = 0;
for(Node end : ends)
{
sum += end.distance(centroid);
}
double average = sum / count;
return(average);
}
/** Maximum distance from center for stroke start/end */
public static double maxDistanceToCenter(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
if(ends.isEmpty())
{
return(0);
}
Node centroid = glyph.getCentroid();
double maxSq = Double.MIN_VALUE;
for(Node end : glyph.getEndsOfStrokes())
{
double distSq = end.distanceSq(centroid);
if(distSq > maxSq)
{
maxSq = distSq;
}
}
double max = Math.sqrt(maxSq);
return(max);
}
/** Number of edges */
public static double edgeCount(JGlyph glyph)
{
int count = glyph.getEdges().size();
return(count);
}
/** Number of connected units */
public static double unitCount(JGlyph glyph)
{
Iterable<Edge> edges = glyph.getEdges();
// List of sets found
List<List<Node>> sets = new ArrayList<List<Node>>();
for (Edge edge : edges) {
// Set of nodes that are connected to this edge
List<Node> currentSet = new ArrayList<Node>();
currentSet.add(edge.from);
currentSet.add(edge.to);
if (sets.size() > 0) {
for (Iterator<List<Node>> iterator = sets.iterator(); iterator.hasNext();) {
List<Node> set = iterator.next();
if (set.contains(edge.from) || set.contains(edge.to)) {
currentSet.addAll(set);
iterator.remove();
}
// TODO test if the edge crosses the set
}
}
sets.add(currentSet);
}
return sets.size();
}
/** An estimate for how many strokes would be needed to draw this */
public static double strokeEstimate(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
int count = ends.size();
int estimate = count / 2;
return(estimate);
}
/** Average X for all edges */
public static double avgX(JGlyph glyph)
{
double sum = 0;
int count = 0;
for (Edge edge : glyph.getEdges()) {
sum += edge.from.x + edge.to.x;
count++;
}
return sum/(count*2);
}
/** Average Y for all edges */
public static double avgY(JGlyph glyph)
{
double sum = 0;
int count = 0;
for (Edge edge : glyph.getEdges()) {
sum += edge.from.y + edge.to.y;
count++;
}
return sum/(count*2);
}
/** Average X for stroke ends */
public static double avgStrokeEndsX(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
int count = ends.size();
Node centroid = glyph.getCentroid();
if(count == 0)
{
return(centroid.x);
}
double sum = 0;
for(Node end : ends)
{
sum += end.x;
}
double average = sum / count;
return(average);
}
/** Average Y for stroke ends */
public static double avgStrokeEndsY(JGlyph glyph)
{
List<Node> ends = glyph.getEndsOfStrokes();
int count = ends.size();
Node centroid = glyph.getCentroid();
if(count == 0)
{
return(centroid.y);
}
double sum = 0;
for(Node end : ends)
{
sum += end.y;
}
double average = sum / count;
return(average);
}
/** Minimum edge length */
public static double minEdgeLength(JGlyph glyph)
{
double minLength = Double.MAX_VALUE;
for (Edge edge : glyph.getEdges()) {
double length = length(edge);
if (length < minLength) minLength = length;
}
return minLength;
}
/** Maximum edge length */
public static double maxEdgeLength(JGlyph glyph)
{
double maxLength = Double.MIN_VALUE;
for (Edge edge : glyph.getEdges()) {
double length = length(edge);
if (length > maxLength) maxLength = length;
}
return maxLength;
}
/** Average edge length */
public static double avgEdgeLength(JGlyph glyph)
{
double sum = 0;
int count = 0;
for (Edge edge : glyph.getEdges()) {
sum += length(edge);
count++;
}
return sum/count;
}
private static double length(Edge edge) {
double dx = edge.from.x-edge.to.x;
double dy = edge.from.y-edge.to.y;
return Math.sqrt(dx*dx+dy*dy);
}
} |
package dk.netarkivet.deploy2;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import dk.netarkivet.common.utils.FileUtils;
/**
* Class for evaluating a config file.
* Tests the settings in the config file against default settings to
* test for wrongly assigned elements.
*
*/
public class EvaluateConfigFile {
/** The elements to check the settings against.*/
private Element completeSettings;
/** The root element in the xml tree.*/
private XmlStructure root;
/** the log, for logging stuff instead of displaying them directly.*/
private final Log log = LogFactory.getLog(getClass().getName());
/**
* Constructor.
* Only initialises the config file and settings list.
*
* @param itConfigFile The file to evaluate.
*/
public EvaluateConfigFile(File itConfigFile) {
try {
initLoadDefaultSettings();
root = new XmlStructure(itConfigFile);
} catch (Exception e) {
System.err.println("Evaluation error!");
}
}
/**
* Evaluates the config file.
* This is done by evaluating the settings branch for all the instances in
* the XML-tree (global, physical locaiton, machine and application)
*/
@SuppressWarnings("unchecked")
public void evaluate() {
try {
// check global settings
evaluateElement(root.getChild(Constants.COMPLETE_SETTINGS_BRANCH));
List<Element> physLocs = root.getChildren(
Constants.DEPLOY_PHYSICAL_LOCATION);
for(Element pl : physLocs) {
// check physical location settings
evaluateElement(pl.element(Constants.COMPLETE_SETTINGS_BRANCH));
List<Element> macs = pl.elements(Constants.DEPLOY_MACHINE);
for(Element mac : macs) {
// check machine settings
evaluateElement(mac
.element(Constants.COMPLETE_SETTINGS_BRANCH));
List<Element> apps = mac
.elements(Constants.DEPLOY_APPLICATION_NAME);
for(Element app : apps) {
// check application settings
evaluateElement(app
.element(Constants.COMPLETE_SETTINGS_BRANCH));
}
}
}
} catch (Exception e) {
System.err.println("Unknown evaluation error: " + e);
log.trace("Error occured during evaluation: " + e);
}
}
/**
* Load the default settings files as reference trees.
* These are used for testing whether the branches in the settings file
* are to be used or not.
* @throws IOException If file not found.
*/
private void initLoadDefaultSettings() throws IOException {
File f = FileUtils.getResourceFileFromClassPath(
Constants.BUILD_COMPLETE_SETTINGS_FILE_PATH);
try {
Document doc;
SAXReader reader = new SAXReader();
if (f.canRead()) {
doc = reader.read(f);
completeSettings = doc.getRootElement();
} else {
System.out.println("Cannot read file: "
+ f.getAbsolutePath());
}
} catch (DocumentException e) {
System.err.println("Problems with file: "
+ f.getAbsolutePath());
}
}
/**
* Evaluates a element (has to called with the settings branch).
* Then tries to evaluate all the branches to the element.
* The method is called recursively for the children of curElem.
*
* @param curElem The current element to evaluate.
*/
@SuppressWarnings("unchecked")
private void evaluateElement(Element curElem) {
// make sure to catch null-pointers
if(curElem == null) {
return;
}
List<Element> elList = curElem.elements();
for(Element el : elList) {
boolean valid = false;
// get path
String path = getSettingsPath(el);
// check if path exists in any default setting.
valid = existBranch(completeSettings, path.split("/"));
if(valid) {
if(!el.isTextOnly()) {
evaluateElement(el);
}
} else {
System.out.println("Branch in settings not found: "
+ path.replace("/", "."));
}
}
}
/**
* For testing whether a branch with the current path exists.
*
* @param settings The root of the default settings XML-tree.
* @param path The path to the branch to test.
* @return Whether the branch at the end of the path in the root exists.
*/
private boolean existBranch(Element settings, String[] path) {
Element curE = settings;
for(String st : path) {
if(curE == null) {
return false;
}
curE = curE.element(st);
}
// return whether the final branch exists.
return (curE != null);
}
/**
* Gets the path from settings of an element.
*
* @param el The element to get the settings path.
* @return The path from settings to the element, in the XML-tree.
*/
private String getSettingsPath(Element el) {
String[] elList = el.getPath().split("/");
StringBuilder res = new StringBuilder();
int i = 0;
// find the index for settings
while(i < elList.length && !elList[i].equalsIgnoreCase("settings")) {
i++;
}
for(i++; i<elList.length; i++) {
res.append(elList[i]);
res.append("/");
}
// remove last '/'
res.deleteCharAt(res.length()-1);
return res.toString();
}
} |
package dr.app.tracer.analysis;
import dr.app.gui.components.RealNumberField;
import dr.app.gui.components.WholeNumberField;
import dr.app.gui.util.LongTask;
import dr.evolution.coalescent.TwoEpochDemographic;
import dr.evolution.util.Units;
import dr.inference.trace.TraceDistribution;
import dr.inference.trace.TraceList;
import dr.stats.Variate;
import jam.framework.DocumentFrame;
import jam.panels.OptionsPanel;
import jebl.evolution.coalescent.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
public class DemographicDialog {
private JFrame frame;
private JComboBox demographicCombo;
private WholeNumberField binCountField;
public static String[] demographicModels = {
"Constant Population",
"Exponential Growth (Growth Rate)",
"Exponential Growth (Doubling Time)",
"Logistic Growth (Growth Rate)",
"Logistic Growth (Doubling Time)",
"Expansion (Growth Rate)",
"Expansion (Doubling Time)",
"Constant-Exponential",
"Constant-Logistic",
"Constant-Exponential-Constant",
"Exponential-Logistic",
"Boom-Bust",
"Two Epoch"
};
private String[][] argumentGuesses = {
{"populationsize", "population", "popsize", "n0", "size", "pop"},
{"ancestralsize", "ancestralproportion", "ancpopsize", "proportion", "ancestral", "n1"},
{"exponentialgrowthrate", "exponentialrate", "growthrate", "expgrowth", "growth", "rate", "r"},
{"doublingtime", "doubling", "time", "t"},
{"logisticshape", "halflife", "t50", "time50", "logt50", "shape"},
{"spikefactor", "spike", "factor", "f"},
{"cataclysmtime", "cataclysm", "time", "t"},
{"transitiontime", "time1", "time", "t1", "t"},
{"logisticgrowthrate", "logisticgrowth", "loggrowth", "logisticrate"},
{"populationsize2", "population2", "popsize2", "n02", "size2", "pop2"},
{"exponentialgrowthrate2", "exponentialrate2", "growthrate2", "expgrowth2", "growth2", "rate2", "r2"}
};
private String[] argumentNames = new String[]{
"Population Size",
"Ancestral Proportion",
"Growth Rate",
"Doubling Time",
"Logistic Shape",
"Spike Factor",
"Spike Time",
"Transition Time",
"Logistic Growth Rate",
"Population Size 2",
"Growth Rate 2"
};
private int[][] argumentIndices = {
{0}, // const
{0, 2}, // exp
{0, 3}, // exp doubling time
{0, 2, 4}, // logistic
{0, 3, 4}, // logistic doubling time
{0, 1, 2}, // expansion
{0, 1, 3}, // expansion doubling time
{0, 7, 2}, // const-exp
{0, 1, 2, 4}, // const-log
{0, 1, 2, 7}, // const-exp-const
{0, 2, 4, 7, 8},// exp-logistic
{0, 2, 5, 6}, // boom bust
{0, 2, 9, 10, 7} // Two Epoch
};
private String[] argumentTraces = new String[argumentNames.length];
private JComboBox[] argumentCombos = new JComboBox[argumentNames.length];
private JComboBox maxHeightCombo = new JComboBox(new String[]{
"Lower 95% HPD", "Median", "Mean", "Upper 95% HPD"});
private JComboBox rootHeightCombo;
private JCheckBox manualRangeCheckBox;
private RealNumberField minTimeField;
private RealNumberField maxTimeField;
private String rootHeightTrace = "None selected";
private RealNumberField ageOfYoungestField = new RealNumberField();
private OptionsPanel optionPanel;
public DemographicDialog(JFrame frame) {
this.frame = frame;
demographicCombo = new JComboBox(demographicModels);
for (int i = 0; i < argumentNames.length; i++) {
argumentCombos[i] = new JComboBox();
argumentTraces[i] = "None selected";
}
rootHeightCombo = new JComboBox();
binCountField = new WholeNumberField(2, 2000);
binCountField.setValue(100);
binCountField.setColumns(4);
manualRangeCheckBox = new JCheckBox("Use manual range for bins:");
maxTimeField = new RealNumberField(0.0, Double.MAX_VALUE);
maxTimeField.setColumns(12);
minTimeField = new RealNumberField(0.0, Double.MAX_VALUE);
minTimeField.setColumns(12);
ageOfYoungestField.setValue(0.0);
ageOfYoungestField.setColumns(12);
optionPanel = new OptionsPanel(12, 12);
}
public int getDemographicModel() {
return demographicCombo.getSelectedIndex();
}
private int findArgument(JComboBox comboBox, String argument) {
for (int i = 0; i < comboBox.getItemCount(); i++) {
String item = ((String) comboBox.getItemAt(i)).toLowerCase();
if (item.indexOf(argument) != -1) return i;
}
return -1;
}
public int showDialog(TraceList traceList, final TemporalAnalysisFrame temporalAnalysisFrame) {
for (int i = 0; i < argumentCombos.length; i++) {
argumentCombos[i].removeAllItems();
for (int j = 0; j < traceList.getTraceCount(); j++) {
String statistic = traceList.getTraceName(j);
argumentCombos[i].addItem(statistic);
}
int index = findArgument(argumentCombos[i], argumentTraces[i]);
for (int j = 0; j < argumentGuesses[i].length; j++) {
if (index != -1) break;
index = findArgument(argumentCombos[i], argumentGuesses[i][j]);
}
if (index == -1) index = 0;
argumentCombos[i].setSelectedIndex(index);
}
setArguments(temporalAnalysisFrame);
for (int j = 0; j < traceList.getTraceCount(); j++) {
String statistic = traceList.getTraceName(j);
rootHeightCombo.addItem(statistic);
}
int index = findArgument(rootHeightCombo, rootHeightTrace);
if (index == -1) index = findArgument(rootHeightCombo, "root");
if (index == -1) index = findArgument(rootHeightCombo, "height");
if (index == -1) index = 0;
rootHeightCombo.setSelectedIndex(index);
JOptionPane optionPane = new JOptionPane(optionPanel,
JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null,
null,
null);
optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));
final JDialog dialog = optionPane.createDialog(frame, "Demographic Analysis");
dialog.pack();
demographicCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setArguments(temporalAnalysisFrame);
dialog.pack();
}
});
dialog.setVisible(true);
int result = JOptionPane.CANCEL_OPTION;
Integer value = (Integer) optionPane.getValue();
if (value != null && value != -1) {
result = value;
}
if (result == JOptionPane.OK_OPTION) {
for (int i = 0; i < argumentCombos.length; i++) {
argumentTraces[i] = (String) argumentCombos[i].getSelectedItem();
}
rootHeightTrace = (String) rootHeightCombo.getSelectedItem();
}
return result;
}
private void setArguments(TemporalAnalysisFrame temporalAnalysisFrame) {
optionPanel.removeAll();
optionPanel.addComponents(new JLabel("Demographic Model:"), demographicCombo);
JLabel label = new JLabel("<html>Warning! Do not select a model other than that which was<br>" +
"specified in BEAST to generate the trace being analysed.<br>" +
"<em>Any other model will produce meaningless results.</em></html>");
label.setFont(label.getFont().deriveFont(((float) label.getFont().getSize() - 2)));
optionPanel.addSpanningComponent(label);
optionPanel.addSeparator();
optionPanel.addLabel("Select the traces to use for the arguments:");
int demo = demographicCombo.getSelectedIndex();
for (int i = 0; i < argumentIndices[demo].length; i++) {
int k = argumentIndices[demo][i];
optionPanel.addComponentWithLabel(argumentNames[k] + ":",
argumentCombos[k]);
}
optionPanel.addSeparator();
optionPanel.addComponentWithLabel("Maximum time is the root height's:", maxHeightCombo);
optionPanel.addComponentWithLabel("Select the trace of the root height:", rootHeightCombo);
if (temporalAnalysisFrame == null) {
optionPanel.addSeparator();
optionPanel.addComponentWithLabel("Number of bins:", binCountField);
optionPanel.addSpanningComponent(manualRangeCheckBox);
final JLabel label1 = optionPanel.addComponentWithLabel("Minimum time:", minTimeField);
final JLabel label2 = optionPanel.addComponentWithLabel("Maximum time:", maxTimeField);
if (manualRangeCheckBox.isSelected()) {
label1.setEnabled(true);
minTimeField.setEnabled(true);
label2.setEnabled(true);
maxTimeField.setEnabled(true);
} else {
label1.setEnabled(false);
minTimeField.setEnabled(false);
label2.setEnabled(false);
maxTimeField.setEnabled(false);
}
manualRangeCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
if (manualRangeCheckBox.isSelected()) {
label1.setEnabled(true);
minTimeField.setEnabled(true);
label2.setEnabled(true);
maxTimeField.setEnabled(true);
} else {
label1.setEnabled(false);
minTimeField.setEnabled(false);
label2.setEnabled(false);
maxTimeField.setEnabled(false);
}
}
});
}
optionPanel.addSeparator();
optionPanel.addComponentWithLabel("Age of youngest tip:", ageOfYoungestField);
JLabel label3 = new JLabel(
"<html>You can set the age of sampling of the most recent tip in<br>" +
"the tree. If this is set to zero then the plot is shown going<br>" +
"backwards in time, otherwise forwards in time.</html>");
label3.setFont(label3.getFont().deriveFont(((float) label3.getFont().getSize() - 2)));
optionPanel.addSpanningComponent(label3);
}
javax.swing.Timer timer = null;
public void createDemographicFrame(TraceList traceList, DocumentFrame parent) {
TemporalAnalysisFrame frame;
int binCount = binCountField.getValue();
double minTime;
double maxTime;
boolean manualRange = manualRangeCheckBox.isSelected();
if (manualRange) {
minTime = minTimeField.getValue();
maxTime = maxTimeField.getValue();
if (minTime >= maxTime) {
JOptionPane.showMessageDialog(parent,
"The minimum time value should be less than the maximum.",
"Error creating Bayesian skyline",
JOptionPane.ERROR_MESSAGE);
return;
}
frame = new TemporalAnalysisFrame(parent, "", binCount, minTime, maxTime);
} else {
frame = new TemporalAnalysisFrame(parent, "", binCount);
}
frame.initialize();
addToTemporalAnalysis(traceList, frame);
}
public void addToTemporalAnalysis(TraceList traceList, TemporalAnalysisFrame frame) {
final AnalyseDemographicTask analyseTask = new AnalyseDemographicTask(traceList, frame);
final ProgressMonitor progressMonitor = new ProgressMonitor(frame,
"Analysing Demographic Model",
"", 0, analyseTask.getLengthOfTask());
progressMonitor.setMillisToPopup(0);
progressMonitor.setMillisToDecideToPopup(0);
timer = new javax.swing.Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
progressMonitor.setProgress(analyseTask.getCurrent());
if (progressMonitor.isCanceled() || analyseTask.done()) {
progressMonitor.close();
analyseTask.stop();
timer.stop();
}
}
});
analyseTask.go();
timer.start();
}
class AnalyseDemographicTask extends LongTask {
TraceList traceList;
TemporalAnalysisFrame frame;
int binCount;
boolean rangeSet;
double minTime;
double maxTime;
double ageOfYoungest;
private int lengthOfTask = 0;
private int current = 0;
public AnalyseDemographicTask(TraceList traceList, TemporalAnalysisFrame frame) {
this.traceList = traceList;
this.frame = frame;
this.binCount = frame.getBinCount();
this.rangeSet = frame.isRangeSet();
ageOfYoungest = ageOfYoungestField.getValue();
}
public int getCurrent() {
return current;
}
public int getLengthOfTask() {
return lengthOfTask;
}
public String getDescription() {
return "Calculating demographic reconstruction...";
}
public String getMessage() {
return null;
}
public Object doWork() {
// int n = traceList.getStateCount();
current = 0;
int[] argIndices = argumentIndices[demographicCombo.getSelectedIndex()];
ArrayList<ArrayList> values = new ArrayList<ArrayList>();
Variate[] bins = new Variate[binCount];
for (int k = 0; k < binCount; k++) {
bins[k] = new Variate.D();
}
List heights = traceList.getValues(traceList.getTraceIndex(rootHeightTrace));
TraceDistribution distribution = new TraceDistribution(heights,
traceList.getTrace(traceList.getTraceIndex(rootHeightTrace)).getTraceType(), traceList.getStepSize());
double timeMean = distribution.getMean();
double timeMedian = distribution.getMedian();
double timeUpper = distribution.getUpperHPD();
double timeLower = distribution.getLowerHPD();
double maxHeight = 0.0;
switch (maxHeightCombo.getSelectedIndex()) {
// setting a timeXXXX to -1 means that it won't be displayed...
case 0:
maxHeight = timeLower;
break;
case 1:
maxHeight = timeMedian;
break;
case 2:
maxHeight = timeMean;
break;
case 3:
maxHeight = timeUpper;
break;
}
if (rangeSet) {
minTime = frame.getMinTime();
maxTime = frame.getMaxTime();
} else {
if (ageOfYoungest > 0.0) {
minTime = ageOfYoungest - maxHeight;
maxTime = ageOfYoungest;
} else {
minTime = 0.0;
maxTime = maxHeight - ageOfYoungest;
}
frame.setRange(minTime, maxTime);
}
if (ageOfYoungest > 0.0) {
// reverse them if ageOfYoungest is set positive
timeMean = ageOfYoungest - timeMean;
timeMedian = ageOfYoungest - timeMedian;
timeUpper = ageOfYoungest - timeUpper;
timeLower = ageOfYoungest - timeLower;
// setting a timeXXXX to -1 means that it won't be displayed...
if (minTime >= timeLower) timeLower = -1;
if (minTime >= timeMean) timeMean = -1;
if (minTime >= timeMedian) timeMedian = -1;
if (minTime >= timeUpper) timeUpper = -1;
} else {
// otherwise use use ageOfYoungest as an offset
timeMean = timeMean - ageOfYoungest;
timeMedian = timeMedian - ageOfYoungest;
timeUpper = timeUpper - ageOfYoungest;
timeLower = timeLower - ageOfYoungest;
// setting a timeXXXX to -1 means that it won't be displayed...
if (maxTime <= timeLower) timeLower = -1;
if (maxTime <= timeMean) timeMean = -1;
if (maxTime <= timeMedian) timeMedian = -1;
if (maxTime <= timeUpper) timeUpper = -1;
}
double delta = (maxTime - minTime) / (binCount - 1);
String title = "";
for (int j = 0; j < argIndices.length; j++) {
int index = traceList.getTraceIndex(argumentTraces[argIndices[j]]);
values.add(new ArrayList(traceList.getValues(index)));
}
if (demographicCombo.getSelectedIndex() == 0) { // Constant Size
title = "Constant Population Size";
ConstantPopulation demo = new ConstantPopulation();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 1) { // Exponential Growth (Growth Rate)
title = "Exponential Growth";
ExponentialGrowth demo = new ExponentialGrowth();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setGrowthRate((Double) values.get(1).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 2) { // Exponential Growth (Doubling Time)
title = "Exponential Growth";
ExponentialGrowth demo = new ExponentialGrowth();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setDoublingTime((Double) values.get(1).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 3) { // Logistic Growth (Growth Rate)
title = "Logistic Growth";
LogisticGrowth demo = new LogisticGrowth();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setGrowthRate((Double) values.get(1).get(i));
demo.setTime50((Double) values.get(2).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 4) { // Logistic Growth (Doubling Time)
title = "Logistic Growth";
LogisticGrowth demo = new LogisticGrowth();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setDoublingTime((Double) values.get(1).get(i));
demo.setTime50((Double) values.get(2).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 5) { // Expansion (Growth Rate)
title = "Expansion";
Expansion demo = new Expansion();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setProportion((Double) values.get(1).get(i));
demo.setGrowthRate((Double) values.get(2).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 6) { // Expansion (Doubling Time)
title = "Expansion";
Expansion demo = new Expansion();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setProportion((Double) values.get(1).get(i));
demo.setDoublingTime((Double) values.get(2).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 7) { // ConstExponential Growth
title = "Constant-Exponential Growth";
ConstExponential demo = new ConstExponential();
for (int i = 0; i < values.get(0).size(); i++) {
double N0 = (Double) values.get(0).get(i);
double time = (Double) values.get(1).get(i);
double r = (Double) values.get(2).get(i);
double N1 = N0 * Math.exp(-r * time);
demo.setN0(N0);
demo.setN1(N1);
demo.setGrowthRate(r);
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 8) { // ConstLogistic Growth
title = "Constant-Logistic Growth";
ConstLogistic demo = new ConstLogistic();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setN1((Double) values.get(1).get(i));
demo.setGrowthRate((Double) values.get(2).get(i));
demo.setTime50((Double) values.get(3).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 9) { // ConstExpConst
// title = "Constant-Exponential-Constant";
// ConstExpConst demo = new ConstExpConst();
// for (int i = 0; i < values[0].size(); i++) {
// demo.setN0(values[0].get(i));
// demo.setN1(values[1].get(i));
// demo.setGrowthRate(values[2].get(i));
// //demo.setTime50(values[3].get(i));
// addDemographic(bins, binCount, maxHeight, delta, demo);
// current++;
} else if (demographicCombo.getSelectedIndex() == 10) { // ExpLogistic Growth
title = "Exponential-Logistic Growth";
ExponentialLogistic demo = new ExponentialLogistic();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setR2((Double) values.get(1).get(i));
demo.setTime50((Double) values.get(2).get(i));
demo.setTime((Double) values.get(3).get(i));
demo.setGrowthRate((Double) values.get(4).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 11) { // Cataclysm
title = "Boom-Bust";
CataclysmicDemographic demo = new CataclysmicDemographic();
for (int i = 0; i < values.get(0).size(); i++) {
demo.setN0((Double) values.get(0).get(i));
demo.setGrowthRate((Double) values.get(1).get(i));
demo.setCataclysmTime((Double) values.get(3).get(i));
demo.setSpikeFactor((Double) values.get(2).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
} else if (demographicCombo.getSelectedIndex() == 12) { // Two Epoch
title = "Two Epoch";
dr.evolution.coalescent.ExponentialGrowth demo1 = new dr.evolution.coalescent.ExponentialGrowth(Units.Type.SUBSTITUTIONS);
dr.evolution.coalescent.ExponentialGrowth demo2 = new dr.evolution.coalescent.ExponentialGrowth(Units.Type.SUBSTITUTIONS);
TwoEpochDemographic demo = new TwoEpochDemographic(demo1, demo2, Units.Type.SUBSTITUTIONS);
for (int i = 0; i < values.get(0).size(); i++) {
demo1.setN0((Double) values.get(0).get(i));
demo1.setGrowthRate((Double) values.get(1).get(i));
demo2.setN0((Double) values.get(2).get(i));
demo2.setGrowthRate((Double) values.get(3).get(i));
demo.setTransitionTime((Double) values.get(4).get(i));
addDemographic(bins, binCount, maxHeight, delta, demo);
current++;
}
}
Variate xData = new Variate.D();
Variate yDataMean = new Variate.D();
Variate yDataMedian = new Variate.D();
Variate yDataUpper = new Variate.D();
Variate yDataLower = new Variate.D();
double t;
if (ageOfYoungest > 0.0) {
t = maxTime;
} else {
t = minTime;
}
for (Variate bin : bins) {
xData.add(t);
if (bin.getCount() > 0) {
yDataMean.add(bin.getMean());
yDataMedian.add(bin.getQuantile(0.5));
yDataLower.add(bin.getQuantile(0.025));
yDataUpper.add(bin.getQuantile(0.975));
} else {
yDataMean.add(Double.NaN);
yDataMedian.add(Double.NaN);
yDataLower.add(Double.NaN);
yDataUpper.add(Double.NaN);
}
if (ageOfYoungest > 0.0) {
t -= delta;
} else {
t += delta;
}
}
frame.addDemographic(title + ": " + traceList.getName(), xData,
yDataMean, yDataMedian,
yDataUpper, yDataLower,
timeMean, timeMedian,
timeUpper, timeLower);
return null;
}
private void addDemographic(Variate[] bins, int binCount, double maxHeight, double delta, DemographicFunction demo) {
double height;
if (ageOfYoungest > 0.0) {
height = ageOfYoungest - maxTime;
} else {
height = ageOfYoungest;
}
for (int k = 0; k < binCount; k++) {
if (height >= 0.0 && height <= maxHeight) {
bins[k].add(demo.getDemographic(height));
}
height += delta;
}
current++;
}
private void addDemographic(Variate[] bins, int binCount, double maxHeight, double delta, dr.evolution.coalescent.DemographicFunction demo) {
double height;
if (ageOfYoungest > 0.0) {
height = ageOfYoungest - maxTime;
} else {
height = ageOfYoungest;
}
for (int k = 0; k < binCount; k++) {
if (height >= 0.0 && height <= maxHeight) {
bins[k].add(demo.getDemographic(height));
}
height += delta;
}
current++;
}
}
} |
package editor.gui.inventory;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import editor.collection.Inventory;
import editor.database.card.Card;
import editor.database.card.CardLayout;
import editor.database.card.FlipCard;
import editor.database.card.MeldCard;
import editor.database.card.SingleCard;
import editor.database.card.SplitCard;
import editor.database.card.TransformCard;
import editor.database.characteristics.Expansion;
import editor.database.characteristics.Legality;
import editor.database.characteristics.ManaType;
import editor.database.characteristics.Rarity;
import editor.filter.leaf.options.multi.CardTypeFilter;
import editor.filter.leaf.options.multi.LegalityFilter;
import editor.filter.leaf.options.multi.SubtypeFilter;
import editor.filter.leaf.options.multi.SupertypeFilter;
import editor.gui.SettingsDialog;
import editor.util.UnicodeSymbols;
/**
* This class represents a dialog that shows the progress for loading the
* inventory and blocking the main frame until it is finished.
*
* @author Alec Roelke
*/
@SuppressWarnings("serial")
public class InventoryLoadDialog extends JDialog
{
/**
* This class represents a worker that loads cards from a JSON file in the background.
*
* @author Alec Roelke
*/
private class InventoryLoadWorker extends SwingWorker<Inventory, String>
{
/**
* File to load from.
*/
private File file;
/**
* Create a new InventoryWorker.
*
* @param f #File to load
*/
public InventoryLoadWorker(File f)
{
super();
file = f;
progressBar.setIndeterminate(true);
addPropertyChangeListener((e) -> {
if ("progress".equals(e.getPropertyName()))
{
int p = (Integer)e.getNewValue();
progressBar.setIndeterminate(p < 0);
progressBar.setValue(p);
}
});
}
/**
* Convert a card that has a single face but incorrectly is loaded as a
* multi-faced card into a card with a {@link CardLayout#NORMAL} layout.
*
* @param card card to convert
* @return a {@link Card} with the same information as the input but a
* {@link CardLayout#NORMAL} layout.
*/
private Card convertToNormal(Card card)
{
return new SingleCard(CardLayout.NORMAL,
card.name().get(0),
card.manaCost().get(0).toString(),
new ArrayList<>(card.colors()),
new ArrayList<>(card.colorIdentity()),
card.supertypes(),
card.types(),
card.subtypes(),
card.printedTypes().get(0),
card.rarity(),
card.expansion(),
card.oracleText().get(0),
card.flavorText().get(0),
card.printedText().get(0),
card.artist().get(0),
card.multiverseid().get(0),
card.number().get(0),
card.power().get(0).toString(),
card.toughness().get(0).toString(),
card.loyalty().get(0).toString(),
new TreeMap<>(card.rulings()),
card.legality());
}
@Override
protected Inventory doInBackground() throws Exception
{
publish("Opening " + file.getName() + "...");
var cards = new ArrayList<Card>();
var faces = new HashMap<Card, List<String>>();
var expansions = new HashSet<Expansion>();
var blockNames = new HashSet<String>();
var supertypeSet = new HashSet<String>();
var typeSet = new HashSet<String>();
var subtypeSet = new HashSet<String>();
var formatSet = new HashSet<String>();
// Read the inventory file
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")))
{
publish("Parsing " + file.getName() + "...");
JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
int numCards = 0;
for (var setNode : root.entrySet())
for (JsonElement card : setNode.getValue().getAsJsonObject().get("cards").getAsJsonArray())
if (card.getAsJsonObject().has("multiverseId"))
numCards += 1;
publish("Reading cards from " + file.getName() + "...");
setProgress(0);
for (var setNode : root.entrySet())
{
if (isCancelled())
{
expansions.clear();
blockNames.clear();
supertypeSet.clear();
typeSet.clear();
subtypeSet.clear();
formatSet.clear();
cards.clear();
return new Inventory();
}
// Create the new Expansion
JsonObject setProperties = setNode.getValue().getAsJsonObject();
JsonArray setCards = setProperties.get("cards").getAsJsonArray();
Expansion set = new Expansion(setProperties.get("name").getAsString(),
Optional.ofNullable(setProperties.get("block")).map(JsonElement::getAsString).orElse("<No Block>"),
setProperties.get("code").getAsString(),
setProperties.get(setProperties.has("oldCode") ? "oldCode" : "code").getAsString(),
setProperties.get(setProperties.has("magicCardsInfoCode") ? "magicCardsInfoCode" : "code").getAsString().toUpperCase(),
setProperties.get(setProperties.has("gathererCode") ? "gathererCode" : "code").getAsString(),
setCards.size(),
LocalDate.parse(setProperties.get("releaseDate").getAsString(), Expansion.DATE_FORMATTER));
expansions.add(set);
blockNames.add(set.block);
publish("Loading cards from " + set + "...");
for (JsonElement cardElement : setCards)
{
// Create the new card for the expansion
JsonObject card = cardElement.getAsJsonObject();
// Card's multiverseid. Skip cards that aren't in gatherer
long multiverseid = Optional.ofNullable(card.get("multiverseId")).map(JsonElement::getAsLong).orElse(-1L);
if (multiverseid < 0)
continue;
// Card's name
String name = card.get("name").getAsString();
// If the card is a token, skip it
CardLayout layout;
try
{
layout = CardLayout.valueOf(card.get("layout").getAsString().toUpperCase().replaceAll("[^A-Z]", "_"));
}
catch (IllegalArgumentException e)
{
errors.add(name + " (" + set + "): " + e.getMessage());
continue;
}
// Card's rarity
Rarity rarity = Rarity.parseRarity(card.get("rarity").getAsString());
// Card's rules text
String text = card.has("text") ? card.get("text").getAsString() : "";
// Card's flavor text
String flavor = card.has("flavorText") ? card.get("flavorText").getAsString() : "";
// Card's printed text
String printed = card.has("originalText") ? card.get("originalText").getAsString() : "";
// Card's artist
String artist = card.get("artist").getAsString();
// Card's number (this is a string since some don't have numbers or are things like "1a")
String number = card.has("number") ? card.get("number").getAsString() : "
// Card's power and toughness (empty if it doesn't have power or toughness)
String power = card.has("power") ? card.get("power").getAsString() : "";
String toughness = card.has("toughness") ? card.get("toughness").getAsString() : "";
// Card's loyalty (empty if it isn't a planeswalker or is Garruk, the Veil-Cursed)
String loyalty = "";
if (card.has("loyalty"))
{
JsonElement element = card.get("loyalty");
loyalty = element.isJsonNull() ? "X" : element.getAsString();
}
// Card's rulings
TreeMap<Date, List<String>> rulings = new TreeMap<>();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (card.has("rulings"))
{
for (JsonElement l : card.get("rulings").getAsJsonArray())
{
JsonObject o = l.getAsJsonObject();
Date date = format.parse(o.get("date").getAsString());
String ruling = o.get("text").getAsString();
if (!rulings.containsKey(date))
rulings.put(date, new ArrayList<>());
rulings.get(date).add(ruling);
}
}
var legality = new HashMap<String, Legality>();
if (card.has("legalities"))
{
for (var entry : card.get("legalities").getAsJsonObject().entrySet())
{
formatSet.add(entry.getKey());
legality.put(entry.getKey(), Legality.parseLegality(entry.getValue().getAsString()));
}
}
// Create the new card with all the values acquired above
Card c = new SingleCard(layout,
name,
Optional.ofNullable(card.get("manaCost")).map(JsonElement::getAsString).orElse(""),
Optional.ofNullable(card.get("colors")).map((e) -> {
var colors = new ArrayList<ManaType>();
for (JsonElement colorElement : e.getAsJsonArray())
colors.add(ManaType.parseManaType(colorElement.getAsString()));
return colors;
}).orElse(new ArrayList<>()),
Optional.ofNullable(card.get("colorIdentity")).map((e) -> {
var colorIdentity = new ArrayList<ManaType>();
for (JsonElement identityElement : e.getAsJsonArray())
colorIdentity.add(ManaType.parseManaType(identityElement.getAsString()));
return colorIdentity;
}).orElse(new ArrayList<>()),
Optional.ofNullable(card.get("supertypes")).map((e) -> {
var supertypes = new LinkedHashSet<String>();
for (JsonElement superElement : e.getAsJsonArray())
supertypes.add(superElement.getAsString());
return supertypes;
}).orElse(new LinkedHashSet<>()),
Optional.ofNullable(card.get("types")).map((e) -> {
var types = new LinkedHashSet<String>();
for (JsonElement typeElement : e.getAsJsonArray())
types.add(typeElement.getAsString());
return types;
}).orElse(new LinkedHashSet<>()),
Optional.ofNullable(card.get("subtypes")).map((e) -> {
var subtypes = new LinkedHashSet<String>();
for (JsonElement subElement : e.getAsJsonArray())
subtypes.add(subElement.getAsString());
return subtypes;
}).orElse(new LinkedHashSet<>()),
Optional.ofNullable(card.get("originalType")).map(JsonElement::getAsString).orElse(""),
rarity,
set,
text,
flavor,
printed,
artist,
multiverseid,
number,
power,
toughness,
loyalty,
rulings,
legality);
supertypeSet.addAll(c.supertypes());
typeSet.addAll(c.types());
subtypeSet.addAll(c.subtypes());
// Add to map of faces if the card has multiple faces
if (layout.isMultiFaced)
{
var names = new ArrayList<String>();
for (JsonElement e : card.get("names").getAsJsonArray())
names.add(e.getAsString());
faces.put(c, names);
}
cards.add(c);
setProgress(cards.size()*100/numCards);
}
}
publish("Processing multi-faced cards...");
List<Card> facesList = new ArrayList<>(faces.keySet());
while (!facesList.isEmpty())
{
boolean error = false;
Card face = facesList.remove(0);
var faceNames = faces.get(face);
var otherFaces = new ArrayList<Card>();
for (Card c : facesList)
if (faceNames.contains(c.unifiedName()) && c.expansion().equals(face.expansion()))
otherFaces.add(c);
facesList.removeAll(otherFaces);
otherFaces.add(face);
cards.removeAll(otherFaces);
otherFaces.sort(Comparator.comparingInt((a) -> faceNames.indexOf(a.unifiedName())));
switch (face.layout())
{
case SPLIT:
if (otherFaces.size() < 2)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't find other face(s) for split card.");
error = true;
}
else
{
for (Card f : otherFaces)
{
if (f.layout() != CardLayout.SPLIT)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't join non-split faces into a split card.");
error = true;
}
}
}
if (!error)
cards.add(new SplitCard(otherFaces));
else
for (Card f : otherFaces)
cards.add(convertToNormal(f));
break;
case FLIP:
if (otherFaces.size() < 2)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't find other side of flip card.");
error = true;
}
else if (otherFaces.size() > 2)
{
errors.add(face.toString() + " (" + face.expansion() + "): Too many sides for flip card.");
error = true;
}
else if (otherFaces.get(0).layout() != CardLayout.FLIP || otherFaces.get(1).layout() != CardLayout.FLIP)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't join non-flip faces into a flip card.");
error = true;
}
if (!error)
cards.add(new FlipCard(otherFaces.get(0), otherFaces.get(1)));
else
for (Card f : otherFaces)
cards.add(convertToNormal(f));
break;
case TRANSFORM:
if (otherFaces.size() < 2)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't find other face of double-faced card.");
error = true;
}
else if (otherFaces.size() > 2)
{
errors.add(face.toString() + " (" + face.expansion() + "): Too many faces for double-faced card.");
error = true;
}
else if (otherFaces.get(0).layout() != CardLayout.TRANSFORM || otherFaces.get(1).layout() != CardLayout.TRANSFORM)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't join single-faced cards into double-faced cards.");
error = true;
}
if (!error)
cards.add(new TransformCard(otherFaces.get(0), otherFaces.get(1)));
else
for (Card f : otherFaces)
cards.add(convertToNormal(f));
break;
case MELD:
if (otherFaces.size() < 3)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't find some faces of meld card.");
error = true;
}
else if (otherFaces.size() > 3)
{
errors.add(face.toString() + " (" + face.expansion() + "): Too many faces for meld card.");
error = true;
}
else if (otherFaces.get(0).layout() != CardLayout.MELD || otherFaces.get(1).layout() != CardLayout.MELD || otherFaces.get(2).layout() != CardLayout.MELD)
{
errors.add(face.toString() + " (" + face.expansion() + "): Can't join single-faced cards into meld cards.");
error = true;
}
if (!error)
{
cards.add(new MeldCard(otherFaces.get(0), otherFaces.get(2), otherFaces.get(1)));
cards.add(new MeldCard(otherFaces.get(2), otherFaces.get(0), otherFaces.get(1)));
}
else
for (Card f : otherFaces)
cards.add(convertToNormal(f));
break;
default:
break;
}
}
publish("Removing duplicate entries...");
var unique = new HashMap<Long, Card>();
for (Card c : cards)
if (!unique.containsKey(c.multiverseid().get(0)))
unique.put(c.multiverseid().get(0), c);
cards = new ArrayList<>(unique.values());
// Store the lists of expansion and block names and types and sort them alphabetically
Expansion.expansions = expansions.stream().sorted().toArray(Expansion[]::new);
Expansion.blocks = blockNames.stream().sorted().toArray(String[]::new);
SupertypeFilter.supertypeList = supertypeSet.stream().sorted().toArray(String[]::new);
CardTypeFilter.typeList = typeSet.stream().sorted().toArray(String[]::new);
SubtypeFilter.subtypeList = subtypeSet.stream().sorted().toArray(String[]::new);
LegalityFilter.formatList = formatSet.stream().sorted().toArray(String[]::new);
}
Inventory inventory = new Inventory(cards);
if (SettingsDialog.getAsString(SettingsDialog.CARD_TAGS) != null)
{
Matcher m = Pattern.compile("\\((.*?)::\\[(.*?)\\]\\)").matcher(SettingsDialog.getAsString(SettingsDialog.CARD_TAGS));
while (m.find())
Card.tags.put(inventory.get(Long.parseLong(m.group(1))), Arrays.stream(m.group(2).split(",")).collect(Collectors.toSet()));
}
return inventory;
}
/**
* {@inheritDoc}
* Close the dialog and allow it to return the Inventory
* that was created.
*/
@Override
protected void done()
{
setVisible(false);
dispose();
if (!SettingsDialog.getAsBoolean(SettingsDialog.SUPPRESS_LOAD_WARNINGS) && !errors.isEmpty())
{
SwingUtilities.invokeLater(() -> {
StringJoiner join = new StringJoiner("\n" + UnicodeSymbols.BULLET + " ");
join.add("Errors ocurred while loading the following card(s):");
for (String failure : errors)
join.add(failure);
JOptionPane.showMessageDialog(null, join.toString(), "Warning", JOptionPane.WARNING_MESSAGE);
});
}
}
/**
* {@inheritDoc}
* Change the label in the dialog to match the stage this worker is in.
*/
@Override
protected void process(List<String> chunks)
{
for (String chunk : chunks)
{
progressLabel.setText(chunk);
progressArea.append(chunk + "\n");
}
}
}
/**
* List of errors that occurred while loading cards.
*/
private List<String> errors;
/**
* Area showing past and current progress of loading.
*/
private JTextArea progressArea;
/**
* Progress bar showing overall progress of loading.
*/
private JProgressBar progressBar;
/**
* Label showing the current stage of loading.
*/
private JLabel progressLabel;
/**
* Worker that loads the inventory.
*/
private InventoryLoadWorker worker;
/**
* Create a new InventoryLoadDialog over the given {@link JFrame}.
*
* @param owner owner of the new InventoryLoadDialog
*/
public InventoryLoadDialog(JFrame owner)
{
super(owner, "Loading Inventory", Dialog.ModalityType.APPLICATION_MODAL);
setPreferredSize(new Dimension(350, 220));
setResizable(false);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
worker = null;
errors = new ArrayList<>();
// Content panel
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[]{0};
layout.columnWeights = new double[]{1.0};
layout.rowHeights = new int[]{0, 0, 0, 0};
layout.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0};
JPanel contentPanel = new JPanel(layout);
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setContentPane(contentPanel);
// Stage progress label
progressLabel = new JLabel("Loading inventory...");
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.anchor = GridBagConstraints.WEST;
labelConstraints.fill = GridBagConstraints.BOTH;
labelConstraints.gridx = 0;
labelConstraints.gridy = 0;
labelConstraints.insets = new Insets(0, 0, 2, 0);
contentPanel.add(progressLabel, labelConstraints);
// Overall progress bar
progressBar = new JProgressBar();
GridBagConstraints barConstraints = new GridBagConstraints();
barConstraints.fill = GridBagConstraints.BOTH;
barConstraints.gridx = 0;
barConstraints.gridy = 1;
barConstraints.insets = new Insets(0, 0, 2, 0);
contentPanel.add(progressBar, barConstraints);
// History text area
progressArea = new JTextArea();
progressArea.setEditable(false);
GridBagConstraints areaConstraints = new GridBagConstraints();
areaConstraints.fill = GridBagConstraints.BOTH;
areaConstraints.gridx = 0;
areaConstraints.gridy = 2;
areaConstraints.insets = new Insets(0, 0, 10, 0);
contentPanel.add(new JScrollPane(progressArea), areaConstraints);
// Cancel button
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener((e) -> {
if (worker != null)
worker.cancel(false);
});
GridBagConstraints cancelConstraints = new GridBagConstraints();
cancelConstraints.gridx = 0;
cancelConstraints.gridy = 3;
contentPanel.add(cancelButton, cancelConstraints);
pack();
}
/**
* Make this dialog visible and then begin loading the inventory. Block until it is
* complete, and then return the newly-created Inventory.
*
* @return the #Inventory that was created.
*/
public Inventory createInventory(File file)
{
worker = new InventoryLoadWorker(file);
worker.execute();
setVisible(true);
progressArea.setText("");
try
{
return worker.get();
}
catch (InterruptedException | ExecutionException e)
{
JOptionPane.showMessageDialog(null, "Error loading inventory: " + e.getCause().getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return new Inventory();
}
catch (CancellationException e)
{
return new Inventory();
}
}
} |
package edu.jhu.thrax.hadoop.jobs;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import edu.jhu.thrax.hadoop.datatypes.TextPair;
import edu.jhu.thrax.hadoop.features.WordLexicalProbabilityCalculator;
public abstract class WordLexprobJob extends ThraxJob {
public static final String SOURCE_GIVEN_TARGET = "thrax.__wordlexprob_sgt";
private boolean isSourceGivenTarget;
public WordLexprobJob(boolean isSrcGivenTgt) {
isSourceGivenTarget = isSrcGivenTgt;
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
result.add(VocabularyJob.class);
return result;
}
public Job getJob(Configuration conf) throws IOException {
Configuration theConf = new Configuration(conf);
theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget);
Job job = new Job(theConf, getName());
job.setJarByClass(WordLexicalProbabilityCalculator.class);
job.setMapperClass(WordLexicalProbabilityCalculator.Map.class);
job.setCombinerClass(IntSumReducer.class);
job.setSortComparatorClass(TextPair.SndMarginalComparator.class);
job.setPartitionerClass(WordLexicalProbabilityCalculator.Partition.class);
job.setReducerClass(WordLexicalProbabilityCalculator.Reduce.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(DoubleWritable.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file")));
int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
if (maxSplitSize != 0) {
FileInputFormat.setMaxInputSplitSize(job, maxSplitSize);
}
return job;
}
} |
package edu.washington.escience.myria;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nullable;
import net.jcip.annotations.ThreadSafe;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Ints;
import edu.washington.escience.myria.column.BooleanColumn;
import edu.washington.escience.myria.column.Column;
import edu.washington.escience.myria.column.DateTimeColumn;
import edu.washington.escience.myria.column.DoubleColumn;
import edu.washington.escience.myria.column.FloatColumn;
import edu.washington.escience.myria.column.IntColumn;
import edu.washington.escience.myria.column.LongColumn;
import edu.washington.escience.myria.column.StringColumn;
import edu.washington.escience.myria.parallel.PartitionFunction;
import edu.washington.escience.myria.proto.TransportProto.TransportMessage;
import edu.washington.escience.myria.util.IPCUtils;
import edu.washington.escience.myria.util.ImmutableBitSet;
import edu.washington.escience.myria.util.ImmutableIntArray;
/**
* Container class for a batch of tuples. The goal is to amortize memory management overhead.
*
* @author dhalperi
*
*/
@ThreadSafe
public class TupleBatch implements Serializable {
private static final long serialVersionUID = 1L;
/** The hard-coded number of tuples in a batch. */
public static final int BATCH_SIZE = 10 * 1000;
/** Class-specific magic number used to generate the hash code. */
private static final int MAGIC_HASHCODE = 243;
/** The hash function for this class. */
private static final HashFunction HASH_FUNCTION = Hashing.murmur3_32(MAGIC_HASHCODE);
/** Schema of tuples in this batch. */
private final Schema schema;
/** Tuple data stored as columns in this batch. */
private final ImmutableList<Column<?>> columns;
/** Number of valid tuples in this TB. */
private final int numValidTuples;
/** Which tuples are valid in this batch. */
private final ImmutableBitSet validTuples;
/**
* valid indices.
* */
private transient ImmutableIntArray validIndices;
/**
* If this TB is an EOI TB.
* */
private final boolean isEOI;
/** Identity mapping. */
protected static final int[] IDENTITY_MAPPING;
static {
IDENTITY_MAPPING = new int[BATCH_SIZE];
for (int i = 0; i < BATCH_SIZE; i++) {
IDENTITY_MAPPING[i] = i;
}
}
/**
* Broken-out copy constructor. Shallow copy of the schema, column list, and the number of tuples; deep copy of the
* valid tuples since that's what we mutate.
*
* @param schema schema of the tuples in this batch. Must match columns.
* @param columns contains the column-stored data. Must match schema.
* @param validTuples BitSet determines which tuples are valid tuples in this batch.
* @param validIndices valid tuple indices.
* @param isEOI eoi TB.
*/
protected TupleBatch(final Schema schema, final ImmutableList<Column<?>> columns, final ImmutableBitSet validTuples,
final ImmutableIntArray validIndices, final boolean isEOI) {
/** For a private copy constructor, no data checks are needed. Checks are only needed in the public constructor. */
this.schema = schema;
this.columns = columns;
numValidTuples = validTuples.cardinality();
this.validTuples = validTuples;
this.validIndices = validIndices;
this.isEOI = isEOI;
}
/**
* EOI TB constructor.
*
* @param schema schema of the tuples in this batch. Must match columns.
* */
private TupleBatch(final Schema schema) {
validTuples = new ImmutableBitSet(new BitSet());
this.schema = schema;
numValidTuples = 0;
ImmutableList.Builder<Column<?>> b = ImmutableList.builder();
columns = b.build();
isEOI = true;
}
/**
* @return if this TB is compact, i.e. tuples occupy from index 0 to numValidTuples-1.
* */
public final boolean isCompact() {
return validTuples.nextClearBit(0) == numValidTuples;
}
/**
* @param columnNames the new column names.
* @return a shallow copy of the specified TupleBatch with the new column names.
*/
public TupleBatch rename(final List<String> columnNames) {
return shallowCopy(Schema.of(getSchema().getColumnTypes(), columnNames), columns, validTuples, validIndices, isEOI);
}
/**
* Call this method instead of the copy constructor for a new TupleBatch copy.
*
* @param schema schema of the tuples in this batch. Must match columns.
* @param columns contains the column-stored data. Must match schema.
* @param validTuples BitSet determines which tuples are valid tuples in this batch.
* @param validIndices valid tuple indices.
* @param isEOI if is EOI
* @return shallow copy
*/
protected TupleBatch shallowCopy(final Schema schema, final ImmutableList<Column<?>> columns,
final ImmutableBitSet validTuples, @Nullable final ImmutableIntArray validIndices, final boolean isEOI) {
return new TupleBatch(schema, columns, validTuples, validIndices, isEOI);
}
/**
* Standard immutable TupleBatch constructor. All fields must be populated before creation and cannot be changed.
*
* @param schema schema of the tuples in this batch. Must match columns.
* @param columns contains the column-stored data. Must match schema.
* @param numTuples number of tuples in the batch.
*/
public TupleBatch(final Schema schema, final List<Column<?>> columns, final int numTuples) {
/* Take the input arguments directly */
this.schema = Objects.requireNonNull(schema);
Objects.requireNonNull(columns);
Preconditions.checkArgument(columns.size() == schema.numColumns(),
"Number of columns in data must equal to the number of fields in schema");
if (columns instanceof ImmutableList) {
this.columns = (ImmutableList<Column<?>>) columns;
} else {
this.columns = ImmutableList.copyOf(columns);
}
Preconditions.checkArgument(numTuples >= 0 && numTuples <= BATCH_SIZE,
"numTuples must be non negative and no more than TupleBatch.BATCH_SIZE");
numValidTuples = numTuples;
validIndices = new ImmutableIntArray(Arrays.copyOfRange(IDENTITY_MAPPING, 0, numTuples));
/* All tuples are valid */
final BitSet tmp = new BitSet(numTuples);
tmp.set(0, numTuples);
validTuples = new ImmutableBitSet(tmp);
isEOI = false;
}
/**
* Standard immutable TupleBatch constructor. All fields must be populated before creation and cannot be changed.
*
* @param schema schema of the tuples in this batch. Must match columns.
* @param columns contains the column-stored data. Must match schema.
* @param validTuples the valid tuple BitSet
*/
public TupleBatch(final Schema schema, final List<Column<?>> columns, final ImmutableBitSet validTuples) {
/* Take the input arguments directly */
this.schema = Objects.requireNonNull(schema);
Objects.requireNonNull(columns);
Preconditions.checkArgument(columns.size() == schema.numColumns(),
"Number of columns in data must equal to the number of fields in schema");
if (columns instanceof ImmutableList) {
this.columns = (ImmutableList<Column<?>>) columns;
} else {
this.columns = ImmutableList.copyOf(columns);
}
numValidTuples = validTuples.cardinality();
this.validTuples = validTuples;
isEOI = false;
}
/**
* Constructor that gets the number of tuples from the columns.
*
* @param schema schema of the tuples in this batch. Must match columns.
* @param columns contains the column-stored data. Must match schema.
*/
public TupleBatch(final Schema schema, final List<Column<?>> columns) {
this(schema, columns, columns.get(0).size());
}
/**
* Helper function to append the specified row into the specified TupleBatchBuffer.
*
* @param mappedRow the true row in column list to append to the buffer.
* @param buffer buffer the row is appended to.
*/
private void appendTupleInto(final int mappedRow, final TupleBatchBuffer buffer) {
Objects.requireNonNull(buffer);
for (int i = 0; i < numColumns(); ++i) {
buffer.put(i, columns.get(i), mappedRow);
}
}
/**
* put the tuple batch into TBB by smashing it into cells and putting them one by one.
*
* @param tbb the TBB buffer.
* */
public final void compactInto(final TupleBatchBuffer tbb) {
if (isEOI()) {
/* an EOI TB has no data */
tbb.appendTB(this);
return;
}
final int numColumns = columns.size();
ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
for (int column = 0; column < numColumns; column++) {
tbb.put(column, columns.get(column), indices.get(i));
}
}
}
/**
* Returns a new TupleBatch where all rows that do not match the specified predicate have been removed. Makes a
* shallow copy of the data, possibly resulting in slowed access to the result, but no copies.
*
* Internal implementation of a SELECT statement.
*
* @param predicate predicate by which to filter rows
* @return a new TupleBatch where all rows that do not match the specified predicate have been removed.
*/
public final TupleBatch filter(final Predicate predicate) {
BitSet newValidTuples = null;
if (numValidTuples > 0) {
ImmutableBitSet filterResult = predicate.filter(this);
newValidTuples = validTuples.cloneAsBitSet();
newValidTuples.and(filterResult);
}
if (newValidTuples != null && newValidTuples.cardinality() != validTuples.cardinality()) {
if (newValidTuples.nextClearBit(0) == newValidTuples.cardinality()) {
// compact
return new TupleBatch(schema, columns, newValidTuples.cardinality());
} else {
return shallowCopy(schema, columns, new ImmutableBitSet(newValidTuples), null, isEOI);
}
}
/* If no tuples are filtered, new TupleBatch instance is not needed */
return this;
}
/**
* Return a new TupleBatch that contains only the filtered rows of the current dataset. Note that if some of the
* tuples in this batch are invalid, we will have to map the indices in the specified filter to the "real" indices in
* the tuple.
*
* @param filter the rows to be retained.
* @return a TupleBatch that contains only the filtered rows of the current dataset.
*/
public final TupleBatch filter(final BitSet filter) {
/* Shortcut 1: the filter is full, so all current tuples are retained. Just return this. */
if (filter.cardinality() == numTuples()) {
return this;
}
/* Shortcut 2: all current tuples in this batch are valid. filter actually is indexed correctly. */
if (validTuples.cardinality() == validTuples.size()) {
return new TupleBatch(getSchema(), getDataColumns(), new ImmutableBitSet(filter));
}
/* Okay, we have to do work. */
BitSet realFilter = new BitSet(validTuples.size());
int[] realValidIndices = new int[filter.cardinality()];
int row = 0;
for (int i = filter.nextSetBit(0); i >= 0; i = filter.nextSetBit(i + 1)) {
int realIndex = getValidIndices().get(i);
realFilter.set(realIndex);
realValidIndices[row] = realIndex;
++row;
}
return new TupleBatch(getSchema(), getDataColumns(), new ImmutableBitSet(realFilter), new ImmutableIntArray(
realValidIndices), false);
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final boolean getBoolean(final int column, final int row) {
return ((BooleanColumn) columns.get(column)).getBoolean(getValidIndices().get(row));
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final double getDouble(final int column, final int row) {
return ((DoubleColumn) columns.get(column)).getDouble(getValidIndices().get(row));
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final float getFloat(final int column, final int row) {
return ((FloatColumn) columns.get(column)).getFloat(getValidIndices().get(row));
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final int getInt(final int column, final int row) {
return ((IntColumn) columns.get(column)).getInt(getValidIndices().get(row));
}
/**
* store this TB into JDBC.
*
* @param statement JDBC statement.
* @throws SQLException any exception caused by JDBC.
* */
public final void getIntoJdbc(final PreparedStatement statement) throws SQLException {
ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
int column = 0;
for (final Column<?> c : columns) {
c.getIntoJdbc(indices.get(i), statement, ++column);
}
statement.addBatch();
}
}
/**
* store this TB into SQLite.
*
* @param statement SQLite statement.
* @throws SQLiteException any exception caused by SQLite.
* */
public final void getIntoSQLite(final SQLiteStatement statement) throws SQLiteException {
ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
int column = 0;
for (final Column<?> c : columns) {
c.getIntoSQLite(indices.get(i), statement, ++column);
}
statement.step();
statement.reset();
}
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final long getLong(final int column, final int row) {
return ((LongColumn) columns.get(column)).getLong(getValidIndices().get(row));
}
/**
* @param column the column of the desired value.
* @param row the row of the desired value.
* @return the value in the specified column and row.
*/
public final Object getObject(final int column, final int row) {
return columns.get(column).get(getValidIndices().get(row));
}
/**
* Returns the Schema of the tuples in this batch.
*
* @return the Schema of the tuples in this batch.
*/
public final Schema getSchema() {
return schema;
}
/**
* Returns the element at the specified column and row position.
*
* @param column column in which the element is stored.
* @param row row in which the element is stored.
* @return the element at the specified position in this TupleBatch.
*/
public final String getString(final int column, final int row) {
return ((StringColumn) columns.get(column)).getString(getValidIndices().get(row));
}
/**
* Returns the element at the specified column and row position.
*
* @param column column in which the element is stored.
* @param row row in which the element is stored.
* @return the element at the specified position in this TupleBatch.
*/
public final DateTime getDateTime(final int column, final int row) {
return ((DateTimeColumn) columns.get(column)).getDateTime(getValidIndices().get(row));
}
/**
* Do groupby on this TupleBatch and return the set of (GroupByKey, TupleBatchBuffer) pairs which have filled
* TupleBatches.
*
* @return the set of (GroupByKey, TupleBatchBuffer).
* @param groupByColumn the column index for doing group by.
* @param buffers the data buffers for holding the groupby results.
* */
public final Set<Pair<Object, TupleBatchBuffer>> groupby(final int groupByColumn,
final Map<Object, Pair<Object, TupleBatchBuffer>> buffers) {
Set<Pair<Object, TupleBatchBuffer>> ready = null;
final Column<?> gC = columns.get(groupByColumn);
ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
int row = indices.get(i);
final Object v = gC.get(row);
Pair<Object, TupleBatchBuffer> kvPair = buffers.get(v);
TupleBatchBuffer tbb = null;
if (kvPair == null) {
tbb = new TupleBatchBuffer(getSchema());
kvPair = Pair.of(v, tbb);
buffers.put(v, kvPair);
} else {
tbb = kvPair.getRight();
}
int j = 0;
for (final Column<?> c : columns) {
tbb.put(j++, c, row);
}
if (tbb.hasFilledTB()) {
if (ready == null) {
ready = new HashSet<Pair<Object, TupleBatchBuffer>>();
}
ready.add(kvPair);
}
}
return ready;
}
/**
* @param row the row to be hashed.
* @return the hash of the tuples in the specified row.
*/
public final int hashCode(final int row) {
Hasher hasher = HASH_FUNCTION.newHasher();
final int mappedRow = getValidIndices().get(row);
for (Column<?> c : columns) {
c.addToHasher(mappedRow, hasher);
}
return hasher.hash().asInt();
}
/**
* Returns the hash code for the specified tuple using the specified key columns.
*
* @param row row of tuple to hash.
* @param hashColumns key columns for the hash.
* @return the hash code value for the specified tuple using the specified key columns.
*/
public final int hashCode(final int row, final int[] hashColumns) {
Objects.requireNonNull(hashColumns);
Hasher hasher = HASH_FUNCTION.newHasher();
final int mappedRow = getValidIndices().get(row);
for (final int i : hashColumns) {
Column<?> c = columns.get(i);
c.addToHasher(mappedRow, hasher);
}
return hasher.hash().asInt();
}
/**
* Returns the hash code for a single cell.
*
* @param row row of tuple to hash.
* @param hashColumn the key column for the hash.
* @return the hash code value for the specified tuple using the specified key columns.
*/
public final int hashCode(final int row, final int hashColumn) {
Hasher hasher = HASH_FUNCTION.newHasher();
final int mappedRow = getValidIndices().get(row);
Column<?> c = columns.get(hashColumn);
c.addToHasher(mappedRow, hasher);
return hasher.hash().asInt();
}
/**
* The number of columns in this TupleBatch.
*
* @return number of columns in this TupleBatch.
*/
public final int numColumns() {
return schema.numColumns();
}
/**
* Returns the number of valid tuples in this TupleBatch.
*
* @return the number of valid tuples in this TupleBatch.
*/
public final int numTuples() {
return numValidTuples;
}
/**
* Partition this TB using the partition function.
*
* @param pf the partition function.
* @param buffers the buffers storing the partitioned data.
* */
public final void partition(final PartitionFunction pf, final TupleBatchBuffer[] buffers) {
final int numColumns = numColumns();
final int[] partitions = pf.partition(this);
ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < partitions.length; i++) {
final int pOfTuple = partitions[i];
final int mappedI = indices.get(i);
for (int j = 0; j < numColumns; j++) {
buffers[pOfTuple].put(j, columns.get(j), mappedI);
}
}
}
/**
* Partition this TB using the partition function. The method is implemented by shallow copy of TupleBatches.
*
* @return an array of TBs. The length of the array is the same as the number of partitions. If no tuple presents in a
* partition, say the i'th partition, the i'th element in the result array is null.
* @param pf the partition function.
* */
public final TupleBatch[] partition(final PartitionFunction pf) {
TupleBatch[] result = new TupleBatch[pf.numPartition()];
if (isEOI) {
Arrays.fill(result, this);
return result;
}
final int[] partitions = pf.partition(this);
final ImmutableIntArray mapping = getValidIndices();
BitSet[] resultBitSet = new BitSet[result.length];
for (int i = 0; i < partitions.length; i++) {
int p = partitions[i];
int actualRow = mapping.get(i);
if (resultBitSet[p] == null) {
resultBitSet[p] = new BitSet(actualRow + 1);
}
resultBitSet[p].set(actualRow);
}
for (int i = 0; i < result.length; i++) {
if (resultBitSet[i] != null) {
result[i] = shallowCopy(schema, columns, new ImmutableBitSet(resultBitSet[i]), null, isEOI);
}
}
return result;
}
/**
* Hash the valid tuples in this batch and partition them into the supplied TupleBatchBuffers. This is a useful helper
* primitive for, e.g., the Scatter operator.
*
* @param destinations TupleBatchBuffers into which these tuples will be partitioned.
* @param hashColumns determines the key columns for the hash.
*/
final void partitionInto(final TupleBatchBuffer[] destinations, final int[] hashColumns) {
Objects.requireNonNull(destinations);
Objects.requireNonNull(hashColumns);
final ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
int dest = hashCode(indices.get(i), hashColumns) % destinations.length;
/* hashCode can be negative, so wrap positive if necessary */
if (dest < destinations.length) {
dest += destinations.length;
}
appendTupleInto(indices.get(i), destinations[dest]);
}
}
/**
* Creates a new TupleBatch with only the indicated columns.
*
* Internal implementation of column selection, like a relational algebra project operator but without duplicate
* elimination.
*
* @param remainingColumns zero-indexed array of columns to retain.
* @return a TupleBatch with only the specified columns remaining.
*/
public final TupleBatch selectColumns(final int[] remainingColumns) {
Objects.requireNonNull(remainingColumns);
final ImmutableList.Builder<Type> newTypes = new ImmutableList.Builder<Type>();
final ImmutableList.Builder<String> newNames = new ImmutableList.Builder<String>();
final ImmutableList.Builder<Column<?>> newColumns = new ImmutableList.Builder<Column<?>>();
for (final int i : remainingColumns) {
newColumns.add(columns.get(i));
newTypes.add(schema.getColumnType(i));
newNames.add(schema.getColumnName(i));
}
return shallowCopy(new Schema(newTypes, newNames), newColumns.build(), validTuples, validIndices, isEOI);
}
/**
* Creates a new TupleBatch with only the indicated columns.
*
* Internal implementation of column selection, like a relational algebra project operator but without duplicate
* elimination.
*
* @param remainingColumns zero-indexed array of columns to retain.
* @return a TupleBatch with only the specified columns remaining.
*/
public final TupleBatch selectColumns(final Integer[] remainingColumns) {
Objects.requireNonNull(remainingColumns);
return selectColumns(Ints.toArray(Arrays.asList(remainingColumns)));
}
/**
* Creates a new TupleBatch with only the indicated columns.
*
* Internal implementation of a (non-duplicate-eliminating) PROJECT statement.
*
* @param remainingColumns zero-indexed array of columns to retain.
* @param resultSchema computing a schema every time is usually not necessary
* @return a projected TupleBatch.
*/
public final TupleBatch selectColumns(final int[] remainingColumns, final Schema resultSchema) {
Objects.requireNonNull(remainingColumns);
final ImmutableList.Builder<Column<?>> newColumns = new ImmutableList.Builder<Column<?>>();
for (final int i : remainingColumns) {
newColumns.add(columns.get(i));
}
return shallowCopy(resultSchema, newColumns.build(), validTuples, validIndices, isEOI);
}
/**
* @param tupleIndicesToRemove the indices to remove
* @return a new TB.
* */
public final TupleBatch remove(final BitSet tupleIndicesToRemove) {
final ImmutableIntArray indices = getValidIndices();
final BitSet newValidTuples = validTuples.cloneAsBitSet();
for (int i = tupleIndicesToRemove.nextSetBit(0); i >= 0; i = tupleIndicesToRemove.nextSetBit(i + 1)) {
newValidTuples.clear(indices.get(i));
}
if (newValidTuples.cardinality() != numValidTuples) {
return shallowCopy(schema, columns, new ImmutableBitSet(newValidTuples), null, isEOI);
} else {
return this;
}
}
@Override
public final String toString() {
if (isEOI) {
return "EOI";
}
final List<Type> columnTypes = schema.getColumnTypes();
final StringBuilder sb = new StringBuilder();
final ImmutableIntArray indices = getValidIndices();
for (int i = 0; i < indices.length(); i++) {
sb.append("|\t");
for (int j = 0; j < schema.numColumns(); j++) {
sb.append(columnTypes.get(j).toString(columns.get(j), indices.get(i)));
sb.append("\t|\t");
}
sb.append('\n');
}
return sb.toString();
}
/**
* For the representation with a BitSet listing which rows are valid, generate and return an array containing the
* indices of all valid rows.
*
* Since we are now using index mapping, it's unnecessary to expose the filtered/removed tuples
*
* @return a list containing the indices of all valid rows.
*/
public final ImmutableIntArray getValidIndices() {
if (validIndices != null) {
return validIndices;
}
int[] validIndicesTmp = new int[numValidTuples];
int i = 0;
for (int valid = validTuples.nextSetBit(0); valid >= 0; valid = validTuples.nextSetBit(valid + 1)) {
validIndicesTmp[i] = valid;
i++;
}
if (validIndices == null) {
validIndices = new ImmutableIntArray(validIndicesTmp);
}
return validIndices;
}
/**
* @return the data columns. Work together with the valid indices.
* */
public final ImmutableList<Column<?>> getDataColumns() {
return columns;
}
/**
* @return expose valid tuple BitSet.
* */
public final ImmutableBitSet getValidTuples() {
return validTuples;
}
/**
* Check whether left (in this tuple batch) and right (in the tuple batch rightTb) tuples match w.r.t. columns in
* leftCompareIndx and rightCompareIndex. This method is used in equi-join operators.
*
* @param leftIdx the index of the left tuple in this tuple batch
* @param leftCompareIdx an array specifying the columns of the left tuple to be used in the comparison
* @param rightTb the tuple batch containing the right tuple
* @param rightIdx the index of the right tuple in the rightTb tuple batch
* @param rightCompareIdx an array specifying the columns of the right tuple to be used in the comparison
* @return true if the tuples match
* */
public final boolean tupleMatches(final int leftIdx, final int[] leftCompareIdx, final TupleBatch rightTb,
final int rightIdx, final int[] rightCompareIdx) {
for (int i = 0; i < leftCompareIdx.length; ++i) {
if (!columns.get(leftCompareIdx[i]).equals(getValidIndices().get(leftIdx),
rightTb.columns.get(rightCompareIdx[i]), rightTb.getValidIndices().get(rightIdx))) {
return false;
}
}
return true;
}
/**
* @return a TransportMessage encoding the TupleBatch.
* */
public final TransportMessage toTransportMessage() {
if (isCompact()) {
return IPCUtils.normalDataMessage(columns, numValidTuples);
} else {
TupleBatchBuffer tbb = new TupleBatchBuffer(getSchema());
compactInto(tbb);
return IPCUtils.normalDataMessage(tbb.popAnyAsRawColumn(), numValidTuples);
}
}
/**
* Create an EOI TupleBatch.
*
* @param schema schema.
* @return EOI TB for the schema.
* */
public static final TupleBatch eoiTupleBatch(final Schema schema) {
return new TupleBatch(schema);
}
/**
* @return if the TupleBatch is an EOI.
* */
public final boolean isEOI() {
return isEOI;
}
/**
* Check if a tuple in uniqueTuples equals to the comparing tuple (cntTuple).
*
* @param hashTable the TupleBatchBuffer holding the tuples to compare against
* @param index the index in the hashTable
* @param row row number of the tuple to compare
* @param compareColumns1 the comparing list of columns of cntTuple
* @param compareColumns2 the comparing list of columns of hashTable
* @return true if equals.
*/
public boolean tupleEquals(final int row, final TupleBuffer hashTable, final int index, final int[] compareColumns1,
final int[] compareColumns2) {
if (compareColumns1.length != compareColumns2.length) {
return false;
}
for (int i = 0; i < compareColumns1.length; ++i) {
switch (schema.getColumnType(compareColumns1[i])) {
case BOOLEAN_TYPE:
if (getBoolean(compareColumns1[i], row) != hashTable.getBoolean(compareColumns2[i], index)) {
return false;
}
break;
case DOUBLE_TYPE:
if (getDouble(compareColumns1[i], row) != hashTable.getDouble(compareColumns2[i], index)) {
return false;
}
break;
case FLOAT_TYPE:
if (getFloat(compareColumns1[i], row) != hashTable.getFloat(compareColumns2[i], index)) {
return false;
}
break;
case INT_TYPE:
if (getInt(compareColumns1[i], row) != hashTable.getInt(compareColumns2[i], index)) {
return false;
}
break;
case LONG_TYPE:
if (getLong(compareColumns1[i], row) != hashTable.getLong(compareColumns2[i], index)) {
return false;
}
break;
case STRING_TYPE:
if (!getString(compareColumns1[i], row).equals(hashTable.getString(compareColumns2[i], index))) {
return false;
}
break;
case DATETIME_TYPE:
if (!getDateTime(compareColumns1[i], row).equals(hashTable.getDateTime(compareColumns2[i], index))) {
return false;
}
break;
}
}
return true;
}
} |
package edu.wustl.xipHost.dicom;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.nema.dicom.wg23.Modality;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.Uid;
import org.nema.dicom.wg23.Uuid;
import com.pixelmed.database.DatabaseInformationModel;
import com.pixelmed.database.PatientStudySeriesConcatenationInstanceModel;
import com.pixelmed.dicom.Attribute;
import com.pixelmed.dicom.AttributeList;
import com.pixelmed.dicom.AttributeTag;
import com.pixelmed.dicom.DicomDictionary;
import com.pixelmed.dicom.DicomException;
import com.pixelmed.dicom.TagFromName;
import com.pixelmed.network.DicomNetworkException;
import com.pixelmed.network.VerificationSOPClassSCU;
import com.pixelmed.query.QueryInformationModel;
import com.pixelmed.query.QueryTreeModel;
import com.pixelmed.query.QueryTreeRecord;
import com.pixelmed.query.StudyRootQueryInformationModel;
import com.pixelmed.server.DicomAndWebStorageServer;
import edu.wustl.xipHost.dataModel.ImageItem;
import edu.wustl.xipHost.dataModel.Item;
import edu.wustl.xipHost.dataModel.Patient;
import edu.wustl.xipHost.dataModel.SearchResult;
import edu.wustl.xipHost.dataModel.Series;
import edu.wustl.xipHost.dataModel.Study;
import edu.wustl.xipHost.hostControl.HostConfigurator;
import edu.wustl.xipHost.iterator.Criteria;
public class DicomManagerImpl implements DicomManager{
final static Logger logger = Logger.getLogger(DicomManagerImpl.class);
Document documentPacs;
Element rootPacs;
SAXBuilder builder = new SAXBuilder();
List<PacsLocation> pacsLocations = new ArrayList<PacsLocation>();
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#loadPacsLocations(java.io.File)
*/
public boolean loadPacsLocations(File file) throws IOException, JDOMException {
documentPacs = builder.build(file);
rootPacs = documentPacs.getRootElement();
List<?> children = rootPacs.getChildren("pacs_location");
for (int i = 0; i < children.size(); i++){
String address = (((Element)children.get(i)).getChildText("hostAddress"));
int port = Integer.valueOf((((Element)children.get(i)).getChildText("hostPort")));
String aeTitle = (((Element)children.get(i)).getChildText("hostAETitle"));
String shortName = (((Element)children.get(i)).getChildText("hostShortName"));
/*System.out.println(address);
System.out.println(port);
System.out.println(aeTitle);*/
try {
PacsLocation loc = new PacsLocation(address, port, aeTitle, shortName);
pacsLocations.add(loc);
} catch (IllegalArgumentException e) {
//Prints invalid location and proceeds to load next one
System.out.println("Unable to load: " + address + " " + port + " " + aeTitle + " " + shortName + " - invalid location.");
}
}
return true;
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#storePacsLocations(java.util.List, java.io.File)
*/
public boolean storePacsLocations(List<PacsLocation> locations, File file) throws FileNotFoundException {
Element rootSave = new Element("locations");
Document document = new Document();
document.setRootElement(rootSave);
if(locations == null){return false;}
for(int i = 0; i < locations.size(); i++){
Element pacsElem = new Element("pacs_location");
Element addressElem = new Element("hostAddress");
Element portElem = new Element("hostPort");
Element aeTitleElem = new Element("hostAETitle");
Element shortNameElem = new Element("hostShortName");
pacsElem.addContent(addressElem);
pacsElem.addContent(portElem);
pacsElem.addContent(aeTitleElem);
pacsElem.addContent(shortNameElem);
rootSave.addContent(pacsElem);
addressElem.addContent(locations.get(i).getAddress());
portElem.addContent(String.valueOf(locations.get(i).getPort()));
aeTitleElem.addContent(locations.get(i).getAETitle());
shortNameElem.addContent(locations.get(i).getShortName());
}
try {
FileOutputStream outStream = new FileOutputStream(file);
XMLOutputter outToXMLFile = new XMLOutputter();
outToXMLFile.setFormat(Format.getPrettyFormat());
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#addPacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean addPacsLocation(PacsLocation pacsLocation){
try {
if(!pacsLocations.contains(pacsLocation)){
return pacsLocations.add(pacsLocation);
} else {
return false;
}
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#modifyPacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation, edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean modifyPacsLocation(PacsLocation oldPacsLocation, PacsLocation newPacsLocation) {
//validate method is used to check if parameters are valid, are notmissing,
//do not contain empty strings or do not start from white spaces
try {
int i = pacsLocations.indexOf(oldPacsLocation);
if (i != -1){
pacsLocations.set(i, newPacsLocation);
return true;
} else{
return false;
}
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#removePacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean removePacsLocation(PacsLocation pacsLocation){
//System.out.println(pacsLocations.indexOf(pacsLocation));
try {
return pacsLocations.remove(pacsLocation);
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#getPacsLocations()
*/
public List<PacsLocation> getPacsLocations(){
return pacsLocations;
}
QueryTreeModel mTree = null;
QueryInformationModel mModel = null;
String calledAETitle;
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#query(com.pixelmed.dicom.AttributeList, edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public SearchResult query(AttributeList criteria, PacsLocation location) {
if(criteria == null || location == null){
return null;
}
//Connecting to the server
logger.debug("Queried source: " + location.toString());
String hostName = location.getAddress();
int port = location.getPort();
calledAETitle = location.getAETitle();
//ensure callingAETitle is not empty (not all stations allow empty value).
String callingAETitle = "";
if(HostConfigurator.getHostConfigurator() != null){
callingAETitle = HostConfigurator.getHostConfigurator().getAETitle();
}
if (callingAETitle == "") {
callingAETitle = "WS_XIP";
}
mModel = new StudyRootQueryInformationModel(hostName, port, calledAETitle, callingAETitle, 0);
try {
new VerificationSOPClassSCU(hostName, port, calledAETitle, callingAETitle, false, 0);
}catch (Exception e) {
return null;
}
SearchResult returnResult = null;
try {
//mTree hangs when supplied callingAETitle is an empty string
mTree = mModel.performHierarchicalQuery(criteria);
result = new SearchResult(location.hostShortName);
Map<Integer, Object> dicomCriteria = DicomUtil.convertToADDicomCriteria(criteria);
Map<String, Object> aimCriteria = new HashMap<String, Object>();
Criteria originalCriteria = new Criteria(dicomCriteria, aimCriteria);
result.setOriginalCriteria(originalCriteria);
Object root = mTree.getRoot();
returnResult = (SearchResult) resolveToSearchResult(root);
if(logger.isDebugEnabled()){
Iterator<Patient> patients = result.getPatients().iterator();
while(patients.hasNext()){
Patient patient = patients.next();
Timestamp patientLastUpdated = patient.getLastUpdated();
String strPatientLastUpdated = null;
if(patientLastUpdated != null){
strPatientLastUpdated = patientLastUpdated.toString();
}
logger.debug(patient.toString() + " Last updated: " + strPatientLastUpdated);
Iterator<Study> studies = patient.getStudies().iterator();
while(studies.hasNext()){
Study study = studies.next();
Timestamp studyLastUpdated = study.getLastUpdated();
String strStudyLastUpdated = null;
if(studyLastUpdated != null){
strStudyLastUpdated = studyLastUpdated.toString();
}
logger.debug(" " + study.toString() + " Last updated: " + strStudyLastUpdated);
Iterator<Series> series = study.getSeries().iterator();
while(series.hasNext()){
Series oneSeries = series.next();
Timestamp seriesLastUpdated = oneSeries.getLastUpdated();
String strSeriesLastUpdated = null;
if(seriesLastUpdated != null){
strSeriesLastUpdated = seriesLastUpdated.toString();
}
logger.debug(" " + oneSeries.toString() + " Last updated: " + strSeriesLastUpdated);
Iterator<Item> images = oneSeries.getItems().iterator();
while(images.hasNext()){
logger.debug(" " + images.next().toString());
}
}
}
}
}
} catch (IOException e) {
return null;
} catch (DicomException e) {
return null;
} catch (DicomNetworkException e) {
return null;
}
return returnResult;
}
Patient patient = null;
Study study = null;
Series series = null;
SearchResult result;
SearchResult resolveToSearchResult(Object node) {
int numChildren = mTree.getChildCount(node);
for(int i = 0; i < numChildren; i++){
Object child = mTree.getChild(node, i);
//find if child is Study, Series or Image
//Case approach
String level = getRetrieveLevel(child);
Timestamp lastUpdated = new Timestamp(Calendar.getInstance().getTime().getTime());
if(level.equalsIgnoreCase("Study")){
String patientName = attValues.get("(0x0010,0x0010)");
if(patientName == null){patientName = "";}
String patientID = attValues.get("(0x0010,0x0020)");
if(patientID == null){patientID = "";}
String patientBirthDate = attValues.get("(0x0010,0x0030)");
if(patientBirthDate == null){patientBirthDate = "";}
patient = new Patient(patientName, patientID, patientBirthDate);
//patient.setLastUpdated(lastUpdated);
if(!result.contains(patientID)){
result.addPatient(patient);
} else {
patient = result.getPatient(patientID);
}
String studyDate = attValues.get("(0x0008,0x0020)");
if(studyDate == null){studyDate = "";}
String studyID = attValues.get("(0x0020,0x0010)");
if(studyID == null){studyID = "";}
String studyDesc = attValues.get("(0x0008,0x1030)");
if(studyDesc == null){studyDesc = "";}
String studyInstanceUID = attValues.get("(0x0020,0x000D)");
if(studyInstanceUID == null){studyInstanceUID = "";}
study = new Study(studyDate, studyID, studyDesc, studyInstanceUID);
if(!patient.contains(studyInstanceUID)){
patient.addStudy(study);
} else {
study = patient.getStudy(studyInstanceUID);
}
patient.setLastUpdated(lastUpdated);
resolveToSearchResult(child);
}else if(level.equalsIgnoreCase("Series")){
String seriesNumber = attValues.get("(0x0020,0x0011)");
if(seriesNumber == null){seriesNumber = "";}
String modality = attValues.get("(0x0008,0x0060)");
if(modality == null){modality = "";}
String seriesDesc = attValues.get("(0x0008,0x103E)");
if(seriesDesc == null){seriesDesc = "";}
String seriesInstanceUID = attValues.get("(0x0020,0x000E)");
if(seriesInstanceUID == null){seriesInstanceUID = "";}
series = new Series(seriesNumber, modality, seriesDesc, seriesInstanceUID);
if(!study.contains(seriesInstanceUID)){
study.addSeries(series);
} else {
series = study.getSeries(seriesInstanceUID);
}
study.setLastUpdated(lastUpdated);
resolveToSearchResult(child);
}else if(level.equalsIgnoreCase("Image")){
String imageNumber = attValues.get("(0x0008,0x0018)"); //SOPIntanceUID
String sopClassUID = attValues.get("(0x0008,0x0016)"); //SOPClassUID
String modCode = attValues.get("(0x0008,0x0060)"); //Modality
if(imageNumber == null){imageNumber = "";}
Item image = new ImageItem(imageNumber);
if(!series.contains(imageNumber)){
series.addItem(image);
ObjectDescriptor objDesc = new ObjectDescriptor();
Uuid objDescUUID = new Uuid();
objDescUUID.setUuid(UUID.randomUUID().toString());
objDesc.setUuid(objDescUUID);
objDesc.setMimeType("application/dicom");
Uid uid = new Uid();
String classUID = sopClassUID;
uid.setUid(classUID);
objDesc.setClassUID(uid);
Modality modality = new Modality();
modality.setModality(modCode);
objDesc.setModality(modality);
image.setObjectDescriptor(objDesc);
}
series.setLastUpdated(lastUpdated);
}else{
return null;
}
}
return result;
}
Map<String, String> attValues;
/**
*
* @param node
* @return
*/
String getRetrieveLevel(Object node){
attValues = new HashMap<String, String>();
if (node instanceof QueryTreeRecord) {
QueryTreeRecord r = (QueryTreeRecord)node;
AttributeList keys = r.getUniqueKeys();
String seriesInstanceUID = Attribute.getSingleStringValueOrNull(keys, TagFromName.SeriesInstanceUID);
String studyInstanceUID = Attribute.getSingleStringValueOrNull(keys, TagFromName.StudyInstanceUID);
attValues.put("(0x0020,0x000D)", studyInstanceUID);
attValues.put("(0x0020,0x000E)", seriesInstanceUID);
AttributeList identifier = r.getAllAttributesReturnedInIdentifier();
DicomDictionary dictionary = AttributeList.getDictionary();
Iterator<?> iter = dictionary.getTagIterator();
String strAtt = null;
String attValue = null;
while(iter.hasNext()){
AttributeTag attTag = (AttributeTag)iter.next();
strAtt = attTag.toString();
attValue = Attribute.getSingleStringValueOrEmptyString(identifier, attTag);
//put only those attributes non empty and non null
if(!attValue.isEmpty()){
//System.out.println(strAtt + " " + attValue);
attValues.put(strAtt, attValue);
}
}
}
String level = attValues.get("(0x0008,0x0052)");
return level;
}
BasicDicomParser2 parser = new BasicDicomParser2();
public boolean submit(File[] dicomFiles, PacsLocation location) {
for(int i = 0; i < dicomFiles.length; i++){
AttributeList attList = parser.parse(dicomFiles[i]);
try {
dbModel.insertObject(attList, dicomFiles[i].getAbsolutePath(), "R");
} catch (DicomException e) {
logger.error(e, e);
return false;
}
}
return true;
}
Boolean isServerReady = false;
File xmlPacsLocFile = new File("./config/pacs_locations.xml");
public void runDicomStartupSequence(String hsqldbServerConfigFilePath, Properties pixelmedProp) {
startHSQLDB(hsqldbServerConfigFilePath);
startPixelmedServer(pixelmedProp);
dbFileName = prop.getProperty("Application.DatabaseFileName");
setDBModel(dbFileName);
}
public boolean runDicomShutDownSequence(String connectionPath, String user, String password){
logger.debug("Running DICOM shutdown sequence.");
closeDicomServer(connectionPath, user, password);
return true;
}
Connection conn;
public void closeDicomServer(String connectionPath, String user, String password){
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException e1) {
logger.error(e1, e1);
}
try {
conn = DriverManager.getConnection(connectionPath, user, password);
if(conn.isClosed() == false){
Statement st = conn.createStatement();
boolean bln = st.execute("SHUTDOWN");
if(bln){
conn.close();
}
}
} catch (SQLException e) {
logger.error("ERROR detected when shuting down DICOM Pixelmed and HSQLDB servers");
logger.error(e, e);
}
}
Server hsqldbServer;
public void startHSQLDB(String hsqldbServerConfigFilePath ) {
hsqldbServer = new Server();
hsqldbServer.putPropertiesFromFile(hsqldbServerConfigFilePath);
hsqldbServer.start();
}
DicomAndWebStorageServer server;
Properties prop = new Properties();
public boolean startPixelmedServer(Properties prop){
try {
this.prop = prop;
server = new DicomAndWebStorageServer(this.prop);
} catch (FileNotFoundException e) {
logger.error(e, e);
return false;
} catch (IOException e) {
logger.error(e, e);
return false;
} catch (DicomException e) {
logger.error(e, e);
return false;
} catch (DicomNetworkException e) {
logger.error(e, e);
return false;
}
return true;
}
DatabaseInformationModel dbModel = null;
public DatabaseInformationModel getDBModel(){
return dbModel;
}
public void setDBModel(String dbModel){
try {
this.dbModel = new PatientStudySeriesConcatenationInstanceModel(dbModel);
} catch (DicomException e) {
logger.error(e, e);
}
}
String dbFileName;
public String getDBFileName(){
return dbFileName;
}
public void closeHSQLDB(){
hsqldbServer.shutdown();
}
@Override
public PacsLocation getDefaultCallingPacsLocation() {
return callingPacsLocation;
}
PacsLocation callingPacsLocation;
public void setDefaultCallingPacsLocation(PacsLocation callingPacsLocation){
this.callingPacsLocation = callingPacsLocation;
}
} |
package com.aragaer.jtt;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity implements OnPreferenceChangeListener, OnPreferenceClickListener, DialogInterface.OnClickListener {
public static final String PREF_LOCATION = "jtt_loc",
PREF_LOCALE = "jtt_locale",
PREF_HNAME = "jtt_hname",
PREF_NOTIFY = "jtt_notify",
PREF_WIDGET_INVERSE = "jtt_widget_text_invert";
private static final String prefcodes[] = new String[] {PREF_LOCATION, PREF_NOTIFY, PREF_WIDGET_INVERSE, PREF_LOCALE, "jtt_theme", PREF_HNAME};
private final Map<String, Integer> listeners = new HashMap<String, Integer>();
public boolean onPreferenceChange(Preference preference, Object newValue) {
switch (listeners.get(preference.getKey())) {
case 3:
case 4:
Intent i = getParent().getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
getParent().finish();
startActivity(i);
break;
case 5:
final ListPreference lp = (ListPreference) preference;
lp.setSummary(lp.getEntries()[lp.findIndexOfValue((String) newValue)]);
break;
default:
break;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
ListPreference pref_locale = (ListPreference) findPreference(PREF_LOCALE);
final CharSequence[] llist = pref_locale.getEntryValues();
final CharSequence[] lnames = new CharSequence[llist.length];
lnames[0] = getString(R.string.locale_default);
for (int i = 1; i < llist.length; i++) {
final Locale l = new Locale(llist[i].toString());
lnames[i] = l.getDisplayLanguage(l);
}
pref_locale.setEntries(lnames);
((Preference) findPreference("jtt_stop")).setOnPreferenceClickListener(this);
for (int i = 0; i < prefcodes.length; i++) {
listeners.put(prefcodes[i], i);
final Preference pref = (Preference) findPreference(prefcodes[i]);
pref.setOnPreferenceChangeListener(this);
if (pref instanceof ListPreference) {
final ListPreference lp = (ListPreference) pref;
lp.setSummary(lp.getEntry());
}
}
}
public boolean onPreferenceClick(Preference preference) {
(new AlertDialog.Builder(this))
.setTitle(R.string.stop)
.setMessage(R.string.stop_ask)
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(android.R.string.no, this).show();
return false;
}
public void onClick(DialogInterface dialog, int id) {
if (id == Dialog.BUTTON_POSITIVE) {
startService(new Intent(this, JttService.class).setAction(JttService.STOP_ACTION));
getParent().finish();
} else
dialog.cancel();
}
public static float[] getLocation(final Context context) {
String[] ll = PreferenceManager
.getDefaultSharedPreferences(context)
.getString(PREF_LOCATION, LocationPreference.DEFAULT)
.split(":");
try {
return new float[] { Float.parseFloat(ll[0]), Float.parseFloat(ll[1]) };
} catch (NumberFormatException e) {
return new float[] { 0, 0 };
}
}
static final int themes[] = {R.style.JTTTheme, R.style.DarkTheme};
public static final int getTheme(final Context context) {
String theme = PreferenceManager
.getDefaultSharedPreferences(context)
.getString("jtt_theme", context.getString(R.string.theme_default));
try {
return themes[Integer.parseInt(theme)];
} catch (NumberFormatException e) {
return themes[0];
}
}
} |
package com.dg.http;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
public class HttpResponse
{
private static final String DATE_FORMAT_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
private static final String DATE_FORMAT_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
private static final String DATE_FORMAT_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
private static final Charset utf8Charset = Charset.forName("UTF8");
private static final int MAX_SIZE_TO_ALLOW_IN_MEMORY = 8192; // When we do not know the Content-Length in advance, we build the request in memory, or in file if it's too big or unknown.
private static final int BUFFER_SIZE = 4096;
private boolean autoDecompress = true;
private boolean isBuffered = false;
private byte[] memoryBuffer = null;
private File fileBuffer = null;
private HttpURLConnection connection;
private int statusCode;
private String statusMessage;
private Map<String, List<String>> headers;
private static final String[] EMPTY_STRING_ARRAY = new String[]{ };
private String originalCharset;
private Charset charset;
private URL url;
public HttpResponse(HttpURLConnection connection) throws IOException
{
this.connection = connection;
this.autoDecompress = true;
readHeaders();
}
public HttpResponse(HttpURLConnection connection, boolean autoDecompress) throws IOException
{
this.connection = connection;
this.autoDecompress = autoDecompress;
readHeaders();
}
private void readHeaders() throws IOException
{
statusCode = this.connection.getResponseCode();
statusMessage = this.connection.getResponseMessage();
headers = this.connection.getHeaderFields();
originalCharset = getHeaderParameter(Headers.CONTENT_TYPE, "charset");
if (originalCharset != null && originalCharset.length() > 0)
{
charset = Charset.forName(originalCharset);
}
else
{
charset = utf8Charset;
}
url = this.connection.getURL();
}
public int getStatusCode()
{
return statusCode;
}
public String getStatusMessage()
{
return statusMessage;
}
public URL getURL()
{
return url;
}
public Map<String, List<String>> getHeaders()
{
return headers;
}
public String[] getHeaders(final String name)
{
List<String> list = headers.get(name);
if (list != null)
{
return list.toArray(new String[list.size()]);
}
return EMPTY_STRING_ARRAY;
}
public String getHeader(final String name)
{
List<String> list = headers.get(name);
if (list != null)
{
return list.isEmpty() ? null : list.get(0);
}
return null;
}
public Date getDateHeader(final String name)
{
String date = getHeader(name);
if (date == null)
{
return null;
}
return parseHttpDate(date);
}
public int getIntHeader(final String name, final int defaultValue)
{
try
{
return Integer.parseInt(getHeader(name));
}
catch (NumberFormatException e)
{
return defaultValue;
}
}
public long getLongHeader(final String name, final long defaultValue)
{
try
{
return Long.parseLong(getHeader(name));
}
catch (NumberFormatException e)
{
return defaultValue;
}
}
public String getHeaderParameter(final String headerName, final String paramName)
{
String header = getHeader(headerName);
if (header != null)
{
Map<String, String> params = parseHeaderParams(header);
return params.get(paramName);
}
return null;
}
public Map<String, String> getHeaderParameters(final String headerName)
{
return parseHeaderParams(getHeader(headerName));
}
public boolean isSuccessful()
{
return statusCode == StatusCodes.OK ||
statusCode == StatusCodes.CREATED ||
statusCode == StatusCodes.NO_CONTENT ||
statusCode == StatusCodes.NON_AUTHORITATIVE_INFORMATION ||
statusCode == StatusCodes.RESET_CONTENT ||
statusCode == StatusCodes.PARTIAL_CONTENT;
}
public String getContentType()
{
return getHeader(Headers.CONTENT_TYPE);
}
public long getContentLength()
{
return getLongHeader(Headers.CONTENT_LENGTH, -1);
}
public boolean hasContentLength()
{
return getContentLength() > -1;
}
public String getContentEncoding()
{
return getHeader(Headers.CONTENT_ENCODING);
}
public String getServer()
{
return getHeader(Headers.SERVER);
}
public Date getDate()
{
return getDateHeader(Headers.DATE);
}
public String getCacheControl()
{
return getHeader(Headers.CACHE_CONTROL);
}
public String getETag()
{
return getHeader(Headers.ETAG);
}
public Date getExpires()
{
return getDateHeader(Headers.EXPIRES);
}
public Date getLastModified()
{
return getDateHeader(Headers.LAST_MODIFIED);
}
public String getLocation()
{
return getHeader(Headers.LOCATION);
}
public String getOriginalCharset()
{
return originalCharset;
}
public Charset getCharset()
{
return charset;
}
public InputStream getInputStream() throws IOException
{
return getInputStream(null);
}
public InputStream getInputStream(HttpRequest.ProgressListener progressListener) throws IOException
{
if (isBuffered)
{
if (memoryBuffer != null)
{
return new ByteArrayInputStream(memoryBuffer);
}
else if (fileBuffer != null)
{
return new FileInputStream(fileBuffer);
}
return new ByteArrayInputStream(new byte[0]);
}
else
{
InputStream stream;
if (statusCode < 400)
{
stream = connection.getInputStream();
}
else
{
stream = connection.getErrorStream();
if (stream == null)
{
try
{
stream = connection.getInputStream();
}
catch (IOException e)
{
if (getContentLength() > 0)
{
disconnect();
throw e;
}
else
{
stream = new ByteArrayInputStream(new byte[0]);
}
}
}
}
if (autoDecompress && "gzip".equals(getContentEncoding()))
{
stream = new GZIPInputStream(stream);
}
if (progressListener != null)
{
stream = new ProgressInputStream(stream, progressListener, getContentLength());
}
return stream;
}
}
public String getResponseText() throws IOException
{
InputStreamReader reader = new InputStreamReader(getInputStream(), getCharset());
StringWriter writer = new StringWriter();
int firstChar = reader.read();
if (firstChar > -1)
{
if (firstChar != 0xFEFF) // 0xFEFF is the BOM, encoded in whatever encoding
{
writer.write(firstChar);
}
}
char[] buffer = new char[BUFFER_SIZE];
int read;
while ((read = reader.read(buffer, 0, BUFFER_SIZE)) > -1)
{
writer.write(buffer, 0, read);
}
String theString = writer.toString();
writer.close();
reader.close();
return theString;
}
public byte[] getResponseBytes() throws IOException
{
if (isBuffered && memoryBuffer != null)
{
return memoryBuffer;
}
else
{
InputStream inputStream = getInputStream();
long contentLength = getContentLength();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(contentLength >= 0 ? (int)contentLength : 64);
byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) > -1)
{
outputStream.write(buffer, 0, read);
}
byte [] theData = outputStream.toByteArray();
outputStream.close();
inputStream.close();
return theData;
}
}
public void prebuffer() throws IOException
{
prebuffer(null);
}
public void prebuffer(HttpRequest.ProgressListener progressListener) throws IOException
{
if (isBuffered) return;
InputStream stream = getInputStream(progressListener);
long contentLength = getContentLength();
if (contentLength >= 0 && contentLength <= MAX_SIZE_TO_ALLOW_IN_MEMORY)
{
memoryBuffer = new byte[(int)contentLength];
int read, totalRead = 0, toRead = (int)contentLength;
while ((read = stream.read(memoryBuffer, totalRead, toRead)) > 0)
{
totalRead += read;
toRead -= read;
}
}
else
{
fileBuffer = File.createTempFile("response-buffer", ".http", null);
fileBuffer.deleteOnExit();
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream(fileBuffer);
}
catch (IOException e)
{
fileBuffer.delete();
fileBuffer = null;
}
if (fileOutputStream != null)
{
byte [] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = stream.read(buffer, 0, BUFFER_SIZE)) > 0)
{
fileOutputStream.write(buffer, 0, read);
}
fileOutputStream.flush();
fileOutputStream.close();
}
else
{
memoryBuffer = new byte[(int)contentLength];
int read, totalRead = 0, toRead = (int)contentLength;
while ((read = stream.read(memoryBuffer, totalRead, toRead)) > 0)
{
totalRead += read;
toRead -= read;
}
}
}
stream.close();
disconnect();
isBuffered = true;
}
public void disconnect()
{
if (connection != null)
{
try
{
connection.disconnect();
}
catch (Exception ignored)
{
}
connection = null;
}
}
protected void finalize ()
{
if (fileBuffer != null)
{
fileBuffer.delete();
fileBuffer = null;
}
}
public static Date parseHttpDate(final String date)
{
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_RFC1123);
try
{
return format.parse(date);
}
catch (ParseException ignored)
{
}
format = new SimpleDateFormat(DATE_FORMAT_RFC1036);
try
{
return format.parse(date);
}
catch (ParseException ignored)
{
}
format = new SimpleDateFormat(DATE_FORMAT_ASCTIME);
try
{
return format.parse(date);
}
catch (ParseException ignored)
{
}
return null;
}
public static Map<String, String> parseHeaderParams(final String header)
{
Map<String, String> params = new LinkedHashMap<String, String>();
if (header == null || header.length() == 0)
{
return params;
}
final int totalLength = header.length();
int semicolon = header.indexOf(';');
if (semicolon == -1 || semicolon == totalLength - 1)
{
return params;
}
int nameStart = semicolon + 1, nameEnd;
int nextSemicolon = header.indexOf(';', nameStart);
if (nextSemicolon == -1)
{
nextSemicolon = totalLength;
}
while (nameStart < nextSemicolon)
{
nameEnd = header.indexOf('=', nameStart);
if (nameEnd != -1 && nameEnd < nextSemicolon)
{
String name = header.substring(nameStart, nameEnd).trim();
if (name.length() > 0)
{
String value = header.substring(nameEnd + 1, nextSemicolon).trim();
int length = value.length();
if (length != 0)
{
if (length > 2 && '"' == value.charAt(0) && '"' == value.charAt(length - 1))
{
params.put(name, value.substring(1, length - 1));
}
else
{
params.put(name, value);
}
}
}
}
nameStart = nextSemicolon + 1;
nextSemicolon = header.indexOf(';', nameStart);
if (nextSemicolon == -1)
{
nextSemicolon = totalLength;
}
}
return params;
}
public abstract static class Headers
{
public static final String CACHE_CONTROL = "Cache-Control";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String CONTENT_TYPE = "Content-Type";
public static final String DATE = "Date";
public static final String ETAG = "ETag";
public static final String EXPIRES = "Expires";
public static final String LAST_MODIFIED = "Last-Modified";
public static final String LOCATION = "Location";
public static final String SERVER = "Server";
}
public abstract static class StatusCodes
{
public static final int OK = 200;
public static final int CREATED = 201;
public static final int ACCEPTED = 202;
public static final int NON_AUTHORITATIVE_INFORMATION = 203;
public static final int NO_CONTENT = 204;
public static final int RESET_CONTENT = 205;
public static final int PARTIAL_CONTENT = 206;
public static final int MULTIPLE_CHOICES = 300;
public static final int MOVED_PERMANENTLY = 301;
public static final int FOUND = 302;
public static final int SEE_OTHER = 303;
public static final int NOT_MODIFIED = 304;
public static final int USE_PROXY = 305;
public static final int TEMPORARY_REDIRECT = 307;
public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int PAYMENT_REQUIRED = 402;
public static final int FORBIDDEN = 403;
public static final int NOT_FOUND = 404;
public static final int METHOD_NOT_ALLOWED = 405;
public static final int NOT_ACCEPTABLE = 406;
public static final int PROXY_AUTHENTICATION_REQUIRED = 407;
public static final int REQUEST_TIMEOUT = 408;
public static final int CONFLICT = 409;
public static final int GONE = 410;
public static final int LENGTH_REQUIRED = 411;
public static final int PRECONFITION_FAILED = 412;
public static final int REQUEST_ENTITY_TOO_LARGE = 413;
public static final int REQUEST_URI_TOO_LONG = 414;
public static final int UNSUPPORTED_MEDIA_TYPE = 415;
public static final int REQUEST_RANGE_NOT_SATISFIABLE = 416;
public static final int EXPECTATION_FAILED = 417;
public static final int INTERNAL_SERVER_ERROR = 500;
public static final int NOT_IMPLEMENTED = 501;
public static final int BAD_GATEWAY = 502;
public static final int SERVICE_UNAVAILABLE = 503;
public static final int GATEWAY_TIMEOUT = 504;
public static final int HTTP_VERSION_NOT_SUPPORTED = 505;
}
public static class ProgressInputStream extends InputStream
{
InputStream inputStream;
long totalBytes;
long totalRead;
HttpRequest.ProgressListener progressListener;
public ProgressInputStream(InputStream inputStream, HttpRequest.ProgressListener progressListener, long totalBytes)
{
super();
this.inputStream = inputStream;
this.totalBytes = totalBytes;
this.totalRead = 0;
this.progressListener = progressListener;
}
@Override
public void close() throws IOException
{
inputStream.close();
}
@Override
public int read() throws IOException
{
int read = inputStream.read();
totalRead += 1;
if (progressListener != null)
{
progressListener.onResponseProgress(totalRead, totalBytes);
}
return read;
}
@Override
public int read(byte[] buffer) throws IOException
{
int read = inputStream.read(buffer);
totalRead += read;
if (progressListener != null)
{
progressListener.onResponseProgress(totalRead, totalBytes);
}
return read;
}
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException
{
int read = inputStream.read(buffer, byteOffset, byteCount);
totalRead += read;
if (progressListener != null)
{
progressListener.onResponseProgress(totalRead, totalBytes);
}
return read;
}
@Override
public long skip(long byteCount) throws IOException
{
long read = inputStream.skip(byteCount);
if (read > -1)
{
totalRead += read;
if (progressListener != null)
{
progressListener.onResponseProgress(totalRead, totalBytes);
}
}
return read;
}
}
} |
package com.logaritmos;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.io.Serializable;
public class Rectangle implements Serializable {
private static final long serialVersionUID = 5L;
private int left;
private int right;
private int top;
private int bottom;
public Rectangle(int l,int r, int t, int b){
this.setXaxis(l,r);
this.setYaxis(t,b);
}
// corrige los valores de un rectangulo en cada eje en caso de estar desordenados
public static void rectify(Rectangle rect) {
rect.setXaxis(rect.left, rect.right);
rect.setYaxis(rect.bottom, rect.top);
}
private void setXaxis(int a, int b){
//el eje crece de izquierda a derecha
this.left = min(a,b);
this.right = max(a,b);
}
private void setYaxis(int a, int b){
//el eje Y crece de abajo hacia arriba
this.top = max(a,b);
this.bottom = min(a,b);
}
// getters
public int getTop() {
return this.top;
}
public int getBottom() {
return this.bottom;
}
public int getLeft() {
return this.left;
}
public int getRight() {
return this.right;
}
public int getHeight() {
return abs(this.top - this.bottom);
}
public int getWidth() {
return abs(this.right - this.left);
}
public double area() {
return (double) this.getHeight()*this.getWidth();
}
public double deltaArea(Rectangle rect1, Rectangle rect2) {
return abs(rect1.area() - rect2.area());
}
public boolean intersects(Rectangle aRectangle) {
return false;
}
public boolean overlaps(Rectangle aRectangle) {
return (this.inVertical(aRectangle) && this.inHorizontal(aRectangle));
}
private boolean inVertical(Rectangle aRectangle){
return (this.inTop(aRectangle.top) || this.inBottom(aRectangle.bottom));
}
private boolean inHorizontal(Rectangle aRectangle){
return (this.inLeft(aRectangle.left) || this.inRight(aRectangle.right));
}
private boolean contains(int number, int min ,int max){
return number>=min && number<=max;
}
private boolean inTop(int aTop){
return contains(aTop,this.bottom,this.top);
}
private boolean inBottom(int aBottom){
return contains(aBottom,this.bottom,this.top);
}
private boolean inLeft(int aLeft){
return contains(aLeft,this.left,this.right);
}
private boolean inRight(int aRight){
return contains(aRight,this.left,this.right);
}
public void multiMax(int i, int i1, int i2, int i3) {
}
} |
package com.nullprogram.gol;
import java.awt.*;
import java.util.*;
/**
* Abstract class for mplementing various types of cells.
*/
public abstract class Cell {
protected Vector<Cell> adj = null;
protected int curState, nextState;
protected static Random rand = new Random();
public Cell() {
adj = new Vector<Cell>();
}
/* Adds adjacent cells for polling */
public void addAdj(Vector<Cell> cells) {
adj.addAll(cells);
}
/* Return current cell state */
public int getState() {
return curState;
}
/* Return current cell state */
public void setState(int state) {
curState = state;
}
/* Get the color corresponding to the current cell state */
abstract public Color getColor();
/* Poll adjacent cells and update the next state */
abstract public void update();
/* Built-in factory: create a new cell with a random state */
abstract public Cell divide();
/* Built-in factory: create a new cell with given state */
abstract public Cell divide(int state);
/* Advance cell to the previously calculated next state */
public void sync() {
curState = nextState;
}
} |
package com.pty4j.windows;
import com.pty4j.PtyException;
import com.pty4j.WinSize;
import com.pty4j.util.PtyUtil;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;
import jtermios.windows.WinAPI;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
/**
* @author traff
*/
public class WinPty {
private final winpty_t myWinpty;
private NamedPipe myNamedPipe;
private boolean myClosed = false;
public WinPty(String cmdline, String cwd, String env) throws PtyException {
int cols = Integer.getInteger("win.pty.cols", 80);
int rows = Integer.getInteger("win.pty.rows", 25);
myWinpty = INSTANCE.winpty_open(cols, rows);
if (myWinpty == null) {
throw new PtyException("winpty is null");
}
int c;
char[] cmdlineArray = cmdline != null ? toCharArray(cmdline) : null;
char[] cwdArray = cwd != null ? toCharArray(cwd) : null;
char[] envArray = env != null ? toCharArray(env) : null;
if ((c = INSTANCE.winpty_start_process(myWinpty, null, cmdlineArray, cwdArray, envArray)) != 0) {
throw new PtyException("Error running process:" + c);
}
myNamedPipe = new NamedPipe(myWinpty.dataPipe);
}
private static char[] toCharArray(String string) {
char[] array = new char[string.length() + 1];
System.arraycopy(string.toCharArray(), 0, array, 0, string.length());
array[string.length()] = 0;
return array;
}
public void setWinSize(WinSize winSize) {
if (myClosed) {
return;
}
INSTANCE.winpty_set_size(myWinpty, winSize.ws_col, winSize.ws_row);
}
public void close() {
if (myClosed) {
return;
}
INSTANCE.winpty_close(myWinpty);
myNamedPipe.markClosed();
myClosed = true;
}
public int exitValue() {
if (myClosed) {
return -2;
}
return INSTANCE.winpty_get_exit_code(myWinpty);
}
public int read(byte[] buf, int len) throws IOException {
if (myClosed) {
return 0;
}
return myNamedPipe.read(buf, len);
}
public void write(byte[] buf, int len) throws IOException {
if (myClosed) {
return;
}
myNamedPipe.write(buf, len);
}
public static class winpty_t extends Structure {
public WinNT.HANDLE controlPipe;
public WinNT.HANDLE dataPipe;
public boolean open;
}
public static final Kern32 KERNEL32 = (Kern32)Native.loadLibrary("kernel32", Kern32.class);
interface Kern32 extends Library {
boolean PeekNamedPipe(WinNT.HANDLE hFile,
Buffer lpBuffer,
int nBufferSize,
IntByReference lpBytesRead,
IntByReference lpTotalBytesAvail,
IntByReference lpBytesLeftThisMessage);
boolean ReadFile(WinNT.HANDLE handle, Buffer buffer, int i, IntByReference reference, WinBase.OVERLAPPED overlapped);
}
public static WinPtyLib INSTANCE = (WinPtyLib)Native.loadLibrary(getLibraryPath(), WinPtyLib.class);
private static String getLibraryPath() {
try {
return PtyUtil.resolveNativeLibrary().getAbsolutePath();
}
catch (Exception e) {
throw new IllegalStateException("Couldn't detect jar containing folder", e);
}
}
interface WinPtyLib extends Library {
/*
* winpty API.
*/
/*
* Starts a new winpty instance with the given size.
*
* This function creates a new agent process and connects to it.
*/
winpty_t winpty_open(int cols, int rows);
/*
* Start a child process. Either (but not both) of appname and cmdline may
* be NULL. cwd and env may be NULL. env is a pointer to an environment
* block like that passed to CreateProcess.
*
* This function never modifies the cmdline, unlike CreateProcess.
*
* Only one child process may be started. After the child process exits, the
* agent will scrape the console output one last time, then close the data pipe
* once all remaining data has been sent.
*
* Returns 0 on success or a Win32 error code on failure.
*/
int winpty_start_process(winpty_t pc,
char[] appname,
char[] cmdline,
char[] cwd,
char[] env);
/*
* Returns the exit code of the process started with winpty_start_process,
* or -1 none is available.
*/
int winpty_get_exit_code(winpty_t pc);
/*
* Returns an overlapped-mode pipe handle that can be read and written
* like a Unix terminal.
*/
WinAPI.HANDLE winpty_get_data_pipe(winpty_t pc);
/*
* Change the size of the Windows console.
*/
int winpty_set_size(winpty_t pc, int cols, int rows);
/*
* Closes the winpty.
*/
void winpty_close(winpty_t pc);
}
} |
package com.ucasoft.orm;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import com.ucasoft.orm.exceptions.*;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.*;
import java.util.*;
@TargetApi(value = Build.VERSION_CODES.GINGERBREAD)
public class OrmUtils {
private final static HashMap<Class<? extends OrmEntity>, List<OrmEntity>> cashedEntityLists = new HashMap<Class<? extends OrmEntity>, List<OrmEntity>>();
private static List<OrmEntity> getCashedList(Class<? extends OrmEntity> entityClass){
if (!cashedEntityLists.containsKey(entityClass))
cashedEntityLists.put(entityClass, new ArrayList<OrmEntity>());
return cashedEntityLists.get(entityClass);
}
private static <T extends OrmEntity> T findCashedEntity(Class<T> entityClass, long id) throws WrongRightJoinReference, NotFindTableAnnotation, IllegalAccessException {
List<OrmEntity> cashedList = getCashedList(entityClass);
OrmField field = OrmFieldWorker.getPrimaryKeyField(entityClass, true);
for (OrmEntity entity : cashedList) {
if (field.get(entity).equals(id))
return (T) entity;
}
return null;
}
private static <T extends OrmEntity> T buildCashedEntity(Class<T> entityClass, Cursor cursor) throws WrongRightJoinReference, NotFindTableAnnotation, IllegalAccessException, NoSuchMethodException, NotFindPrimaryKeyField, DiscrepancyMappingColumns, InstantiationException, WrongListReference, InvocationTargetException, WrongJoinLeftReference {
OrmField field = OrmFieldWorker.getPrimaryKeyField(entityClass, true);
Long id = cursor.getLong(cursor.getColumnIndex(field.getName()));
T result = findCashedEntity(entityClass, id);
if (result == null){
result = createEntity(entityClass, cursor);
getCashedList(entityClass).add(result);
}
return result;
}
static boolean delete(OrmEntity entity) throws NotFindTableAnnotation, NotFindPrimaryKeyField, WrongRightJoinReference, IllegalAccessException {
SQLiteDatabase database = OrmFactory.getDatabase();
Class<? extends OrmEntity> entityClass = entity.getClass();
if (OrmTableWorker.getTableJoinLeftClass(entityClass) != null)
entityClass = OrmTableWorker.getTableJoinLeftClass(entityClass);
int rowDeleted = database.delete(OrmTableWorker.getTableName(entityClass),String.format("%s = ?", getPrimaryKeyColumn(entityClass).getName()), new String[]{Long.toString(getEntityKey(entityClass, entity))});
return rowDeleted == 1;
}
static boolean alterInTransaction(OrmEntity entity) throws WrongRightJoinReference, NotFindTableAnnotation, IllegalAccessException, WrongListReference {
SQLiteDatabase database = OrmFactory.getDatabase();
return alter(entity, database);
}
static boolean alter(OrmEntity entity) throws WrongRightJoinReference, NotFindTableAnnotation, IllegalAccessException, WrongListReference {
SQLiteDatabase database = OrmFactory.getDatabase();
database.beginTransaction();
boolean result = alter(entity, database);
if (result)
database.setTransactionSuccessful();
database.endTransaction();
return result;
}
private static boolean alter(OrmEntity entity, SQLiteDatabase database) throws WrongRightJoinReference, NotFindTableAnnotation, IllegalAccessException, WrongListReference {
boolean result = false;
Class<? extends OrmEntity> entityClass = entity.getClass();
Class<? extends OrmEntity> joinLeftClass = OrmTableWorker.getTableJoinLeftClass(entity.getClass());
OrmField primaryKeyField;
if (joinLeftClass != null)
primaryKeyField = OrmFieldWorker.getPrimaryKeyField(joinLeftClass);
else
primaryKeyField = OrmFieldWorker.getPrimaryKeyField(entityClass);
primaryKeyField.setAccessible(true);
if (primaryKeyField.get(entity) == null) {
long id;
if (joinLeftClass != null){
ContentValues contentValues = getContentValues(entity, joinLeftClass);
id = database.insert(OrmTableWorker.getTableName(joinLeftClass), "", contentValues);
if (id > 0){
contentValues = getContentValues(entity, null);
contentValues.put(OrmFieldWorker.getPrimaryKeyField(entityClass).getName(), id);
long leftJoinResult = database.insert(OrmTableWorker.getTableName(entityClass), "", contentValues);
if (leftJoinResult < 0)
return false;
}
}
else
id = database.insert(OrmTableWorker.getTableName(entityClass), "", getContentValues(entity));
if (id > 0) {
primaryKeyField.set(entity, id);
if (OrmTableWorker.isCashed(entityClass))
getCashedList(entityClass).add(entity);
result = true;
}
} else {
int rowUpdated = 0;
if (joinLeftClass != null) {
rowUpdated = database.update(OrmTableWorker.getTableName(joinLeftClass), getContentValues(entity, joinLeftClass), String.format("%s = ?", DbColumn.getColumnName(primaryKeyField)), new String[]{primaryKeyField.get(entity).toString()});
primaryKeyField = OrmFieldWorker.getPrimaryKeyField(entityClass);
}
rowUpdated += database.update(OrmTableWorker.getTableName(entityClass), getContentValues(entity, null), String.format("%s = ?", DbColumn.getColumnName(primaryKeyField)), new String[]{primaryKeyField.get(entity).toString()});
result = rowUpdated > 0;
}
if (result) {
List<OrmField> foreignFields = new ArrayList<OrmField>(OrmFieldWorker.getForeignFields(entityClass));
if (joinLeftClass != null)
foreignFields.addAll(0, OrmFieldWorker.getForeignFields(joinLeftClass));
for (OrmField field : foreignFields){
field.setAccessible(true);
for(OrmEntity entityItem : (List<OrmEntity>)field.get(entity)) {
result = alter(entityItem, database);
if (!result)
return false;
}
}
}
return result;
}
private static ContentValues getContentValues(OrmEntity entity) throws IllegalAccessException, WrongRightJoinReference, WrongListReference, NotFindTableAnnotation {
return getContentValues(entity, null);
}
private static ContentValues getContentValues(OrmEntity entity, Class<? extends OrmEntity> joinLeftClass) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference, IllegalAccessException {
ContentValues values = new ContentValues();
Class<? extends OrmEntity> findToClass;
if (joinLeftClass != null)
findToClass = joinLeftClass;
else
findToClass = entity.getClass();
for (OrmField field : OrmFieldWorker.getAnnotationFieldsWithOutPrimaryKey(findToClass)) {
field.setAccessible(true);
String columnName = DbColumn.getColumnName(field);
if (DbColumn.isReferenceField(field)) {
OrmEntity referenceEntity = (OrmEntity) field.get(entity);
if (referenceEntity != null){
OrmField primaryKeyField = OrmFieldWorker.getPrimaryKeyField(referenceEntity.getClass());
primaryKeyField.setAccessible(true);
values.put(columnName, (Long) primaryKeyField.get(referenceEntity));
}
}
else {
Class type = field.getType();
if (type.isArray()) {
if (type.getComponentType().isPrimitive()) {
String componentType = type.getComponentType().getSimpleName().toUpperCase();
String data = "";
if (componentType.equals("INT"))
data = Arrays.toString((int[]) field.get(entity));
values.put(columnName, data.substring(1, data.length() - 1));
}
} else {
String fieldType = type.getSimpleName().toUpperCase();
if (fieldType.equals("INT"))
values.put(columnName, field.getInt(entity));
else if (fieldType.equals("LONG"))
values.put(columnName, (Long) field.get(entity));
else if (fieldType.equals("DATE"))
values.put(columnName, ((Date) field.get(entity)).getTime());
else if (fieldType.equals("BOOLEAN"))
values.put(columnName, ((Boolean) field.get(entity)) ? 1 : 0);
else if (fieldType.equals("STRING"))
values.put(columnName, (String) field.get(entity));
else if (fieldType.equals("DOUBLE"))
values.put(columnName, field.getDouble(entity));
else if (fieldType.equals("DRAWABLE")) {
Bitmap bitmap = ((BitmapDrawable) field.get(entity)).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
values.put(columnName, stream.toByteArray());
} else if (fieldType.equals("DOCUMENT"))
values.put(columnName, getStringFromDocument((Document) field.get(entity)));
}
}
}
return values;
}
private static String getStringFromDocument(Document document) {
try{
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(new DOMSource(document), result);
return writer.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
static <T extends OrmEntity> List<T> getEntitiesWhere(Class<T> entityClass, String where, String[] params, String order) throws IllegalAccessException, WrongJoinLeftReference, InstantiationException, InvocationTargetException, NoSuchMethodException, WrongRightJoinReference, NotFindTableAnnotation, DiscrepancyMappingColumns, NotFindPrimaryKeyField, WrongListReference {
return getEntities(entityClass, where, params, order, false);
}
public static OrmUpdater UpdateTable(Class<? extends OrmEntity> entityClass) {
return new OrmUpdater(entityClass);
}
static List<DbColumn> getBaseColumns(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation {
List<DbColumn> result = new ArrayList<DbColumn>();
String sql = String.format("PRAGMA table_info(%s);", OrmTableWorker.getTableName(entityClass));
Cursor cursor = OrmFactory.getDatabase().rawQuery(sql, null);
try {
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndexOrThrow("name");
int typeIndex = cursor.getColumnIndexOrThrow("type");
do {
result.add(new DbColumn(cursor.getString(nameIndex), cursor.getString(typeIndex), ""));
} while (cursor.moveToNext());
}
} finally {
cursor.close();
}
return result;
}
interface DefaultValues {
void getDefaultValues(Class<? extends OrmEntity> entityClass, List<OrmEntity> valueList);
}
public static void CreateTable(Class<? extends OrmEntity> entityClass) throws NotFindPrimaryKeyField, WrongListReference, NotFindTableAnnotation, WrongRightJoinReference, IllegalAccessException {
String table;
table = "CREATE TABLE " + OrmTableWorker.getTableName(entityClass);
table = table + " (" + getColumns(entityClass);
Class<? extends OrmEntity> leftJoinTo = OrmTableWorker.getTableJoinLeftClass(entityClass);
if (leftJoinTo != null)
table += ", PRIMARY KEY (" + OrmFieldWorker.getPrimaryKeyField(entityClass).getName() + "));";
else
table += ");";
OrmFactory.getDatabase().execSQL(table);
InsertDefaultValues(entityClass);
}
static <T extends OrmEntity> List<T> getAllEntities(Class<T> entityClass) throws NotFindTableAnnotation, WrongRightJoinReference, NoSuchMethodException, NotFindPrimaryKeyField, DiscrepancyMappingColumns, InstantiationException, WrongListReference, IllegalAccessException, InvocationTargetException, WrongJoinLeftReference {
return getEntities(entityClass, null, null, null, false);
}
static <T extends OrmEntity> List<T> getAllEntities(Class<T> entityClass, boolean includeLeftChild) throws NotFindTableAnnotation, WrongRightJoinReference, NoSuchMethodException, NotFindPrimaryKeyField, DiscrepancyMappingColumns, InstantiationException, WrongListReference, IllegalAccessException, InvocationTargetException, WrongJoinLeftReference {
return getEntities(entityClass, null, null, null, includeLeftChild);
}
static <T extends OrmEntity> List<T> getEntities(Class<T> entityClass, String where, String[] params, String order, boolean includeLeftChild) throws NotFindTableAnnotation, WrongRightJoinReference, NoSuchMethodException, NotFindPrimaryKeyField, DiscrepancyMappingColumns, InstantiationException, WrongListReference, IllegalAccessException, InvocationTargetException, WrongJoinLeftReference {
ArrayList<T> result = new ArrayList<T>();
boolean cashed = OrmTableWorker.isCashed(entityClass);
List<Class<? extends OrmEntity>> rightToClasses = OrmTableWorker.getTableRightJoinClasses(entityClass);
Class<? extends OrmEntity> joinLeftClass = OrmTableWorker.getTableJoinLeftClass(entityClass);
String sql = "SELECT * FROM " + OrmTableWorker.getTableName(entityClass);
if (joinLeftClass != null) {
sql += " LEFT JOIN " + OrmTableWorker.getTableName(joinLeftClass) + " ON " + OrmFieldWorker.getPrimaryKeyField(entityClass).getName() + " = " + OrmFieldWorker.getPrimaryKeyField(joinLeftClass).getName();
}
if (where != null)
sql += String.format(" WHERE " + where.replace("?", "%s"), params).replace("[", "").replace("]", "");
if (rightToClasses.size() > 0) {
String notExists;
if (where == null)
notExists = " WHERE ";
else
notExists = " AND ";
for (Class<? extends OrmEntity> rightEntityClass : rightToClasses){
if (notExists.length() > 7)
notExists += "AND ";
notExists += "NOT EXISTS(SELECT 1 FROM " + OrmTableWorker.getTableName(rightEntityClass) + " WHERE " + OrmFieldWorker.getPrimaryKeyField(rightEntityClass).getName() + " = " + OrmFieldWorker.getPrimaryKeyField(entityClass).getName() + ") ";
}
sql += notExists;
}
if (order != null)
sql += " ORDER BY " + order;
Cursor cursor = OrmFactory.getDatabase().rawQuery(sql, null);
if (cursor.moveToFirst()) {
if (cashed){
do {
result.add(buildCashedEntity(entityClass, cursor));
} while (cursor.moveToNext());
} else {
do{
result.add(createEntity(entityClass, cursor));
} while (cursor.moveToNext());
}
}
cursor.close();
if (includeLeftChild){
for(Class<? extends OrmEntity> rightEntityClass : rightToClasses) {
sql = "SELECT * FROM " + OrmTableWorker.getTableName(rightEntityClass) + " LEFT JOIN " + OrmTableWorker.getTableName(entityClass) + " ON " + OrmFieldWorker.getPrimaryKeyField(rightEntityClass).getName() + " = " + OrmFieldWorker.getPrimaryKeyField(entityClass).getName();
if (where != null)
sql += String.format(" WHERE " + where.replace("?", "%s"), params).replace("[", "").replace("]", "");
if (order != null)
sql += " ORDER BY " + order;
cursor = OrmFactory.getDatabase().rawQuery(sql, null);
if (cursor.moveToFirst()){
if (cashed) {
do{
result.add((T) buildCashedEntity(rightEntityClass, cursor));
} while (cursor.moveToNext());
} else {
do{
result.add((T) createEntity(rightEntityClass, cursor));
} while (cursor.moveToNext());
}
}
cursor.close();
}
}
return result;
}
static <T extends OrmEntity> List<T> getAllEntitiesForParent(Class<OrmEntity> entityClass, Class<T> parentEntityClass, OrmEntity entity) throws NotFindTableAnnotation, NotFindPrimaryKeyField, WrongListReference, WrongRightJoinReference, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, DiscrepancyMappingColumns, WrongJoinLeftReference {
ArrayList<T> result = new ArrayList<T>();
Long parentKey = getEntityKey(parentEntityClass, entity);
Cursor cursor = OrmFactory.getDatabase().query(OrmTableWorker.getTableName(entityClass), null, String.format("%s = ?", getParentColumn(entityClass, parentEntityClass).getName()), new String[]{Long.toString(parentKey)}, "", "", "");
if (cursor.moveToFirst()){
do {
result.add((T) createEntity(entityClass, entity, cursor));
} while (cursor.moveToNext());
}
cursor.close();
return result;
}
private static <T extends OrmEntity> Long getEntityKey(Class<? extends OrmEntity> entityClass, T entity) throws NotFindTableAnnotation, WrongRightJoinReference, IllegalAccessException {
OrmField parentKeyField = OrmFieldWorker.getPrimaryKeyField(entityClass);
parentKeyField.setAccessible(true);
return (Long)parentKeyField.get(entity);
}
private static <T extends OrmEntity> DbColumn getParentColumn(Class<OrmEntity> entityClass, Class<T> parentEntityClass) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference, NotFindPrimaryKeyField {
for (OrmField field : OrmFieldWorker.getAnnotationFieldsWithOutPrimaryKey(entityClass)){
if (field.getType().equals(parentEntityClass))
return new DbColumn(field);
}
return null;
}
private static <T extends OrmEntity> T createEntity(Class<T> entityClass, Cursor cursor) throws NotFindTableAnnotation, InstantiationException, InvocationTargetException, NoSuchMethodException, WrongRightJoinReference, IllegalAccessException, WrongListReference, NotFindPrimaryKeyField, DiscrepancyMappingColumns, WrongJoinLeftReference {
return createEntity(entityClass, null, cursor);
}
private static <T extends OrmEntity> T createEntity(Class<T> entityClass, T parentEntity, Cursor cursor) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, WrongRightJoinReference, NotFindTableAnnotation, WrongListReference, DiscrepancyMappingColumns, NotFindPrimaryKeyField, WrongJoinLeftReference {
T entity = entityClass.getConstructor().newInstance();
if (OrmTableWorker.getTableJoinLeftClass(entityClass) != null)
buildEntity((Class<OrmEntity>) OrmTableWorker.getTableJoinLeftClass(entityClass), parentEntity, cursor, entity);
buildEntity(entityClass, parentEntity, cursor, entity);
return entity;
}
private static <T extends OrmEntity> void buildEntity(Class<T> entityClass, T parentEntity, Cursor cursor, T entity) throws WrongRightJoinReference, NotFindTableAnnotation, WrongListReference, DiscrepancyMappingColumns, IllegalAccessException, NotFindPrimaryKeyField, InstantiationException, NoSuchMethodException, InvocationTargetException, WrongJoinLeftReference {
Class<? extends OrmEntity> tableJoinLeftClass = OrmTableWorker.getTableJoinLeftClass(entityClass);
for(OrmField field : OrmFieldWorker.getAllAnnotationFields(entityClass)){
int cursorIndex = cursor.getColumnIndex(DbColumn.getColumnName(field));
if (cursorIndex < 0)
throw new DiscrepancyMappingColumns(entityClass, field);
field.setAccessible(true);
if (DbColumn.isReferenceField(field) && !field.getType().equals(tableJoinLeftClass)) {
Class<? extends OrmEntity> fieldType = (Class<? extends OrmEntity>) field.getType();
if (parentEntity != null && fieldType.isAssignableFrom(parentEntity.getClass()))
field.set(entity, parentEntity);
else {
long referenceEntityId = cursor.getLong(cursorIndex);
if (referenceEntityId > 0)
field.set(entity, getEntityByKey(fieldType, referenceEntityId));
}
} else
field.set(entity, getValue(cursor, cursorIndex, field));
}
for (OrmField field : OrmFieldWorker.getForeignFields(entityClass)) {
field.setAccessible(true);
field.set(entity, getAllEntitiesForParent((Class<OrmEntity>) ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0], entityClass, entity));
}
}
private static <T extends OrmEntity> T getEntityByKey(Class<T> entityClass, Long entityId) throws NotFindTableAnnotation, NotFindPrimaryKeyField, WrongRightJoinReference, IllegalAccessException, DiscrepancyMappingColumns, InstantiationException, WrongListReference, NoSuchMethodException, InvocationTargetException, WrongJoinLeftReference {
if (entityId > 0){
if (OrmTableWorker.isCashed(entityClass)) {
T result = findCashedEntity(entityClass, entityId);
if (result != null)
return result;
}
List<T> result = getEntities(entityClass, String.format("%s = ?", getPrimaryKeyColumn(entityClass).getName()), new String[]{entityId.toString()}, null, true);
if (result.size() > 0)
return result.get(0);
}
return null;
}
private static Object getValue(Cursor cursor, int cursorIndex, OrmField field) {
Class<?> type = field.getType();
if (type.isArray()) {
if (type.getComponentType().isPrimitive()) {
String[] items;
String itemsStr = cursor.getString(cursorIndex);
if(!itemsStr.equals("")) {
items = itemsStr.split(",");
} else {
items = new String[0];
}
Object result = null;
String componentName = type.getComponentType().getSimpleName().toUpperCase();
if (componentName.equals("INT"))
result = new int[items.length];
for (int i = 0; i < items.length; i++) {
if (componentName.equals("INT"))
((int[])result)[i] = Integer.parseInt(items[i].trim());
}
return result;
}
} else {
String fieldType = type.getSimpleName().toUpperCase();
if (fieldType.equals("INT"))
return cursor.getInt(cursorIndex);
else if (fieldType.equals("LONG"))
return cursor.getLong(cursorIndex);
else if (fieldType.equals("DATE"))
return new Date(cursor.getLong(cursorIndex));
else if (fieldType.equals("BOOLEAN"))
return cursor.getInt(cursorIndex) == 1;
else if (fieldType.equals("STRING"))
return cursor.getString(cursorIndex);
else if (fieldType.equals("DOUBLE")) {
String value = cursor.getString(cursorIndex);
if (value != null)
return Double.valueOf(value);
} else if (fieldType.equals("DRAWABLE")) {
byte[] bytes = cursor.getBlob(cursorIndex);
return new BitmapDrawable(null, BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
} else if (fieldType.equals("DOCUMENT"))
return getDocumentFromString(cursor.getString(cursorIndex));
}
return null;
}
private static Document getDocumentFromString(String string) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(string)));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static void InsertDefaultValues(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference, IllegalAccessException {
List<OrmEntity> valueList = new ArrayList<OrmEntity>();
OrmFactory.getHelper().getDefaultValues(entityClass, valueList);
if (valueList.size() > 0) {
for (OrmEntity values : valueList) {
values.alter();
}
}
}
private static List<DbColumn> getColumnsWithOutPrimaryKey(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation, WrongListReference, NotFindPrimaryKeyField, WrongRightJoinReference {
ArrayList<DbColumn> columns = new ArrayList<DbColumn>();
for(OrmField field : OrmFieldWorker.getAnnotationFieldsWithOutPrimaryKey(entityClass))
columns.add(new DbColumn(field));
return columns;
}
private static String getColumns(Class<? extends OrmEntity> entityClass) throws NotFindPrimaryKeyField, WrongListReference, NotFindTableAnnotation, WrongRightJoinReference {
String columns = "";
for (DbColumn column : getAllColumn(entityClass))
columns += ", " + column.toString();
if (columns.length() > 0)
columns = columns.substring(2);
return columns;
}
static List<DbColumn> getAllColumn(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation, NotFindPrimaryKeyField, WrongRightJoinReference, WrongListReference {
ArrayList<DbColumn> result = new ArrayList<DbColumn>();
for(OrmField field : OrmFieldWorker.getAllAnnotationFields(entityClass))
result.add(new DbColumn(field));
return result;
}
private static DbColumn getPrimaryKeyColumn(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation, NotFindPrimaryKeyField, WrongRightJoinReference {
OrmField primaryField = OrmFieldWorker.getPrimaryKeyField(entityClass);
return new DbColumn(primaryField);
}
static <T> List<Class<? extends OrmEntity>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type type = childClass;
while (!getClass(type).equals(baseClass)) {
if (type instanceof Class) {
type = ((Class) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
if (!rawType.equals(baseClass)) {
type = rawType.getGenericSuperclass();
}
}
}
Type[] actualTypeArguments;
if (type instanceof Class) {
actualTypeArguments = ((Class) type).getTypeParameters();
} else {
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
}
List<Class<? extends OrmEntity>> typeArgumentsAsClasses = new ArrayList<Class<? extends OrmEntity>>();
for (Type baseType : actualTypeArguments) {
while (resolvedTypes.containsKey(baseType)) {
baseType = resolvedTypes.get(baseType);
}
typeArgumentsAsClasses.add(getClass(baseType));
}
return typeArgumentsAsClasses;
}
private static Class<? extends OrmEntity> getClass(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type)
.getGenericComponentType();
Class<? extends OrmEntity> componentClass = getClass(componentType);
if (componentClass != null) {
return (Class<? extends OrmEntity>) Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
}
} |
package org.voltdb.compiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
import org.hsqldb_voltpatches.HSQLInterface;
import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.logging.VoltLogger;
import org.voltdb.planner.CompiledPlan;
import org.voltdb.planner.CompiledPlan.Fragment;
import org.voltdb.planner.QueryPlanner;
import org.voltdb.planner.TrivialCostModel;
import org.voltdb.plannodes.PlanNodeList;
import org.voltdb.utils.Encoder;
/**
* Planner tool accepts an already compiled VoltDB catalog and then
* interactively accept SQL and outputs plans on standard out.
*/
public class PlannerTool {
private static final VoltLogger hostLog = new VoltLogger("HOST");
public static final String POISON_SQL = "*kill*";
Process m_process;
OutputStreamWriter m_in;
AtomicLong m_timeOfLastPlannerCall = new AtomicLong(0);
String m_lastSql = "";
public static class Result {
String onePlan = null;
String allPlan = null;
String errors = null;
boolean replicatedDML = false;
public String getErrors()
{
return errors;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("RESULT {\n");
sb.append(" ONE: ").append(onePlan == null ? "null" : onePlan).append("\n");
sb.append(" ALL: ").append(allPlan == null ? "null" : allPlan).append("\n");
sb.append(" ERR: ").append(errors == null ? "null" : errors).append("\n");
sb.append(" RTD: ").append(replicatedDML ? "true" : "false").append("\n");
sb.append("}");
return sb.toString();
}
}
PlannerTool(Process process, OutputStreamWriter in) {
assert(process != null);
assert(in != null);
m_process = process;
m_in = in;
}
public void kill() {
m_process.destroy();
try {
m_process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean expensiveIsRunningCheck() {
try {
m_process.exitValue();
}
catch (IllegalThreadStateException e) {
return true;
}
return false;
}
public int getExitValue()
{
return m_process.exitValue();
}
public String getLastSql()
{
synchronized (m_lastSql)
{
return m_lastSql;
}
}
public boolean perhapsIsHung(long msTimeout) {
long start = m_timeOfLastPlannerCall.get();
if (start == 0) return false;
long duration = System.currentTimeMillis() - start;
if (duration > msTimeout) return true;
return false;
}
public synchronized Result planSql(String sql, boolean singlePartition) {
Result retval = new Result();
retval.errors = "";
// note when this call started / ensure value was previously zero
if (m_timeOfLastPlannerCall.compareAndSet(0, System.currentTimeMillis()) == false) {
retval.errors = "Multiple simultanious calls to out of process planner are not allowed";
return retval;
}
if ((sql == null) || (sql.length() == 0)) {
m_timeOfLastPlannerCall.set(0);
retval.errors = "Can't plan empty or null SQL.";
return retval;
}
// remove any spaces or newlines
sql = sql.trim();
synchronized (m_lastSql) {
m_lastSql = sql;
}
try {
// format is S#sql for single-partition and M#sql for multi
m_in.write((singlePartition ? "S" : "M") + "#" + sql + "\n");
m_in.flush();
} catch (IOException e) {
m_timeOfLastPlannerCall.set(0);
//e.printStackTrace();
retval.errors = e.getMessage();
return retval;
}
BufferedReader r = new BufferedReader(new InputStreamReader(m_process.getInputStream()));
ArrayList<String> output = new ArrayList<String>();
// read all the lines of output until a newline
while (true) {
String line = null;
try {
line = r.readLine();
}
catch (Exception e) {
m_timeOfLastPlannerCall.set(0);
//e.printStackTrace();
retval.errors = e.getMessage();
return retval;
}
if (line == null)
continue;
line = line.trim();
if (line.length() == 0)
break;
//System.err.println(line);
output.add(line);
}
// bucket and process the lines into a response
for (String line : output) {
if (line.equals("No logging configuration supplied via -Dlog4j.configuration. Supplying default config that logs INFO or higher to STDOUT")) {
continue;
}
if (line.startsWith("PLAN-ONE: ")) {
// trim PLAN-ONE: from the front
assert(retval.onePlan == null);
retval.onePlan = line.substring(10);
}
else if (line.startsWith("PLAN-ALL: ")) {
// trim PLAN-ALL: from the front
assert(retval.allPlan == null);
retval.allPlan = line.substring(10);
}
else if (line.startsWith("REPLICATED-DML: ")) {
retval.replicatedDML = true;
}
else {
// assume error output
retval.errors += line.substring(7) + "\n";
}
}
// post-process errors
// removes newlines
retval.errors = retval.errors.trim();
// no errors => null
if (retval.errors.length() == 0) retval.errors = null;
// reset the clock to zero, meaning not currently planning
m_timeOfLastPlannerCall.set(0);
synchronized (m_lastSql)
{
m_lastSql = "";
}
return retval;
}
public static PlannerTool createPlannerToolProcess(String serializedCatalog) {
assert(serializedCatalog != null);
String classpath = System.getProperty("java.class.path");
assert(classpath != null);
ArrayList<String> cmd = new ArrayList<String>();
cmd.add("java");
cmd.add("-cp");
cmd.add(classpath);
cmd.add("-Xmx256m");
cmd.add(PlannerTool.class.getName());
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
hostLog.error("Failed to start out of process planner, AdHoc SQL will not work", e);
}
OutputStreamWriter in = new OutputStreamWriter(process.getOutputStream());
String encodedCatalog = Encoder.compressAndBase64Encode(serializedCatalog);
try {
in.write(encodedCatalog + "\n");
in.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new PlannerTool(process, in);
}
static void log(String str) {
try {
FileWriter log = new FileWriter(m_logfile, true);
log.write(str + "\n");
log.flush();
log.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static File m_logfile;
/**
* @param args
*/
public static void main(String[] args) {
// name this thread
Thread.currentThread().setName("VoltDB Planner Process Main");
// PARSE COMMAND LINE ARGS
String logfile_dir = "";
if (System.getenv().get("TEST_DIR") != null) {
logfile_dir = System.getenv().get("TEST_DIR") + File.separator;
}
m_logfile = new File(logfile_dir + "plannerlog.txt");
log("\ngetting started at: " + new Date().toString());
// LOAD THE CATALOG
BufferedReader br = null;
final int TEN_MEGS = 10 * 1024 * 1024;
br = new BufferedReader(new InputStreamReader(System.in), TEN_MEGS);
String encodedSerializedCatalog = null;
try {
encodedSerializedCatalog = br.readLine();
} catch (IOException e) {
log("Couldn't read catalog: " + e.getMessage());
System.exit(50);
}
final String serializedCatalog = Encoder.decodeBase64AndDecompress(encodedSerializedCatalog);
if ((serializedCatalog == null) || (serializedCatalog.length() == 0)) {
log("Catalog is null or empty");
// need real error path
System.exit(28);
}
Catalog catalog = new Catalog();
catalog.execute(serializedCatalog);
Cluster cluster = catalog.getClusters().get("cluster");
Database db = cluster.getDatabases().get("database");
log("catalog loaded");
// LOAD HSQL
HSQLInterface hsql = HSQLInterface.loadHsqldb();
String hexDDL = db.getSchema();
String ddl = Encoder.hexDecodeToString(hexDDL);
String[] commands = ddl.split("\n");
for (String command : commands) {
String decoded_cmd = Encoder.hexDecodeToString(command);
decoded_cmd = decoded_cmd.trim();
if (decoded_cmd.length() == 0)
continue;
try {
hsql.runDDLCommand(decoded_cmd);
} catch (HSQLParseException e) {
// need a good error message here
log("Error creating hsql: " + e.getMessage());
log(" in DDL statement: " + decoded_cmd);
System.exit(82);
}
}
log("hsql loaded");
// BEGIN THE MAIN INPUT LOOP
String inputLine = "";
while (true) {
// READ THE SQL
try {
inputLine = br.readLine();
} catch (IOException e) {
log("Exception: " + e.getMessage());
System.out.println("ERROR: " + e.getMessage() + "\n");
System.exit(81);
}
// check the input
if (inputLine.length() == 0) {
log("got a zero-length input to the sql planner");
continue;
}
inputLine = inputLine.trim();
log("recieved sql stmt: " + inputLine);
String[] parts = inputLine.split("
log(String.format("Got %d parts", parts.length));
if (parts.length != 2) {
log("got a malformed input to the sql planner (bad hash splitting)");
continue;
}
if ((parts[0].charAt(0) != 'S') && (parts[0].charAt(0) != 'M')) {
log("got a malformed input to the sql planner (bad single/multi hinting)");
continue;
}
boolean isSinglePartition = parts[0].charAt(0) == 'S';
String sql = parts[1];
// the poison sql causes the process to exit
if (sql.equalsIgnoreCase("POISON_SQL")) {
log("Dying a horrible death (on purpose).");
System.exit(-1);
}
// PLAN THE STMT
TrivialCostModel costModel = new TrivialCostModel();
QueryPlanner planner = new QueryPlanner(
cluster, db, hsql, new DatabaseEstimates(), false, true);
CompiledPlan plan = null;
try {
plan = planner.compilePlan(
costModel, sql, null, "PlannerTool", "PlannerToolProc", isSinglePartition, null);
} catch (Exception e) {
log("Error creating planner: " + e.getMessage());
String plannerMsg = e.getMessage();
if (plannerMsg != null) {
System.out.println("ERROR: " + plannerMsg + "\n");
}
else {
System.out.println("ERROR: UNKNOWN PLANNING ERROR\n");
}
continue;
}
if (plan == null) {
String plannerMsg = planner.getErrorMessage();
if (plannerMsg != null) {
System.out.println("ERROR: " + plannerMsg + "\n");
}
else {
System.out.println("ERROR: UNKNOWN PLANNING ERROR\n");
}
continue;
}
if (plan.parameters.size() > 0) {
System.out.println("ERROR: PARAMETERIZATION IN AD HOC QUERY\n");
continue;
}
log("finished planning stmt:");
log("SQL: " + plan.sql);
log("COST: " + Double.toString(plan.cost));
log("PLAN:\n");
log(plan.explainedPlan);
assert(plan.fragments.size() <= 2);
// OUTPUT THE RESULT
// print out the run-at-every-partition fragment
for (int i = 0; i < plan.fragments.size(); i++) {
Fragment frag = plan.fragments.get(i);
PlanNodeList planList = new PlanNodeList(frag.planGraph);
String serializedPlan = planList.toJSONString();
String encodedPlan = serializedPlan; //Encoder.compressAndBase64Encode(serializedPlan);
if (frag.multiPartition) {
log("PLAN-ALL GENERATED");
System.out.println("PLAN-ALL: " + encodedPlan);
}
else {
log("PLAN-ONE GENERATED");
System.out.println("PLAN-ONE: " + encodedPlan);
}
}
if (plan.replicatedTableDML) {
System.out.println("REPLICATED-DML: true");
}
log("finished loop");
// print a newline to delimit
System.out.println();
System.out.flush();
}
}
} |
package galileo.test.net;
import java.net.Socket;
import java.nio.ByteBuffer;
import galileo.net.MessageRouter;
import galileo.net.NetworkDestination;
import galileo.util.PerformanceTimer;
public class BlockingScaleTestClient implements Runnable {
private static boolean verbose = false;
private PerformanceTimer pt = new PerformanceTimer("response");
private Socket socket;
public BlockingScaleTestClient(NetworkDestination netDest) throws Exception {
socket = new Socket(netDest.getHostname(), netDest.getPort());
}
@Override
public void run() {
try {
while (true) {
byte[] payload = new byte[ScaleTestServer.QUERY_SIZE];
ByteBuffer buffer = ByteBuffer.allocate(
payload.length + MessageRouter.PREFIX_SZ);
buffer.putInt(ScaleTestServer.QUERY_SIZE);
buffer.put(payload);
buffer.flip();
byte[] data = buffer.array();
if (verbose) {
pt.start();
}
socket.getOutputStream().write(data);
byte[] reply = new byte[ScaleTestServer.REPLY_SIZE];
socket.getInputStream().read(reply);
if (verbose) {
pt.stopAndPrint();
}
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("galileo.test.net.ScaleTestClient "
+ "host num-threads");
System.out.println("Add a 3rd parameter to turn on verbose mode.");
return;
}
String hostname = args[0];
int threads = Integer.parseInt(args[1]);
if (args.length >= 3) {
BlockingScaleTestClient.verbose = true;
}
for (int i = 0; i < threads; ++i) {
NetworkDestination netDest = new NetworkDestination(
hostname, ScaleTestServer.PORT);
BlockingScaleTestClient stc = new BlockingScaleTestClient(netDest);
new Thread(stc).start();
}
}
} |
package charts.builder.spreadsheet;
import static charts.ChartType.LOADS;
import static charts.ChartType.LOADS_DIN;
import static charts.ChartType.LOADS_PSII;
import static charts.ChartType.LOADS_TN;
import static charts.ChartType.LOADS_TSS;
import static com.google.common.collect.Lists.newLinkedList;
import static java.lang.String.format;
import java.awt.Dimension;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.supercsv.io.CsvListWriter;
import org.supercsv.prefs.CsvPreference;
import charts.AbstractChart;
import charts.Chart;
import charts.ChartDescription;
import charts.ChartType;
import charts.Drawable;
import charts.Region;
import charts.builder.DataSource.MissingDataException;
import charts.graphics.Loads;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public class LoadsBuilder extends AbstractBuilder {
private static final String PERIOD = "period";
private static final String TOTAL = "Total";
private static enum Indicator {
TSS("Total suspended solids", true),
TP("Total phosphorus", true),
PP("Particulate phosphorus", true),
DIP(false),
DOP(false),
TN("Total nitrogen", true),
PN("Particulate nitrogen", true),
DIN("Dissolved Inorganic nitrogen", true),
DON(false),
PSII("PSII pesticides", true);
private String label;
private boolean include;
private Indicator(boolean include) {
this.include = include;
}
private Indicator(String label, boolean include) {
this(include);
this.label = label;
}
public boolean include() {
return include;
}
public String getLabel() {
return label!=null?label:name();
}
}
private static final ImmutableMap<Region, Integer> ROWS =
new ImmutableMap.Builder<Region, Integer>()
.put(Region.CAPE_YORK, 5)
.put(Region.WET_TROPICS, 6)
.put(Region.BURDEKIN, 7)
.put(Region.MACKAY_WHITSUNDAY, 8)
.put(Region.FITZROY, 9)
.put(Region.BURNETT_MARY, 10)
.put(Region.GBR, 12)
.build();
private static final ImmutableMap<ChartType, Indicator> INDICATORS =
new ImmutableMap.Builder<ChartType, Indicator>()
.put(LOADS_DIN, Indicator.DIN)
.put(LOADS_TN, Indicator.TN)
.put(LOADS_PSII, Indicator.PSII)
.put(LOADS_TSS, Indicator.TSS)
.build();
public LoadsBuilder() {
super(Lists.newArrayList(LOADS, LOADS_DIN, LOADS_TN, LOADS_PSII, LOADS_TSS));
}
@Override
public boolean canHandle(SpreadsheetDataSource datasource) {
return sheet(datasource) != -1;
}
private int sheet(SpreadsheetDataSource ds) {
for(int i=0;i<ds.sheets();i++) {
try {
String name = ds.getSheetname(i);
if(name != null) {
if(StringUtils.equalsIgnoreCase("Region", ds.select(name, "C3").asString()) &&
StringUtils.equalsIgnoreCase("Total Change (%)", ds.select(name, "C12").asString())) {
return i;
}
}
} catch(Exception e) {}
}
return -1;
}
@Override
protected Map<String, List<String>> getParameters(SpreadsheetDataSource datasource, ChartType type) {
return new ImmutableMap.Builder<String, List<String>>()
.put(PERIOD, Lists.newArrayList(TOTAL))
.build();
}
private List<String> getPeriods(SpreadsheetDataSource ds) {
try {
List<String> periods = Lists.newArrayList();
int row = 2;
for(int col = 3;true;col++) {
String s = ds.select(row, col).asString();
if(StringUtils.isBlank(s) || periods.contains(s)) {
return periods;
} else {
periods.add(s);
}
}
} catch(MissingDataException e) {
throw new RuntimeException(e);
}
}
@Override
public Chart build(final SpreadsheetDataSource datasource, final ChartType type,
final Region region, Dimension queryDimensions, final Map<String, String> parameters) {
int sheet = sheet(datasource);
if(sheet == -1) {
return null;
} else {
datasource.setDefaultSheet(sheet);
}
if(type == LOADS) {
return buildLoads(datasource, type, region, queryDimensions, parameters);
} else if(region == Region.GBR) {
return buildLoadRegions(datasource, type, region, queryDimensions, parameters);
} else {
return null;
}
}
public Chart buildLoadRegions(final SpreadsheetDataSource datasource, final ChartType type,
final Region region, final Dimension queryDimensions, final Map<String, ?> parameters ) {
final String period = (String)parameters.get(PERIOD);
if(StringUtils.isBlank(period)) {
return null;
}
final Indicator indicator = INDICATORS.get(type);
if(indicator == null) {
throw new RuntimeException(String.format("chart type %s not implemented", type.name()));
}
return new AbstractChart(queryDimensions) {
@Override
public ChartDescription getDescription() {
return new ChartDescription(type, region, parameters);
}
@Override
public Drawable getChart() {
return Loads.createChart(getTitle(datasource, indicator, period),
"Region",
getRegionsDataset(datasource, indicator, period),
new Dimension(750, 500));
}
@Override
public String getCSV() throws UnsupportedFormatException {
final StringWriter sw = new StringWriter();
try {
final CategoryDataset dataset =
getRegionsDataset(datasource, indicator, period);
final CsvListWriter csv = new CsvListWriter(sw,
CsvPreference.STANDARD_PREFERENCE);
@SuppressWarnings("unchecked")
List<String> columnKeys = dataset.getColumnKeys();
@SuppressWarnings("unchecked")
List<String> rowKeys = dataset.getRowKeys();
final List<String> heading = ImmutableList.<String>builder()
.add(format("%s %s %s load reductions",
region, indicator, period))
.addAll(rowKeys)
.build();
csv.write(heading);
for (String col : columnKeys) {
List<String> line = newLinkedList();
line.add(col);
for (String row : rowKeys) {
line.add(format("%.1f",
dataset.getValue(row, col).doubleValue()));
}
csv.write(line);
}
csv.close();
} catch (IOException e) {
// How on earth would you get an IOException with a StringWriter?
throw new RuntimeException(e);
}
return sw.toString();
}
@Override
public String getCommentary() throws UnsupportedFormatException {
throw new UnsupportedFormatException();
}};
}
private Chart buildLoads(final SpreadsheetDataSource datasource, final ChartType type,
final Region region, Dimension queryDimensions, final Map<String, ?> parameters) {
final String period = (String)parameters.get(PERIOD);
if(StringUtils.isBlank(period)) {
return null;
}
return new AbstractChart(queryDimensions) {
@Override
public ChartDescription getDescription() {
return new ChartDescription(type, region, parameters);
}
@Override
public Drawable getChart() {
return Loads.createChart(getTitle(datasource, region, period),
"Pollutants", getDataset(datasource, region, period),
new Dimension(750, 500));
}
@Override
public String getCSV() throws UnsupportedFormatException {
final StringWriter sw = new StringWriter();
try {
final CategoryDataset dataset =
getDataset(datasource, region, period);
final CsvListWriter csv = new CsvListWriter(sw,
CsvPreference.STANDARD_PREFERENCE);
@SuppressWarnings("unchecked")
List<String> columnKeys = dataset.getColumnKeys();
@SuppressWarnings("unchecked")
List<String> rowKeys = dataset.getRowKeys();
final List<String> heading = ImmutableList.<String>builder()
.add(format("%s %s load reductions", region, period))
.addAll(rowKeys)
.build();
csv.write(heading);
for (String col : columnKeys) {
List<String> line = newLinkedList();
line.add(col);
for (String row : rowKeys) {
line.add(format("%.1f",
dataset.getValue(row, col).doubleValue()));
}
csv.write(line);
}
csv.close();
} catch (IOException e) {
// How on earth would you get an IOException with a StringWriter?
throw new RuntimeException(e);
}
return sw.toString();
}
@Override
public String getCommentary() throws UnsupportedFormatException {
throw new UnsupportedFormatException();
}};
}
private CategoryDataset getRegionsDataset(SpreadsheetDataSource ds,
Indicator indicator, String period) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(Region region : Region.values()) {
Integer row = ROWS.get(region);
if(row == null) {
throw new RuntimeException(String.format("region %s not configured", region.getName()));
}
try {
double val = selectAsDouble(ds, region, indicator, period);
dataset.addValue(val, indicator.getLabel(), region.getProperName());
} catch(Exception e) {
throw new RuntimeException("region "+region.getName(), e);
}
}
return dataset;
}
private CategoryDataset getDataset(SpreadsheetDataSource ds, Region region, String period) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
Integer row = ROWS.get(region);
if(row == null) {
throw new RuntimeException("unknown region "+region);
}
row
try {
for(Indicator indicator : Indicator.values()) {
if(indicator.include()) {
dataset.addValue(selectAsDouble(ds, region, indicator, period),
region.getProperName() , indicator.getLabel());
}
}
return dataset;
} catch(MissingDataException e) {
throw new RuntimeException(e);
}
}
private Double selectAsDouble(SpreadsheetDataSource ds, Region region,
Indicator indicator, String period) throws MissingDataException {
List<String> periods = getPeriods(ds);
int row = ROWS.get(region) - 1;
int col = indicator.ordinal() * periods.size() + periods.indexOf(period) + 3;
return ds.select(row, col).asDouble();
}
private String getTitle(SpreadsheetDataSource ds, Indicator indicator, String period) {
return getTitle(ds, indicator.getLabel() + " load reductions from\n", period);
}
private String getTitle(SpreadsheetDataSource ds, Region region, String period) {
String title = region.getProperName() + " total load reductions from\n";
return getTitle(ds, title, period);
}
private String getTitle(SpreadsheetDataSource ds, String prefix, String period) {
String title = prefix;
List<String> periods = getPeriods(ds);
if(StringUtils.equalsIgnoreCase(period, TOTAL)) {
title += formatPeriods(periods, -1, periods.size()-2);
} else {
int start = periods.indexOf(period);
title += formatPeriods(periods, start-1, start);
}
return title;
}
private String formatPeriods(List<String> periods, int start, int end) {
if(start == -1) {
return " the baseline (2008-2009) to " + formatPeriod(periods.get(end));
} else {
return formatPeriod(periods.get(start)) + " to " +
formatPeriod(periods.get(end));
}
}
private String formatPeriod(String period) {
try {
String p = StringUtils.substringBetween(period, "(", ")");
String[] sa = StringUtils.split(p, "/");
if(sa[0].length() == 2 && sa[1].length() == 2) {
return "20"+sa[0]+"-"+"20"+sa[1];
}
return period;
} catch(Exception e) {
return period;
}
}
} |
package gov.nih.nci.calab.dto.common;
import gov.nih.nci.calab.domain.DerivedDataFile;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.LabFile;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class represents attributes of a lab file to be
* viewed in a view page.
*
* @author pansu
*
*/
public class LabFileBean {
private String title;
private String description;
private String comments;
private String[] keywords = new String[0];
private String[] visibilityGroups;
private Date createdDate;
private String createdBy;
private String id;
private String path;
private String name;
private String type;
private String keywordsStr;
private String visibilityStr;
/*
* name to be displayed as a part of the drop-down list
*/
private String displayName;
public LabFileBean() {
super();
// TODO Auto-generated constructor stub
}
public LabFileBean(LabFile charFile) {
this.id=charFile.getId().toString();
this.name=charFile.getFilename();
this.path=charFile.getPath();
this.title=charFile.getTitle();
this.description=charFile.getDescription();
this.createdBy=charFile.getCreatedBy();
this.createdDate=charFile.getCreatedDate();
if (charFile instanceof DerivedDataFile){
List<String> allkeywords = new ArrayList<String>();
for (Keyword keyword: ((DerivedDataFile)charFile).getKeywordCollection()) {
allkeywords.add(keyword.getName());
}
allkeywords.toArray(this.keywords);
}
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String[] getKeywords() {
return keywords;
}
public void setKeywords(String[] keywords) {
this.keywords = keywords;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String[] getVisibilityGroups() {
return visibilityGroups;
}
public void setVisibilityGroups(String[] visibilityGroups) {
this.visibilityGroups = visibilityGroups;
}
public DerivedDataFile getDomainObject(){
DerivedDataFile labfile = new DerivedDataFile();
if (id != null && id.length() > 0) {
labfile.setId(new Long(id));
}
labfile.setCreatedBy(createdBy);
labfile.setCreatedDate(createdDate);
labfile.setDescription(description);
labfile.setFilename(name);
labfile.setPath(path);
labfile.setTitle(title);
return labfile;
}
public String getDisplayName() {
displayName=path.replaceAll("/decompressedFiles", "");
return displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKeywordsStr() {
keywordsStr=StringUtils.join(keywords, "<br>");
return keywordsStr;
}
public String getVisibilityStr() {
visibilityStr=StringUtils.join(visibilityGroups, ", ");
return visibilityStr;
}
} |
package info.ata4.unity.asset.bundle;
import info.ata4.io.DataInputReader;
import info.ata4.io.DataOutputWriter;
import info.ata4.io.buffer.ByteBufferUtils;
import info.ata4.io.file.FileHandler;
import info.ata4.log.LogUtils;
import info.ata4.unity.asset.bundle.codec.AssetBundleCodec;
import info.ata4.unity.asset.bundle.codec.XianjianCodec;
import info.ata4.unity.asset.bundle.struct.AssetBundleHeader;
import info.ata4.unity.util.UnityVersion;
import info.ata4.util.io.lzma.LzmaBufferUtils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
/**
* Reader for Unity asset bundles.
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class AssetBundle extends FileHandler {
private static final Logger L = LogUtils.getLogger();
private static final int ALIGN = 4;
private static int align(int length) {
int rem = length % ALIGN;
if (rem != 0) {
length += ALIGN - rem;
}
return length;
}
public static boolean isAssetBundle(Path file) {
// check signature of the file
try (DataInputReader in = DataInputReader.newReader(file)) {
AssetBundleHeader info = new AssetBundleHeader();
info.setSignature(in.readStringNull());
return info.hasValidSignature();
} catch (IOException ex) {
return false;
}
}
private final List<AssetBundleCodec> codecsLoad = new ArrayList<>();
private final List<AssetBundleCodec> codecsSave = new ArrayList<>();
private final AssetBundleHeader header = new AssetBundleHeader();
private final Map<String, ByteBuffer> entries = new LinkedHashMap<>();
private boolean compressed = false;
public AssetBundle() {
// register known codecs
codecsLoad.add(new XianjianCodec());
}
@Override
public void load(ByteBuffer bb) throws IOException {
// decode buffer if required
for (AssetBundleCodec codec : codecsLoad) {
if (codec.isEncoded(bb)) {
L.log(Level.INFO, "Decoding: {0}", codec.getName());
bb = codec.decode(bb);
codecsSave.add(codec);
}
}
DataInputReader in = DataInputReader.newReader(bb);
in.readStruct(header);
// check signature
if (!header.hasValidSignature()) {
throw new AssetBundleException("Invalid signature");
}
// check compression flag in the signature
compressed = header.isCompressed();
// get buffer slice for bundle data
ByteBuffer bbData = ByteBufferUtils.getSlice(bb, header.getDataOffset());
// uncompress bundle data if required
if (isCompressed()) {
L.log(Level.INFO, "Uncompressing asset bundle, this may take a while");
bbData = LzmaBufferUtils.decode(bbData);
}
// read bundle entries
in = DataInputReader.newReader(bbData);
int files = in.readInt();
for (int i = 0; i < files; i++) {
String name = in.readStringNull();
int offset = in.readInt();
int length = in.readInt();
ByteBuffer bbEntry = ByteBufferUtils.getSlice(bbData, offset, length);
entries.put(name, bbEntry);
}
}
@Override
public void save(Path file) throws IOException {
int bundleHeaderSize = 4;
int bundleDataSize = 0;
int assets = 0;
Set<Map.Entry<String, ByteBuffer>> entrySet = entries.entrySet();
for (Map.Entry<String, ByteBuffer> entry : entrySet) {
String name = entry.getKey();
ByteBuffer buffer = entry.getValue();
// name length + null byte + 2 ints
bundleHeaderSize += name.length() + 9;
// count asset files
if (name.equals("mainData") || name.startsWith("level") || name.startsWith("CAB")) {
assets++;
}
bundleDataSize += align(buffer.limit());
}
// first entry starts after the header
int bundleDataOffset = align(bundleHeaderSize);
// allocate data buffer
ByteBuffer bbData = ByteBuffer.allocateDirect(bundleDataOffset + bundleDataSize);
DataOutputWriter out = DataOutputWriter.newWriter(bbData.duplicate());
// write bundle entries
out.writeInt(entrySet.size());
for (Map.Entry<String, ByteBuffer> entry : entrySet) {
String name = entry.getKey();
ByteBuffer buffer = entry.getValue();
buffer.rewind();
out.writeStringNull(name);
out.writeInt(bundleDataOffset);
out.writeInt(buffer.limit());
bbData.position(bundleDataOffset);
bbData.put(buffer);
bundleDataOffset += align(buffer.limit());
}
bbData.flip();
int dataSizeC = bbData.limit();
int dataSizeU = dataSizeC;
// compress bundle data if required
if (isCompressed()) {
L.log(Level.INFO, "Compressing asset bundle, this may take a while");
bbData = LzmaBufferUtils.encode(bbData);
dataSizeC = bbData.limit();
}
// Mess with offset map before calculating header size
List<Pair<Integer, Integer>> offsetMap = header.getOffsetMap();
offsetMap.clear();
// TODO: Original asset bundles have ascending lengths for each asset
// file. The exact calculation of these values is not yet known, so use
// the maximum size for each entry for now to avoid crashes.
for (int i = 0; i < assets; i++) {
offsetMap.add(new ImmutablePair<>(dataSizeC, dataSizeU));
}
// configure header
int headerSize = header.getSize();
int bundleSize = headerSize + dataSizeC;
header.setCompressed(isCompressed());
header.setDataOffset(headerSize);
header.setFileSize1(bundleSize);
header.setFileSize2(bundleSize);
header.setUnknown1(assets);
header.setUnknown2(bundleHeaderSize);
// create bundle buffer
ByteBuffer bb = ByteBuffer.allocateDirect(bundleSize);
out = DataOutputWriter.newWriter(bb);
out.writeStruct(header);
out.writeBuffer(bbData);
bb.flip();
// encode bundle buffer
for (AssetBundleCodec codec : codecsSave) {
L.log(Level.INFO, "Encoding: {0}", codec.getName());
bb = codec.encode(bb);
}
// write buffer to file
bb.rewind();
ByteBufferUtils.save(file, bb);
}
public Map<String, ByteBuffer> getEntries() {
return entries;
}
public List<AssetBundleCodec> getLoadCodecs() {
return codecsLoad;
}
public List<AssetBundleCodec> getSaveCodecs() {
return codecsSave;
}
public int getFormat() {
return header.getFormat();
}
public void setFormat(byte format) {
header.setFormat(format);
}
public UnityVersion getPlayerVersion() {
return header.getPlayerVersion();
}
public void setPlayerVersion(UnityVersion version) {
header.setPlayerVersion(version);
}
public UnityVersion getEngineVersion() {
return header.getEngineVersion();
}
public void setEngineVersion(UnityVersion revision) {
header.setEngineVersion(revision);
}
public boolean isCompressed() {
return compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
} |
package jamaica.faces.novdl;
import static jamaica.faces.novdl.is_el.is_el;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
public class set_value_expression {
/**
* Set a value expression for a component property using the given
* EL expression.
*/
public static ValueExpression set_value_expression(FacesContext faces,
UIComponent component, String property, String expression) {
if (!is_el(expression)) {
throw new IllegalArgumentException("expression is not valid EL");
} else {
ELContext context = faces.getELContext();
ValueExpression ex = faces.getApplication().getExpressionFactory()
.createValueExpression(context, expression, Object.class);
component.setValueExpression(property, ex);
return ex;
}
}
} |
package com.gotometrics.hbase.rowkey;
import java.io.IOException;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/** Base class for translating objects to/from sort-order preserving byte
* arrays. In contrast to other common object serialization methods,
* <code>RowKey</code>
* serializations use a byte array representation that preserves
* the object's natural sort ordering. Sorting the raw byte arrays yields
* the same sort order as sorting the actual objects themselves, without
* requiring the object to be instantiated. Using the serialized byte arrays
* as HBase row keys ensures that the HBase will sort rows in the natural sort
* order of the object. Both primitive and complex/nested
* row keys types are supported, and all types support ascending and descending
* sort orderings.
*/
public abstract class RowKey
{
protected Order order;
private ImmutableBytesWritable w;
public RowKey() {
this.order = Order.ASCENDING;
}
/** Sets the sort order of the row key - ascending or descending. */
public RowKey setOrder(Order order) {
this.order = order;
return this;
}
/** Gets the sort order of the row key - ascending or descending */
public Order getOrder() { return order; }
/** Returns the class of the object used for serialization/deserialization.
* @see #serialize
* @see #deserialize
*/
public abstract Class<?> getSerializedClass();
/** Gets the length of the byte array when serializing an object.
* @param o object to serialize
* @return the length of the byte array used to serialize o
*/
public abstract int getSerializedLength(Object o) throws IOException;
/** Serializes an object o to a byte array. When this
* method returns, the byte array's position will be adjusted by the number
* of bytes written. The offset (length) of the byte array is incremented
* (decremented) by the number of bytes used to serialize o.
* @param o object to serialize
* @param w byte array used to store the serialized object
*/
public abstract void serialize(Object o, ImmutableBytesWritable w)
throws IOException;
public void serialize(Object o, byte[] b) throws IOException {
serialize(o, b, 0);
}
public void serialize(Object o, byte[] b, int offset) throws IOException {
if (w == null)
w = new ImmutableBytesWritable();
w.set(b, offset, b.length - offset);
serialize(o, w);
}
public byte[] serialize(Object o) throws IOException {
byte[] b = new byte[getSerializedLength(o)];
serialize(o, b, 0);
return b;
}
/** Skips over a serialized key in the byte array. When this
* method returns, the byte array's position will be adjusted by the number of
* bytes in the serialized key. The offset (length) of the byte array is
* incremented (decremented) by the number of bytes in the serialized key.
* @param w the byte array containing the serialized key
*/
public abstract void skip(ImmutableBytesWritable w) throws IOException;
/** Deserializes a key from the byte array. The returned object is an
* instance of the class returned by {@link getSerializedClass}. When this
* method returns, the byte array's position will be adjusted by the number of
* bytes in the serialized key. The offset (length) of the byte array is
* incremented (decremented) by the number of bytes in the serialized key.
* @param w the byte array used for key deserialization
* @return the deserialized key from the current position in the byte array
*/
public abstract Object deserialize(ImmutableBytesWritable w)
throws IOException;
public Object deserialize(byte[] b) throws IOException {
return deserialize(b, 0);
}
public Object deserialize(byte[] b, int offset) throws IOException {
if (w == null)
w = new ImmutableBytesWritable();
w.set(b, offset, b.length - offset);
return deserialize(w);
}
/** Orders serialized byte b by XOR'ing it with the sort order mask. This
* allows descending sort orders to invert the byte values of the serialized
* byte stream.
*/
protected byte mask(byte b) {
return (byte) (b ^ order.mask());
}
} |
package com.sun.facelets;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.application.StateManager;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.sun.facelets.compiler.Compiler;
import com.sun.facelets.compiler.SAXCompiler;
import com.sun.facelets.compiler.TagLibraryConfig;
import com.sun.facelets.impl.DefaultFaceletFactory;
import com.sun.facelets.tag.TagLibrary;
import com.sun.facelets.util.DevTools;
import com.sun.facelets.util.FacesAPI;
/**
* ViewHandler implementation for Facelets
*
* @author Jacob Hookom
* @version $Id: FaceletViewHandler.java,v 1.30 2005/08/02 05:03:30 jhook Exp $
*/
public class FaceletViewHandler extends ViewHandler {
protected final static Logger log = Logger
.getLogger("facelets.viewhandler");
public final static long DEFAULT_REFRESH_PERIOD = 2;
public final static String REFRESH_PERIOD_PARAM_NAME = "facelets.REFRESH_PERIOD";
public final static String SKIP_COMMENTS_PARAM_NAME = "facelets.SKIP_COMMENTS";
* <code>/faces/*</code>, not <code>*.jsf</code>).
* </p>
*/
public final static String VIEW_MAPPINGS_PARAM_NAME = "facelets.VIEW_MAPPINGS";
public final static String LIBRARIES_PARAM_NAME = "facelets.LIBRARIES";
public final static String DEVELOPMENT_PARAM_NAME = "facelets.DEVELOPMENT";
protected final static String STATE_KEY = "com.sun.facelets.VIEW_STATE";
private final ViewHandler parent;
private boolean development = false;
private boolean initialized = false;
private String defaultSuffix;
// Array of viewId extensions that should be handled by Facelets
private String[] extensionsArray;
// Array of viewId prefixes that should be handled by Facelets
private String[] prefixesArray;
protected static void removeTransient(UIComponent c) {
UIComponent d, e;
if (c.getChildCount() > 0) {
for (Iterator itr = c.getChildren().iterator(); itr.hasNext();) {
d = (UIComponent) itr.next();
if (d.getFacets().size() > 0) {
for (Iterator jtr = d.getFacets().values().iterator(); jtr
.hasNext();) {
e = (UIComponent) jtr.next();
if (e.isTransient()) {
jtr.remove();
} else {
removeTransient(e);
}
}
}
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
if (c.getFacets().size() > 0) {
for (Iterator itr = c.getFacets().values().iterator(); itr
.hasNext();) {
d = (UIComponent) itr.next();
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
}
public FaceletViewHandler(ViewHandler parent) {
this.parent = parent;
}
/**
* Initialize the ViewHandler during its first request.
*/
protected void initialize(FacesContext context) {
synchronized (this) {
if (!this.initialized) {
log.fine("Initializing");
Compiler c = this.createCompiler();
this.initializeCompiler(c);
FaceletFactory f = this.createFaceletFactory(c);
FaceletFactory.setInstance(f);
this.initializeMappings(context);
this.initializeMode(context);
this.initialized = true;
log.fine("Initialization Successful");
}
}
}
private void initializeMode(FacesContext context) {
ExternalContext external = context.getExternalContext();
String param = external.getInitParameter(DEVELOPMENT_PARAM_NAME);
this.development = (param != null && "true".equals(param));
}
/**
* Initialize mappings, during the first request.
*/
private void initializeMappings(FacesContext context) {
ExternalContext external = context.getExternalContext();
String viewMappings = external
.getInitParameter(VIEW_MAPPINGS_PARAM_NAME);
if ((viewMappings != null) && (viewMappings.length() > 0)) {
String[] mappingsArray = viewMappings.split(";");
List extensionsList = new ArrayList(mappingsArray.length);
List prefixesList = new ArrayList(mappingsArray.length);
for (int i = 0; i < mappingsArray.length; i++) {
String mapping = mappingsArray[i].trim();
int mappingLength = mapping.length();
if (mappingLength <= 1) {
continue;
}
if (mapping.charAt(0) == '*') {
extensionsList.add(mapping.substring(1));
} else if (mapping.charAt(mappingLength - 1) == '*') {
prefixesList.add(mapping.substring(0, mappingLength - 1));
}
}
extensionsArray = new String[extensionsList.size()];
extensionsList.toArray(extensionsArray);
prefixesArray = new String[prefixesList.size()];
prefixesList.toArray(prefixesArray);
}
}
protected FaceletFactory createFaceletFactory(Compiler c) {
long refreshPeriod = DEFAULT_REFRESH_PERIOD;
FacesContext ctx = FacesContext.getCurrentInstance();
String userPeriod = ctx.getExternalContext().getInitParameter(
REFRESH_PERIOD_PARAM_NAME);
if (userPeriod != null && userPeriod.length() > 0) {
refreshPeriod = Long.parseLong(userPeriod);
}
log.fine("Using Refresh Period: " + refreshPeriod + " sec");
try {
return new DefaultFaceletFactory(c, ctx.getExternalContext()
.getResource("/"), refreshPeriod);
} catch (MalformedURLException e) {
throw new FaceletException("Error Creating FaceletFactory", e);
}
}
protected Compiler createCompiler() {
return new SAXCompiler();
}
protected void initializeCompiler(Compiler c) {
FacesContext ctx = FacesContext.getCurrentInstance();
ExternalContext ext = ctx.getExternalContext();
String libParam = ext.getInitParameter(LIBRARIES_PARAM_NAME);
if (libParam != null) {
libParam = libParam.trim();
String[] libs = libParam.split(";");
URL src;
TagLibrary libObj;
for (int i = 0; i < libs.length; i++) {
try {
src = ext.getResource(libs[i]);
if (src == null) {
throw new FileNotFoundException(libs[i]);
}
libObj = TagLibraryConfig.create(src);
c.addTagLibrary(libObj);
log.fine("Successfully Loaded Library: " + libs[i]);
} catch (IOException e) {
log.log(Level.SEVERE, "Error Loading Library: " + libs[i],
e);
}
}
}
String skipParam = ext.getInitParameter(SKIP_COMMENTS_PARAM_NAME);
if (skipParam != null && "false".equals(skipParam)) {
c.setTrimmingComments(false);
}
}
public UIViewRoot restoreView(FacesContext context, String viewId) {
UIViewRoot root = null;
try {
root = this.parent.restoreView(context, viewId);
} catch (Exception e) {
log.log(Level.WARNING, "Error Restoring View: " + viewId, e);
}
if (root != null) {
log.fine("View Restored: " + root.getViewId());
} else {
log.fine("Unable to restore View");
}
return root;
}
/*
* (non-Javadoc)
*
* @see javax.faces.application.ViewHandlerWrapper#getWrapped()
*/
protected ViewHandler getWrapped() {
return this.parent;
}
protected ResponseWriter createResponseWriter(FacesContext context)
throws IOException, FacesException {
ExternalContext extContext = context.getExternalContext();
RenderKit renderKit = context.getRenderKit();
ServletRequest request = (ServletRequest) extContext.getRequest();
ServletResponse response = (ServletResponse) extContext.getResponse();
// get our content type
String contentType = (String) extContext.getRequestHeaderMap().get(
"Accept");
if (contentType == null) {
contentType = "text/html";
}
// get the encoding
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
// Create a dummy ResponseWriter with a bogus writer,
// so we can figure out what content type the ReponseWriter
// is really going to ask for
// TODO This needs to be changed back from null once
// MyFaces corrects the bug in their RenderKit
ResponseWriter writer = renderKit.createResponseWriter(
NullWriter.Instance, "text/html", encoding);
contentType = writer.getContentType();
encoding = writer.getCharacterEncoding();
// apply them to the response
response.setContentType(contentType + "; charset = " + encoding);
// Now, clone with the real writer
writer = writer.cloneWithWriter(response.getWriter());
return writer;
}
protected void buildView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
// setup our viewId
String renderedViewId = this.getRenderedViewId(context, viewToRender
.getViewId());
viewToRender.setViewId(renderedViewId);
if (log.isLoggable(Level.FINE)) {
log.fine("Building View: " + renderedViewId);
}
// grab our FaceletFactory and create a Facelet
FaceletFactory factory = FaceletFactory.getInstance();
Facelet f = factory.getFacelet(viewToRender.getViewId());
// populate UIViewRoot
f.apply(context, viewToRender);
}
public void renderView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
// lazy initialize so we have a FacesContext to use
if (!this.initialized) {
this.initialize(context);
}
// exit if the view is not to be rendered
if (!viewToRender.isRendered()) {
return;
}
// if facelets is not supposed to handle this request
if (!handledByFacelets(viewToRender)) {
this.parent.renderView(context, viewToRender);
return;
}
// log request
if (log.isLoggable(Level.FINE)) {
log.fine("Rendering View: " + viewToRender.getViewId());
}
try {
// build view
this.buildView(context, viewToRender);
// setup writer and assign it to the context
ResponseWriter writer = this.createResponseWriter(context);
context.setResponseWriter(writer);
// render the view to the response
writer.startDocument();
if (FacesAPI.getVersion() >= 12) {
viewToRender.encodeAll(context);
} else {
encodeRecursive(context, viewToRender);
}
writer.endDocument();
writer.close();
} catch (FileNotFoundException fnfe) {
String origViewId = this.getActionURL(context, viewToRender.getViewId());
this.handleFaceletNotFound(context, origViewId);
} catch (Exception e) {
this.handleEncodeException(context, e);
}
// remove transients for older versions
if (FacesAPI.getVersion() < 12) {
removeTransient(viewToRender);
}
}
protected void handleEncodeException(FacesContext context, Exception e)
throws IOException, ELException, FacesException {
Object resp = context.getExternalContext().getResponse();
if (this.development && !context.getResponseComplete()
&& resp instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse) resp;
httpResp.reset();
httpResp.setContentType("text/html; charset=UTF-8");
PrintWriter w = httpResp.getWriter();
DevTools.debugHtml(w, context, e);
w.flush();
context.responseComplete();
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else {
throw new FacesException(e.getMessage(), e);
}
}
protected void handleFaceletNotFound(FacesContext context, String viewId)
throws FacesException, IOException {
Object respObj = context.getExternalContext().getResponse();
if (respObj instanceof HttpServletResponse) {
HttpServletResponse respHttp = (HttpServletResponse) respObj;
respHttp.sendError(HttpServletResponse.SC_NOT_FOUND, viewId);
context.responseComplete();
}
}
protected final static void encodeRecursive(FacesContext context,
UIComponent viewToRender) throws IOException, FacesException {
if (viewToRender.isRendered()) {
viewToRender.encodeBegin(context);
if (viewToRender.getRendersChildren()) {
viewToRender.encodeChildren(context);
} else if (viewToRender.getChildCount() > 0) {
Iterator kids = viewToRender.getChildren().iterator();
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
encodeRecursive(context, kid);
}
}
viewToRender.encodeEnd(context);
}
}
/**
* Determine if Facelets needs to handle this request.
*/
private boolean handledByFacelets(UIViewRoot viewToRender) {
// If there's no extensions array or prefixes array, then
// just make Facelets handle everything
if ((extensionsArray == null) && (prefixesArray == null)) {
return true;
}
String viewId = viewToRender.getViewId();
if (extensionsArray != null) {
for (int i = 0; i < extensionsArray.length; i++) {
String extension = extensionsArray[i];
if (viewId.endsWith(extension)) {
return true;
}
}
}
if (prefixesArray != null) {
for (int i = 0; i < prefixesArray.length; i++) {
String prefix = prefixesArray[i];
if (viewId.startsWith(prefix)) {
return true;
}
}
}
return false;
}
public String getDefaultSuffix(FacesContext context) throws FacesException {
if (this.defaultSuffix == null) {
ExternalContext extCtx = context.getExternalContext();
String viewSuffix = extCtx
.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
this.defaultSuffix = (viewSuffix != null) ? viewSuffix
: ViewHandler.DEFAULT_SUFFIX;
}
return this.defaultSuffix;
}
protected String getRenderedViewId(FacesContext context, String actionId) {
ExternalContext extCtx = context.getExternalContext();
String viewId = actionId;
if (extCtx.getRequestPathInfo() == null) {
String facesSuffix = actionId.substring(actionId.lastIndexOf('.'));
String viewSuffix = this.getDefaultSuffix(context);
viewId = actionId.replaceFirst(facesSuffix, viewSuffix);
}
if (log.isLoggable(Level.FINE)) {
log.fine("ActionId -> ViewId: " + actionId + " -> " + viewId);
}
return viewId;
}
public void writeState(FacesContext context) throws IOException {
StateManager stateMgr = context.getApplication().getStateManager();
ExternalContext extContext = context.getExternalContext();
Object state = extContext.getRequestMap().get(STATE_KEY);
if (state == null) {
state = stateMgr.saveSerializedView(context);
extContext.getRequestMap().put(STATE_KEY, state);
}
if (stateMgr.isSavingStateInClient(context) || FacesAPI.getVersion() >= 12) {
stateMgr.writeState(context, (StateManager.SerializedView) state);
}
}
public Locale calculateLocale(FacesContext context) {
return this.parent.calculateLocale(context);
}
public String calculateRenderKitId(FacesContext context) {
return this.parent.calculateRenderKitId(context);
}
public UIViewRoot createView(FacesContext context, String viewId) {
return this.parent.createView(context, viewId);
}
public String getActionURL(FacesContext context, String viewId) {
return this.parent.getActionURL(context, viewId);
}
public String getResourceURL(FacesContext context, String path) {
return this.parent.getResourceURL(context, path);
}
static private class NullWriter extends Writer {
static final NullWriter Instance = new NullWriter();
public void write(char[] buffer) {
}
public void write(char[] buffer, int off, int len) {
}
public void write(String str) {
}
public void write(int c) {
}
public void write(String str, int off, int len) {
}
public void close() {
}
public void flush() {
}
}
} |
// Getdown - application installer, patcher and launcher
// provided that the following conditions are met:
// with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.threerings.getdown.tools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.security.MessageDigest;
import com.sun.javaws.jardiff.JarDiff;
import com.samskivert.io.StreamUtil;
import com.threerings.getdown.data.Application;
import com.threerings.getdown.data.Digest;
import com.threerings.getdown.data.Resource;
/**
* Generates patch files between two particular revisions of an
* application. The differences between all the files in the two
* revisions are bundled into a single patch file which is placed into the
* target version directory.
*/
public class Differ
{
/**
* Creates a single patch file that contains the differences between
* the two specified application directories. The patch file will be
* created in the <code>nvdir</code> directory with name
* <code>patchV.dat</code> where V is the old application version.
*/
public void createDiff (File nvdir, File ovdir, boolean verbose)
throws IOException
{
// sanity check
String nvers = nvdir.getName();
String overs = ovdir.getName();
try {
if (Long.parseLong(nvers) <= Long.parseLong(overs)) {
String err = "New version (" + nvers + ") must be greater " +
"than old version (" + overs + ").";
throw new IOException(err);
}
} catch (NumberFormatException nfe) {
throw new IOException("Non-numeric versions? [nvers=" + nvers +
", overs=" + overs + "].");
}
Application oapp = new Application(ovdir, null);
oapp.init(false);
ArrayList<Resource> orsrcs = new ArrayList<Resource>();
orsrcs.addAll(oapp.getCodeResources());
orsrcs.addAll(oapp.getResources());
Application napp = new Application(nvdir, null);
napp.init(false);
ArrayList<Resource> nrsrcs = new ArrayList<Resource>();
nrsrcs.addAll(napp.getCodeResources());
nrsrcs.addAll(napp.getResources());
// first create a patch for the main application
File patch = new File(nvdir, "patch" + overs + ".dat");
createPatch(patch, orsrcs, nrsrcs, verbose);
// next create patches for any auxiliary resource groups
for (String auxgroup : napp.getAuxGroups()) {
orsrcs = new ArrayList<Resource>();
orsrcs.addAll(oapp.getResources(auxgroup));
nrsrcs = new ArrayList<Resource>();
nrsrcs.addAll(napp.getResources(auxgroup));
patch = new File(nvdir, "patch-" + auxgroup + overs + ".dat");
createPatch(patch, orsrcs, nrsrcs, verbose);
}
}
protected void createPatch (File patch, ArrayList<Resource> orsrcs,
ArrayList<Resource> nrsrcs, boolean verbose)
throws IOException
{
MessageDigest md = Digest.getMessageDigest();
JarOutputStream jout = null;
try {
jout = new JarOutputStream(
new BufferedOutputStream(new FileOutputStream(patch)));
// for each file in the new application, it either already exists
// in the old application, or it is new
for (Resource rsrc : nrsrcs) {
int oidx = orsrcs.indexOf(rsrc);
Resource orsrc = (oidx == -1) ? null : orsrcs.remove(oidx);
if (orsrc != null) {
// first see if they are the same
String odig = orsrc.computeDigest(md, null);
String ndig = rsrc.computeDigest(md, null);
if (odig.equals(ndig)) {
if (verbose) {
System.out.println("Unchanged: " + rsrc.getPath());
}
// by leaving it out, it will be left as is during the
// patching process
continue;
}
// otherwise potentially create a jar diff
if (rsrc.getPath().endsWith(".jar")) {
if (verbose) {
System.out.println("JarDiff: " + rsrc.getPath());
}
// here's a juicy one: JarDiff blindly pulls ZipEntry
// objects out of one jar file and stuffs them into
// another without clearing out things like the
// compressed size, so if, for whatever reason (like
// different JRE versions or phase of the moon) the
// compressed size in the old jar file is different
// than the compressed size generated when creating the
// jardiff jar file, ZipOutputStream will choke and
// we'll be hosed; so we recreate the jar files in
// their entirety before running jardiff on 'em
File otemp = rebuildJar(orsrc.getLocal());
File temp = rebuildJar(rsrc.getLocal());
jout.putNextEntry(new ZipEntry(rsrc.getPath() + Patcher.PATCH));
jarDiff(otemp, temp, jout);
otemp.delete();
temp.delete();
continue;
}
}
if (verbose) {
System.out.println("Addition: " + rsrc.getPath());
}
jout.putNextEntry(new ZipEntry(rsrc.getPath() + Patcher.CREATE));
pipe(rsrc.getLocal(), jout);
}
// now any file remaining in orsrcs needs to be removed
for (Resource rsrc : orsrcs) {
// add an entry with the resource name and the deletion suffix
if (verbose) {
System.out.println("Removal: " + rsrc.getPath());
}
jout.putNextEntry(new ZipEntry(rsrc.getPath() + Patcher.DELETE));
}
StreamUtil.close(jout);
System.out.println("Created patch file: " + patch);
} catch (IOException ioe) {
StreamUtil.close(jout);
patch.delete();
throw ioe;
}
}
protected File rebuildJar (File target)
throws IOException
{
JarFile jar = new JarFile(target);
File temp = File.createTempFile("differ", "jar");
JarOutputStream jout = new JarOutputStream(
new BufferedOutputStream(new FileOutputStream(temp)));
byte[] buffer = new byte[4096];
for (Enumeration<JarEntry> iter = jar.entries(); iter.hasMoreElements(); ) {
JarEntry entry = iter.nextElement();
entry.setCompressedSize(-1);
jout.putNextEntry(entry);
InputStream in = jar.getInputStream(entry);
int size = in.read(buffer);
while (size != -1) {
jout.write(buffer, 0, size);
size = in.read(buffer);
}
in.close();
}
jout.close();
jar.close();
return temp;
}
protected void jarDiff (File ofile, File nfile, JarOutputStream jout)
throws IOException
{
JarDiff.createPatch(ofile.getPath(), nfile.getPath(), jout, false);
}
public static void main (String[] args)
{
if (args.length < 2) {
System.err.println(
"Usage: Differ [-verbose] new_vers_dir old_vers_dir");
System.exit(255);
}
Differ differ = new Differ();
boolean verbose = false;
int aidx = 0;
if (args[0].equals("-verbose")) {
verbose = true;
aidx++;
}
try {
differ.createDiff(new File(args[aidx++]),
new File(args[aidx++]), verbose);
} catch (IOException ioe) {
System.err.println("Error: " + ioe.getMessage());
System.exit(255);
}
}
protected static void pipe (File file, JarOutputStream jout)
throws IOException
{
FileInputStream fin = null;
try {
StreamUtil.copy(fin = new FileInputStream(file), jout);
} finally {
StreamUtil.close(fin);
}
}
} |
package org.apache.velocity.texen;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.Runtime;
/**
* A text/code generator class
*
* @author <a href="mailto:leon@opticode.co.za">Leon Messerschmidt</a>
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @version $Id: Generator.java,v 1.15 2001/04/02 01:15:18 geirm Exp $
*/
public class Generator
{
/**
* Where the texen output will placed.
*/
public static final String OUTPUT_PATH = "output.path";
/**
* Where the velocity templates live.
*/
public static final String TEMPLATE_PATH = "template.path";
/**
* Default properties file used for controlling the
* tools placed in the context.
*/
private static final String DEFAULT_TEXEN_PROPERTIES =
"org/apache/velocity/texen/defaults/texen.properties";
/**
* Default properties used by texen.
*/
private Properties props = new Properties();
/**
* Context used for generating the texen output.
*/
private Context controlContext;
/**
* Keep track of the file writers used for outputting
* to files. If we come across a file writer more
* then once then the additional output will be
* appended to the file instead of overwritting
* the contents.
*/
private Hashtable fileWriters = new Hashtable();
/**
* The generator tools used for creating additional
* output withing the control template. This could
* use some cleaning up.
*/
private static Generator instance = new Generator();
/**
* Default constructor.
*/
private Generator()
{
setDefaultProps();
}
/**
* Create a new generator object with default properties.
*
* @return Generator generator used in the control context.
*/
public static Generator getInstance()
{
return instance;
}
/**
* Create a new generator object with properties loaded from
* a file. If the file does not exist or any other exception
* occurs during the reading operation the default properties
* are used.
*
* @param String properties used to help populate the control context.
* @return Generator generator used in the control context.
*/
public Generator (String propFile)
{
try
{
FileInputStream fi = new FileInputStream (propFile);
BufferedInputStream bi = new BufferedInputStream (fi);
try
{
props.load (bi);
}
finally
{
bi.close();
}
}
catch (Exception e)
{
/*
* If something goes wrong we use default properties
*/
setDefaultProps();
}
}
/**
* Create a new Generator object with a given property
* set. The property set will be duplicated.
*
* @param Properties properties object to help populate the control context.
*/
public Generator (Properties props)
{
this.props = (Properties)props.clone();
}
/**
* Set default properties.
*/
protected void setDefaultProps()
{
ClassLoader classLoader = Runtime.class.getClassLoader();
try
{
InputStream inputStream = classLoader.getResourceAsStream(
DEFAULT_TEXEN_PROPERTIES);
props.load( inputStream );
}
catch (Exception ioe)
{
System.err.println("Cannot get default properties!");
}
}
/**
* Set the template path, where Texen will look
* for Velocity templates.
*
* @param String template path for velocity templates.
*/
public void setTemplatePath(String templatePath)
{
props.put(TEMPLATE_PATH, templatePath);
}
/**
* Get the template path.
*
* @return String template path for velocity templates.
*/
public String getTemplatePath()
{
return props.getProperty(TEMPLATE_PATH);
}
/**
* Set the output path for the generated
* output.
*
* @return String output path for texen output.
*/
public void setOutputPath(String outputPath)
{
props.put(OUTPUT_PATH, outputPath);
}
/**
* Get the output path for the generated
* output.
*
* @return String output path for texen output.
*/
public String getOutputPath()
{
return props.getProperty(OUTPUT_PATH);
}
/**
* Parse an input and write the output to an output file. If the
* output file parameter is null or an empty string the result is
* returned as a string object. Otherwise an empty string is returned.
*
* @param String input template
* @param String output file
*/
public String parse (String inputTemplate, String outputFile)
throws Exception
{
return parse(inputTemplate, outputFile, null, null);
}
/**
* Parse an input and write the output to an output file. If the
* output file parameter is null or an empty string the result is
* returned as a string object. Otherwise an empty string is returned.
* You can add objects to the context with the objs Hashtable.
*
* @param String input template
* @param String output file
* @param String id for object to be placed in the control context
* @param String object to be placed in the context
* @return String generated output from velocity
*/
public String parse (String inputTemplate,
String outputFile,
String objectID,
Object object)
throws Exception
{
if (objectID != null && object != null)
{
controlContext.put(objectID, object);
}
Template template = Runtime.getTemplate(inputTemplate);
if (outputFile == null || outputFile.equals(""))
{
StringWriter sw = new StringWriter();
template.merge (controlContext,sw);
return sw.toString();
}
else
{
FileWriter fileWriter = null;
if (fileWriters.get(outputFile) == null)
{
/*
* We have never seen this file before so create
* a new file writer for it.
*/
fileWriter = new FileWriter(
getOutputPath() + File.separator + outputFile);
/*
* Place the file writer in our collection
* of file writers.
*/
fileWriters.put(outputFile, fileWriter);
}
else
{
fileWriter = (FileWriter) fileWriters.get(outputFile);
}
VelocityContext vc = new VelocityContext( controlContext );
template.merge (vc,fileWriter);
//fw.close();
return "";
}
}
/**
* Parse the control template and merge it with the control
* context. This is the starting point in texen.
*
* @param String control template
* @param Context control context
* @return String generated output
*/
public String parse (String controlTemplate, Context controlContext)
throws Exception
{
this.controlContext = controlContext;
fillContextDefaults(this.controlContext);
fillContextProperties(this.controlContext);
Template template = Runtime.getTemplate(controlTemplate);
StringWriter sw = new StringWriter();
template.merge (controlContext,sw);
return sw.toString();
}
/**
* Create a new context and fill it with the elements of the
* objs Hashtable. Default objects and objects that comes from
* the properties of this Generator object is also added.
*
* @param Hashtable objects to place in the control context
* @return Context context filled with objects
*/
protected Context getContext (Hashtable objs)
{
fillContextHash (controlContext,objs);
return controlContext;
}
/**
* Add all the contents of a Hashtable to the context.
*
* @param Context context to fill with objects
* @param Hashtable source of objects
*/
protected void fillContextHash (Context context, Hashtable objs)
{
Enumeration enum = objs.keys();
while (enum.hasMoreElements())
{
String key = enum.nextElement().toString();
context.put (key, objs.get(key));
}
}
/**
* Add properties that will aways be in the context by default
*
* @param Context control context to fill with default values.
*/
protected void fillContextDefaults (Context context)
{
context.put ("generator", instance);
context.put ("outputDirectory", getOutputPath());
}
/**
* Add objects to the context from the current properties.
*
* @param Context control context to fill with objects
* that are specified in the default.properties
* file
*/
protected void fillContextProperties (Context context)
{
Enumeration enum = props.propertyNames();
while (enum.hasMoreElements())
{
String nm = (String)enum.nextElement();
if (nm.startsWith ("context.objects."))
{
String contextObj = props.getProperty (nm);
int colon = nm.lastIndexOf ('.');
String contextName = nm.substring (colon+1);
try
{
Class cls = Class.forName (contextObj);
Object o = cls.newInstance();
context.put (contextName,o);
}
catch (Exception e)
{
e.printStackTrace();
//TO DO: Log Something Here
}
}
}
}
/**
* Properly shut down the generator, right now
* this is simply flushing and closing the file
* writers that we have been holding on to.
*/
public void shutdown()
{
Iterator iterator = fileWriters.values().iterator();
while(iterator.hasNext())
{
FileWriter fileWriter = (FileWriter) iterator.next();
try
{
fileWriter.flush();
fileWriter.close();
}
catch (Exception e)
{
/* do nothing */
}
}
}
} |
package org.apache.velocity.util;
/**
* Simple object pool. Based on ThreadPool and few other classes
*
* The pool will ignore overflow and return null if empty.
*
* @author Gal Shachor
* @author Costin
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: SimplePool.java,v 1.3 2003/10/27 12:35:17 geirm Exp $
*/
public final class SimplePool
{
/*
* Where the objects are held.
*/
private Object pool[];
/**
* max amount of objects to be managed
* set via CTOR
*/
private int max;
/**
* index of previous to next
* free slot
*/
private int current=-1;
public SimplePool(int max)
{
this.max = max;
pool = new Object[max];
}
/**
* Add the object to the pool, silent nothing if the pool is full
*/
public void put(Object o)
{
int idx=-1;
synchronized(this)
{
/*
* if we aren't full
*/
if (current < max - 1)
{
/*
* then increment the
* current index.
*/
idx = ++current;
}
if (idx >= 0)
{
pool[idx] = o;
}
}
}
/**
* Get an object from the pool, null if the pool is empty.
*/
public Object get()
{
synchronized(this)
{
/*
* if we have any in the pool
*/
if( current >= 0 )
{
/*
* remove the current one
*/
Object o = pool[current];
pool[current] = null;
current
return o;
}
}
return null;
}
/** Return the size of the pool
*/
public int getMax()
{
return max;
}
/**
* for testing purposes, so we can examine the pool
*
* @return
*/
Object[] getPool()
{
return pool;
}
} |
package org.pantsbuild.tools.jar;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipException;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.io.ByteProcessor;
import com.google.common.io.ByteSource;
import com.google.common.io.Closer;
import com.google.common.io.Files;
/**
* A utility than can create or update jar archives with special handling of duplicate entries.
*/
public class JarBuilder implements Closeable {
/**
* Indicates a problem encountered when building up a jar's contents for writing out.
*/
public static class JarBuilderException extends IOException {
public JarBuilderException(String message) {
super(message);
}
public JarBuilderException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Indicates a problem writing out a jar.
*/
public static class JarCreationException extends JarBuilderException {
public JarCreationException(String message) {
super(message);
}
}
/**
* Indicates a problem indexing a pre-existing jar that will be added or updated to the target
* jar.
*/
public static class IndexingException extends JarBuilderException {
public IndexingException(File jarPath, Throwable t) {
super("Problem indexing jar at " + jarPath + ": " + t.getMessage(), t);
}
}
/**
* Indicates a duplicate jar entry is being rejected.
*/
public static class DuplicateEntryException extends RuntimeException {
private final ReadableEntry entry;
DuplicateEntryException(ReadableEntry entry) {
super("Detected a duplicate entry for " + entry.getJarPath());
this.entry = entry;
}
/**
* Returns the duplicate path.
*/
public String getPath() {
return entry.getJarPath();
}
/**
* Returns the contents of the duplicate entry.
*/
public ByteSource getSource() {
return entry.contents;
}
}
/**
* Identifies an action to take when duplicate jar entries are encountered.
*/
public enum DuplicateAction {
/**
* This action skips the duplicate entry keeping the original entry.
*/
SKIP,
/**
* This action replaces the original entry with the duplicate entry.
*/
REPLACE,
/**
* This action appends the content of the duplicate entry to the original entry.
*/
CONCAT,
/**
* This action throws a {@link DuplicateEntryException}.
*/
THROW
}
/**
* Encapsulates a policy for treatment of duplicate jar entries.
*/
public static class DuplicatePolicy implements Predicate<CharSequence> {
/**
* Creates a policy that applies to entries based on a path match.
*
* @param regex A regular expression to match entry paths against.
* @param action The action to apply to duplicate entries with path matching {@code regex}.
* @return The path matching policy.
*/
public static DuplicatePolicy pathMatches(String regex, DuplicateAction action) {
return new DuplicatePolicy(Predicates.containsPattern(regex), action);
}
private final Predicate<CharSequence> selector;
private final DuplicateAction action;
/**
* Creates a policy that will be applied to duplicate entries matching the given
* {@code selector}.
*
* @param selector A predicate that selects entries this policy has jurisdiction over.
* @param action The action to apply to entries selected by this policy.
*/
public DuplicatePolicy(Predicate<CharSequence> selector, DuplicateAction action) {
this.selector = Preconditions.checkNotNull(selector);
this.action = Preconditions.checkNotNull(action);
}
/**
* Returns the action that should be applied when a duplicate entry falls under this policy's
* jurisdiction.
*/
public DuplicateAction getAction() {
return action;
}
@Override
public boolean apply(CharSequence jarPath) {
return selector.apply(jarPath);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("action", action)
.add("selector", selector)
.toString();
}
}
/**
* Handles duplicate jar entries by selecting an appropriate action based on the entry path.
*/
public static class DuplicateHandler {
/**
* Creates a handler that always applies the given {@code action}.
*
* @param action The action to perform on all duplicate entries encountered.
*/
public static DuplicateHandler always(DuplicateAction action) {
Preconditions.checkNotNull(action);
return new DuplicateHandler(action,
ImmutableList.of(new DuplicatePolicy(Predicates.<CharSequence>alwaysTrue(), action)));
}
/**
* Creates a handler that merges well-known mergeable resources and otherwise skips duplicates.
* <p/>
* Merged resources include META-INF/services/ files.
*/
public static DuplicateHandler skipDuplicatesConcatWellKnownMetadata() {
DuplicatePolicy concatServices =
DuplicatePolicy.pathMatches("^META-INF/services/", DuplicateAction.CONCAT);
ImmutableList<DuplicatePolicy> policies = ImmutableList.of(concatServices);
return new DuplicateHandler(DuplicateAction.SKIP, policies);
}
private final DuplicateAction defaultAction;
private final Iterable<DuplicatePolicy> policies;
/**
* A convenience constructor equivalent to calling:
* {@code DuplicateHandler(defaultAction, Arrays.asList(policies))}
*/
public DuplicateHandler(DuplicateAction defaultAction, DuplicatePolicy... policies) {
this(defaultAction, ImmutableList.copyOf(policies));
}
/**
* Creates a handler that applies the 1st matching policy when a duplicate entry is encountered,
* falling back to the given {@code defaultAction} if no policy applies.
*
* @param defaultAction The default action to apply when no policy matches.
* @param policies The policies to apply in preference order.
*/
public DuplicateHandler(DuplicateAction defaultAction, Iterable<DuplicatePolicy> policies) {
this.defaultAction = Preconditions.checkNotNull(defaultAction);
this.policies = ImmutableList.copyOf(policies);
}
@VisibleForTesting
DuplicateAction actionFor(String jarPath) {
for (DuplicatePolicy policy : policies) {
if (policy.apply(jarPath)) {
return policy.getAction();
}
}
return defaultAction;
}
}
/**
* Identifies a source for jar entries.
*/
public interface Source {
/**
* Returns a name for this source.
*/
String name();
/**
* Identifies a member of this source.
*/
String identify(String name);
}
private abstract static class FileSource implements Source {
protected final File source;
protected FileSource(File source) {
this.source = source;
}
public String name() {
return source.getPath();
}
}
private abstract static class JarSource extends FileSource {
protected JarSource(File source) {
super(source);
}
}
private static Source jarSource(File jar) {
return new JarSource(jar) {
@Override public String identify(String name) {
return String.format("%s!%s", source.getPath(), name);
}
@Override public String toString() {
return String.format("JarSource{jar=%s}", source.getPath());
}
};
}
private static Source fileSource(final File file) {
return new FileSource(new File("/")) {
@Override public String identify(String name) {
if (!file.getPath().equals(name)) {
throw new IllegalArgumentException(
"Cannot identify any entry name save for " + file.getPath());
}
return file.getPath();
}
@Override public String toString() {
return String.format("FileSource{file=%s}", file.getPath());
}
};
}
private static Source directorySource(File directory) {
return new FileSource(directory) {
@Override public String identify(String name) {
return new File(source, name).getPath();
}
@Override public String toString() {
return String.format("FileSource{directory=%s}", source.getPath());
}
};
}
private static Source memorySource() {
return new Source() {
@Override public String name() {
return "<memory>";
}
@Override public String identify(String name) {
return "<memory>!" + name;
}
@Override public String toString() {
return String.format("MemorySource{@%s}", Integer.toHexString(hashCode()));
}
};
}
private static final class NamedByteSource extends ByteSource {
static NamedByteSource create(Source source, String name, ByteSource inputSupplier) {
return new NamedByteSource(source, name, inputSupplier);
}
private final Source source;
private final String name;
private final ByteSource inputSupplier;
private NamedByteSource(Source source, String name, ByteSource inputSupplier) {
this.source = source;
this.name = name;
this.inputSupplier = inputSupplier;
}
@Override
public InputStream openStream() throws IOException {
return inputSupplier.openStream();
}
}
/**
* Represents an entry to be added to a jar.
*/
public interface Entry {
/**
* Returns the source that contains the entry.
*/
Source getSource();
/**
* Returns the name of the entry within its source.
*/
String getName();
/**
* Returns the path this entry will be added into the jar at.
*/
String getJarPath();
}
private static class ReadableEntry implements Entry {
static final Function<ReadableEntry, NamedByteSource> GET_CONTENTS =
new Function<ReadableEntry, NamedByteSource>() {
@Override public NamedByteSource apply(ReadableEntry item) {
return item.contents;
}
};
private final NamedByteSource contents;
private final String path;
ReadableEntry(NamedByteSource contents, String path) {
this.contents = contents;
this.path = path;
}
@Override
public Source getSource() {
return contents.source;
}
@Override
public String getName() {
return contents.name;
}
@Override
public String getJarPath() {
return path;
}
}
private static class ReadableJarEntry extends ReadableEntry {
private final JarEntry jarEntry;
public ReadableJarEntry(NamedByteSource contents, JarEntry jarEntry) {
super(contents, jarEntry.getName());
this.jarEntry = jarEntry;
}
public JarEntry getJarEntry() { return jarEntry; }
}
/**
* An interface for those interested in the progress of writing the target jar.
*/
public interface Listener {
/**
* A listener that ignores all events.
*/
Listener NOOP = new Listener() {
@Override public void onSkip(Optional<? extends Entry> original,
Iterable<? extends Entry> skipped) {
// noop
}
@Override public void onReplace(Iterable<? extends Entry> originals, Entry replacement) {
// noop
}
@Override public void onConcat(String name, Iterable<? extends Entry> entries) {
// noop
}
@Override public void onWrite(Entry entry) {
// noop
}
};
/**
* Called to notify the listener that entries are being skipped.
*
* If original is present this indicates it it being retained in preference to the skipped
* entries.
*
* @param original The original entry being retained.
* @param skipped The new entries being skipped.
*/
void onSkip(Optional<? extends Entry> original, Iterable<? extends Entry> skipped);
/**
* Called to notify the listener that original entries are being replaced by a subsequently
* added entry.
*
* @param originals The original entry candidates that will be replaced.
* @param replacement The entry that overwrites the originals.
*/
void onReplace(Iterable<? extends Entry> originals, Entry replacement);
/**
* Called to notify the listener an original entry is being concatenated with one or more
* subsequently added entries.
*
* @param name The name of the entry in question.
* @param entries The entries that will be concatenated with the original entry.
*/
void onConcat(String name, Iterable<? extends Entry> entries);
/**
* Called to notify the listener of a newly written non-duplicate entry.
*
* @param entry The entry to be added to the target jar.
*/
void onWrite(Entry entry);
}
private static ByteSource manifestSupplier(final Manifest mf) {
return new ByteSource() {
@Override public InputStream openStream() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
mf.write(out);
return new ByteArrayInputStream(out.toByteArray());
}
};
}
static Manifest ensureDefaultManifestEntries(Manifest manifest) {
if (!manifest.getMainAttributes().containsKey(Name.MANIFEST_VERSION)) {
manifest.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0");
}
Name createdBy = new Name("Created-By");
if (!manifest.getMainAttributes().containsKey(createdBy)) {
manifest.getMainAttributes().put(createdBy, JarBuilder.class.getName());
}
return manifest;
}
private static Manifest createDefaultManifest() {
return ensureDefaultManifestEntries(new Manifest());
}
private static final ByteSource DEFAULT_MANIFEST = manifestSupplier(createDefaultManifest());
private interface InputSupplier<T> {
T getInput() throws IOException;
}
private static class JarSupplier implements InputSupplier<JarFile>, Closeable {
private final Closer closer;
private final InputSupplier<JarFile> supplier;
JarSupplier(final File file) {
closer = Closer.create();
supplier = new InputSupplier<JarFile>() {
@Override public JarFile getInput() throws IOException {
try {
// Do not verify signed.
return JarFileUtil.openJarFile(closer, file, false);
} catch (ZipException zex) {
// JarFile is not very verbose and doesn't tell the user which file it was
// so we will create a new Exception instead
ZipException e = new ZipException("error in opening zip file " + file);
e.initCause(zex);
throw e;
}
}
};
}
@Override
public JarFile getInput() throws IOException {
return supplier.getInput();
}
@Override
public void close() throws IOException {
closer.close();
}
}
private static final Splitter JAR_PATH_SPLITTER = Splitter.on('/');
private static final Joiner JAR_PATH_JOINER = Joiner.on('/');
/*
* Implementations should add jar entries to the given {@code Multimap} index when executed.
*/
private interface EntryIndexer {
void execute(Multimap<String, ReadableEntry> entries) throws JarBuilderException;
}
private final File target;
private final Listener listener;
private final Closer closer = Closer.create();
private final List<EntryIndexer> additions = Lists.newLinkedList();
@Nullable private ByteSource manifest;
/**
* Creates a JarBuilder that will write scheduled jar additions to {@code target} upon
* {@link #write}.
* <p>
* If the {@code target} exists an attempt will be made to over-write it and if it does not
* exist a then a new jar will be created at its path.
*
* @param target The target jar file to write.
*/
public JarBuilder(File target) {
this(target, Listener.NOOP);
}
/**
* Creates a JarBuilder that will write scheduled jar additions to {@code target} upon
* {@link #write}.
* <p>
* If the {@code target} does not exist a new jar will be created at its path.
*
* @param target The target jar file to write.
*/
public JarBuilder(File target, Listener listener) {
this.target = Preconditions.checkNotNull(target);
this.listener = Preconditions.checkNotNull(listener);
}
@Override
public void close() throws IOException {
closer.close();
}
/**
* Schedules addition of the given {@code contents} to the entry at {@code jarPath}. In addition,
* individual parent directory entries will be created when this builder is
* {@link #write written} in he spirit of {@code mkdir -p}.
*
* @param contents The contents of the entry to add.
* @param jarPath The path of the entry to add.
* @return This builder for chaining.
*/
public JarBuilder add(final ByteSource contents, final String jarPath) {
Preconditions.checkNotNull(contents);
Preconditions.checkNotNull(jarPath);
additions.add(new EntryIndexer() {
@Override public void execute(Multimap<String, ReadableEntry> entries) {
add(entries, NamedByteSource.create(memorySource(), jarPath, contents), jarPath);
}
});
return this;
}
private static boolean isEmpty(@Nullable String value) {
return value == null || value.trim().isEmpty();
}
/**
* Schedules recursive addition of all files contained within {@code directory} to the resulting
* jar. The path of each file relative to {@code directory} will be used for the corresponding
* jar entry path. If a {@code jarPath} is present then all subtree entries will be prefixed
* with it.
*
* @param directory An existing directory to add to the jar.
* @param jarPath An optional base path to graft the {@code directory} onto.
* @return This builder for chaining.
*/
public JarBuilder addDirectory(final File directory, final Optional<String> jarPath) {
Preconditions.checkArgument(directory.isDirectory(),
"Expected a directory, given a file: %s", directory);
Preconditions.checkArgument(!jarPath.isPresent() || !isEmpty(jarPath.get()));
additions.add(new EntryIndexer() {
@Override public void execute(Multimap<String, ReadableEntry> entries)
throws JarBuilderException {
Source directorySource = directorySource(directory);
Iterable<String> jarBasePath = jarPath.isPresent()
? JAR_PATH_SPLITTER.split(jarPath.get()) : ImmutableList.<String>of();
Iterable<File> files =
Files.fileTreeTraverser()
.preOrderTraversal(directory)
.filter(Files.isFile());
for (File child : files) {
Iterable<String> relpathComponents = relpathComponents(child, directory);
Iterable<String> path = Iterables.concat(jarBasePath, relpathComponents);
String entryPath = JAR_PATH_JOINER.join(relpathComponents);
if (!JarFile.MANIFEST_NAME.equals(entryPath)) {
NamedByteSource contents =
NamedByteSource.create(
directorySource,
entryPath,
Files.asByteSource(child));
add(entries, contents, JAR_PATH_JOINER.join(path));
}
}
}
});
return this;
}
/**
* Schedules addition of the given {@code file}'s contents to the entry at {@code jarPath}. In
* addition, individual parent directory entries will be created when this builder is
* {@link #write written} in the spirit of {@code mkdir -p}.
*
* @param file An existing file to add to the jar.
* @param jarPath The path of the entry to add.
* @return This builder for chaining.
*/
public JarBuilder addFile(final File file, final String jarPath) {
Preconditions.checkArgument(!file.isDirectory(),
"Expected a file, given a directory: %s", file);
Preconditions.checkArgument(!isEmpty(jarPath));
additions.add(new EntryIndexer() {
@Override
public void execute(Multimap<String, ReadableEntry> entries)
throws JarBuilderException {
if (JarFile.MANIFEST_NAME.equals(jarPath)) {
throw new JarBuilderException(
"A custom manifest entry should be added via the useCustomManifest methods");
}
NamedByteSource contents =
NamedByteSource.create(
fileSource(file),
file.getName(),
Files.asByteSource(file));
add(entries, contents, jarPath);
}
});
return this;
}
/**
* Schedules addition of the given jar's contents to the file at {@code jarPath}. Even if the jar
* does not contain individual parent directory entries, they will be added for each entry added.
*
* @param file The path of the jar to add.
* @return This builder for chaining.
*/
public JarBuilder addJar(final File file) {
Preconditions.checkNotNull(file);
additions.add(new EntryIndexer() {
@Override
public void execute(final Multimap<String, ReadableEntry> entries)
throws IndexingException {
final InputSupplier<JarFile> jarSupplier = closer.register(new JarSupplier(file));
final Source jarSource = jarSource(file);
try {
enumerateJarEntries(file, new JarEntryVisitor() {
@Override public void visit(JarEntry entry) throws IOException {
if (!entry.isDirectory() && !JarFile.MANIFEST_NAME.equals(entry.getName())) {
NamedByteSource contents =
NamedByteSource.create(
jarSource,
entry.getName(),
entrySupplier(jarSupplier, entry));
add(entries, contents, entry);
}
}
});
} catch (IOException e) {
throw new IndexingException(file, e);
}
}
});
return this;
}
private static void add(
Multimap<String, ReadableEntry> entries,
NamedByteSource contents,
String jarPath) {
entries.put(jarPath, new ReadableEntry(contents, jarPath));
}
private static void add(
Multimap<String, ReadableEntry> entries,
NamedByteSource contents,
JarEntry jarEntry) {
entries.put(jarEntry.getName(), new ReadableJarEntry(contents, jarEntry));
}
/**
* Registers the given Manifest to be used in the jar written out by {@link #write}.
*
* @param customManifest The manifest to use for the built jar.
* @return This builder for chaining.
*/
public JarBuilder useCustomManifest(final Manifest customManifest) {
Preconditions.checkNotNull(customManifest);
manifest = manifestSupplier(customManifest);
return this;
}
/**
* Registers the given Manifest to be used in the jar written out by {@link #write}.
*
* @param customManifest The manifest to use for the built jar.
* @return This builder for chaining.
*/
public JarBuilder useCustomManifest(File customManifest) {
Preconditions.checkNotNull(customManifest);
NamedByteSource contents =
NamedByteSource.create(
fileSource(customManifest),
customManifest.getPath(),
Files.asByteSource(customManifest));
return useCustomManifest(contents);
}
/**
* Registers the given Manifest to be used in the jar written out by {@link #write}.
*
* @param customManifest The manifest to use for the built jar.
* @return This builder for chaining.
*/
public JarBuilder useCustomManifest(CharSequence customManifest) {
Preconditions.checkNotNull(customManifest);
return useCustomManifest(
NamedByteSource.create(
memorySource(),
JarFile.MANIFEST_NAME,
ByteSource.wrap(customManifest.toString().getBytes(Charsets.UTF_8))));
}
/**
* Registers the given Manifest to be used in the jar written out by {@link #write}.
*
* @param customManifest The manifest to use for the built jar.
* @return This builder for chaining.
*/
public JarBuilder useCustomManifest(final NamedByteSource customManifest) {
Preconditions.checkNotNull(customManifest);
return useCustomManifest(new InputSupplier<Manifest>() {
@Override public Manifest getInput() throws IOException {
Manifest mf = new Manifest();
try {
mf.read(customManifest.openStream());
return mf;
} catch (IOException e) {
throw new JarCreationException(
"Invalid manifest from " + customManifest.source.identify(customManifest.name));
}
}
});
}
private JarBuilder useCustomManifest(final InputSupplier<Manifest> manifestSource) {
manifest = new ByteSource() {
@Override public InputStream openStream() throws IOException {
return manifestSupplier(manifestSource.getInput()).openStream();
}
};
return this;
}
/**
* Creates a jar at the configured target path applying the scheduled additions and skipping any
* duplicate entries found. Entries will not be compressed.
*
* @return The jar file that was written.
* @throws IOException if there was a problem writing the jar file.
*/
public File write() throws IOException {
return write(false, DuplicateHandler.always(DuplicateAction.SKIP));
}
/**
* Creates a jar at the configured target path applying the scheduled additions and skipping any
* duplicate entries found.
*
* @param compress Pass {@code true} to compress all jar entries; otherwise, they will just be
* stored.
* @return The jar file that was written.
* @throws IOException if there was a problem writing the jar file.
*/
public File write(boolean compress) throws IOException {
return write(compress, DuplicateHandler.always(DuplicateAction.SKIP));
}
/**
* Creates a jar at the configured target path applying the scheduled additions per the given
* {@code duplicateHandler}.
*
* @param compress Pass {@code true} to compress all jar entries; otherwise, they will just be
* stored.
* @param duplicateHandler A handler for dealing with duplicate entries.
* @param skipPatterns An optional list of patterns that match entry paths that should be
* excluded.
* @return The jar file that was written.
* @throws IOException if there was a problem writing the jar file.
* @throws DuplicateEntryException if the the policy in effect for an entry is
* {@link DuplicateAction#THROW} and that entry is a duplicate.
*/
public File write(
boolean compress,
DuplicateHandler duplicateHandler,
Pattern... skipPatterns)
throws IOException {
return write(compress, duplicateHandler, ImmutableList.copyOf(skipPatterns));
}
private static final Function<Pattern, Predicate<CharSequence>> AS_PATH_SELECTOR =
new Function<Pattern, Predicate<CharSequence>>() {
@Override public Predicate<CharSequence> apply(Pattern item) {
return Predicates.contains(item);
}
};
/**
* Creates a jar at the configured target path applying the scheduled additions per the given
* {@code duplicateHandler}.
*
* @param compress Pass {@code true} to compress all jar entries; otherwise, they will just be
* stored.
* @param duplicateHandler A handler for dealing with duplicate entries.
* @param skipPatterns An optional sequence of patterns that match entry paths that should be
* excluded.
* @return The jar file that was written.
* @throws IOException if there was a problem writing the jar file.
* @throws DuplicateEntryException if the the policy in effect for an entry is
* {@link DuplicateAction#THROW} and that entry is a duplicate.
*/
public File write(
final boolean compress,
DuplicateHandler duplicateHandler,
Iterable<Pattern> skipPatterns)
throws DuplicateEntryException, IOException {
Preconditions.checkNotNull(duplicateHandler);
Predicate<CharSequence> skipPath =
Predicates.or(Iterables.transform(ImmutableList.copyOf(skipPatterns), AS_PATH_SELECTOR));
final Iterable<ReadableEntry> entries = getEntries(skipPath, duplicateHandler);
File tmp = File.createTempFile(target.getName(), ".tmp", target.getParentFile());
try {
try {
JarWriter writer = jarWriter(tmp, compress);
writer.write(JarFile.MANIFEST_NAME, manifest == null ? DEFAULT_MANIFEST : manifest);
List<ReadableJarEntry> jarEntries = Lists.newArrayList();
for (ReadableEntry entry : entries) {
if (entry instanceof ReadableJarEntry) {
jarEntries.add((ReadableJarEntry) entry);
} else {
writer.write(entry.getJarPath(), entry.contents);
}
}
copyJarFiles(writer, jarEntries);
// Close all open files, the moveFile below might need to copy instead of just rename.
closer.close();
// Rename the file (or copy if it can't be renamed)
target.delete();
Files.move(tmp, target);
} catch (IOException e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
} finally {
tmp.delete();
}
return target;
}
/**
* As an optimization, use {@link JarEntryCopier} to copy one jar file to
* another without decompressing and recompressing.
*
* @param writer target to copy JAR file entries to.
* @param entries entries that came from a jar file
*/
private void copyJarFiles(JarWriter writer, Iterable<ReadableJarEntry> entries)
throws IOException {
// Walk the entries to bucketize by input jar file names
Multimap<JarSource, ReadableJarEntry> jarEntries = HashMultimap.create();
for (ReadableJarEntry entry : entries) {
Preconditions.checkState(entry.getSource() instanceof JarSource);
jarEntries.put((JarSource) entry.getSource(), entry);
}
// Copy the data from each jar input file to the output
for (JarSource source : jarEntries.keySet()) {
Closer jarFileCloser = Closer.create();
try {
final InputSupplier<JarFile> jarSupplier = jarFileCloser.register(
new JarSupplier(new File(source.name())));
JarFile jarFile = jarSupplier.getInput();
for (ReadableJarEntry readableJarEntry : jarEntries.get(source)) {
JarEntry jarEntry = readableJarEntry.getJarEntry();
String resource = jarEntry.getName();
writer.copy(resource, jarFile, jarEntry);
}
} catch (IOException ex) {
throw jarFileCloser.rethrow(ex);
} finally {
jarFileCloser.close();
}
}
}
private Iterable<ReadableEntry> getEntries(
final Predicate<CharSequence> skipPath,
final DuplicateHandler duplicateHandler)
throws JarBuilderException {
Function<Map.Entry<String, Collection<ReadableEntry>>, Iterable<ReadableEntry>> mergeEntries =
new Function<Map.Entry<String, Collection<ReadableEntry>>, Iterable<ReadableEntry>>() {
@Override
public Iterable<ReadableEntry> apply(Map.Entry<String, Collection<ReadableEntry>> item) {
String jarPath = item.getKey();
Collection<ReadableEntry> entries = item.getValue();
return processEntries(skipPath, duplicateHandler, jarPath, entries).asSet();
}
};
return FluentIterable.from(getAdditions().asMap().entrySet()).transformAndConcat(mergeEntries);
}
private Optional<ReadableEntry> processEntries(
Predicate<CharSequence> skipPath,
DuplicateHandler duplicateHandler,
String jarPath,
Collection<ReadableEntry> itemEntries) {
if (skipPath.apply(jarPath)) {
listener.onSkip(Optional.<Entry>absent(), itemEntries);
return Optional.absent();
}
if (itemEntries.size() < 2) {
ReadableEntry entry = Iterables.getOnlyElement(itemEntries);
listener.onWrite(entry);
return Optional.of(entry);
}
DuplicateAction action = duplicateHandler.actionFor(jarPath);
switch (action) {
case SKIP:
ReadableEntry original = Iterables.get(itemEntries, 0);
listener.onSkip(Optional.of(original), Iterables.skip(itemEntries, 1));
return Optional.of(original);
case REPLACE:
ReadableEntry replacement = Iterables.getLast(itemEntries);
listener.onReplace(Iterables.limit(itemEntries, itemEntries.size() - 1), replacement);
return Optional.of(replacement);
case CONCAT:
ByteSource concat =
ByteSource.concat(Iterables.transform(itemEntries, ReadableEntry.GET_CONTENTS));
ReadableEntry concatenatedEntry =
new ReadableEntry(
NamedByteSource.create(memorySource(), jarPath, concat),
jarPath);
listener.onConcat(jarPath, itemEntries);
return Optional.of(concatenatedEntry);
case THROW:
throw new DuplicateEntryException(Iterables.get(itemEntries, 1));
default:
throw new IllegalArgumentException("Unrecognized DuplicateAction " + action);
}
}
private Multimap<String, ReadableEntry> getAdditions() throws JarBuilderException {
final Multimap<String, ReadableEntry> entries = LinkedListMultimap.create();
if (target.exists() && target.length() > 0) {
final InputSupplier<JarFile> jarSupplier = closer.register(new JarSupplier(target));
try {
enumerateJarEntries(target, new JarEntryVisitor() {
@Override public void visit(JarEntry jarEntry) throws IOException {
String entryPath = jarEntry.getName();
ByteSource contents = entrySupplier(jarSupplier, jarEntry);
if (JarFile.MANIFEST_NAME.equals(entryPath)) {
if (manifest == null) {
manifest = contents;
}
} else if (!jarEntry.isDirectory()) {
entries.put(
entryPath,
new ReadableJarEntry(
NamedByteSource.create(jarSource(target), entryPath, contents),
jarEntry));
}
}
});
} catch (IOException e) {
throw new IndexingException(target, e);
}
}
for (EntryIndexer addition : additions) {
addition.execute(entries);
}
return entries;
}
private interface JarEntryVisitor {
void visit(JarEntry item) throws IOException;
}
private void enumerateJarEntries(File jarFile, JarEntryVisitor visitor)
throws IOException {
Closer jarFileCloser = Closer.create();
JarFile jar = JarFileUtil.openJarFile(jarFileCloser, jarFile);
try {
for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
visitor.visit(entries.nextElement());
}
} catch (IOException e) {
throw jarFileCloser.rethrow(e);
} finally {
jarFileCloser.close();
}
}
private static final class JarWriter {
static class EntryFactory {
private final boolean compress;
EntryFactory(boolean compress) {
this.compress = compress;
}
JarEntry createEntry(String path, ByteSource contents)
throws IOException {
JarEntry entry = new JarEntry(path);
entry.setMethod(compress ? JarEntry.DEFLATED : JarEntry.STORED);
if (!compress) {
prepareEntry(entry, contents);
}
return entry;
}
private void prepareEntry(JarEntry entry, ByteSource contents)
throws IOException {
final CRC32 crc32 = new CRC32();
long size = contents.read(new ByteProcessor<Long>() {
private long size = 0;
@Override
public boolean processBytes(byte[] buf, int off, int len) throws IOException {
size += len;
crc32.update(buf, off, len);
return true;
}
@Override
public Long getResult() {
return size;
}
});
entry.setSize(size);
entry.setCompressedSize(size);
entry.setCrc(crc32.getValue());
}
}
private static final Joiner JAR_PATH_JOINER = Joiner.on('/');
private final Set<List<String>> directories = Sets.newHashSet();
private final JarOutputStream out;
private final EntryFactory entryFactory;
private JarWriter(JarOutputStream out, boolean compress) {
this.out = out;
this.entryFactory = new EntryFactory(compress);
}
public void write(String path, ByteSource contents) throws IOException {
ensureParentDir(path);
out.putNextEntry(entryFactory.createEntry(path, contents));
contents.copyTo(out);
}
public void copy(String path, JarFile jarIn, JarEntry srcJarEntry) throws IOException {
ensureParentDir(path);
JarEntryCopier.copyEntry(out, path, jarIn, srcJarEntry);
}
private void ensureParentDir(String path) throws IOException {
File file = new File(path);
File parent = file.getParentFile();
if (parent != null) {
List<String> components = components(parent);
List<String> ancestry = Lists.newArrayListWithCapacity(components.size());
for (String component : components) {
ancestry.add(component);
if (!directories.contains(ancestry)) {
directories.add(ImmutableList.copyOf(ancestry));
out.putNextEntry(new JarEntry(JAR_PATH_JOINER.join(ancestry) + "/"));
}
}
}
}
}
private JarWriter jarWriter(File path, boolean compress) throws IOException {
// The JAR-writing process seems to be I/O bound. To make writes to disk less frequent,
// BufferedOutputStream is used. This way, compressed data is stored in a buffer before being
// flushed to disk.
// For benchmarking, "./pants binary --no-use-nailgun" command was executed on a large project.
// The machine was 2013 MPB with SSD. The resulting project JAR is about 500 MB.
// Without BufferedOutputStream, the jar-tool step took on average about 113 seconds.
// With BufferedOutputStream and 1MB buffer, the jar-tool step took on average about 80 seconds.
// The performance gain on this particular project on this particular machine is 30%.
FileOutputStream fout = closer.register(new FileOutputStream(path));
BufferedOutputStream bout = closer.register(new BufferedOutputStream(fout, 1024 * 1024));
final JarOutputStream jar = closer.register(new JarOutputStream(bout));
closer.register(new Closeable() {
@Override public void close() throws IOException {
jar.closeEntry();
}
});
return new JarWriter(jar, compress);
}
private static ByteSource entrySupplier(final InputSupplier<JarFile> jar, final JarEntry entry) {
return new ByteSource() {
@Override public InputStream openStream() throws IOException {
return jar.getInput().getInputStream(entry);
}
};
}
@VisibleForTesting
static Iterable<String> relpathComponents(File fullPath, File relativeTo) {
List<String> base = components(relativeTo);
List<String> path = components(fullPath);
for (Iterator<String> baseIter = base.iterator(), pathIter = path.iterator();
baseIter.hasNext() && pathIter.hasNext();) {
if (!baseIter.next().equals(pathIter.next())) {
break;
} else {
baseIter.remove();
pathIter.remove();
}
}
if (!base.isEmpty()) {
path.addAll(0, Collections.nCopies(base.size(), ".."));
}
return path;
}
private static List<String> components(File file) {
LinkedList<String> components = Lists.newLinkedList();
File path = file;
do {
components.addFirst(path.getName());
} while((path = path.getParentFile()) != null);
return components;
}
} |
package org.helioviewer.jhv.gui;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import com.jidesoft.icons.IconsFactory;
public class IconBank {
// The enum has all the icons, you supply these enums to the getIcon method.
public enum JHVIcon {
// The formatter will not merge together multiple lines, if at least one
// empty line is inserted in between:
PROPERTIES("properties16.gif"), BLANK("blank_square.gif"), ADD("edit_add.png"), DOWNLOAD("download_dm.png"),
// MOVIE CONTROLS
PLAY("play_dm.png"), PAUSE("agt_pause-queue.png"), BACK("agt_back.png"), FORWARD("agt_forward.png"), RECORD("rec.png"),
// ZOOMING
ZOOM_IN("zoomIn24.png"), ZOOM_IN_SMALL("zoomIn24small.png"),
ZOOM_FIT("zoomFit24.png"), ZOOM_FIT_SMALL("zoomFit24small.png"),
ZOOM_OUT("zoomOut24.png"), ZOOM_OUT_SMALL("zoomOut24small.png"),
ZOOM_1TO1("zoom1to124.png"), ZOOM_1TO1_SMALL("zoom1to124small.png"),
// ARROWS
LEFT("arrow_left.gif"), RIGHT("arrow_right.gif"), UP("1uparrow1.png"), DOWN("1downarrow1.png"), RIGHT2("arrow.plain.right.gif"), DOWN2("arrow.plain.down.gif"),
// MOUSE POINTERS
OPEN_HAND("OpenedHand.gif"), OPEN_HAND_SMALL("OpenedHand2.gif"), CLOSED_HAND("ClosedHand.gif"), OPEN_HAND_MAC("pointer.png"), CLOSED_HAND_MAC("drag.png"),
PAN("pan24x24.png"), PAN_SELECTED("pan_selected24x24.png"),
SELECT("select24x24.png"), SELECT_SELECTED("select_selected24x24.png"),
FOCUS("crosshairs24x24.png"), FOCUS_SELECTED("crosshairs_checked24x24.png"),
// MISC ICONS
VISIBLE("layer_visible_dm.png"), HIDDEN("layer_invisible_dm.png"),
REMOVE_LAYER_GRAY("button_cancel_gray.png"), REMOVE_LAYER("button_cancel.png"), INFO("info.png"),
CHECK("button_ok.png"), EX("button_cancel.png"), RUBBERBAND("rubberband.gif"), NOIMAGE("NoImageLoaded_256x256.png"),
CONNECTED("connected_dm.png"), DISCONNECTED("not_connected_dm.png"),
MOVIE_LINK("locked.png"), MOVIE_UNLINK("unlocked.png"),
SPLASH("jhv_splash.png"), HVLOGO_SMALL("hvImage_160x160.png"),
SIMPLE_ARROW_RIGHT("Arrow-Right.png"), SIMPLE_ARROW_LEFT("Arrow-Left.png"),
SIMPLE_DOUBLEARROW_RIGHT("DoubleArrow-Right.png"),
SIMPLE_DOUBLEARROW_LEFT("DoubleArrow-Left.png"),
DATE("date.png"),
SHOW_LESS("1uparrow1.png"), SHOW_MORE("1downarrow1.png"),
INVERT("invert.png"), LOADING_BIG("Loading_256x256.png"), LOADING_SMALL("Loading_219x50.png"),
// 3D Icons
MODE_3D("3D_24x24.png"), MODE_2D("2D_24x24.png"), MODE_3D_SELECTED("3D_selected_24x24.png"), MODE_2D_SELECTED("2D_selected_24x24.png"), RESET("Reset_24x24.png"), ROTATE("Rotate_24x24.png"), ROTATE_SELECTED("Rotate_selected_24x24.png"),
// LAYER ICONS
LAYER_IMAGE("layer-image.png"), LAYER_IMAGE_OFF("layer-image-off.png"), LAYER_IMAGE_TIME("layer-image-time.png"), LAYER_IMAGE_TIME_MASTER("layer-image-time-master.png"), LAYER_IMAGE_TIME_OFF("layer-image-time-off.png"), LAYER_MOVIE("layer-movie.png"), LAYER_MOVIE_OFF("layer-movie-off.png"), LAYER_MOVIE_TIME("layer-movie-time.png"), LAYER_MOVIE_TIME_MASTER("layer-movie-time-master.png"), LAYER_MOVIE_TIME_OFF("layer-movie-time-off.png"),
SDO_CUTOUT("sdocutout24x24.png");
private final String fname;
JHVIcon(String _fname) {
fname = _fname;
}
String getFilename() {
return fname;
}
}
/**
* Returns the ImageIcon associated with the given enum
*
* @param icon
* enum which represents the image
* @return the image icon of the given enum
* */
public static ImageIcon getIcon(JHVIcon icon) {
return IconsFactory.getImageIcon(IconBank.class, "/images/" + icon.getFilename());
}
public static ImageIcon getIcon(JHVIcon icon, int w, int h) {
return new ImageIcon(getIcon(icon).getImage().getScaledInstance(w, h, Image.SCALE_SMOOTH));
}
/**
* Returns the Image with the given enum.
*
* @param icon
* Name of the image which should be loaded
* @return Image for the given name or null if it fails to load the image.
* */
public static BufferedImage getImage(JHVIcon icon) {
Image image = getIcon(icon).getImage();
if (image != null && image.getWidth(null) > 0 && image.getHeight(null) > 0) {
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bi;
}
return null;
}
} |
package org.apache.jorphan.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.reflect.ClassFinder;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
public final class AllTests
{
transient private static Logger log = LoggingManager.getLoggerForClass();
/**
* Private constructor to prevent instantiation.
*/
private AllTests()
{
}
/**
* Starts a run through all unit tests found in the specified classpaths.
* The first argument should be a list of paths to search. The second
* argument is optional and specifies a properties file used to initialize
* logging. The third argument is also optional, and specifies a class
* that implements the UnitTestManager interface. This provides a means of
* initializing your application with a configuration file prior to the
* start of any unit tests.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
if (args.length < 1)
{
System.out.println(
"You must specify a comma-delimited list of paths to search " +
"for unit tests");
System.exit(0);
}
initializeLogging(args);
initializeManager(args);
// end : added - 11 July 2001
// GUI tests throw the error
// testArgumentCreation(org.apache.jmeter.config.gui.ArgumentsPanel$Test)java.lang.NoClassDefFoundError
// at java.lang.Class.forName0(Native Method)
// at java.lang.Class.forName(Class.java:141)
// at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62)
// Try to find out why this is ...
String e = "java.awt.headless";
String g="java.awt.graphicsenv";
System.out.println(e+"="+System.getProperty(e));
System.out.println(g+"="+System.getProperty(g));
// don't call any graphics routines here, as some have side effects
TestSuite suite = suite(args[0]);
// Jeremy Arnold: This method used to attempt to write results to
// a file, but it had a bug and instead just wrote to System.out.
// Since nobody has complained about this behavior, I'm changing
// the code to not attempt to write to a file, so it will continue
// behaving as it did before. It would be simple to make it write
// to a file instead if that is the desired behavior.
TestRunner.run(suite);
// Recheck settings:
System.out.println(e+"="+System.getProperty(e));
System.out.println(g+"="+System.getProperty(g));
System.out.println("Headless? "+java.awt.GraphicsEnvironment.isHeadless());
System.exit(0);
}
/**
* An overridable method that initializes the logging for the unit test
* run, using the properties file passed in as the second argument.
* @param args
*/
protected static void initializeLogging(String[] args)
{
if (args.length >= 2)
{
Properties props = new Properties();
try
{
System.out.println(
"setting up logging props using file: " + args[1]);
props.load(new FileInputStream(args[1]));
LoggingManager.initializeLogging(props);
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
}
/**
* An overridable method that that instantiates a UnitTestManager (if one
* was specified in the command-line arguments), and hands it the name of
* the properties file to use to configure the system.
* @param args
*/
protected static void initializeManager(String[] args)
{
if (args.length >= 3)
{
try
{
UnitTestManager um =
(UnitTestManager) Class.forName(args[2]).newInstance();
um.initializeProperties(args[1]);
}
catch (Exception e)
{
System.out.println("Couldn't create: " + args[2]);
e.printStackTrace();
}
}
}
/**
* A unit test suite for JUnit.
*
* @return The test suite
*/
private static TestSuite suite(String searchPaths)
{
TestSuite suite = new TestSuite();
try
{
Iterator classes =
ClassFinder
.findClassesThatExtend(
JOrphanUtils.split(searchPaths, ","),
new Class[] { TestCase.class },
true)
.iterator();
while (classes.hasNext())
{
String name = (String) classes.next();
try
{
suite.addTest(new TestSuite(Class.forName(name)));
}
catch (Exception ex)
{
log.error("error adding test :" + ex);
}
}
}
catch (IOException e)
{
log.error("", e);
}
catch (ClassNotFoundException e)
{
log.error("", e);
}
return suite;
}
} |
package krasa.grepconsole.filter;
import com.intellij.execution.filters.InputFilter;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import krasa.grepconsole.filter.support.FilterState;
import krasa.grepconsole.filter.support.GrepProcessor;
import krasa.grepconsole.model.GrepExpressionItem;
import krasa.grepconsole.model.Profile;
import krasa.grepconsole.plugin.ExtensionManager;
import krasa.grepconsole.utils.Notifier;
import krasa.grepconsole.utils.Utils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class GrepInputFilter extends AbstractGrepFilter implements InputFilter {
private static final Logger log = Logger.getInstance(GrepInputFilter.class);
private static final Pair<String, ConsoleViewContentType> REMOVE_OUTPUT_PAIR = new Pair<>(null, null);
private static final Pattern PATTERN = Pattern.compile("(?<=\n)");
private WeakReference<ConsoleView> console;
private volatile boolean lastLineFiltered = false;
private volatile boolean removeNextNewLine = false;
private boolean testConsole;
private volatile GrepCopyingFilter grepFilter;
public GrepInputFilter(Project project, Profile profile) {
super(project, profile);
}
public GrepInputFilter(Profile profile, List<GrepProcessor> grepProcessors) {
super(profile, grepProcessors);
}
public void init(WeakReference<ConsoleView> console, Profile profile) {
this.profile = profile;
this.console = console;
ConsoleView consoleView = console.get();
if (consoleView != null) {
testConsole = consoleView.getClass().getName().startsWith("com.intellij.execution.testframework.ui");
log.info("Initializing for " + consoleView.getClass().getName());
}
}
@Override
public List<Pair<String, ConsoleViewContentType>> applyFilter(String text, ConsoleViewContentType consoleViewContentType) {
List<Pair<String, ConsoleViewContentType>> result = filter(text, consoleViewContentType);
grep(result, text, consoleViewContentType);
return result;
}
@Nullable
protected List<Pair<String, ConsoleViewContentType>> filter(String text, ConsoleViewContentType consoleViewContentType) {
List<Pair<String, ConsoleViewContentType>> result = null;
if (!grepProcessors.isEmpty()) {
String[] split;
try {
split = PATTERN.split(profile.limitProcessingTime(text), 0);
} catch (ProcessCanceledException e) {
notifyError(text);
return null;
}
result = new ArrayList<>(split.length);
for (int i = 0; i < split.length; i++) {
String s = split[i];
if (lastLineFiltered && removeNextNewLine && s.equals("\n")) {
removeNextNewLine = false;
result.add(REMOVE_OUTPUT_PAIR);
continue;
}
FilterState state = super.filter(s, -1);
clearConsole(state, result, consoleViewContentType);
prepareResult(result, s, state, consoleViewContentType);
}
//let other InputFilters work
if (split.length == 1 && result.size() == 1) {
if (result.get(0).first == text) {
result = null;
}
}
}
return result;
}
private void notifyError(String text) {
String message = "preparing input text for matching took too long, aborting to prevent GUI freezing.\n"
+ "Consider reporting bug, not logging huge chunks of text, or changing following settings: 'Max processing time for a line'\n"
+ "Text: " + Utils.toNiceLineForLog(text);
if (showLimitNotification) {
showLimitNotification = false;
Notifier.notify_InputAndHighlight(project, message);
} else {
log.warn(message);
}
}
//if we change output, then next InputFilter won't get processed, so Grep it here.
private void grep(List<Pair<String, ConsoleViewContentType>> pairs, String text, ConsoleViewContentType consoleViewContentType) {
if (grepFilter != null) {
if (pairs == null) {
grepFilter.applyFilter(text, consoleViewContentType);
} else {
for (int i = 0; i < pairs.size(); i++) {
Pair<String, ConsoleViewContentType> pair = pairs.get(i);
if (pair == REMOVE_OUTPUT_PAIR) {
} else if (pair != null) {
grepFilter.applyFilter(pair.first, pair.second);
}
}
}
}
}
public void clearConsole(FilterState state, List<Pair<String, ConsoleViewContentType>> pairs, ConsoleViewContentType consoleViewContentType) {
if (state != null && state.isClearConsole()) {
ConsoleView consoleView = console.get();
if (consoleView != null) {
consoleView.clear();
grep(pairs, null, consoleViewContentType);
pairs.clear();
}
}
}
private List<Pair<String, ConsoleViewContentType>> prepareResult(List<Pair<String, ConsoleViewContentType>> result, String s, FilterState state, ConsoleViewContentType consoleViewContentType) {
boolean previousLineFiltered = lastLineFiltered;
lastLineFiltered = false;
removeNextNewLine = false;
if (state != null) {
if (state.isExclude()) {
result.add(REMOVE_OUTPUT_PAIR);
lastLineFiltered = true;
removeNextNewLine = testConsole && state.notTerminatedWithNewline();
return result;
} else if (profile.isMultilineInputFilter() && !state.isMatchesSomething() && previousLineFiltered) {
result.add(REMOVE_OUTPUT_PAIR);
lastLineFiltered = true;
removeNextNewLine = testConsole && state.notTerminatedWithNewline();
return result;
}
}
if (state != null && state.isTextChanged()) {
result.add(new Pair<>(state.getText(), consoleViewContentType));
return result;
} else {
// input is not changed
result.add(new Pair<>(s, consoleViewContentType));
return result;
}
}
@Override
public void onChange() {
super.onChange();
lastLineFiltered = false;
}
@Override
protected void initProcessors() {
grepProcessors = new ArrayList<>();
if (profile.isEnabledInputFiltering()) {
boolean inputFilterExists = false;
if (profile.isTestHighlightersInInputFilter()) {
grepProcessors.add(new HighlighterTestProcessor(profile.getAllGrepExpressionItems()));
}
for (GrepExpressionItem grepExpressionItem : profile.getAllInputFilterExpressionItems()) {
if (!grepExpressionItem.isEnabled()) {
continue;
}
GrepProcessor processor = createProcessor(grepExpressionItem);
validate(processor);
grepProcessors.add(processor);
inputFilterExists = true;
}
if (!inputFilterExists) {
grepProcessors.clear();
}
}
}
private void validate(GrepProcessor processor) {
String action = processor.getGrepExpressionItem().getAction();
if (StringUtils.isNotBlank(action) //blank == no action
&& !GrepExpressionItem.ACTION_REMOVE_UNLESS_MATCHED.equals(action)
&& !GrepExpressionItem.ACTION_BUFFER_UNTIL_NEWLINE.equals(action)
&& !GrepExpressionItem.ACTION_REMOVE.equals(action)
&& !GrepExpressionItem.ACTION_NO_ACTION.equals(action)) {
if (ExtensionManager.getFunction(action) == null) {
Notifier.notify_MissingExtension(action, project);
}
}
}
@Override
protected boolean shouldAdd(GrepExpressionItem item) {
// return profile.isEnabledInputFiltering() && (item.isInputFilter() || item.isClearConsole());
throw new UnsupportedOperationException();
}
public GrepCopyingFilter getGrepFilter() {
return grepFilter;
}
public void setGrepFilter(GrepCopyingFilter copyingFilter) {
this.grepFilter = copyingFilter;
}
} |
package java.awt;
import java.awt.event.InvocationEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import org.videolan.Libbluray;
public class BDRootWindow extends Frame {
public BDRootWindow () {
super();
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
BDToolkit.setFocusedWindow(this);
}
public Rectangle getDirtyRect() {
return dirty;
}
public void setBounds(int x, int y, int width, int height) {
if (!isVisible()) {
if ((width > 0) && (height > 0)) {
if ((backBuffer == null) || (getWidth() * getHeight() < width * height)) {
backBuffer = new int[width * height];
dirty = new Rectangle(0, 0, width, height);
Arrays.fill(backBuffer, 0);
}
}
super.setBounds(x, y, width, height);
Libbluray.updateGraphic(width, height, null);
dirty.setBounds(0, 0, width, height);
}
}
public int[] getBdBackBuffer() {
return backBuffer;
}
public Image getBackBuffer() {
/* exists only in J2SE */
org.videolan.Logger.getLogger("BDRootWindow").unimplemented("getBackBuffer");
return null;
}
public static void stopEventQueue(EventQueue eq) {
EventDispatchThread t = eq.getDispatchThread();
if (t != null) {
final long DISPOSAL_TIMEOUT = 5000;
final Object notificationLock = new Object();
Runnable runnable = new Runnable() { public void run() {
synchronized(notificationLock) {
notificationLock.notifyAll();
}
} };
synchronized (notificationLock) {
eq.postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));
try {
notificationLock.wait(DISPOSAL_TIMEOUT);
} catch (InterruptedException e) {
}
}
t.stopDispatching();
}
}
public void postKeyEvent(int id, int modifiers, int keyCode) {
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getGlobalFocusOwner();
if (focusOwner != null) {
long when = System.currentTimeMillis();
KeyEvent event;
try {
if (id == KeyEvent.KEY_TYPED)
event = new KeyEvent(focusOwner, id, when, modifiers, KeyEvent.VK_UNDEFINED, (char)keyCode);
else
event = new KeyEvent(focusOwner, id, when, modifiers, keyCode, KeyEvent.CHAR_UNDEFINED);
BDToolkit.getEventQueue(focusOwner).postEvent(event);
return;
} catch (Throwable e) {
System.err.println(" *** " + e + "");
}
} else {
org.videolan.Logger.getLogger("BDRootWindow").error("*** KEY event dropped ***");
}
}
public void notifyChanged() {
if (!isVisible()) {
org.videolan.Logger.getLogger("BDRootWindow").error("sync(): not visible");
return;
}
synchronized (this) {
changeCount++;
if (timerTask == null) {
timerTask = new RefreshTimerTask(this);
timer.schedule(timerTask, 50, 50);
}
}
}
public void sync() {
synchronized (this) {
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
changeCount = 0;
//Libbluray.updateGraphic(getWidth(), getHeight(), backBuffer, dirty.x, dirty.y, dirty.width, dirty.height);
Libbluray.updateGraphic(getWidth(), getHeight(), backBuffer);
dirty.setBounds(getWidth(), getHeight(), 0, 0);
}
}
private class RefreshTimerTask extends TimerTask {
public RefreshTimerTask(BDRootWindow window) {
this.window = window;
this.changeCount = window.changeCount;
}
public void run() {
synchronized (window) {
if (this.changeCount == window.changeCount)
window.sync();
else
this.changeCount = window.changeCount;
}
}
private BDRootWindow window;
private int changeCount;
}
public void dispose()
{
if (isVisible()) {
hide();
}
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
BDToolkit.setFocusedWindow(null);
super.dispose();
}
private int[] backBuffer = null;
private Rectangle dirty = new Rectangle();
private int changeCount = 0;
private Timer timer = new Timer();
private TimerTask timerTask = null;
private static final long serialVersionUID = -8325961861529007953L;
} |
package SW9.controllers;
import SW9.abstractions.*;
import SW9.code_analysis.CodeAnalysis;
import SW9.code_analysis.Nearable;
import SW9.model_canvas.arrow_heads.SimpleArrowHead;
import SW9.presentations.CanvasPresentation;
import SW9.presentations.DropDownMenu;
import SW9.presentations.Link;
import SW9.presentations.NailPresentation;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.Color;
import SW9.utility.helpers.BindingHelper;
import SW9.utility.helpers.Circular;
import SW9.utility.helpers.ItemDragHelper;
import SW9.utility.helpers.SelectHelper;
import com.jfoenix.controls.JFXPopup;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.util.Duration;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import static SW9.presentations.CanvasPresentation.GRID_SIZE;
public class EdgeController implements Initializable, SelectHelper.ItemSelectable {
private static final Map<Edge, Boolean> initializedEdgeFromTargetError = new HashMap<>();
private static final Map<Edge, Boolean> initializedEdgeToInitialError = new HashMap<>();
private static final Map<Edge, Boolean> initializedEdgeToForkError = new HashMap<>();
private static final Map<Edge, Boolean> initializedEdgeFromJoinError = new HashMap<>();
private final ObservableList<Link> links = FXCollections.observableArrayList();
private final ObjectProperty<Edge> edge = new SimpleObjectProperty<>();
private final ObjectProperty<Component> component = new SimpleObjectProperty<>();
private final SimpleArrowHead simpleArrowHead = new SimpleArrowHead();
private final SimpleBooleanProperty isHoveringEdge = new SimpleBooleanProperty(false);
private final SimpleIntegerProperty timeHoveringEdge = new SimpleIntegerProperty(0);
private final Map<Nail, NailPresentation> nailNailPresentationMap = new HashMap<>();
public Group edgeRoot;
private Runnable collapseNail;
private Thread runningThread;
private Consumer<Nail> enlargeNail;
private Consumer<Nail> shrinkNail;
private Circle dropDownMenuHelperCircle;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
initializeNailCollapse();
edge.addListener((obsEdge, oldEdge, newEdge) -> {
newEdge.targetCircularProperty().addListener(getNewTargetCircularListener(newEdge));
component.addListener(getComponentChangeListener(newEdge));
// Invalidate the list of edges (to update UI and errors)
newEdge.targetCircularProperty().addListener(observable -> {
getComponent().getEdges().remove(getEdge());
getComponent().getEdges().add(getEdge());
});
});
initializeLinksListener();
ensureNailsInFront();
initializeSelectListener();
}
private void initializeSelectListener() {
SelectHelper.elementsToBeSelected.addListener(new ListChangeListener<Nearable>() {
@Override
public void onChanged(final Change<? extends Nearable> c) {
while (c.next()) {
if (c.getAddedSize() == 0) return;
for (final Nearable nearable : SelectHelper.elementsToBeSelected) {
if (nearable instanceof Edge) {
if (nearable.equals(getEdge())) {
SelectHelper.addToSelection(EdgeController.this);
break;
}
}
}
}
}
});
}
public void initializeEdgeErrorFromTargetLocation() {
if (initializedEdgeFromTargetError.containsKey(getEdge())) return; // Already initialized
initializedEdgeFromTargetError.put(getEdge(), true); // Set initialized
final CodeAnalysis.Message message = new CodeAnalysis.Message("Outgoing edges from a target location are not allowed", CodeAnalysis.MessageType.ERROR, getEdge());
final Consumer<Location> checkIfErrorIsPresent = (sourceLocation) -> {
if (sourceLocation != null
&& sourceLocation.getType().equals(Location.Type.FINAl)
&& getComponent().getEdges().contains(getEdge())
&& getEdge().getTargetCircular() != null) {
// Add the message to the UI
CodeAnalysis.addMessage(getComponent(), message);
} else {
// Remove the message from the UI
CodeAnalysis.removeMessage(getComponent(), message);
}
};
// When the source location is updated
getEdge().sourceLocationProperty().addListener((obs, oldSource, newSource) -> checkIfErrorIsPresent.accept(newSource));
// When the list of edges are updated
final InvalidationListener listener = observable -> checkIfErrorIsPresent.accept(getEdge().getSourceLocation());
getComponent().getEdges().addListener(listener);
// Check if the error is present right now
checkIfErrorIsPresent.accept(getEdge().getSourceLocation());
}
public void initializeEdgeErrorToInitialLocation() {
if (initializedEdgeToInitialError.containsKey(getEdge())) return; // Already initialized
initializedEdgeToInitialError.put(getEdge(), true); // Set initialized
final CodeAnalysis.Message message = new CodeAnalysis.Message("Incoming edges to an initial location are not allowed", CodeAnalysis.MessageType.ERROR, getEdge());
final Consumer<Location> checkIfErrorIsPresent = (targetLocation) -> {
if (targetLocation != null
&& targetLocation.getType().equals(Location.Type.INITIAL)
&& getComponent().getEdges().contains(getEdge())) {
// Add the message to the UI
CodeAnalysis.addMessage(getComponent(), message);
} else {
// Remove the message from the UI
CodeAnalysis.removeMessage(getComponent(), message);
}
};
// When the source location is updated
getEdge().targetLocationProperty().addListener((obs, oldTarget, newTarget) -> checkIfErrorIsPresent.accept(newTarget));
// When the list of edges are updated
final InvalidationListener listener = observable -> checkIfErrorIsPresent.accept(getEdge().getTargetLocation());
getComponent().getEdges().addListener(listener);
// Check if the error is present right now
checkIfErrorIsPresent.accept(getEdge().getTargetLocation());
}
public void initializeEdgeToForkError() {
if (initializedEdgeToForkError.containsKey(getEdge())) return; // Already initialized
initializedEdgeToForkError.put(getEdge(), true); // Set initialized
final CodeAnalysis.Message message = new CodeAnalysis.Message("Only subcomponents can run in parallel", CodeAnalysis.MessageType.ERROR, getEdge());
final Consumer<Edge> checkIfErrorIsPresent = (edge) -> {
if (edge != null // The edge is not null
// The edge is not being drawn
&& !edge.equals(getComponent().getUnfinishedEdge())
// The edge has a source jork
&& edge.getSourceJork() != null
// The source jork is a fork
&& edge.getSourceJork().getType().equals(Jork.Type.FORK)
// The jork does not have a sub component as its target
&& edge.getTargetSubComponent() == null
// The edge is in the component (not deleted)
&& getComponent().getEdges().contains(edge)) {
// Add the message to the UI
CodeAnalysis.addMessage(getComponent(), message);
} else {
// Add the message to the UI
CodeAnalysis.removeMessage(getComponent(), message);
}
};
// When the target location is updated
getEdge().targetCircularProperty().addListener((obs, oldTarget, newTarget) -> checkIfErrorIsPresent.accept(getEdge()));
// When the list of edges are updated
final InvalidationListener listener = observable -> checkIfErrorIsPresent.accept(getEdge());
getComponent().getEdges().addListener(listener);
// Check if the error is present right now
checkIfErrorIsPresent.accept(getEdge());
}
public void initializeEdgeFromJoinError() {
if (initializedEdgeFromJoinError.containsKey(getEdge())) return; // Already initialized
initializedEdgeFromJoinError.put(getEdge(), true); // Set initialized
final CodeAnalysis.Message message = new CodeAnalysis.Message("Only subcomponents that are running in parallel can be joined", CodeAnalysis.MessageType.ERROR, getEdge());
final Consumer<Edge> checkIfErrorIsPresent = (edge) -> {
if (edge != null // The edge is not null
// The edge is not being drawn
&& !edge.equals(getComponent().getUnfinishedEdge())
// The edge has a target jork
&& edge.getTargetJork() != null
// The target jork is a join
&& edge.getTargetJork().getType().equals(Jork.Type.JOIN)
// The jork does not have a sub component as its source
&& edge.getSourceSubComponent() == null
// The edge is in the component (not deleted)
&& getComponent().getEdges().contains(edge)) {
// Add the message to the UI
CodeAnalysis.addMessage(getComponent(), message);
} else {
// Add the message to the UI
CodeAnalysis.removeMessage(getComponent(), message);
}
};
// When the target location is updated
getEdge().targetCircularProperty().addListener((obs, oldTarget, newTarget) -> checkIfErrorIsPresent.accept(getEdge()));
// When the list of edges are updated
final InvalidationListener listener = observable -> checkIfErrorIsPresent.accept(getEdge());
getComponent().getEdges().addListener(listener);
// Check if the error is present right now
checkIfErrorIsPresent.accept(getEdge());
}
private void ensureNailsInFront() {
// When ever changes happens to the children of the edge root force nails in front and other elements to back
edgeRoot.getChildren().addListener((ListChangeListener<? super Node>) c -> {
while (c.next()) {
for (int i = 0; i < c.getAddedSize(); i++) {
final Node node = c.getAddedSubList().get(i);
if (node instanceof NailPresentation) {
node.toFront();
} else {
node.toBack();
}
}
}
});
}
private ChangeListener<Component> getComponentChangeListener(final Edge newEdge) {
return (obsComponent, oldComponent, newComponent) -> {
if (newEdge.getNails().isEmpty() && newEdge.getTargetCircular() == null) {
final Link link = new Link();
links.add(link);
// Add the link and its arrowhead to the view
edgeRoot.getChildren().addAll(link, simpleArrowHead);
// Bind the first link and the arrowhead from the source location to the mouse
BindingHelper.bind(link, simpleArrowHead, newEdge.getSourceCircular(), newComponent.xProperty(), newComponent.yProperty());
} else if (newEdge.getTargetCircular() != null) {
edgeRoot.getChildren().add(simpleArrowHead);
final Circular[] previous = {newEdge.getSourceCircular()};
newEdge.getNails().forEach(nail -> {
final Link link = new Link();
links.add(link);
final NailPresentation nailPresentation = new NailPresentation(nail, newEdge, getComponent());
nailNailPresentationMap.put(nail, nailPresentation);
edgeRoot.getChildren().addAll(link, nailPresentation);
BindingHelper.bind(link, previous[0], nail);
previous[0] = nail;
});
final Link link = new Link();
links.add(link);
edgeRoot.getChildren().add(link);
BindingHelper.bind(link, simpleArrowHead, previous[0], newEdge.getTargetCircular());
}
// Changes are made to the nails list
newEdge.getNails().addListener(getNailsChangeListener(newEdge, newComponent));
};
}
private ListChangeListener<Nail> getNailsChangeListener(final Edge newEdge, final Component newComponent) {
return change -> {
while (change.next()) {
// There were added some nails
change.getAddedSubList().forEach(newNail -> {
// Create a new nail presentation based on the abstraction added to the list
final NailPresentation newNailPresentation = new NailPresentation(newNail, newEdge, newComponent);
nailNailPresentationMap.put(newNail, newNailPresentation);
edgeRoot.getChildren().addAll(newNailPresentation);
if (newEdge.getTargetCircular() != null) {
final int indexOfNewNail = edge.get().getNails().indexOf(newNail);
final Link newLink = new Link();
final Link pressedLink = links.get(indexOfNewNail);
links.add(indexOfNewNail, newLink);
edgeRoot.getChildren().addAll(newLink);
Circular oldStart = getEdge().getSourceCircular();
Circular oldEnd = getEdge().getTargetCircular();
if (indexOfNewNail != 0) {
oldStart = getEdge().getNails().get(indexOfNewNail - 1);
}
if (indexOfNewNail != getEdge().getNails().size() - 1) {
oldEnd = getEdge().getNails().get(indexOfNewNail + 1);
}
BindingHelper.bind(newLink, oldStart, newNail);
if (oldEnd.equals(getEdge().getTargetCircular())) {
BindingHelper.bind(pressedLink, simpleArrowHead, newNail, oldEnd);
} else {
BindingHelper.bind(pressedLink, newNail, oldEnd);
}
if (isHoveringEdge.get()) {
enlargeNail.accept(newNail);
}
} else {
// The previous last link must end in the new nail
final Link lastLink = links.get(links.size() - 1);
// If the nail is the first in the list, bind it to the source location
// otherwise, bind it the the previous nail
final int nailIndex = edge.get().getNails().indexOf(newNail);
if (nailIndex == 0) {
BindingHelper.bind(lastLink, newEdge.getSourceCircular(), newNail);
} else {
final Nail previousNail = edge.get().getNails().get(nailIndex - 1);
BindingHelper.bind(lastLink, previousNail, newNail);
}
// Create a new link that will bind from the new nail to the mouse
final Link newLink = new Link();
links.add(newLink);
BindingHelper.bind(newLink, simpleArrowHead, newNail, newComponent.xProperty(), newComponent.yProperty());
edgeRoot.getChildren().add(newLink);
}
});
change.getRemoved().forEach(removedNail -> {
final int removedIndex = change.getFrom();
final NailPresentation removedNailPresentation = nailNailPresentationMap.remove(removedNail);
final Link danglingLink = links.get(removedIndex + 1);
edgeRoot.getChildren().remove(removedNailPresentation);
edgeRoot.getChildren().remove(links.get(removedIndex));
Circular newFrom = getEdge().getSourceCircular();
Circular newTo = getEdge().getTargetCircular();
if (removedIndex > 0) {
newFrom = getEdge().getNails().get(removedIndex - 1);
}
if (removedIndex - 1 != getEdge().getNails().size() - 1) {
newTo = getEdge().getNails().get(removedIndex);
}
if (newTo.equals(getEdge().getTargetCircular())) {
BindingHelper.bind(danglingLink, simpleArrowHead, newFrom, newTo);
} else {
BindingHelper.bind(danglingLink, newFrom, newTo);
}
links.remove(removedIndex);
});
}
};
}
private ChangeListener<Circular> getNewTargetCircularListener(final Edge newEdge) {
// When the target location is set, finish drawing the edge
return (obsTargetLocation, oldTargetCircular, newTargetCircular) -> {
// If the nails list is empty, directly connect the source and target locations
// otherwise, bind the line from the last nail to the target location
final Link lastLink = links.get(links.size() - 1);
final ObservableList<Nail> nails = getEdge().getNails();
if (nails.size() == 0) {
// Check if the source and target locations are the same, if they are, add proper amount of nails
if (newEdge.getSourceCircular().equals(newTargetCircular)) {
final Nail nail1 = new Nail(newTargetCircular.xProperty(), newTargetCircular.yProperty().add(3 * CanvasPresentation.GRID_SIZE));
final Nail nail2 = new Nail(newTargetCircular.xProperty(), newTargetCircular.yProperty().add(5 * CanvasPresentation.GRID_SIZE));
final Nail nail3 = new Nail(newTargetCircular.xProperty(), newTargetCircular.yProperty().add(7 * CanvasPresentation.GRID_SIZE));
final Nail nail4 = new Nail(newTargetCircular.xProperty(), newTargetCircular.yProperty().add(9 * CanvasPresentation.GRID_SIZE));
final Nail nail5 = new Nail(newTargetCircular.xProperty().subtract(4 * CanvasPresentation.GRID_SIZE), newTargetCircular.yProperty().add(9 * CanvasPresentation.GRID_SIZE));
final Nail nail6 = new Nail(newTargetCircular.xProperty().subtract(4 * CanvasPresentation.GRID_SIZE), newTargetCircular.yProperty());
// Add the nails to the nails collection (will draw links between them)
nails.addAll(nail1, nail2, nail3, nail4, nail5, nail6);
// Find the new last link (updated by adding nails to the collection) and bind it from the last nail to the target location
final Link newLastLink = links.get(links.size() - 1);
BindingHelper.bind(newLastLink, simpleArrowHead, nail6, newTargetCircular);
} else {
BindingHelper.bind(lastLink, simpleArrowHead, newEdge.getSourceCircular(), newEdge.getTargetCircular());
}
} else {
final Nail lastNail = nails.get(nails.size() - 1);
BindingHelper.bind(lastLink, simpleArrowHead, lastNail, newEdge.getTargetCircular());
}
// When the target location is set the
edgeRoot.setMouseTransparent(false);
};
}
private void initializeNailCollapse() {
enlargeNail = nail -> {
if (!nail.getPropertyType().equals(Edge.PropertyType.NONE)) return;
final Timeline animation = new Timeline();
final KeyValue radius0 = new KeyValue(nail.radiusProperty(), NailPresentation.COLLAPSED_RADIUS);
final KeyValue radius2 = new KeyValue(nail.radiusProperty(), NailPresentation.HOVERED_RADIUS * 1.2);
final KeyValue radius1 = new KeyValue(nail.radiusProperty(), NailPresentation.HOVERED_RADIUS);
final KeyFrame kf1 = new KeyFrame(Duration.millis(0), radius0);
final KeyFrame kf2 = new KeyFrame(Duration.millis(80), radius2);
final KeyFrame kf3 = new KeyFrame(Duration.millis(100), radius1);
animation.getKeyFrames().addAll(kf1, kf2, kf3);
animation.play();
};
shrinkNail = nail -> {
if (!nail.getPropertyType().equals(Edge.PropertyType.NONE)) return;
final Timeline animation = new Timeline();
final KeyValue radius0 = new KeyValue(nail.radiusProperty(), NailPresentation.COLLAPSED_RADIUS);
final KeyValue radius1 = new KeyValue(nail.radiusProperty(), NailPresentation.HOVERED_RADIUS);
final KeyFrame kf1 = new KeyFrame(Duration.millis(0), radius1);
final KeyFrame kf2 = new KeyFrame(Duration.millis(100), radius0);
animation.getKeyFrames().addAll(kf1, kf2);
animation.play();
};
collapseNail = () -> {
final int interval = 50;
int previousValue = 1;
try {
while (true) {
Thread.sleep(interval);
if (isHoveringEdge.get()) {
// Do not let the timer go above this threshold
if (timeHoveringEdge.get() <= 500) {
timeHoveringEdge.set(timeHoveringEdge.get() + interval);
}
} else {
timeHoveringEdge.set(timeHoveringEdge.get() - interval);
}
if (previousValue >= 0 && timeHoveringEdge.get() < 0) {
// Run on UI thread
Platform.runLater(() -> {
// Collapse all nails
getEdge().getNails().forEach(shrinkNail);
});
break;
}
previousValue = timeHoveringEdge.get();
}
} catch (final InterruptedException e) {
e.printStackTrace();
}
};
}
private void initializeLinksListener() {
// Tape
dropDownMenuHelperCircle = new Circle(5);
dropDownMenuHelperCircle.setOpacity(0);
dropDownMenuHelperCircle.setMouseTransparent(true);
edgeRoot.getChildren().add(dropDownMenuHelperCircle);
links.addListener(new ListChangeListener<Link>() {
@Override
public void onChanged(final Change<? extends Link> c) {
links.forEach((link) -> link.setOnMousePressed(event -> {
if (event.isSecondaryButtonDown() && getComponent().getUnfinishedEdge() == null) {
event.consume();
final DropDownMenu dropDownMenu = new DropDownMenu(((Pane) edgeRoot.getParent().getParent().getParent().getParent()), dropDownMenuHelperCircle, 230, true);
addEdgePropertyRow(dropDownMenu, "Add Select", Edge.PropertyType.SELECTION, link);
addEdgePropertyRow(dropDownMenu, "Add Guard", Edge.PropertyType.GUARD, link);
addEdgePropertyRow(dropDownMenu, "Add Synchronization", Edge.PropertyType.SYNCHRONIZATION, link);
addEdgePropertyRow(dropDownMenu, "Add Update", Edge.PropertyType.UPDATE, link);
dropDownMenu.addSpacerElement();
dropDownMenu.addClickableListElement("Delete", mouseEvent -> {
dropDownMenu.close();
UndoRedoStack.push(() -> { // Perform
getComponent().getEdges().remove(getEdge());
}, () -> { // Undo
getComponent().getEdges().add(getEdge());
}, "Deleted edge " + getEdge(), "delete");
});
dropDownMenu.show(JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT, event.getX(), event.getY());
DropDownMenu.x = CanvasPresentation.mouseTracker.getGridX();
DropDownMenu.y = CanvasPresentation.mouseTracker.getGridY();
} else if ((event.isAltDown() && event.isPrimaryButtonDown()) || event.isMiddleButtonDown()) {
final double nailX = CanvasPresentation.mouseTracker.gridXProperty().subtract(getComponent().xProperty()).doubleValue();
final double nailY = CanvasPresentation.mouseTracker.gridYProperty().subtract(getComponent().yProperty()).doubleValue();
final Nail newNail = new Nail(nailX, nailY);
UndoRedoStack.push(
() -> getEdge().insertNailAt(newNail, links.indexOf(link)),
() -> getEdge().removeNail(newNail),
"Nail added",
"add-circle"
);
}
}));
}
});
}
private void addEdgePropertyRow(final DropDownMenu dropDownMenu, final String rowTitle, final Edge.PropertyType type, final Link link) {
final SimpleBooleanProperty isDisabled = new SimpleBooleanProperty(false);
final int[] data = {-1, -1, -1, -1};
int i = 0;
for (final Nail nail : getEdge().getNails()) {
if (nail.getPropertyType().equals(Edge.PropertyType.SELECTION)) data[Edge.PropertyType.SELECTION.getI()] = i;
if (nail.getPropertyType().equals(Edge.PropertyType.GUARD)) data[Edge.PropertyType.GUARD.getI()] = i;
if (nail.getPropertyType().equals(Edge.PropertyType.SYNCHRONIZATION)) data[Edge.PropertyType.SYNCHRONIZATION.getI()] = i;
if (nail.getPropertyType().equals(Edge.PropertyType.UPDATE)) data[Edge.PropertyType.UPDATE.getI()] = i;
if (nail.getPropertyType().equals(type)) {
isDisabled.set(true);
}
i++;
}
final SimpleIntegerProperty insertAt = new SimpleIntegerProperty(links.indexOf(link));
final int clickedLinkedIndex = links.indexOf(link);
// Check the elements before me, and ensure that I am placed after these
for (int i1 = type.getI() - 1; i1 >= 0; i1
if (data[i1] != -1 && data[i1] >= clickedLinkedIndex) {
insertAt.set(data[i1] + 1);
}
}
// Check the elements after me, and ensure that I am placed before these
for (int i1 = type.getI() + 1; i1 < data.length; i1++) {
if (data[i1] != -1 && data[i1] < clickedLinkedIndex) {
insertAt.set(data[i1]);
}
}
dropDownMenu.addClickableAndDisableableListElement(rowTitle, isDisabled, event -> {
final double nailX = Math.round((DropDownMenu.x - getComponent().getX()) / GRID_SIZE) * GRID_SIZE;
final double nailY = Math.round((DropDownMenu.y - getComponent().getY()) / GRID_SIZE) * GRID_SIZE;
final Nail newNail = new Nail(nailX, nailY);
newNail.setPropertyType(type);
UndoRedoStack.push(
() -> getEdge().insertNailAt(newNail, insertAt.get()),
() -> getEdge().removeNail(newNail),
"Nail property added (" + type + ")",
"add-circle"
);
dropDownMenu.close();
});
}
public Edge getEdge() {
return edge.get();
}
public void setEdge(final Edge edge) {
this.edge.set(edge);
}
public ObjectProperty<Edge> edgeProperty() {
return edge;
}
public Component getComponent() {
return component.get();
}
public void setComponent(final Component component) {
this.component.set(component);
}
public ObjectProperty<Component> componentProperty() {
return component;
}
public void edgeEntered() {
isHoveringEdge.set(true);
if ((runningThread != null && runningThread.isAlive())) return; // Do not re-animate
timeHoveringEdge.set(500);
runningThread = new Thread(collapseNail);
runningThread.start();
getEdge().getNails().forEach(enlargeNail);
}
public void edgeExited() {
isHoveringEdge.set(false);
}
@FXML
public void edgePressed(final MouseEvent event) {
if (!event.isShiftDown()) {
event.consume();
if (event.isShortcutDown()) {
SelectHelper.addToSelection(this);
} else {
SelectHelper.select(this);
}
}
}
@Override
public void color(final Color color, final Color.Intensity intensity) {
final Edge edge = getEdge();
// Set the color of the edge
edge.setColorIntensity(intensity);
edge.setColor(color);
}
@Override
public Color getColor() {
return getEdge().getColor();
}
@Override
public Color.Intensity getColorIntensity() {
return getEdge().getColorIntensity();
}
@Override
public ItemDragHelper.DragBounds getDragBounds() {
return ItemDragHelper.DragBounds.generateLooseDragBounds();
}
@Override
public void select() {
edgeRoot.getChildren().forEach(node -> {
if (node instanceof SelectHelper.Selectable) {
((SelectHelper.Selectable) node).select();
}
});
}
@Override
public void deselect() {
edgeRoot.getChildren().forEach(node -> {
if (node instanceof SelectHelper.Selectable) {
((SelectHelper.Selectable) node).deselect();
}
});
}
@Override
public DoubleProperty xProperty() {
return edgeRoot.layoutXProperty();
}
@Override
public DoubleProperty yProperty() {
return edgeRoot.layoutYProperty();
}
@Override
public double getX() {
return xProperty().get();
}
@Override
public double getY() {
return yProperty().get();
}
} |
package app.bvk.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class WrappedImageView extends ImageView {
private static final Logger LOGGER = LoggerFactory.getLogger(WrappedImageView.class);
public WrappedImageView(final Image img) {
super(img);
setPreserveRatio(true);
setOnScroll(event -> {
final double amount = event.getDeltaY();
scaleXProperty().add(amount);
scaleYProperty().add(amount);
LOGGER.debug("{}", amount);
});
}
@Override
public double maxWidth(final double height) {
return 16384;
}
@Override
public double minWidth(final double height) {
return 40;
}
@Override
public double prefWidth(final double height) {
Image img = getImage();
if (img == null) {
return minWidth(height);
}
return img.getWidth();
}
@Override
public double maxHeight(final double width) {
return 16384;
}
@Override
public double minHeight(final double width) {
return 40;
}
@Override
public double prefHeight(final double width) {
Image img = getImage();
if (img == null) {
return minHeight(width);
}
return img.getHeight();
}
@Override
public boolean isResizable() {
return true;
}
@Override
public void resize(final double width, final double height) {
setFitWidth(width);
setFitHeight(height);
LOGGER.info("Resize");
}
} |
package br.com.caelum.brutal.infra;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
/**
* Encodes a string
*
* @param str
* String to encode
* @return Encoded String
*/
public static String crypt(String str) {
if (str == null || str.length() == 0) return str;
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return hexString.toString();
}
} |
package br.uff.ic.utility.graph;
import br.uff.ic.utility.GraphAttribute;
import br.uff.ic.utility.Utils;
import static br.uff.ic.utility.Utils.isItTime;
import java.awt.BasicStroke;
import java.awt.Paint;
import java.awt.Stroke;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract (Generic) vertex type for the provenance graph
*
* Time format must be either a Number or DayNumber:DayName (for the weekend display mode)
* @author Kohwalter
*/
public abstract class Vertex extends GraphObject {
private String id; // prov:id
private double normalizedTime;
// private String time; // prov:startTime
// Refactor for datetime type
private String timeFormat;
private String timeScale;
private String timeLabel = "Timestamp";
/**
* Constructor without attributes
* Using this constructor, attributes must be added later
*
* @param id vertex unique ID
* @param label HUman readable name
* @param time Time-related value. Used for temporal layouts
*/
public Vertex(String id, String label, String time) {
this.id = id;
// this.time = time;
GraphAttribute t = new GraphAttribute(timeLabel, time);
this.attributes = new HashMap<>();
this.attributes.put(t.getName(), t);
setLabel(label);
timeFormat = "nanoseconds";
timeScale = "nanoseconds";
}
/**
* Constructor with attributes
* @param id
* @param label
* @param time
* @param attributes
*/
public Vertex(String id, String label, String time, Map<String, GraphAttribute> attributes) {
this.id = id;
this.attributes = new HashMap<>();
this.attributes.putAll(attributes);
GraphAttribute t = new GraphAttribute(timeLabel, time);
this.attributes.put(t.getName(), t);
setLabel(label);
timeFormat = "nanoseconds";
timeScale = "nanoseconds";
}
/**
* Return the vertex ID
*
* @return (String) id
*/
public String getID() {
return id;
}
/**
* Set vertex ID
* @param t is the new ID
*/
public void setID(String t) {
id = t;
}
public void setNormalizedTime(double t) {
this.normalizedTime = t;
}
public double getNormalizedTime() {
return this.normalizedTime;
}
/**
* Method for returning the vertex name (not type) from the sub-classes.
* i.e. Agent Vertex name = Kohwalter
*
* @return (String) name
*/
/**
* Method for returning the vertex day (if any)
*
* @return (int) date
*/
public double getTime() {
// String[] day = this.time.split(":");
String time = this.attributes.get(timeLabel).getAverageValue();
if(Utils.tryParseFloat(time))
return (Double.parseDouble(time));
else if(Utils.tryParseDate(time))
{
double milliseconds = Utils.convertStringDateToFloat(time);
return milliseconds;
}
else
return -1;
}
/**
* Method to get the value of the variable time
* @return time
*/
public String getTimeString() {
return this.attributes.get(timeLabel).getAverageValue();
}
/**
* Method to set the value of the variable time
* @param t is the new value
*/
public void setTime(String t){
GraphAttribute time = new GraphAttribute(timeLabel, t);
this.attributes.put(timeLabel, time);
}
/**
* (Optional) Method for returning the day of the week instead of the day's
* number.
*
* @return (String) the day of the week (mon, tue, wed, ...)
*/
public String getDayName() {
String[] day = this.attributes.get(timeLabel).getAverageValue().split(":");
return day[1];
}
/**
* This overrides the default JUNG method for displaying information
*
* @return (String) id
*/
@Override
public String toString() {
return this.getNodeType() + "<br> "
+ "<br>ID: " + this.id + "<br>"
+ "<b>Label: " + getLabel() + "</b>"
+ " <br>" + printTime()
+ " <br>" + printAttributes();
}
public String printTime()
{
double nt = this.getTime();
return "Timestamp: " + Utils.convertTime(timeFormat, nt, timeScale) + " (" + timeScale + ")";
}
public void setTimeScalePrint(String timeFormat, String timeScale) {
this.timeFormat = timeFormat;
this.timeScale = timeScale;
}
/**
* Method to return the attribute value (not necessarily a number)
* If the attribute does not exist, returns "Unknown"
* @param attribute
* @return
*/
@Override
public String getAttributeValue(String attribute) {
if(attribute.equalsIgnoreCase("Label")) {
return getLabel();
}
GraphAttribute aux = attributes.get(attribute);
if(aux != null) {
return aux.getAverageValue();
}
else {
return deltaAttributeValue(attribute);
// return "Unknown";
}
}
/**
* Method to return the values in an attribute that were separated by a comma
* @param attribute is the attribute that we want to get the values
* @return an array with the values
*/
@Override
public String[] getAttributeValues(String attribute) {
String values = this.getAttributeValue(attribute);
return values.split(", ");
}
/**
* Method to return the attribute value as float
* @param attribute
* @return
*/
public float getAttributeValueFloat(String attribute) {
if(isItTime(attribute)) {
return (float)getNormalizedTime();
}
if(attributes.get(attribute) == null) {
return deltaAttributeFloatValue(attribute);
}
return getAttFloatValue(attribute);
}
/**
* Method that gets both attributes in the string and subtracts them. I.e.: First_Attribute - Second_Attribute
* @param attribute must be a string with both atributes separared by " - ". Example: "First_Attribute - Second_Attribute"
* @return the delta
*/
private float deltaAttributeFloatValue(String attribute) {
String[] atts = attribute.split(" - ");
if(atts.length == 2)
return getAttFloatValue(atts[0]) - getAttFloatValue(atts[1]);
else
return Float.NaN;
}
/**
* Method that returns the delta from the two attributes or Unknown if any attribute is invalid
* @param attribute must be a string with both atributes separared by " - ". Example: "First_Attribute - Second_Attribute"
* @return the delta as a String
*/
private String deltaAttributeValue(String attribute) {
if(attribute.equalsIgnoreCase("Label")) {
return getLabel();
}
if(isItTime(attribute)) {
return String.valueOf(getTime());
}
String[] atts = attribute.split(" - ");
if(atts.length == 2) {
if("Unknown".equals(getAttributeValue(atts[0])) || "Unknown".equals(getAttributeValue(atts[1]))) return "Unknown";
else {
String delta = Float.toString(getAttFloatValue(atts[0]) - getAttFloatValue(atts[1]));
return delta;
}
}
else
return "Unknown";
}
/**
* Method that returns the float value of the attribute. If it is not convertable, then it returns Float.NaN
* @param attribute the attribute that we want to get the value from
* @return the float value or Float.NaN if it is not possible to convert to float
*/
private float getAttFloatValue(String attribute) {
if(isItTime(attribute)) {
return (float)getNormalizedTime();
}
if(attributes.get(attribute) != null) {
if(Utils.tryParseFloat(attributes.get(attribute).getAverageValue())) {
return Utils.convertFloat(attributes.get(attribute).getAverageValue());
}
else {
return Float.NaN;
}
}
else {
return Float.NaN;
}
}
/**
* Method that returns TRUE if the vertex has the attribute and FALSE if it does not
* @param att is the name of the attribute we want to query
* @return if the vertex has the attribute
*/
public boolean hasAttribute(String att) {
if(this.attributes.containsKey(att))
return true;
else
return false;
}
/**
* Method for getting the vertex border size
*
* @deprecated use VertexStroke class instead
* @param width Define the border width
* @return (Stroke) returns the new vertex border width
*/
public Stroke getStroke(float width) {
float dash[] = null;
final Stroke nodeStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
return nodeStroke;
}
/**
* Method for defining the vertex color
*
* @return (Paint) vertex color
*/
public abstract Paint getColor();
/**
* Method used to identify the vertex type
*
*
* @return (String) vertex type
*/
public abstract String getNodeType();
} |
package ch.pontius.nio.smb;
public final class SMBPathUtil {
/**
* Private constructor; this class cannot be instantiated.
*/
private SMBPathUtil() {}
/**
* Checks if the provided path string points to a folder (i.e. ends with an /).
*
* @param path Path that should be checked.
* @return True if provided path points to a folder and false otherwise.
*/
public static boolean isFolder(String path) {
return path.endsWith(SMBFileSystem.PATH_SEPARATOR);
}
/**
* Checks if provided path string is an absolute path (i.e. starts with an /).
*
* @param path Path that should be checked.
* @return True if provided path is a relative path and false otherwise.
*/
public static boolean isAbsolutePath(String path) {
return path.startsWith(SMBFileSystem.PATH_SEPARATOR);
}
/**
* Checks if provided path string is a relative path (i.e. does not start with an /).
*
* @param path Path that should be checked.
* @return True if provided path is a relative path and false otherwise.
*/
public static boolean isRelativePath(String path) {
return !path.startsWith(SMBFileSystem.PATH_SEPARATOR);
}
/**
* Splits the provided path string into its path components.
*
* @param path Path string that should be split.
* @return Array of path components.
*/
public static String[] splitPath(String path) {
String[] split = path.split(SMBFileSystem.PATH_SEPARATOR);
if (split.length > 0 && split[0].equals("")) {
String[] truncated = new String[split.length-1];
System.arraycopy(split, 1,truncated, 0, split.length-1);
return truncated;
} else {
return split;
}
}
/**
* Merges the provided path components into a single pat string.
*
* @param components Array of path components.
* @param start Index of the first item in the list that should be considered; inclusive.
* @param end Index of the last item in the list that should be considered; exclusive.
* @param absolute Boolean indicating whether resulting path should be treated as absolute path.
* @param folder Boolean indicating whether resulting path should point to a folder.
* @return Resulting path string
*/
public static String mergePath(String[] components, int start, int end, boolean absolute, boolean folder) {
StringBuilder builder = new StringBuilder();
if (absolute) builder.append(SMBFileSystem.PATH_SEPARATOR);
for (int i = start; i<end; i++) {
builder.append(components[i]);
builder.append(SMBFileSystem.PATH_SEPARATOR);
}
if (!folder) {
return builder.substring(0, Math.max(0,builder.length()-1));
} else {
return builder.toString();
}
}
} |
package codechicken.lib;
import codechicken.lib.render.CCRenderEventHandler;
import codechicken.lib.render.block.CCExtendedBlockRendererDispatcher;
import codechicken.lib.util.FuelUtils;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Mod(modid = CodeChickenLib.MOD_ID, name = CodeChickenLib.MOD_NAME, acceptedMinecraftVersions = CodeChickenLib.mcVersion, version = CodeChickenLib.version)
public class CodeChickenLib {
public static final String MOD_ID = "CodeChickenLib";
public static final String MOD_NAME = "CodeChicken Lib";
public static final String version = "${mod_version}";
public static final String mcVersion = "[1.10.2]";
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
GameRegistry.registerFuelHandler(new FuelUtils());
if (event.getSide().equals(Side.CLIENT)){
CCRenderEventHandler.init();
}
}
@EventHandler
@SideOnly(Side.CLIENT)
public void init(FMLInitializationEvent event){
CCExtendedBlockRendererDispatcher.init();
}
} |
package cofh.api.energy;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Implement this interface on TileEntities which should handle energy, generally storing it in one or more internal {@link IEnergyStorage} objects.
*
* A reference implementation is provided {@link TileEnergyHandler}.
*
* @author King Lemming
*
*/
public interface IEnergyHandler extends IEnergyConnection {
/**
* Add energy to an IEnergyHandler, internal distribution is left entirely to the IEnergyHandler.
*
* @param from
* Orientation the energy is received from.
* @param maxReceive
* Maximum amount of energy to receive.
* @param simulate
* If TRUE, the charge will only be simulated.
* @return Amount of energy that was (or would have been, if simulated) received.
*/
int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate);
/**
* Remove energy from an IEnergyHandler, internal distribution is left entirely to the IEnergyHandler.
*
* @param from
* Orientation the energy is extracted from.
* @param maxExtract
* Maximum amount of energy to extract.
* @param simulate
* If TRUE, the extraction will only be simulated.
* @return Amount of energy that was (or would have been, if simulated) extracted.
*/
int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate);
/**
* Returns the amount of energy currently stored.
*/
int getEnergyStored(ForgeDirection from);
/**
* Returns the maximum amount of energy that can be stored.
*/
int getMaxEnergyStored(ForgeDirection from);
} |
package com.apm4all.tracy;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.spring.SpringRouteBuilder;
public class RouteBuilder extends SpringRouteBuilder {
@Override
public void configure() throws Exception {
from("restlet:http://localhost:8050/tracy/segment?restletMethod=POST")
// Tracy publishing should never block the sender
// waitForTaskToComplete allows endpoint to respond
// without having to wait until tracy is finally stored
.to("seda:tracySegmentProcessor?waitForTaskToComplete=Never")
//TODO: Return taskId-component as reference with HTTP 202 code
.setBody(simple("{\"tracySegmentId\":\"123456\"}"));
from("seda:tracySegmentProcessor")
.unmarshal().json(JsonLibrary.Jackson)
.transform().simple("${body[tracySegment]}")
// TODO: Validate tracySegment messages
// TODO: Send invalid segments to audit log
.split(body())
.to("seda:storeTracy");
from("seda:storeTracy")
// TODO: Store Tracy frames in repository
.delay(0);
// .log("${body}");
}
} |
package com.codahale.metrics;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
// CHECKSTYLE:OFF
/**
* One or more variables that together maintain an initially zero {@code long}
* sum. When updates (method {@link #add}) are contended across threads, the set
* of variables may grow dynamically to reduce contention. Method {@link #sum}
* (or, equivalently, {@link #longValue}) returns the current total combined
* across the variables maintaining the sum.
* <p/>
* <p>
* This class is usually preferable to {@link AtomicLong} when multiple threads
* update a common sum that is used for purposes such as collecting statistics,
* not for fine-grained synchronization control. Under low update contention,
* the two classes have similar characteristics. But under high contention,
* expected throughput of this class is significantly higher, at the expense of
* higher space consumption.
* <p/>
* <p>
* This class extends {@link Number}, but does <em>not</em> define methods such
* as {@code equals}, {@code hashCode} and {@code compareTo} because instances
* are expected to be mutated, and so are not useful as collection keys.
* <p/>
* <p>
* <em>jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.</em>
*
* @author Doug Lea
* @since 1.8
*/
@SuppressWarnings("all")
class LongAdder extends Striped64 implements Serializable {
private static final long serialVersionUID = 7249069246863182397L;
/**
* Version of plus for use in retryUpdate
*/
@Override
final long fn(final long v, final long x) {
return v + x;
}
/**
* Creates a new adder with initial sum of zero.
*/
LongAdder() {
}
/**
* Adds the given value.
*
* @param x
* the value to add
*/
public void add(final long x) {
Cell[] as;
long b, v;
HashCode hc;
Cell a;
int n;
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
final int h = (hc = threadHashCode.get()).code;
if (as == null || (n = as.length) < 1 || (a = as[(n - 1) & h]) == null
|| !(uncontended = a.cas(v = a.value, v + x))) {
retryUpdate(x, hc, uncontended);
}
}
}
/**
* Equivalent to {@code add(1)}.
*/
public void increment() {
add(1L);
}
/**
* Equivalent to {@code add(-1)}.
*/
public void decrement() {
add(-1L);
}
/**
* Returns the current sum. The returned value is <em>NOT</em> an atomic
* snapshot; invocation in the absence of concurrent updates returns an
* accurate result, but concurrent updates that occur while the sum is being
* calculated might not be incorporated.
*
* @return the sum
*/
public long sum() {
long sum = base;
final Cell[] as = cells;
if (as != null) {
final int n = as.length;
for (int i = 0; i < n; ++i) {
final Cell a = as[i];
if (a != null) {
sum += a.value;
}
}
}
return sum;
}
/**
* Resets variables maintaining the sum to zero. This method may be a useful
* alternative to creating a new adder, but is only effective if there are
* no concurrent updates. Because this method is intrinsically racy, it
* should only be used when it is known that no threads are concurrently
* updating.
*/
public void reset() {
internalReset(0L);
}
/**
* Equivalent in effect to {@link #sum} followed by {@link #reset}. This
* method may apply for example during quiescent points between
* multithreaded computations. If there are updates concurrent with this
* method, the returned value is <em>not</em> guaranteed to be the final
* value occurring before the reset.
*
* @return the sum
*/
public long sumThenReset() {
long sum = base;
final Cell[] as = cells;
base = 0L;
if (as != null) {
final int n = as.length;
for (int i = 0; i < n; ++i) {
final Cell a = as[i];
if (a != null) {
sum += a.value;
a.value = 0L;
}
}
}
return sum;
}
/**
* Returns the String representation of the {@link #sum}.
*
* @return the String representation of the {@link #sum}
*/
@Override
public String toString() {
return Long.toString(sum());
}
/**
* Equivalent to {@link #sum}.
*
* @return the sum
*/
@Override
public long longValue() {
return sum();
}
/**
* Returns the {@link #sum} as an {@code int} after a narrowing primitive
* conversion.
*/
@Override
public int intValue() {
return (int) sum();
}
/**
* Returns the {@link #sum} as a {@code float} after a widening primitive
* conversion.
*/
@Override
public float floatValue() {
return sum();
}
/**
* Returns the {@link #sum} as a {@code double} after a widening primitive
* conversion.
*/
@Override
public double doubleValue() {
return sum();
}
}
// CHECKSTYLE:ON |
package com.collective.celos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
/**
* TODO: timeout slots if trigger doesn't return true for too long
* TODO: retry handling
*/
public class Scheduler {
private final int slidingWindowHours;
private final WorkflowConfiguration configuration;
private final StateDatabase database;
public Scheduler(WorkflowConfiguration configuration, StateDatabase database, int slidingWindowHours) {
if (slidingWindowHours <= 0) {
throw new IllegalArgumentException("Sliding window hours must greater then zero.");
}
this.slidingWindowHours = slidingWindowHours;
this.configuration = Util.requireNonNull(configuration);
this.database = Util.requireNonNull(database);
}
/**
* Returns the start of the sliding window, given the current time.
*/
ScheduledTime getStartTime(ScheduledTime current) {
return new ScheduledTime(current.getDateTime().minusHours(slidingWindowHours));
}
/**
* Main method, called every minute.
*
* Steps through all workflows.
*/
public void step(ScheduledTime current) {
for (Workflow wf : configuration.getWorkflows()) {
try {
stepWorkflow(wf, current);
} catch(Exception e) {
Util.logException(e);
}
}
}
/**
* Steps a single workflow:
*
* - Submit any READY slots to the external service.
*
* - Check any WAITING slots for data availability.
*
* - Check any RUNNING slots for their current external status.
*/
private void stepWorkflow(Workflow wf, ScheduledTime current) throws Exception {
List<SlotState> slotStates = getSlotStates(wf, current);
runExternalWorkflows(wf, slotStates);
for (SlotState slotState : slotStates) {
updateSlotState(wf, slotState);
}
}
/**
* Get the slot states of all slots of the workflow from within the sliding window.
*/
private List<SlotState> getSlotStates(Workflow wf, ScheduledTime current) throws Exception {
SortedSet<ScheduledTime> scheduledTimes = wf.getSchedule().getScheduledTimes(getStartTime(current), current);
List<SlotState> slotStates = new ArrayList<SlotState>(scheduledTimes.size());
for (ScheduledTime t : scheduledTimes) {
SlotID slotID = new SlotID(wf.getID(), t);
SlotState slotState = database.getSlotState(slotID);
if (slotState != null) {
slotStates.add(slotState);
} else {
// Database doesn't have any info on the slot yet -
// synthesize a fresh waiting slot and put it in the list
// (not in the database).
slotStates.add(new SlotState(slotID, SlotState.Status.WAITING));
}
}
return Collections.unmodifiableList(slotStates);
}
/**
* Get scheduled slots from scheduling strategy and submit them to external system.
*/
private void runExternalWorkflows(Workflow wf, List<SlotState> slotStates) throws Exception {
List<SlotState> scheduledSlots = wf.getSchedulingStrategy().getSchedulingCandidates(slotStates);
for (SlotState slotState : scheduledSlots) {
if (!slotState.getStatus().equals(SlotState.Status.READY)) {
throw new IllegalStateException("Scheduling strategy returned non-ready slot: " + slotState);
}
String externalID = wf.getExternalService().run(slotState.getScheduledTime());
database.putSlotState(slotState.transitionToRunning(externalID));
}
}
/**
* Check the trigger for all WAITING slots, and update them to READY if data is available.
*
* Check the external status of all RUNNING slots, and update them to SUCCESS or FAILURE if they're finished.
*/
private void updateSlotState(Workflow wf, SlotState slotState) throws Exception {
if (slotState.getStatus().equals(SlotState.Status.WAITING)) {
if (wf.getTrigger().isDataAvailable(slotState.getScheduledTime())) {
database.putSlotState(slotState.transitionToReady());
}
} else if (slotState.getStatus().equals(SlotState.Status.RUNNING)) {
ExternalStatus xStatus = wf.getExternalService().getStatus(slotState.getExternalID());
if (!xStatus.isRunning()) {
if (xStatus.isSuccess()) {
database.putSlotState(slotState.transitionToSuccess());
} else {
database.putSlotState(slotState.transitionToFailure());
}
}
}
}
} |
package com.doctusoft.math;
import com.doctusoft.annotation.Beta;
import java.math.BigDecimal;
import java.math.BigInteger;
import static com.doctusoft.java.Failsafe.checkArgument;
import static com.doctusoft.math.Interval.*;
import static com.doctusoft.math.Interval.monotonicIncreasingValues;
import static java.util.Objects.*;
@Beta
@SuppressWarnings("rawtypes")
public final class ClosedRange<C extends Comparable> implements Interval<C> {
public static final <C extends Comparable> ClosedRange<C> create(C lowerBound, C upperBound) {
requireNonNull(lowerBound, "lowerBound");
requireNonNull(upperBound, "upperBound");
checkArgument(monotonicIncreasingValues(lowerBound, upperBound),
() -> "Invalid interval: " + lowerBound + " > " + upperBound);
return new ClosedRange<>(lowerBound, upperBound);
}
private final C lowerBound;
private final C upperBound;
private ClosedRange(C lowerBound, C upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public C getLowerBound() {
return lowerBound;
}
public C getUpperBound() {
return upperBound;
}
public boolean isEmpty() {
return false;
}
public boolean contains(C value) {
return monotonicIncreasingValues(lowerBound, requireNonNull(value), upperBound);
}
public boolean isConnected(ClosedRange<C> other) {
return monotonicIncreasingValues(lowerBound, other.upperBound)
&& monotonicIncreasingValues(other.lowerBound, upperBound);
}
public boolean isValidLowerBound(C lowerBound) {
requireNonNull(lowerBound, "lowerBound");
return monotonicIncreasingValues(lowerBound, upperBound);
}
public boolean isValidUpperBound(C upperBound) {
requireNonNull(upperBound, "upperBound");
return monotonicIncreasingValues(lowerBound, upperBound);
}
public ClosedRange<C> withLowerBound(C lowerBound) {
return ClosedRange.create(lowerBound, upperBound);
}
public ClosedRange<C> withUpperBound(C upperBound) {
return ClosedRange.create(lowerBound, upperBound);
}
@SuppressWarnings("unchecked")
public ClosedRange<C> intersection(ClosedRange<C> other) {
int lowerCmp = lowerBound.compareTo(other.lowerBound);
int upperCmp = upperBound.compareTo(other.upperBound);
if (lowerCmp >= 0 && upperCmp <= 0) {
return this;
} else if (lowerCmp <= 0 && upperCmp >= 0) {
return other;
} else {
return create(
(lowerCmp >= 0) ? lowerBound : other.lowerBound,
(upperCmp <= 0) ? upperBound : other.upperBound);
}
}
public String toString() {
return "[" + lowerBound + ", " + upperBound + "]";
}
public static int intSizeExact(ClosedRange<Integer> intRange) {
long length = intRange.getUpperBound().longValue() - intRange.getLowerBound().longValue();
return Math.toIntExact(length + 1L);
}
public static long longSizeExact(ClosedRange<Long> longRange) {
BigInteger length = BigInteger.valueOf(longRange.getUpperBound())
.subtract(BigInteger.valueOf(longRange.getLowerBound()));
return length.subtract(BigInteger.ONE).longValueExact();
}
} |
package com.featheredtoast.javad;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Properties;
import javax.swing.Timer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JavaD {
private Log log = LogFactory.getLog(this.getClass());
private String directoryPath;
private Properties properties;
private Timer timer;
private int interval = 60000;
private String systemVar = null;
public JavaD(String directoryPath) throws IOException {
this.directoryPath = directoryPath;
properties = new Properties();
loadPropertiesInDirectory();
}
public JavaD(String directoryPath, int interval) throws IOException {
this.directoryPath = directoryPath;
this.interval = interval;
properties = new Properties();
loadPropertiesInDirectory();
}
public JavaD(String directoryPath, Properties defaults) throws IOException {
this.directoryPath = directoryPath;
properties = new Properties(defaults);
loadPropertiesInDirectory();
}
public JavaD(String directoryPath, Properties defaults, int interval) throws IOException {
this.directoryPath = directoryPath;
this.interval = interval;
properties = new Properties(defaults);
loadPropertiesInDirectory();
}
public void addLoadFromSystemProperty(String envVar) throws IOException {
this.systemVar = envVar;
loadPropertiesInDirectory();
}
public synchronized void start() {
startJavaD();
}
public synchronized void stop() {
if(timer != null) {
timer.stop();
}
}
public Properties getProperties() {
return properties;
}
public void resetProperties(Properties properties) {
this.properties = new Properties(properties);
}
private void startJavaD() {
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
loadPropertiesInDirectory();
} catch (IOException e1) {
log.warn("error loading properties", e1);
}
}
};
log.debug("properties javad starting");
timer = new Timer(interval, al);
timer.setRepeats(true);
timer.start();
}
private synchronized void loadPropertiesInDirectory() throws IOException {
File dir = new File(directoryPath);
if(dir.isDirectory()) {
File[] propertyFiles = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File arg0, String arg1) {
return arg1.endsWith(".properties");
}
});
for(File file : propertyFiles) {
loadProperteisInFile(file);
}
}
}
private void loadProperteisInFile(File propertyFile) throws IOException {
log.debug("loading properties: " + propertyFile.getName());
InputStream is = new FileInputStream(propertyFile);
Properties newFileProperties = new Properties();
newFileProperties.load(is);
Properties newEnvironmentProperties = new Properties();
if(systemVar != null) {
log.debug(systemVar);
String environmentPropertyString = System.getenv(systemVar);
if(environmentPropertyString == null ||
"".equals(environmentPropertyString)) {
environmentPropertyString = System.getProperty(systemVar);
}
log.debug(environmentPropertyString);
if(environmentPropertyString != null) {
newEnvironmentProperties.load(new StringReader(environmentPropertyString));
}
}
properties.putAll(newFileProperties);
properties.putAll(newEnvironmentProperties);
is.close();
}
} |
package com.fishercoder.solutions;
/**
* 121. Best Time to Buy and Sell Stock
*
* Say you have an array for which the ith element is the price of a given stock on day i.
*
* If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock),
* design an algorithm to find the maximum profit.
*
* Example 1:
* Input: [7, 1, 5, 3, 6, 4]
* Output: 5
*
* max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
*
*
* Example 2:
* Input: [7, 6, 4, 3, 1]
* Output: 0
*
* In this case, no transaction is done, i.e. max profit = 0.
*/
public class _121 {
/**
* The key here is that you'll have to buy first, before you can sell.
* That means, if the lower price comes after a higher price, their combination won't work! Since you cannot sell first
* before you buy it.
*/
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int minBuy = prices[0];
int maxSell = prices[1];
int maxProfit = (maxSell - minBuy) > 0 ? (maxSell - minBuy) : 0;
for (int i = 1; i < prices.length; i++) {
minBuy = Math.min(minBuy, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - minBuy);
}
return maxProfit;
}
public static void main(String... strings) {
// int[] prices = new int[]{7,1,5,3,6,4};
// int[] prices = new int[]{7,6,4,3,1};
// int[] prices = new int[]{2,4,1};
int[] prices = new int[]{1, 2};
_121 test = new _121();
System.out.println(test.maxProfit(prices));
}
} |
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
import static com.fishercoder.solutions._189.Solution2.rotate_naive;
/**
* 189. Rotate Array
*
* Rotate an array of n elements to the right by k steps.
* For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
* */
public class _189 {
public static class Solution1 {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] tmp = new int[len];
for (int i = 0; i < len; i++) {
tmp[(i + k) % len] = nums[i];
}
for (int i = 0; i < len; i++) {
nums[i] = tmp[i];
}
}
}
public static class Solution2 {
/**
* My original idea and got AC'ed.
* One thing to notice is that when k > nums.length, we'll continue to rotate_naive the array, it just becomes k -= nums.length
*/
public static void rotate_naive(int[] nums, int k) {
if (k == 0 || k == nums.length) {
return;
}
if (k > nums.length) {
k -= nums.length;
}
List<Integer> tmp = new ArrayList();
int i = 0;
if (nums.length - k >= 0) {
i = nums.length - k;
for (; i < nums.length; i++) {
tmp.add(nums[i]);
}
} else {
i = nums.length - 1;
for (; i >= 0; i
tmp.add(nums[i]);
}
}
for (i = 0; i < nums.length - k; i++) {
tmp.add(nums[i]);
}
for (i = 0; i < tmp.size(); i++) {
nums[i] = tmp.get(i);
}
}
}
public static void main(String... strings) {
// int k = 1;
// int[] nums = new int[]{1,2,3};
// int[] nums = new int[]{1};
// int[] nums = new int[]{1,2};
// int k = 3;
// int[] nums = new int[]{1,2};
// int k = 2;
// int[] nums = new int[]{1,2};
int k = 4;
int[] nums = new int[]{1, 2, 3};
// int k = 2;
// int[] nums = new int[]{-1};
rotate_naive(nums, k);
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _222 {
public static class Solution1 {
public int countNodes(TreeNode root) {
int leftH = getLeftHeight(root);
int rightH = getRightHeight(root);
if (leftH == rightH) {
return (1 << leftH) - 1;
} else {
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
private int getRightHeight(TreeNode root) {
int height = 0;
while (root != null) {
root = root.right;
height++;
}
return height;
}
private int getLeftHeight(TreeNode root) {
int height = 0;
while (root != null) {
root = root.left;
height++;
}
return height;
}
}
} |
package smarta.smarta;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class TripHistory extends AppCompatActivity {
RecyclerView mRecycler;
private RVAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trip_history);
mRecycler = (RecyclerView) findViewById(R.id.recycler_view);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
ArrayList<Trip> trips = (ArrayList<Trip>) getIntent().getSerializableExtra("data");
adapter = new RVAdapter(TripHistory.this,trips);
mRecycler.setAdapter(adapter);
}
} |
package com.fishercoder.solutions;
public class _387 {
public static class Solution1 {
public static int firstUniqChar(String s) {
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i) - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
} |
package com.jaamsim.render;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.jaamsim.math.Mat4d;
import com.jaamsim.math.Plane;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec2d;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.ui.LogBox;
/**
* A big pile of static methods that currently don't have a better place to live. All Rendering specific
* @author matt.chudleigh
*
*/
public class RenderUtils {
public static List<Vec4d> CIRCLE_POINTS;
public static List<Vec4d> RECT_POINTS;
public static List<Vec4d> TRIANGLE_POINTS;
public static List<Vec4d> DIAMOND_POINTS;
static {
CIRCLE_POINTS = getCirclePoints(32);
// Scale the points down (as JaamSim uses a 1x1 box [-0.5, 0.5] not [-1, 1]
for (int i = 0; i < CIRCLE_POINTS.size(); ++i) {
CIRCLE_POINTS.get(i).scale3(0.5);
}
RECT_POINTS = new ArrayList<Vec4d>();
RECT_POINTS.add(new Vec4d( 0.5, 0.5, 0, 1.0d));
RECT_POINTS.add(new Vec4d(-0.5, 0.5, 0, 1.0d));
RECT_POINTS.add(new Vec4d(-0.5, -0.5, 0, 1.0d));
RECT_POINTS.add(new Vec4d( 0.5, -0.5, 0, 1.0d));
TRIANGLE_POINTS = new ArrayList<Vec4d>();
TRIANGLE_POINTS.add(new Vec4d( 0.5, -0.5, 0, 1.0d));
TRIANGLE_POINTS.add(new Vec4d( 0.5, 0.5, 0, 1.0d));
TRIANGLE_POINTS.add(new Vec4d(-0.5, 0.0, 0, 1.0d));
DIAMOND_POINTS = new ArrayList<Vec4d>();
DIAMOND_POINTS.add(new Vec4d( 1, 0, 0, 1.0d));
DIAMOND_POINTS.add(new Vec4d( 0, 1, 0, 1.0d));
DIAMOND_POINTS.add(new Vec4d( -1, 0, 0, 1.0d));
DIAMOND_POINTS.add(new Vec4d( 0, -1, 0, 1.0d));
}
// Transform the list of points in place
public static void transformPointsLocal(Transform trans, List<Vec4d> points, int dummy) {
for (Vec4d p : points) {
trans.apply(p, p);
}
}
public static List<Vec4d> transformPoints(Mat4d mat, List<Vec4d> points, int dummy) {
List<Vec4d> ret = new ArrayList<Vec4d>();
for (Vec4d p : points) {
Vec4d v = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
v.mult4(mat, p);
ret.add(v);
}
return ret;
}
public static List<Vec3d> transformPointsWithTrans(Mat4d mat, List<Vec3d> points) {
List<Vec3d> ret = new ArrayList<Vec3d>();
for (Vec3d p : points) {
Vec3d v = new Vec3d();
v.multAndTrans3(mat, p);
ret.add(v);
}
return ret;
}
static void putPointXY(FloatBuffer fb, Vec2d v) {
fb.put((float)v.x);
fb.put((float)v.y);
}
static void putPointXYZ(FloatBuffer fb, Vec3d v) {
fb.put((float)v.x);
fb.put((float)v.y);
fb.put((float)v.z);
}
static void putPointXYZW(FloatBuffer fb, Vec4d v) {
fb.put((float)v.x);
fb.put((float)v.y);
fb.put((float)v.z);
fb.put((float)v.w);
}
/**
* Returns a list of points for a circle in the XY plane at the origin
* @return
*/
public static ArrayList<Vec4d> getCirclePoints(int numSegments) {
if (numSegments < 3) {
return null;
}
ArrayList<Vec4d> ret = new ArrayList<Vec4d>();
double thetaStep = 2 * Math.PI / numSegments;
for (int i = 0; i < numSegments + 1; ++i) {
double theta = i * thetaStep;
ret.add(new Vec4d(Math.cos(theta), Math.sin(theta), 0, 1.0d));
}
return ret;
}
/**
* Build up a rounded rectangle (similar to the existing stockpiles). Assumes rounding width-wise
* @param width
* @param height
* @return
*/
public static ArrayList<Vec4d> getRoundedRectPoints(double width, double height, int numSegments) {
ArrayList<Vec4d> ret = new ArrayList<Vec4d>();
// Create semi circles on the ends
double xScale = 1;
double radius = height/2;
double fociiPoint = width/2 - radius;
// If the width is too small, the focii are at 0, and we scale in the x component of the curvature
if (width < height) {
xScale = width/height;
fociiPoint = 0;
}
double thetaStep = 2 * Math.PI / numSegments;
// +X cap
for (int i = 0; i < numSegments/2 + 1; ++i) {
double theta = i * thetaStep;
ret.add(new Vec4d(xScale*(radius*Math.sin(theta) + fociiPoint), -radius*Math.cos(theta), 0, 1.0d));
}
// -X cap
for (int i = 0; i < numSegments/2 + 1; ++i) {
double theta = i * thetaStep;
ret.add(new Vec4d(xScale*(-radius*Math.sin(theta) - fociiPoint), radius*Math.cos(theta), 0, 1.0d));
}
return ret;
}
/**
* Return a number of points that can draw an arc. This returns pairs for lines (unlike the getCirclePoints() which
* returns points for a line-strip).
* @param radius
* @param center
* @param startAngle
* @param endAngle
* @param numSegments
* @return
*/
public static ArrayList<Vec4d> getArcPoints(double radius, Vec4d center, double startAngle, double endAngle, int numSegments) {
if (numSegments < 3) {
return null;
}
ArrayList<Vec4d> ret = new ArrayList<Vec4d>();
double thetaStep = (startAngle - endAngle) / numSegments;
for (int i = 0; i < numSegments; ++i) {
double theta0 = i * thetaStep + startAngle;
double theta1 = (i+1) * thetaStep + startAngle;
ret.add(new Vec4d(radius * Math.cos(theta0) + center.x, radius * Math.sin(theta0) + center.y, 0, 1.0d));
ret.add(new Vec4d(radius * Math.cos(theta1) + center.x, radius * Math.sin(theta1) + center.y, 0, 1.0d));
}
return ret;
}
/**
*
* @param cameraInfo
* @param x - x coord in window space
* @param y - y coord in window space
* @param width - window width
* @param height - window height
* @return
*/
public static Ray getPickRayForPosition(CameraInfo cameraInfo, int x, int y, int width, int height) {
double aspectRatio = (double)width / (double)height;
double normX = 2.0*((double)x / (double)width) - 1.0;
double normY = 1.0 - 2.0*((double)y / (double)height); // In openGL space, y is -1 at the bottom
return RenderUtils.getViewRay(cameraInfo, aspectRatio, normX, normY);
}
/**
* Get a Ray representing a line starting at the camera position and projecting through the current mouse pointer
* in this window
* @param mouseInfo
* @return
*/
public static Ray getPickRay(Renderer.WindowMouseInfo mouseInfo) {
if (mouseInfo == null || !mouseInfo.mouseInWindow) {
return null;
}
return getPickRayForPosition(mouseInfo.cameraInfo,
mouseInfo.x,
mouseInfo.y,
mouseInfo.width,
mouseInfo.height);
}
/**
* Get a ray from the camera's point of view
* @param camInfo
* @param aspectRatio
* @param x - normalized [-1. 1] screen x coord
* @param y - normalized [-1. 1] screen y coord
* @return
*/
public static Ray getViewRay(CameraInfo camInfo, double aspectRatio, double x, double y) {
double yScale, xScale;
if (aspectRatio > 1) {
xScale = Math.tan(camInfo.FOV/2);
yScale = xScale / aspectRatio;
} else {
yScale = Math.tan(camInfo.FOV/2);
xScale = yScale * aspectRatio;
}
Vec4d dir = new Vec4d(x * xScale, y * yScale, -1, 0); // This will be normalized by Ray()
Vec4d start = new Vec4d(0, 0, 0, 1.0d);
// Temp is the ray in eye-space
Ray temp = new Ray(start, dir);
// Transform by the camera transform to get to global space
return temp.transform(camInfo.trans);
}
/**
* Return a matrix that is the combination of the transform and non-uniform scale
* @param trans
* @param scale
* @return
*/
public static Mat4d mergeTransAndScale(Transform trans, Vec3d scale) {
Mat4d ret = new Mat4d();
trans.getMat4d(ret);
ret.scaleCols3(scale);
return ret;
}
/**
* Get the inverse (in Matrix4d form) of the combined Transform and non-uniform scale factors
* @param trans
* @param scale
* @return
*/
public static Mat4d getInverseWithScale(Transform trans, Vec3d scale) {
Transform t = new Transform(trans);
t.inverse(t);
Mat4d ret = new Mat4d();
t.getMat4d(ret);
Vec3d s = new Vec3d(scale);
// Prevent dividing by zero
if (s.x == 0) { s.x = 1; }
if (s.y == 0) { s.y = 1; }
if (s.z == 0) { s.z = 1; }
ret.scaleRows3(new Vec3d(1/s.x, 1/s.y, 1/s.z));
return ret;
}
/**
* Scale an awt BufferedImage to a given resolution
* @param img
* @param newWidth
* @param newHeight
* @return a new BufferedImage of the appropriate size
*/
public static BufferedImage scaleToRes(BufferedImage img, int newWidth, int newHeight) {
int oldWidth = img.getWidth();
int oldHeight = img.getHeight();
BufferedImage ret = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale((double)newWidth/(double)oldWidth, (double)newHeight/(double)oldHeight);
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
ret = scaleOp.filter(img, ret);
return ret;
}
// Get the closest point in a line segment to a ray
public static Vec4d rayClosePoint(Mat4d rayMatrix, Vec4d worldA, Vec4d worldB) {
// Create vectors for a and b in ray space
Vec4d a = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
a.mult4(rayMatrix, worldA);
Vec4d b = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
b.mult4(rayMatrix, worldB);
Vec4d ab = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); // The line A to B
Vec4d negA = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); // -1 * A
negA.sub3(a);
ab.sub3(b, a);
double dot = negA.dot2(ab)/ab.magSquare2();
if (dot < 0) {
// The closest point is the A point
return new Vec4d(worldA);
} else if (dot >= 1) {
// B is closest
return new Vec4d(worldB);
} else {
// An intermediate point is closest
Vec4d worldAB = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
worldAB.sub3(worldB, worldA);
Vec4d ret = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
ret.scale3(dot, worldAB);
ret.add3(worldA);
return ret;
}
}
// Get the angle (in rads) this point is off the ray, this is useful for collision cones
// This will return an negative angle for points behind the start of the ray
public static double angleToRay(Mat4d rayMatrix, Vec4d worldP) {
Vec4d p = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
p.mult4(rayMatrix, worldP);
return Math.atan(p.mag2() / p.z);
}
public static Vec4d getGeometricMedian(ArrayList<Vec3d> points) {
assert(points.size() > 0);
double minX = points.get(0).x;
double maxX = points.get(0).x;
double minY = points.get(0).y;
double maxY = points.get(0).y;
double minZ = points.get(0).z;
double maxZ = points.get(0).z;
for (Vec3d p : points) {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
if (p.z < minZ) minZ = p.z;
if (p.z > maxZ) maxZ = p.z;
}
return new Vec4d((minX+maxX)/2, (minY+maxY)/2, (minZ+maxZ)/2, 1.0d);
}
public static Vec3d getPlaneCollisionDiff(Plane p, Ray r0, Ray r1) {
double r0Dist = p.collisionDist(r0);
double r1Dist = p.collisionDist(r1);
if (r0Dist < 0 || r0Dist == Double.POSITIVE_INFINITY ||
r1Dist < 0 || r1Dist == Double.POSITIVE_INFINITY)
{
// The plane is parallel or behind one of the rays...
return new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); // Just ignore it for now...
}
// The points where the previous pick ended and current position. Collision is with the entity's XY plane
Vec3d r0Point = r0.getPointAtDist(r0Dist);
Vec3d r1Point = r1.getPointAtDist(r1Dist);
Vec3d ret = new Vec3d();
ret.sub3(r0Point, r1Point);
return ret;
}
/**
* This is scratch space for matrix marshaling
*/
private static final float[] MAT_MARSHAL = new float[16];
/**
* Marshal a Mat4d into a static scratch space, this should only be called by the render thread, but I'm not
* putting a guard here for performance reasons. This returns a colum major float array
* @param mat
* @return
*/
public static float[] MarshalMat4d(Mat4d mat) {
MAT_MARSHAL[ 0] = (float)mat.d00;
MAT_MARSHAL[ 1] = (float)mat.d10;
MAT_MARSHAL[ 2] = (float)mat.d20;
MAT_MARSHAL[ 3] = (float)mat.d30;
MAT_MARSHAL[ 4] = (float)mat.d01;
MAT_MARSHAL[ 5] = (float)mat.d11;
MAT_MARSHAL[ 6] = (float)mat.d21;
MAT_MARSHAL[ 7] = (float)mat.d31;
MAT_MARSHAL[ 8] = (float)mat.d02;
MAT_MARSHAL[ 9] = (float)mat.d12;
MAT_MARSHAL[10] = (float)mat.d22;
MAT_MARSHAL[11] = (float)mat.d32;
MAT_MARSHAL[12] = (float)mat.d03;
MAT_MARSHAL[13] = (float)mat.d13;
MAT_MARSHAL[14] = (float)mat.d23;
MAT_MARSHAL[15] = (float)mat.d33;
return MAT_MARSHAL;
}
/**
* Marshal a 4x4 matrix into 'array', filling the 16 values starting at 'offset'
* @param mat
* @param array
* @param offset
*/
public static void MarshalMat4dToArray(Mat4d mat, float[] array, int offset) {
array[ 0 + offset] = (float)mat.d00;
array[ 1 + offset] = (float)mat.d10;
array[ 2 + offset] = (float)mat.d20;
array[ 3 + offset] = (float)mat.d30;
array[ 4 + offset] = (float)mat.d01;
array[ 5 + offset] = (float)mat.d11;
array[ 6 + offset] = (float)mat.d21;
array[ 7 + offset] = (float)mat.d31;
array[ 8 + offset] = (float)mat.d02;
array[ 9 + offset] = (float)mat.d12;
array[10 + offset] = (float)mat.d22;
array[11 + offset] = (float)mat.d32;
array[12 + offset] = (float)mat.d03;
array[13 + offset] = (float)mat.d13;
array[14 + offset] = (float)mat.d23;
array[15 + offset] = (float)mat.d33;
}
private static final double SMALL_SCALE = 0.000001;
public static Vec3d fixupScale(Vec3d inScale) {
Vec3d ret = new Vec3d(inScale);
if (ret.x <= 0.0) ret.x = SMALL_SCALE;
if (ret.y <= 0.0) ret.y = SMALL_SCALE;
if (ret.z <= 0.0) ret.z = SMALL_SCALE;
return ret;
}
private static boolean isValidExtension(String fileName) {
int idx = fileName.lastIndexOf(".");
if (idx < 0)
return false;
String ext = fileName.substring(idx + 1).trim().toUpperCase();
if (ext.equals("DAE") || ext.equals("OBJ") || ext.equals("JSM") || ext.equals("JSB"))
return true;
return false;
}
public static MeshProtoKey FileNameToMeshProtoKey(URI fileURI) {
try {
URL meshURL = fileURI.toURL();
String fileString = fileURI.toString();
String ext = fileString.substring(fileString.length() - 4,
fileString.length());
if (ext.toUpperCase().equals(".ZIP")) {
// This is a zip, use a zip stream to actually pull out
// the .dae file
ZipInputStream zipInputStream = new ZipInputStream(meshURL.openStream());
// Loop through zipEntries
for (ZipEntry zipEntry; (zipEntry = zipInputStream
.getNextEntry()) != null;) {
String entryName = zipEntry.getName();
if (!isValidExtension(entryName))
continue;
// This zipEntry is a collada file, no need to look
// any further
meshURL = new URL("jar:" + meshURL + "!/"
+ entryName);
break;
}
}
MeshProtoKey ret = new MeshProtoKey(meshURL.toURI());
return ret;
} catch (MalformedURLException e) {
LogBox.renderLogException(e);
assert (false);
} catch (IOException e) {
assert (false);
} catch (URISyntaxException e) {
LogBox.renderLogException(e);
assert (false);
}
return null;
}
/**
* Get the difference in Z height from projecting the two rays onto the vertical plane
* defined at the provided centerPoint
* @param centerPoint
* @param currentRay
* @param lastRay
* @return
*/
public static double getZDiff(Vec3d centerPoint, Ray currentRay, Ray lastRay) {
// Create a plane, orthogonal to the camera, but parallel to the Z axis
Vec4d normal = new Vec4d(currentRay.getDirRef());
normal.z = 0;
normal.normalize3();
double planeDist = centerPoint.dot3(normal);
Plane plane = new Plane(normal, planeDist);
double currentDist = plane.collisionDist(currentRay);
double lastDist = plane.collisionDist(lastRay);
if (currentDist < 0 || currentDist == Double.POSITIVE_INFINITY ||
lastDist < 0 || lastDist == Double.POSITIVE_INFINITY)
{
// The plane is parallel or behind one of the rays...
return 0; // Just ignore it for now...
}
// The points where the previous pick ended and current position. Collision is with the entity's XY plane
Vec3d currentPoint = currentRay.getPointAtDist(currentDist);
Vec3d lastPoint = lastRay.getPointAtDist(lastDist);
return currentPoint.z - lastPoint.z;
}
public static int[] stringToCodePoints(String s) {
int numCodePoints = s.codePointCount(0, s.length());
int[] ret = new int[numCodePoints];
for (int i = 0; i < numCodePoints; ++i) {
ret[i] = s.codePointAt(s.offsetByCodePoints(0, i));
}
return ret;
}
} |
package com.loadimpact.util;
import com.loadimpact.eval.DelayUnit;
import com.loadimpact.eval.LoadTestResult;
import com.loadimpact.eval.Operator;
import com.loadimpact.resource.testresult.StandardMetricResult;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Container for a set of parameters, plus some convenience methods.
*
* @author jens
*/
public class Parameters {
private Map<String, String> parameters;
private static final String NULL_String = null;
public Parameters() {
this.parameters = new TreeMap<String, String>();
}
public Parameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public int size() {
return parameters.size();
}
/**
* Adds a parameter
*
* @param key its key
* @param value its value
*/
public void add(String key, String value) {
parameters.put(key, value);
}
/**
* Returns all keys.
*
* @return set of keys
*/
public Set<String> keys() {
return parameters.keySet();
}
/**
* Returns all keys matching the given pattern.
*
* @param pattern key pattern
* @return set of keys
*/
public Set<String> keys(String pattern) {
Set<String> result = new TreeSet<String>();
for (String key : keys()) {
if (key.matches(pattern)) result.add(key);
}
return result;
}
/**
* Returns true if key is a member.
*
* @param key key to check
* @return true if member
*/
public boolean has(String key) {
return parameters.containsKey(key);
}
/**
* Returns the value associated with the key, or the given default value.
*
* @param key key to find
* @param defaultValue if not found
* @return value
*/
public String get(String key, String defaultValue) {
String value = parameters.get(key);
return StringUtils.isBlank(value) ? defaultValue : value;
}
public int get(String key, int defaultValue) {
try {
return Integer.parseInt(get(key, NULL_String));
} catch (Exception e) {
return defaultValue;
}
}
public boolean get(String key, boolean defaultValue) {
try {
return Boolean.parseBoolean(get(key, NULL_String));
} catch (Exception e) {
return defaultValue;
}
}
public float get(String key, float defaultValue) {
try {
return Float.parseFloat(get(key, NULL_String));
} catch (Exception e) {
return defaultValue;
}
}
public StandardMetricResult.Metrics get(String key, StandardMetricResult.Metrics defaultValue) {
try {
return StandardMetricResult.Metrics.valueOf(get(key, defaultValue.name()).toUpperCase());
} catch (Exception e) {
e.printStackTrace();
return defaultValue;
}
}
public DelayUnit get(String key, DelayUnit defaultValue) {
return DelayUnit.valueOf(get(key, defaultValue.name()));
}
public Operator get(String key, Operator defaultValue) {
return Operator.valueOf(get(key, defaultValue.name()));
}
public LoadTestResult get(String key, LoadTestResult defaultValue) {
return LoadTestResult.valueOf(get(key, defaultValue.name()));
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(10000);
buf.append(String.format("
for (Map.Entry<String, String> e : parameters.entrySet()) {
buf.append(String.format(" %s=%s%n", e.getKey(), e.getValue()));
}
buf.append(String.format("
return buf.toString();
}
} |
package com.matt.forgehax.mods;
import com.matt.forgehax.asm.ForgeHaxHooks;
import com.matt.forgehax.asm.events.PacketEvent;
import com.matt.forgehax.asm.events.RenderBoatEvent;
import com.matt.forgehax.asm.reflection.FastReflection;
import com.matt.forgehax.events.RenderEvent;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.entity.EntityUtils;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.util.MovementInput;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraft.entity.item.EntityBoat;
import static com.matt.forgehax.Helper.*;
@RegisterMod
public class BoatFly extends ToggleMod {
public final Setting<Double> speed = getCommandStub().builders().<Double>newSettingBuilder()
.name("speed").description("how fast to move").defaultTo(5.0D).build();
/*public final Setting<Double> maintainY = getCommandStub().builders().<Double>newSettingBuilder()
.name("YLevel").description("automatically teleport back up to this Y level").defaultTo(0.0D).build();*/
public final Setting<Double> speedY = getCommandStub().builders().<Double>newSettingBuilder()
.name("FallSpeed").description("how slowly to fall").defaultTo(0.033D).build();
public final Setting<Boolean> setYaw = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("SetYaw").description("set the boat yaw").defaultTo(true).build();
public final Setting<Boolean> noClamp = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("NoClamp").description("clamp view angles").defaultTo(true).build();
public final Setting<Boolean> noGravity = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("NoGravity").description("disable boat gravity").defaultTo(true).build();
public BoatFly() {
super(Category.MISC,"BoatFly", false, "Boathax");
}
@SubscribeEvent // disable gravity
public void onLocalPlayerUpdate(LocalPlayerUpdateEvent event) {
ForgeHaxHooks.isNoBoatGravityActivated = getRidingEntity() instanceof EntityBoat; // disable gravity if in boat
}
@Override
public void onDisabled() {
//ForgeHaxHooks.isNoClampingActivated = false; // disable view clamping
ForgeHaxHooks.isNoBoatGravityActivated = false; // disable gravity
ForgeHaxHooks.isBoatSetYawActivated = false;
//ForgeHaxHooks.isNotRowingBoatActivated = false; // items always usable - can not be disabled
}
@Override
public void onLoad() {
ForgeHaxHooks.isNoClampingActivated = noClamp.getAsBoolean();
ForgeHaxHooks.isNoBoatGravityActivated = noGravity.getAsBoolean();
ForgeHaxHooks.isBoatSetYawActivated = setYaw.getAsBoolean();
}
@SubscribeEvent
public void onRenderBoat (RenderBoatEvent event) {
if (EntityUtils.isDrivenByPlayer(event.getBoat()) && setYaw.getAsBoolean()) {
float yaw = getLocalPlayer().rotationYaw;
event.getBoat().rotationYaw = yaw;
event.setYaw(yaw);
}
}
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) {
//check if the player is really riding a entity
if (MC.player != null && MC.player.getRidingEntity() != null) {
ForgeHaxHooks.isNoClampingActivated = noClamp.getAsBoolean();
ForgeHaxHooks.isNoBoatGravityActivated = noGravity.getAsBoolean();
ForgeHaxHooks.isBoatSetYawActivated = setYaw.getAsBoolean();
if (MC.gameSettings.keyBindJump.isKeyDown()) {
//trick the riding entity to think its onground
MC.player.getRidingEntity().onGround = false;
//teleport up
MC.player.getRidingEntity().motionY = MC.gameSettings.keyBindSprint.isKeyDown() ? 5 : 1.5;
} else {
MC.player.getRidingEntity().motionY = MC.gameSettings.keyBindSprint.isKeyDown() ? -1.0 : -speedY.getAsDouble();
}
/*if ((MC.player.posY <= maintainY.getAsDouble()-5D) && (MC.player.posY > maintainY.getAsDouble()-10D) && maintainY.getAsDouble() != 0D)
MC.player.getRidingEntity().setPositionAndUpdate(MC.player.posX, maintainY.getAsDouble(), MC.player.posZ );*/
setMoveSpeedEntity(speed.getAsDouble());
}
}
public static void setMoveSpeedEntity(double speed) {
if (MC.player != null && MC.player.getRidingEntity() != null) {
MovementInput movementInput = MC.player.movementInput;
double forward = movementInput.moveForward;
double strafe = movementInput.moveStrafe;
float yaw = MC.player.rotationYaw;
if ((forward == 0.0D) && (strafe == 0.0D)) {
MC.player.getRidingEntity().motionX = (0.0D);
MC.player.getRidingEntity().motionZ = (0.0D);
} else {
if (forward != 0.0D) {
if (strafe > 0.0D) yaw += (forward > 0.0D ? -45 : 45);
else if (strafe < 0.0D) yaw += (forward > 0.0D ? 45 : -45);
strafe = 0.0D;
if (forward > 0.0D) forward = 1.0D;
else if (forward < 0.0D) forward = -1.0D;
}
MC.player.getRidingEntity().motionX = (forward * speed * Math.cos(Math.toRadians(yaw + 90.0F)) + strafe * speed * Math.sin(Math.toRadians(yaw + 90.0F)));
MC.player.getRidingEntity().motionZ = (forward * speed * Math.sin(Math.toRadians(yaw + 90.0F)) - strafe * speed * Math.cos(Math.toRadians(yaw + 90.0F)));
}
}
}
} |
package com.matt.forgehax.mods;
import com.matt.forgehax.asm.ForgeHaxHooks;
import com.matt.forgehax.asm.events.RenderBlockInLayerEvent;
import com.matt.forgehax.asm.events.RenderBlockLayerEvent;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@RegisterMod
public class XrayMod extends ToggleMod {
public final Setting<Integer> opacity = getCommandStub().builders().<Integer>newSettingBuilder()
.name("opacity")
.description("Xray opacity")
.defaultTo(150)
.min(0)
.max(255)
.changed(cb -> {
ForgeHaxHooks.COLOR_MULTIPLIER_ALPHA = (cb.getTo().floatValue() / 255.f);
reloadRenderers();
})
.build();
private boolean previousForgeLightPipelineEnabled = false;
public XrayMod() {
super("Xray", false, "See blocks through walls");
}
public void reloadRenderers() {
if(MC.renderGlobal != null) {
if (!MC.isCallingFromMinecraftThread())
MC.addScheduledTask(() -> {
MC.renderGlobal.loadRenderers();
});
else
MC.renderGlobal.loadRenderers();
}
}
@Override
public void onEnabled() {
previousForgeLightPipelineEnabled = ForgeModContainer.forgeLightPipelineEnabled;
ForgeModContainer.forgeLightPipelineEnabled = false;
ForgeHaxHooks.COLOR_MULTIPLIER_ALPHA = (this.opacity.getAsFloat() / 255.f);
ForgeHaxHooks.SHOULD_UPDATE_ALPHA = true;
reloadRenderers();
ForgeHaxHooks.SHOULD_DISABLE_CAVE_CULLING.enable();
}
@Override
public void onDisabled() {
ForgeModContainer.forgeLightPipelineEnabled = previousForgeLightPipelineEnabled;
ForgeHaxHooks.SHOULD_UPDATE_ALPHA = false;
reloadRenderers();
ForgeHaxHooks.SHOULD_DISABLE_CAVE_CULLING.disable();
}
private boolean isInternalCall = false;
@SubscribeEvent
public void onPreRenderBlockLayer(RenderBlockLayerEvent.Pre event) {
if(!isInternalCall) {
if (!event.getRenderLayer().equals(BlockRenderLayer.TRANSLUCENT)) {
event.setCanceled(true);
} else if (event.getRenderLayer().equals(BlockRenderLayer.TRANSLUCENT)) {
isInternalCall = true;
Entity renderEntity = MC.getRenderViewEntity();
GlStateManager.disableAlpha();
MC.renderGlobal.renderBlockLayer(BlockRenderLayer.SOLID, event.getPartialTicks(), 0, renderEntity);
GlStateManager.enableAlpha();
MC.renderGlobal.renderBlockLayer(BlockRenderLayer.CUTOUT_MIPPED, event.getPartialTicks(), 0, renderEntity);
MC.getTextureManager().getTexture(TextureMap.LOCATION_BLOCKS_TEXTURE).setBlurMipmap(false, false);
MC.renderGlobal.renderBlockLayer(BlockRenderLayer.CUTOUT, event.getPartialTicks(), 0, renderEntity);
MC.getTextureManager().getTexture(TextureMap.LOCATION_BLOCKS_TEXTURE).restoreLastBlurMipmap();
GlStateManager.disableAlpha();
isInternalCall = false;
}
}
}
@SubscribeEvent
public void onPostRenderBlockLayer(RenderBlockLayerEvent.Post event) {}
@SubscribeEvent
public void onRenderBlockInLayer(RenderBlockInLayerEvent event) {
if(event.getCompareToLayer().equals(BlockRenderLayer.TRANSLUCENT)) {
event.setLayer(event.getCompareToLayer());
}
}
} |
package com.ociweb.gl.api;
import com.ociweb.gl.impl.BuilderImpl;
import com.ociweb.gl.impl.schema.TrafficOrderSchema;
import com.ociweb.pronghorn.network.schema.ClientHTTPRequestSchema;
import com.ociweb.pronghorn.pipe.PipeConfigManager;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.ScriptedNonThreadScheduler;
import com.ociweb.pronghorn.stage.scheduling.StageVisitor;
public class GreenRuntime extends MsgRuntime<BuilderImpl, ListenerFilter>{
public GreenRuntime() {
this(new String[0],null);
}
public GreenRuntime(String name) {
this(new String[0],name);
}
public GreenRuntime(String[] args) {
super(args,null);
}
public GreenRuntime(String[] args, String name) {
super(args,name);
}
public GreenCommandChannel newCommandChannel() {
return newCommandChannel(0);
}
public GreenCommandChannel newCommandChannel(int features) {
PipeConfigManager pcm = new PipeConfigManager(4, defaultCommandChannelLength,
defaultCommandChannelMaxPayload);
pcm.addConfig(defaultCommandChannelLength, defaultCommandChannelHTTPMaxPayload, ClientHTTPRequestSchema.class);
pcm.addConfig(defaultCommandChannelLength,0,TrafficOrderSchema.class);
return this.builder.newCommandChannel(
features,
parallelInstanceUnderActiveConstruction,
pcm
);
}
public static GreenRuntime run(GreenApp app) {
return run(app,new String[0]);
}
public static GreenRuntime run(GreenApp app, String[] args) {
GreenRuntime runtime = new GreenRuntime(args, app.getClass().getSimpleName());
app.declareConfiguration(runtime.getBuilder());
GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS());
runtime.declareBehavior(app);
System.out.println("To exit app press Ctrl-C");
runtime.builder.buildStages(runtime);
runtime.logStageScheduleRates();
TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig();
if (telemetryConfig != null) {
runtime.telemetryHost = runtime.gm.enableTelemetry(telemetryConfig.getHost(), telemetryConfig.getPort());
}
//exportGraphDotFile();
//runtime.scheduler = StageScheduler.threadPerStage(runtime.gm);//hack test.
runtime.setScheduler(runtime.builder.createScheduler(runtime));
System.gc();
runtime.getScheduler().startup();
return runtime;
}
public void checkForException() {
getScheduler().checkForException();
}
public static boolean testConcurrentUntilShutdownRequested(GreenApp app, long timeoutMS) {
long limit = System.nanoTime() + (timeoutMS*1_000_000L);
MsgRuntime runtime = run(app);
while (!runtime.isShutdownRequested()) {
if (System.nanoTime() > limit) {
System.err.println("exit due to timeout");
return false;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
return false;
}
}
return true;
}
public static boolean testUntilShutdownRequested(GreenApp app, long timeoutMS) {
return testConcurrentUntilShutdownRequested(app, timeoutMS);
}
private static ScriptedNonThreadScheduler test(GreenApp app, GreenRuntime runtime) {
//force hardware to TestHardware regardless of where or what platform its run on.
//this is done because this is the test() method and must behave the same everywhere.
runtime.builder = new BuilderImpl(runtime.gm,runtime.args);
//lowered for tests, we want tests to run faster, tests probably run on bigger systems.
runtime.builder.setDefaultRate(10_000);
app.declareConfiguration(runtime.builder);
GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS());
runtime.declareBehavior(app);
runtime.builder.buildStages(runtime);
runtime.logStageScheduleRates();
TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig();
if (telemetryConfig != null) {
runtime.gm.enableTelemetry(telemetryConfig.getPort());
}
//exportGraphDotFile();
boolean reverseOrder = false;
StageVisitor badPlayers = new StageVisitor(){
byte[] seen = new byte[GraphManager.countStages(runtime.gm)+1];
@Override
public void visit(PronghornStage stage) {
if (0==seen[stage.stageId]) {
seen[stage.stageId] = 1;
logger.warn("Slow or blocking stage detected, investigation required: {}",stage);
}
}
};
runtime.setScheduler(new ScriptedNonThreadScheduler(runtime.gm, reverseOrder, badPlayers,null));
return (ScriptedNonThreadScheduler) runtime.getScheduler();
}
} |
package com.thegongoliers.math;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class MathExt {
private MathExt() {
}
/**
* isOdd : int -> boolean
* <p>
* Determines if a number is odd
*
* @param value
* @return
*/
public static boolean isOdd(int value) {
return divisibleBy(value, 2);
}
/**
* isEven : int -> boolean
* <p>
* Determines if a number is even
*
* @param value
* @return
*/
public static boolean isEven(int value) {
return !isOdd(value);
}
/**
* Calculate the magnitude of the given values.
*
* @param values The value to calculate the magnitude of.
* @return The magnitude of the values.
*/
public static double magnitude(double... values) {
double squaredSum = 0;
for (double val : values) {
squaredSum += square(val);
}
return Math.sqrt(squaredSum);
}
/**
* Determines the sign of a value
* <p>
* Produces 1 if the value if positive, -1 if it is negative, and 0 if it is
* 0
*
* @param value The value which to get the sign from
* @return 1 if the value if positive, -1 if it is negative, and 0 if it is
* 0
*/
public static int sign(double value) {
if (value > 0) {
return 1;
} else if (value < 0) {
return -1;
} else {
return 0;
}
}
/**
* Calculates the percentage of the value
*
* @param value The initial value
* @param percent The percent of the value to keep
* @return The percent of the initial value
*/
public static double percent(double value, double percent) {
return value * percent / 100.0;
}
/**
* Calculates the square of some value
*
* @param value The base value
* @return The square of value
*/
public static double square(double value) {
return Math.pow(value, 2);
}
/**
* Normalizes a value to the given range.
*
* @param value The value to normalize.
* @param min The min of the range.
* @param max The max of the range.
* @return The normalized value in the range.
*/
public static double normalize(double value, double min, double max) {
return (value - min) / (max - min);
}
/**
* Normalize the values to the max of the array.
*
* @param values The values to normalize.
* @return The normalized values.
*/
public static double[] normalize(double[] values) {
double max = max(values);
return toPrimitiveArray(toList(values).stream().map(x -> x / max).collect(Collectors.toList()));
}
/**
* Converts an array to a list.
*
* @param values The array to convert.
* @return The list containing all of the array values.
*/
public static List<Double> toList(double[] values) {
ArrayList<Double> arrVals = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
arrVals.add(values[i]);
}
return arrVals;
}
/**
* Converts a list to an array.
*
* @param values The list to convert.
* @return The array containing all of the list values.
*/
public static double[] toPrimitiveArray(List<Double> values) {
double[] primValues = new double[values.size()];
for (int i = 0; i < primValues.length; i++) {
primValues[i] = values.get(i);
}
return primValues;
}
/**
* Calculate the sum of an array.
*
* @param values The array to sum.
* @return The sum of the array.
*/
public static double sum(double[] values) {
double total = 0;
for (double value : values) {
total += value;
}
return total;
}
/**
* Find the min of the array.
*
* @param values The array.
* @return The min value of the array.
*/
public static double min(double[] values) {
if (values.length == 0) {
return Double.NEGATIVE_INFINITY;
}
double min = values[0];
for (double value : values) {
if (min > value) {
min = value;
}
}
return min;
}
/**
* Find the max of the array.
*
* @param values The array.
* @return The max value of the array.
*/
public static double max(double[] values) {
if (values.length == 0) {
return Double.POSITIVE_INFINITY;
}
double max = values[0];
for (double value : values) {
if (max < value) {
max = value;
}
}
return max;
}
/**
* Constrain a value to the range, where if the value is out of the range it
* is converted to the nearest range bound.
*
* @param value The value to constrain.
* @param min The min of the range.
* @param max The max of the range.
* @return The value which is constrained to the range.
*/
public static double toRange(double value, double min, double max) {
double newVal = Math.max(min, value);
newVal = Math.min(newVal, max);
return newVal;
}
/**
* Round a value to the nearest int.
*
* @param value The value to round.
* @return The rounded value as an int.
*/
public static int roundToInt(double value) {
return (int) Math.round(value);
}
/**
* Round a value to the given number of decimal places.
*
* @param value The value to round.
* @param numPlaces The number of decimal places to round to.
* @return The rounded value.
*/
public static double roundPlaces(double value, int numPlaces) {
double multiplier = Math.pow(10, numPlaces);
return snap(value, 1 / multiplier);
}
/**
* Snap a value to the nearest multiple of the nearest parameter.
*
* @param value The value to snap.
* @param nearest The value to snap to.
* @return The value snapped to the nearest multiple of nearest.
*/
public static double snap(double value, double nearest) {
return Math.round(value / nearest) * nearest;
}
/**
* Determines if a number is divisible by another number.
*
* @param value The numerator.
* @param divisor The denominator.
* @return True if the value is divisible by the divider.
*/
public static boolean divisibleBy(int value, int divisor) {
return value % divisor == 0;
}
/**
* Determines if a value is approximately equal to another value.
*
* @param value The value to compare.
* @param compare The value to compare.
* @param precision The precision of the equality.
* @return True if the value is equal to the compare value with the given
* precision.
*/
public static boolean approxEqual(double value, double compare, double precision) {
return Math.abs(value - compare) <= precision;
}
/**
* Get the slope from the angle in degrees.
*
* @param angle The angle in degrees.
* @return The slope of the line which the angle creates.
*/
public static double slopeFromAngleDegrees(double angle) {
return slopeFromAngleRadians(Math.toRadians(angle));
}
/**
* Get the slope from the angle in radians.
*
* @param angle The angle in radians.
* @return The slope of the line which the angle creates.
*/
public static double slopeFromAngleRadians(double angle) {
return Math.tan(angle);
}
} |
package com.tkb.delab.alg;
import com.tkb.delab.model.Edge;
import com.tkb.delab.model.Triangle;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.set.hash.THashSet;
import gnu.trove.set.hash.TIntHashSet;
/**
* A triangulator implementing the node iteration plus algorithm listing all
* triangles within a given graph, assuming there is no duplicate edges and no
* loops. Be aware each edge must be ordered by vertices, the left vertex should
* have id less than the id of the right vertex.
*
* @author Akis Papadopoulos
*/
public class NodeIterator implements Triangulator {
/**
* A method listing all triangles within a graph represented by a given edge
* set using the node iteration plus method.
*
* @param edges edge set graph induced by.
* @return a set of all triangles within the graph.
*/
@Override
public THashSet<Triangle> list(THashSet<Edge> edges) {
//Creating an empty set of triangles
THashSet<Triangle> triangles = new THashSet<Triangle>();
//Creating an empty vertex neighborhood map
TIntObjectHashMap<TIntHashSet> n = new TIntObjectHashMap<TIntHashSet>();
//Getting the edge set iterator
TObjectHashIterator eit = edges.iterator();
//Iterating through the edge set
while (eit.hasNext()) {
//Getting the next edge
Edge e = (Edge) eit.next();
//Getting the first vertex
int v = e.v;
//Getting the second vertex
int u = e.u;
//Checking if the first vertex mapped already
if (n.contains(v)) {
//Adding it's next neighbor
n.get(v).add(u);
} else {
//Creating an empty set of neighbors
TIntHashSet set = new TIntHashSet();
//Adding it's next neighbor
set.add(u);
//Mapping the vertex into the neighborhood map
n.put(v, set);
}
//Checking if the second vertex mapped already
if (n.contains(u)) {
//Adding it's next neighbor
n.get(u).add(v);
} else {
//Creating an empty set of neighbors
TIntHashSet set = new TIntHashSet();
//Adding it's next neighbor
set.add(v);
//Mapping the vertex into the neighborhood map
n.put(u, set);
}
}
//Getting the vertex set
int[] vertices = n.keys();
//Iterating through the vertex set
for (int i = 0; i < vertices.length; i++) {
//Getting the next vertex
int v = vertices[i];
//Getting the neighborhood of the vertex
int[] nv = n.get(v).toArray();
//Getting the degree of the vertex
int dv = nv.length;
//Iterating through all possible vertex neighbor pairs
for (int j = 0; j < nv.length; j++) {
//Getting the next neighbor
int u = nv[j];
//Getting the degree of the vertex
int du = n.get(u).size();
//Checking vertices by degree
if (du > dv || (du == dv && v < u)) {
for (int k = 0; k < nv.length; k++) {
//Getting the next neighbor
int w = nv[k];
//Getting the degree of the vertex
int dw = n.get(w).size();
//Checking vertices by degree
if (dw > du || (dw == du && u < w)) {
//Creating the edge iinduced by the found vertex pair
Edge edge = new Edge(u, w);
//Sorting edge vertices
edge.sort();
//Checking if the edge exist
if (edges.contains(edge)) {
//Creating the found triangle
Triangle triangle = new Triangle(v, u, w);
//Sorting the triangle
triangle.sort();
//Adding the triangle into the set
triangles.add(triangle);
}
}
}
}
}
}
return triangles;
}
} |
package org.commcare.android.view;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Vector;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.model.XYValueSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.models.RangeXYValueSeries;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.view.View;
import android.widget.LinearLayout;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private Context mContext;
private int mTextSize;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context, String title) {
mContext = context;
mTextSize = (int) context.getResources().getDimension(R.dimen.text_large);
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer(2); // initialize with two scales, to support a secondary y axis
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(mTextSize);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int) mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle(1).equals("")) {
rightMargin += textAllowance;
}
int leftMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
private void render(GraphData data) {
mData = data;
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
}
public Intent getIntent(GraphData data) {
render(data);
String title = mRenderer.getChartTitle();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartIntent(mContext, mDataset, mRenderer, title);
}
return ChartFactory.getLineChartIntent(mContext, mDataset, mRenderer, title);
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
public View getView(GraphData data) {
render(data);
// Graph will not render correctly unless it has data.
// Add a dummy series to guarantee this.
// Do this after adding any real data and after configuring
// so that get_AxisMin functions return correct values.
SeriesData s = new SeriesData();
double minX = mRenderer.getXAxisMin();
double minY = mRenderer.getYAxisMin();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
s.addPoint(new BubblePointData(minX, minY, 0.0));
}
else {
s.addPoint(new XYPointData(minX, minY));
}
s.setConfiguration("line-color", "#00000000");
s.setConfiguration("point-style", "none");
renderSeries(s);
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);
}
/*
* Allow or disallow clicks on this graph - really, on the view generated by getView.
*/
public void setClickable(boolean enabled) {
mRenderer.setClickEnabled(enabled);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series;
int scaleIndex = Boolean.valueOf(s.getConfiguration("secondary-y", "false")).equals(Boolean.TRUE) ? 1 : 0;
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
// TODO: This also ought to respect scaleIndex. However, XYValueSeries doesn't expose the
// (String title, int scaleNumber) constructor, so RangeXYValueSeries doesn't have access to it.
if (scaleIndex > 0) {
throw new IllegalArgumentException("Bubble series do not support a secondary y axis");
}
series = new RangeXYValueSeries("");
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries) series).setMaxValue(Double.valueOf(s.getConfiguration("radius-max")));
}
}
else {
series = new XYSeries("", scaleIndex);
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Collections.sort(sortedPoints, new PointComparator());
for (XYPointData p : sortedPoints) {
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
BubblePointData b = (BubblePointData) p;
((RangeXYValueSeries) series).add(b.getX(), b.getY(), b.getRadius());
}
else {
series.add(p.getX(), p.getY());
}
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public static LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
// Using an XYSeries will fail for bubble graphs, but using an
// XYValueSeries will work for both xy graphs and bubble graphs
XYValueSeries series = new XYValueSeries("");
for (AnnotationData a : annotations) {
series.addAnnotation(a.getAnnotation(), a.getX(), a.getY());
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(mTextSize);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.drawable.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow other shapes or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
if (pointStyle.equals("circle")) {
style = PointStyle.CIRCLE;
}
else if (pointStyle.equals("x")) {
style = PointStyle.X;
}
else if (pointStyle.equals("square")) {
style = PointStyle.SQUARE;
}
else if (pointStyle.equals("triangle")) {
style = PointStyle.TRIANGLE;
}
else if (pointStyle.equals("diamond")) {
style = PointStyle.DIAMOND;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
currentRenderer.setPointStrokeWidth(2);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor == null) {
currentRenderer.setColor(Color.BLACK);
}
else {
currentRenderer.setColor(Color.parseColor(lineColor));
}
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() {
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.drawable.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.drawable.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(1, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsAlign(Align.LEFT, 1);
mRenderer.setYLabelsPadding(10);
mRenderer.setYAxisAlign(Align.RIGHT, 1);
mRenderer.setAxesColor(mContext.getResources().getColor(R.color.grey_lighter));
mRenderer.setLabelsTextSize(mTextSize);
mRenderer.setAxisTitleTextSize(mTextSize);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowLegend(false);
mRenderer.setShowGrid(true);
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-title", ""));
mRenderer.setYTitle(mData.getConfiguration("secondary-y-title", ""), 1);
if (mData.getConfiguration("x-min") != null) {
mRenderer.setXAxisMin(Double.valueOf(mData.getConfiguration("x-min")));
}
if (mData.getConfiguration("y-min") != null) {
mRenderer.setYAxisMin(Double.valueOf(mData.getConfiguration("y-min")));
}
if (mData.getConfiguration("secondary-y-min") != null) {
mRenderer.setYAxisMin(Double.valueOf(mData.getConfiguration("secondary-y-min")), 1);
}
if (mData.getConfiguration("x-max") != null) {
mRenderer.setXAxisMax(Double.valueOf(mData.getConfiguration("x-max")));
}
if (mData.getConfiguration("y-max") != null) {
mRenderer.setYAxisMax(Double.valueOf(mData.getConfiguration("y-max")));
}
if (mData.getConfiguration("secondary-y-max") != null) {
mRenderer.setYAxisMax(Double.valueOf(mData.getConfiguration("secondary-y-max")), 1);
}
String showGrid = mData.getConfiguration("show-grid", "true");
if (Boolean.valueOf(showGrid).equals(Boolean.FALSE)) {
mRenderer.setShowGridX(false);
mRenderer.setShowGridY(false);
}
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
// Labels
boolean hasXLabels = configureLabels("x-labels");
boolean hasYLabels = configureLabels("y-labels");
boolean hasSecondaryYLabels = configureLabels("secondary-y-labels");
boolean showLabels = hasXLabels || hasYLabels || hasSecondaryYLabels;
mRenderer.setShowLabels(showLabels);
mRenderer.setShowTickMarks(showLabels);
boolean panAndZoom = Boolean.valueOf(mData.getConfiguration("zoom", "false")).equals(Boolean.TRUE);
mRenderer.setPanEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomEnabled(panAndZoom, panAndZoom);
mRenderer.setZoomButtonsVisible(panAndZoom);
}
/**
* Customize labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @return True if any labels at all will be displayed.
*/
private boolean configureLabels(String key) {
boolean hasLabels = false;
// The labels setting might be a JSON array of numbers,
// a JSON object of number => string, or a single number
String labelString = mData.getConfiguration(key);
if (labelString != null) {
try {
// Array: label each given value
JSONArray labels = new JSONArray(labelString);
setLabelCount(key, 0);
for (int i = 0; i < labels.length(); i++) {
String value = labels.getString(i);
addTextLabel(key, Double.valueOf(value), value);
}
hasLabels = labels.length() > 0;
}
catch (JSONException je) {
// Assume try block failed because labelString isn't an array.
// Try parsing it as an object.
try {
// Object: each keys is a location on the axis,
// and the value is the text with which to label it
JSONObject labels = new JSONObject(labelString);
setLabelCount(key, 0);
Iterator i = labels.keys();
while (i.hasNext()) {
String location = (String) i.next();
addTextLabel(key, Double.valueOf(location), labels.getString(location));
hasLabels = true;
}
}
catch (JSONException e) {
// Assume labelString is just a scalar, which
// represents the number of labels the user wants.
Integer count = Integer.valueOf(labelString);
setLabelCount(key, count);
hasLabels = count != 0;
}
}
}
return hasLabels;
}
/**
* Helper for configureLabels. Adds a label to the appropriate axis.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param location Point on axis to add label
* @param text String for label
*/
private void addTextLabel(String key, Double location, String text) {
if (isXKey(key)) {
mRenderer.addXTextLabel(location, text);
}
else {
int scaleIndex = getScaleIndex(key);
if (mRenderer.getYAxisAlign(scaleIndex) == Align.RIGHT) {
text = " " + text;
}
mRenderer.addYTextLabel(location, text, scaleIndex);
}
}
/**
* Helper for configureLabels. Sets desired number of labels for the appropriate axis.
* AChartEngine will then determine how to space the labels.
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param value Number of labels
*/
private void setLabelCount(String key, int value) {
if (isXKey(key)) {
mRenderer.setXLabels(value);
}
else {
mRenderer.setYLabels(value);
}
}
/**
* Helper for turning key into scale.
* @param key Something like "x-labels" or "y-secondary-labels"
* @return Index for passing to AChartEngine functions that accept a scale
*/
private int getScaleIndex(String key) {
return key.contains("secondary") ? 1 : 0;
}
/**
* Helper for parsing axis from configuration key.
* @param key Something like "x-min" or "y-labels"
* @return True iff key is relevant to x axis
*/
private boolean isXKey(String key) {
return key.startsWith("x-");
}
/**
* Comparator to sort PointData objects by x value.
* @author jschweers
*/
private class PointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
if (lhs.getX() > rhs.getX()) {
return 1;
}
if (lhs.getX() < rhs.getX()) {
return -1;
}
return 0;
}
}
} |
package crpoon.nwHacks.service;
import crpoon.nwHacks.database.StockDao;
import crpoon.nwHacks.database.StockInfoDao;
import crpoon.nwHacks.model.Stock;
import crpoon.nwHacks.model.StockInfo;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public abstract class Service {
protected static final int MAX_COUNT = 25;
private static final long ONE_HOUR = 1000 * 60 * 60;
public double getAverageIncomePerHour(String hashtag) {
Date oneHourAgo = new Date(System.currentTimeMillis() - ONE_HOUR);
List<Stock> stocks = StockDao.getInstance().getAllStockByNameAfterDate(hashtag, oneHourAgo);
double sumIncrease = 0.0;
for (Stock stock : stocks) {
sumIncrease += stock.getCurIncrease();
}
return sumIncrease / stocks.size();
}
public double getCurrentIncreasePerHour(String hashtag, Stock lastStock) {
if (lastStock == null) {
return 100.0;
}
int count = getCurrentIncrease(hashtag);
Date lastStockDate = lastStock.getDate();
double diffTime = System.currentTimeMillis() - lastStockDate.getTime();
diffTime = ONE_HOUR / diffTime;
return count * diffTime;
}
public void calculateAndPersistStock(String hashtag) {
StockInfo info = StockInfoDao.getInstance().getStockInfoByName(hashtag);
String ticker = info.getTicker();
double currentPrice;
double currentIncrease;
List<Stock> stocks = StockDao.getInstance().getAllStockByName(hashtag);
if (stocks == null || stocks.isEmpty()) {
currentPrice = 100.0;
currentIncrease = 0.0;
} else {
Stock lastStock = stocks.get(0);
double currentIncreasePerHour = getCurrentIncreasePerHour(hashtag, lastStock);
currentPrice = calculatePrice(getAverageIncomePerHour(hashtag),
currentIncreasePerHour, lastStock);
currentIncrease = currentPrice - lastStock.getPrice();
}
Stock stock = new Stock(hashtag, ticker, new Date(), currentPrice, currentIncrease);
StockDao.getInstance().insertStock(stock);
}
private double calculatePrice(double avgIncPerHour, double curIncPerHour, Stock lastStock) {
double fullAverage = avgIncPerHour;
double averageWithCur = (((MAX_COUNT - 1)/ MAX_COUNT) * avgIncPerHour) + ((1 / MAX_COUNT) * curIncPerHour);
return lastStock.getPrice() + (averageWithCur - fullAverage);
}
public abstract int getCurrentIncrease(String hashtag);
} |
package edu.jhu.gm.data;
import java.util.Map;
import org.apache.commons.collections.map.LRUMap;
import org.apache.commons.collections.map.ReferenceMap;
import edu.jhu.util.cache.GzipMap;
/**
* An immutable collection of instances for a graphical model.
*
* This implementation assumes that the given examplesFactory requires some slow
* computation for each call to get(i). Accordingly, a cache is placed in front
* of the factory to reduce the number of calls.
*
* @author mgormley
*
*/
public class FgExampleCache extends AbstractFgExampleList implements FgExampleList {
private FgExampleList exampleFactory;
private Map<Integer, FgExample> cache;
/**
* Constructor with a cache that uses SoftReferences.
*/
public FgExampleCache(FgExampleList exampleFactory) {
this(exampleFactory, -1, false);
}
/**
* Constructor with LRU cache.
* @param maxEntriesInMemory The maximum number of entries to keep in the
* in-memory cache or -1 to use a SoftReference cache.
*/
@SuppressWarnings("unchecked")
public FgExampleCache(FgExampleList exampleFactory, int maxEntriesInMemory, boolean gzipOnSerialize) {
this.exampleFactory = exampleFactory;
@SuppressWarnings("rawtypes")
Map tmp;
if (maxEntriesInMemory == -1) {
tmp = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.SOFT);
} else {
tmp = new LRUMap(maxEntriesInMemory);
}
if (gzipOnSerialize) {
cache = new GzipMap<Integer, FgExample>(tmp);
} else {
cache = tmp;
}
}
/** Gets the i'th example. */
public FgExample get(int i) {
FgExample ex;
synchronized (cache) {
ex = cache.get(i);
}
if (ex == null) {
ex = exampleFactory.get(i);
synchronized (cache) {
cache.put(i, ex);
}
}
return ex;
}
/** Gets the number of examples. */
public synchronized int size() {
return exampleFactory.size();
}
/** removes all cached FgExamples */
public synchronized void clear() {
cache.clear();
}
} |
package main.java.elegit;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.util.Pair;
import main.java.elegit.exceptions.NoOwnerInfoException;
import main.java.elegit.exceptions.NoRepoSelectedException;
import org.eclipse.jgit.api.errors.GitAPIException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
/**
*
* An implementation of the abstract RepoHelperBuilder that builds
* a ClonedRepoHelper by presenting dialogs to get the necessary
* parameters.
*
*/
public class ClonedRepoHelperBuilder extends RepoHelperBuilder {
private static String prevRemoteURL, prevDestinationPath, prevRepoName;
public ClonedRepoHelperBuilder(SessionModel sessionModel) {
super(sessionModel);
}
/**
* Builds (with a grid) and shows dialogs that prompt the user for
* information needed to construct a ClonedRepoHelper.
*
* @return the new ClonedRepoHelper.
* @throws Exception when constructing the new ClonedRepoHelper
*/
@Override
public RepoHelper getRepoHelperFromDialogs() throws GitAPIException, NoOwnerInfoException, IOException, NoRepoSelectedException{
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Clone");
dialog.setHeaderText("Clone a remote repository");
Text instructionsText = new Text("Select an enclosing folder for the repository folder\n" +
"to be created in.");
// Set the button types.
ButtonType cloneButtonType = new ButtonType("Clone", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(cloneButtonType, ButtonType.CANCEL);
// Create the Remote URL and destination path labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10, 10, 10, 10));
TextField remoteURLField = new TextField();
remoteURLField.setPromptText("Remote URL");
if(prevRemoteURL != null) remoteURLField.setText(prevRemoteURL);
TextField enclosingFolderField = new TextField();
enclosingFolderField.setEditable(false); // for now, it will just show the folder you selected
if(prevDestinationPath != null) enclosingFolderField.setText(prevDestinationPath);
Text enclosingDirectoryPathText = new Text();
Button chooseDirectoryButton = new Button();
Text folderIcon = GlyphsDude.createIcon(FontAwesomeIcon.FOLDER_OPEN);
chooseDirectoryButton.setGraphic(folderIcon);
chooseDirectoryButton.setOnAction(t -> {
File cloneRepoDirectory = this.getDirectoryPathFromChooser("Choose clone destination folder", null);
enclosingFolderField.setText(cloneRepoDirectory.toString());
enclosingDirectoryPathText.setText(cloneRepoDirectory.toString() + File.separator);
});
TextField repoNameField = new TextField();
repoNameField.setPromptText("Repository name...");
if(prevRepoName != null) repoNameField.setText(prevRepoName);
grid.add(instructionsText, 0, 0, 2, 1);
grid.add(new Label("Remote URL:"), 0, 1);
grid.add(remoteURLField, 1, 1);
grid.add(new Label("Enclosing folder:"), 0, 2);
grid.add(enclosingFolderField, 1, 2);
grid.add(chooseDirectoryButton, 2, 2);
grid.add(new Label("Repository name:"), 0, 3);
grid.add(repoNameField, 1, 3);
// Enable/Disable login button depending on whether a username was entered.
Node cloneButton = dialog.getDialogPane().lookupButton(cloneButtonType);
cloneButton.setDisable(true);
// Do some validation:
// On completion of every field, check that the other fields
// are also filled in and with valid characters. Then enable login.
repoNameField.textProperty().addListener((observable, oldValue, newValue) -> {
boolean someFieldIsEmpty = enclosingFolderField.getText().isEmpty() || repoNameField.getText().isEmpty()
|| remoteURLField.getText().isEmpty();
cloneButton.setDisable(someFieldIsEmpty || newValue.trim().contains("/") || newValue.trim().contains("."));
});
enclosingFolderField.textProperty().addListener((observable, oldValue, newValue) -> {
boolean someFieldIsEmpty = enclosingFolderField.getText().isEmpty() || repoNameField.getText().isEmpty()
|| remoteURLField.getText().isEmpty();
cloneButton.setDisable(someFieldIsEmpty);
});
remoteURLField.textProperty().addListener((observable, oldValue, newValue) -> {
boolean someFieldIsEmpty = enclosingFolderField.getText().isEmpty() || repoNameField.getText().isEmpty()
|| remoteURLField.getText().isEmpty();
cloneButton.setDisable(someFieldIsEmpty);
});
dialog.getDialogPane().setContent(grid);
// Request focus on the remote URL field by default.
Platform.runLater(remoteURLField::requestFocus);
// Convert the result to a destination-remote pair when the clone button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == cloneButtonType) {
// Store these values for callback after a login (if user isn't logged in):
prevRemoteURL = remoteURLField.getText();
prevDestinationPath = enclosingFolderField.getText();
prevRepoName = repoNameField.getText();
return new Pair<>(enclosingFolderField.getText() + File.separator + repoNameField.getText(), remoteURLField.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
if (result.isPresent()) {
// Unpack the destination-remote Pair created above:
Path destinationPath = Paths.get(result.get().getKey());
String remoteURL = result.get().getValue();
RepoHelper repoHelper = new ClonedRepoHelper(destinationPath, remoteURL, this.sessionModel.getDefaultOwner());
return repoHelper;
} else {
// This happens when the user pressed cancel.
throw new NoRepoSelectedException();
}
}
} |
package imagej.ops.threshold;
import imagej.ops.statistics.Mean;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
import org.scijava.plugin.Parameter;
/**
* @author Martin Horn
*/
public class LocalMean<T extends RealType<T>> extends LocalThresholdMethod<T> {
@Parameter
private double c;
@Parameter
private Mean<Iterable<T>, DoubleType> mean;
@Override
public BitType compute(Pair<T> input, BitType output) {
final DoubleType m = mean.compute(input.neighborhood, new DoubleType());
output.set(input.pixel.getRealDouble() > m.getRealDouble() - c);
return output;
}
} |
package io.scif.formats.tiff;
import io.scif.FormatException;
import io.scif.SCIFIO;
import io.scif.codec.CodecOptions;
import io.scif.io.ByteArrayHandle;
import io.scif.io.RandomAccessInputStream;
import io.scif.io.RandomAccessOutputStream;
import io.scif.util.FormatTools;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.log.LogService;
/**
* Writes TIFF data to an output location.
*
* @author Curtis Rueden
* @author Eric Kjellman
* @author Melissa Linkert
* @author Chris Allan
*/
public class TiffSaver extends AbstractContextual {
// -- Fields --
/** Output stream to use when saving TIFF data. */
private final RandomAccessOutputStream out;
/** Output filename. */
private String filename;
/** Output bytes. */
private ByteArrayHandle bytes;
/** Whether or not to write BigTIFF data. */
private boolean bigTiff = false;
private boolean sequentialWrite = false;
/** The codec options if set. */
private CodecOptions options;
private SCIFIO scifio;
private LogService log;
// -- Constructors --
/**
* Constructs a new TIFF saver from the given filename.
*
* @param filename Filename of the output stream that we may use to create
* extra input or output streams as required.
*/
public TiffSaver(final Context ctx, final String filename) throws IOException
{
this(ctx, new RandomAccessOutputStream(ctx, filename), filename);
}
/**
* Constructs a new TIFF saver from the given output source.
*
* @param out Output stream to save TIFF data to.
* @param filename Filename of the output stream that we may use to create
* extra input or output streams as required.
*/
public TiffSaver(final Context ctx, final RandomAccessOutputStream out,
final String filename)
{
if (out == null) {
throw new IllegalArgumentException(
"Output stream expected to be not-null");
}
if (filename == null) {
throw new IllegalArgumentException("Filename expected to be not null");
}
this.out = out;
this.filename = filename;
setContext(ctx);
scifio = new SCIFIO(ctx);
log = scifio.log();
}
/**
* Constructs a new TIFF saver from the given output source.
*
* @param out Output stream to save TIFF data to.
* @param bytes In memory byte array handle that we may use to create extra
* input or output streams as required.
*/
public TiffSaver(final RandomAccessOutputStream out,
final ByteArrayHandle bytes)
{
if (out == null) {
throw new IllegalArgumentException(
"Output stream expected to be not-null");
}
if (bytes == null) {
throw new IllegalArgumentException("Bytes expected to be not null");
}
this.out = out;
this.bytes = bytes;
}
// -- TiffSaver methods --
/**
* Sets whether or not we know that the planes will be written sequentially.
* If we are writing planes sequentially and set this flag, then performance
* is slightly improved.
*/
public void setWritingSequentially(final boolean sequential) {
sequentialWrite = sequential;
}
/** Gets the stream from which TIFF data is being saved. */
public RandomAccessOutputStream getStream() {
return out;
}
/** Sets whether or not little-endian data should be written. */
public void setLittleEndian(final boolean littleEndian) {
out.order(littleEndian);
}
/** Sets whether or not BigTIFF data should be written. */
public void setBigTiff(final boolean bigTiff) {
this.bigTiff = bigTiff;
}
/** Returns whether or not we are writing little-endian data. */
public boolean isLittleEndian() {
return out.isLittleEndian();
}
/** Returns whether or not we are writing BigTIFF data. */
public boolean isBigTiff() {
return bigTiff;
}
/**
* Sets the codec options.
*
* @param options The value to set.
*/
public void setCodecOptions(final CodecOptions options) {
this.options = options;
}
/** Writes the TIFF file header. */
public void writeHeader() throws IOException {
// write endianness indicator
out.seek(0);
if (isLittleEndian()) {
out.writeByte(TiffConstants.LITTLE);
out.writeByte(TiffConstants.LITTLE);
}
else {
out.writeByte(TiffConstants.BIG);
out.writeByte(TiffConstants.BIG);
}
// write magic number
if (bigTiff) {
out.writeShort(TiffConstants.BIG_TIFF_MAGIC_NUMBER);
}
else out.writeShort(TiffConstants.MAGIC_NUMBER);
// write the offset to the first IFD
// for vanilla TIFFs, 8 is the offset to the first IFD
// for BigTIFFs, 8 is the number of bytes in an offset
if (bigTiff) {
out.writeShort(8);
out.writeShort(0);
// write the offset to the first IFD for BigTIFF files
out.writeLong(16);
}
else {
out.writeInt(8);
}
}
public void writeImage(final byte[][] buf, final IFDList ifds,
final int pixelType) throws FormatException, IOException
{
if (ifds == null) {
throw new FormatException("IFD cannot be null");
}
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
for (int i = 0; i < ifds.size(); i++) {
if (i < buf.length) {
writeImage(buf[i], ifds.get(i), i, pixelType, i == ifds.size() - 1);
}
}
}
public void writeImage(final byte[] buf, final IFD ifd, final int no,
final int pixelType, final boolean last) throws FormatException,
IOException
{
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
final int w = (int) ifd.getImageWidth();
final int h = (int) ifd.getImageLength();
writeImage(buf, ifd, no, pixelType, 0, 0, w, h, last);
}
/**
* Writes to any rectangle from the passed block.
*
* @param buf The block that is to be written.
* @param ifd The Image File Directories. Mustn't be <code>null</code>.
* @param planeIndex The image index within the current file, starting from 0.
* @param pixelType The type of pixels.
* @param x The X-coordinate of the top-left corner.
* @param y The Y-coordinate of the top-left corner.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param last Pass <code>true</code> if it is the last image,
* <code>false</code> otherwise.
* @throws FormatException
* @throws IOException
*/
public void writeImage(final byte[] buf, final IFD ifd,
final long planeIndex, final int pixelType, final int x, final int y,
final int w, final int h, final boolean last) throws FormatException,
IOException
{
writeImage(buf, ifd, planeIndex, pixelType, x, y, w, h, last, null, false);
}
public void writeImage(final byte[] buf, final IFD ifd,
final long planeIndex, final int pixelType, final int x, final int y,
final int w, final int h, final boolean last, Integer nChannels,
final boolean copyDirectly) throws FormatException, IOException
{
log.debug("Attempting to write image.");
// b/c method is public should check parameters again
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
// These operations are synchronized
TiffCompression compression;
int tileWidth, tileHeight, nStrips;
boolean interleaved;
ByteArrayOutputStream[] stripBuf;
synchronized (this) {
final int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
final int blockSize = w * h * bytesPerPixel;
if (nChannels == null) {
nChannels = buf.length / (w * h * bytesPerPixel);
}
interleaved = ifd.getPlanarConfiguration() == 1;
makeValidIFD(ifd, pixelType, nChannels);
// create pixel output buffers
compression = ifd.getCompression();
tileWidth = (int) ifd.getTileWidth();
tileHeight = (int) ifd.getTileLength();
final int tilesPerRow = (int) ifd.getTilesPerRow();
final int rowsPerStrip = (int) ifd.getRowsPerStrip()[0];
int stripSize = rowsPerStrip * tileWidth * bytesPerPixel;
nStrips =
((w + tileWidth - 1) / tileWidth) * ((h + tileHeight - 1) / tileHeight);
if (interleaved) stripSize *= nChannels;
else nStrips *= nChannels;
stripBuf = new ByteArrayOutputStream[nStrips];
final DataOutputStream[] stripOut = new DataOutputStream[nStrips];
for (int strip = 0; strip < nStrips; strip++) {
stripBuf[strip] = new ByteArrayOutputStream(stripSize);
stripOut[strip] = new DataOutputStream(stripBuf[strip]);
}
final int[] bps = ifd.getBitsPerSample();
int off;
// write pixel strips to output buffers
final int effectiveStrips = !interleaved ? nStrips / nChannels : nStrips;
if (effectiveStrips == 1 && copyDirectly) {
stripOut[0].write(buf);
}
else {
for (int strip = 0; strip < effectiveStrips; strip++) {
final int xOffset = (strip % tilesPerRow) * tileWidth;
final int yOffset = (strip / tilesPerRow) * tileHeight;
for (int row = 0; row < tileHeight; row++) {
for (int col = 0; col < tileWidth; col++) {
final int ndx =
((row + yOffset) * w + col + xOffset) * bytesPerPixel;
for (int c = 0; c < nChannels; c++) {
for (int n = 0; n < bps[c] / 8; n++) {
if (interleaved) {
off = ndx * nChannels + c * bytesPerPixel + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
}
else {
stripOut[strip].writeByte(buf[off]);
}
}
else {
off = c * blockSize + ndx + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
}
else {
stripOut[c * (nStrips / nChannels) + strip]
.writeByte(buf[off]);
}
}
}
}
}
}
}
}
}
// Compress strips according to given differencing and compression
// schemes,
// this operation is NOT synchronized and is the ONLY portion of the
// TiffWriter.saveBytes() --> TiffSaver.writeImage() stack that is NOT
// synchronized.
final byte[][] strips = new byte[nStrips][];
for (int strip = 0; strip < nStrips; strip++) {
strips[strip] = stripBuf[strip].toByteArray();
scifio.tiff().difference(strips[strip], ifd);
final CodecOptions codecOptions =
compression.getCompressionCodecOptions(ifd, options);
codecOptions.height = tileHeight;
codecOptions.width = tileWidth;
codecOptions.channels = interleaved ? nChannels : 1;
strips[strip] =
compression.compress(scifio.codec(), strips[strip], codecOptions);
if (log.isDebug()) {
log.debug(String.format("Compressed strip %d/%d length %d", strip + 1,
nStrips, strips[strip].length));
}
}
// This operation is synchronized
synchronized (this) {
writeImageIFD(ifd, planeIndex, strips, nChannels, last, x, y);
}
}
/**
* Performs the actual work of dealing with IFD data and writing it to the
* TIFF for a given image or sub-image.
*
* @param ifd The Image File Directories. Mustn't be <code>null</code>.
* @param planeIndex The image index within the current file, starting from 0.
* @param strips The strips to write to the file.
* @param last Pass <code>true</code> if it is the last image,
* <code>false</code> otherwise.
* @param x The initial X offset of the strips/tiles to write.
* @param y The initial Y offset of the strips/tiles to write.
* @throws FormatException
* @throws IOException
*/
private void writeImageIFD(IFD ifd, final long planeIndex,
final byte[][] strips, final int nChannels, final boolean last,
final int x, final int y) throws FormatException, IOException
{
log.debug("Attempting to write image IFD.");
final int tilesPerRow = (int) ifd.getTilesPerRow();
final int tilesPerColumn = (int) ifd.getTilesPerColumn();
final boolean interleaved = ifd.getPlanarConfiguration() == 1;
final boolean isTiled = ifd.isTiled();
if (!sequentialWrite) {
RandomAccessInputStream in = null;
if (filename != null) {
in = new RandomAccessInputStream(getContext(), filename);
}
else if (bytes != null) {
in = new RandomAccessInputStream(getContext(), bytes);
}
else {
throw new IllegalArgumentException(
"Filename and bytes are null, cannot create new input stream!");
}
try {
final TiffParser parser = new TiffParser(getContext(), in);
final long[] ifdOffsets = parser.getIFDOffsets();
log.debug("IFD offsets: " + Arrays.toString(ifdOffsets));
if (planeIndex < ifdOffsets.length) {
out.seek(ifdOffsets[(int) planeIndex]);
log.debug("Reading IFD from " + ifdOffsets[(int) planeIndex] +
" in non-sequential write.");
ifd = parser.getIFD(ifdOffsets[(int) planeIndex]);
}
}
finally {
in.close();
}
}
// record strip byte counts and offsets
final List<Long> byteCounts = new ArrayList<>();
final List<Long> offsets = new ArrayList<>();
long totalTiles = tilesPerRow * tilesPerColumn;
if (!interleaved) {
totalTiles *= nChannels;
}
if (ifd.containsKey(IFD.STRIP_BYTE_COUNTS) ||
ifd.containsKey(IFD.TILE_BYTE_COUNTS))
{
final long[] ifdByteCounts =
isTiled ? ifd.getIFDLongArray(IFD.TILE_BYTE_COUNTS) : ifd
.getStripByteCounts();
for (final long stripByteCount : ifdByteCounts) {
byteCounts.add(stripByteCount);
}
}
else {
while (byteCounts.size() < totalTiles) {
byteCounts.add(0L);
}
}
final int tileOrStripOffsetX = x / (int) ifd.getTileWidth();
final int tileOrStripOffsetY = y / (int) ifd.getTileLength();
final int firstOffset =
(tileOrStripOffsetY * tilesPerRow) + tileOrStripOffsetX;
if (ifd.containsKey(IFD.STRIP_OFFSETS) || ifd.containsKey(IFD.TILE_OFFSETS))
{
final long[] ifdOffsets =
isTiled ? ifd.getIFDLongArray(IFD.TILE_OFFSETS) : ifd.getStripOffsets();
for (final long ifdOffset : ifdOffsets) {
offsets.add(ifdOffset);
}
}
else {
while (offsets.size() < totalTiles) {
offsets.add(0L);
}
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
final long fp = out.getFilePointer();
writeIFD(ifd, 0);
for (int i = 0; i < strips.length; i++) {
out.seek(out.length());
final int thisOffset = firstOffset + i;
offsets.set(thisOffset, out.getFilePointer());
byteCounts.set(thisOffset, new Long(strips[i].length));
if (log.isDebug()) {
log.debug(String.format("Writing tile/strip %d/%d size: %d offset: %d",
thisOffset + 1, totalTiles, byteCounts.get(thisOffset), offsets
.get(thisOffset)));
}
out.write(strips[i]);
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
final long endFP = out.getFilePointer();
if (log.isDebug()) {
log.debug("Offset before IFD write: " + out.getFilePointer() +
" Seeking to: " + fp);
}
out.seek(fp);
if (log.isDebug()) {
log.debug("Writing tile/strip offsets: " +
Arrays.toString(toPrimitiveArray(offsets)));
log.debug("Writing tile/strip byte counts: " +
Arrays.toString(toPrimitiveArray(byteCounts)));
}
writeIFD(ifd, last ? 0 : endFP);
if (log.isDebug()) {
log.debug("Offset after IFD write: " + out.getFilePointer());
}
}
public void writeIFD(final IFD ifd, final long nextOffset)
throws FormatException, IOException
{
final TreeSet<Integer> keys = new TreeSet<>(ifd.keySet());
int keyCount = keys.size();
if (ifd.containsKey(new Integer(IFD.LITTLE_ENDIAN))) keyCount
if (ifd.containsKey(new Integer(IFD.BIG_TIFF))) keyCount
if (ifd.containsKey(new Integer(IFD.REUSE))) keyCount
final long fp = out.getFilePointer();
final int bytesPerEntry =
bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY
: TiffConstants.BYTES_PER_ENTRY;
final int ifdBytes = (bigTiff ? 16 : 6) + bytesPerEntry * keyCount;
if (bigTiff) out.writeLong(keyCount);
else out.writeShort(keyCount);
final ByteArrayHandle extra = new ByteArrayHandle();
final RandomAccessOutputStream extraStream =
new RandomAccessOutputStream(extra);
for (final Integer key : keys) {
if (key.equals(IFD.LITTLE_ENDIAN) || key.equals(IFD.BIG_TIFF) ||
key.equals(IFD.REUSE)) continue;
final Object value = ifd.get(key);
writeIFDValue(extraStream, ifdBytes + fp, key.intValue(), value);
}
if (bigTiff) out.seek(out.getFilePointer());
writeIntValue(out, nextOffset);
out.write(extra.getBytes(), 0, (int) extra.length());
}
/**
* Writes the given IFD value to the given output object.
*
* @param extraOut buffer to which "extra" IFD information should be written
* @param offset global offset to use for IFD offset values
* @param tag IFD tag to write
* @param value IFD value to write
*/
public void writeIFDValue(final RandomAccessOutputStream extraOut,
final long offset, final int tag, Object value) throws FormatException,
IOException
{
extraOut.order(isLittleEndian());
// convert singleton objects into arrays, for simplicity
if (value instanceof Short) {
value = new short[] { ((Short) value).shortValue() };
}
else if (value instanceof Integer) {
value = new int[] { ((Integer) value).intValue() };
}
else if (value instanceof Long) {
value = new long[] { ((Long) value).longValue() };
}
else if (value instanceof TiffRational) {
value = new TiffRational[] { (TiffRational) value };
}
else if (value instanceof Float) {
value = new float[] { ((Float) value).floatValue() };
}
else if (value instanceof Double) {
value = new double[] { ((Double) value).doubleValue() };
}
final int dataLength = bigTiff ? 8 : 4;
// write directory entry to output buffers
out.writeShort(tag); // tag
if (value instanceof short[]) {
final short[] q = (short[]) value;
out.writeShort(IFDType.BYTE.getCode());
writeIntValue(out, q.length);
if (q.length <= dataLength) {
for (int i = 0; i < q.length; i++)
out.writeByte(q[i]);
for (int i = q.length; i < dataLength; i++)
out.writeByte(0);
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++)
extraOut.writeByte(q[i]);
}
}
else if (value instanceof String) { // ASCII
final char[] q = ((String) value).toCharArray();
out.writeShort(IFDType.ASCII.getCode()); // type
writeIntValue(out, q.length + 1);
if (q.length < dataLength) {
for (int i = 0; i < q.length; i++)
out.writeByte(q[i]); // value(s)
for (int i = q.length; i < dataLength; i++)
out.writeByte(0); // padding
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++)
extraOut.writeByte(q[i]); // values
extraOut.writeByte(0); // concluding NULL byte
}
}
else if (value instanceof int[]) { // SHORT
final int[] q = (int[]) value;
out.writeShort(IFDType.SHORT.getCode()); // type
writeIntValue(out, q.length);
if (q.length <= dataLength / 2) {
for (int i = 0; i < q.length; i++) {
out.writeShort(q[i]); // value(s)
}
for (int i = q.length; i < dataLength / 2; i++) {
out.writeShort(0); // padding
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++) {
extraOut.writeShort(q[i]); // values
}
}
}
else if (value instanceof long[]) { // LONG
final long[] q = (long[]) value;
final int type =
bigTiff ? IFDType.LONG8.getCode() : IFDType.LONG.getCode();
out.writeShort(type);
writeIntValue(out, q.length);
final int div = bigTiff ? 8 : 4;
if (q.length <= dataLength / div) {
for (int i = 0; i < q.length; i++) {
writeIntValue(out, q[0]);
}
for (int i = q.length; i < dataLength / div; i++) {
writeIntValue(out, 0);
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++) {
writeIntValue(extraOut, q[i]);
}
}
}
else if (value instanceof TiffRational[]) { // RATIONAL
final TiffRational[] q = (TiffRational[]) value;
out.writeShort(IFDType.RATIONAL.getCode()); // type
writeIntValue(out, q.length);
if (bigTiff && q.length == 1) {
out.writeInt((int) q[0].getNumerator());
out.writeInt((int) q[0].getDenominator());
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++) {
extraOut.writeInt((int) q[i].getNumerator());
extraOut.writeInt((int) q[i].getDenominator());
}
}
}
else if (value instanceof float[]) { // FLOAT
final float[] q = (float[]) value;
out.writeShort(IFDType.FLOAT.getCode()); // type
writeIntValue(out, q.length);
if (q.length <= dataLength / 4) {
for (int i = 0; i < q.length; i++) {
out.writeFloat(q[0]); // value
}
for (int i = q.length; i < dataLength / 4; i++) {
out.writeInt(0); // padding
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i = 0; i < q.length; i++) {
extraOut.writeFloat(q[i]); // values
}
}
}
else if (value instanceof double[]) { // DOUBLE
final double[] q = (double[]) value;
out.writeShort(IFDType.DOUBLE.getCode()); // type
writeIntValue(out, q.length);
writeIntValue(out, offset + extraOut.length());
for (final double doubleVal : q) {
extraOut.writeDouble(doubleVal); // values
}
}
else {
throw new FormatException("Unknown IFD value type (" +
value.getClass().getName() + "): " + value);
}
}
public void overwriteLastIFDOffset(final RandomAccessInputStream raf)
throws FormatException, IOException
{
if (raf == null) throw new FormatException("Output cannot be null");
final TiffParser parser = new TiffParser(getContext(), raf);
parser.getIFDOffsets();
out.seek(raf.getFilePointer() - (bigTiff ? 8 : 4));
writeIntValue(out, 0);
}
/**
* Surgically overwrites an existing IFD value with the given one. This method
* requires that the IFD directory entry already exist. It intelligently
* updates the count field of the entry to match the new length. If the new
* length is longer than the old length, it appends the new data to the end of
* the file and updates the offset field; if not, or if the old data is
* already at the end of the file, it overwrites the old data in place.
*/
public void overwriteIFDValue(final RandomAccessInputStream raf,
final int ifd, final int tag, final Object value) throws FormatException,
IOException
{
if (raf == null) throw new FormatException("Output cannot be null");
log.debug("overwriteIFDValue (ifd=" + ifd + "; tag=" + tag + "; value=" +
value + ")");
raf.seek(0);
final TiffParser parser = new TiffParser(getContext(), raf);
final Boolean valid = parser.checkHeader();
if (valid == null) {
throw new FormatException("Invalid TIFF header");
}
final boolean little = valid.booleanValue();
final boolean bigTiff = parser.isBigTiff();
setLittleEndian(little);
setBigTiff(bigTiff);
final long offset = bigTiff ? 8 : 4; // offset to the IFD
final int bytesPerEntry =
bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY
: TiffConstants.BYTES_PER_ENTRY;
raf.seek(offset);
// skip to the correct IFD
final long[] offsets = parser.getIFDOffsets();
if (ifd >= offsets.length) {
throw new FormatException("No such IFD (" + ifd + " of " +
offsets.length + ")");
}
raf.seek(offsets[ifd]);
// get the number of directory entries
final long num = bigTiff ? raf.readLong() : raf.readUnsignedShort();
// search directory entries for proper tag
for (int i = 0; i < num; i++) {
raf.seek(offsets[ifd] + (bigTiff ? 8 : 2) + bytesPerEntry * i);
final TiffIFDEntry entry = parser.readTiffIFDEntry();
if (entry.getTag() == tag) {
// write new value to buffers
final ByteArrayHandle ifdBuf = new ByteArrayHandle(bytesPerEntry);
final RandomAccessOutputStream ifdOut =
new RandomAccessOutputStream(ifdBuf);
final ByteArrayHandle extraBuf = new ByteArrayHandle();
final RandomAccessOutputStream extraOut =
new RandomAccessOutputStream(extraBuf);
extraOut.order(little);
final TiffSaver saver = new TiffSaver(ifdOut, ifdBuf);
saver.setLittleEndian(isLittleEndian());
saver.writeIFDValue(extraOut, entry.getValueOffset(), tag, value);
ifdBuf.seek(0);
extraBuf.seek(0);
// extract new directory entry parameters
final int newTag = ifdBuf.readShort();
final int newType = ifdBuf.readShort();
int newCount;
long newOffset;
if (bigTiff) {
newCount = ifdBuf.readInt();
newOffset = ifdBuf.readLong();
}
else {
newCount = ifdBuf.readInt();
newOffset = ifdBuf.readInt();
}
log.debug("overwriteIFDValue:");
log.debug("\told (" + entry + ");");
log.debug("\tnew: (tag=" + newTag + "; type=" + newType + "; count=" +
newCount + "; offset=" + newOffset + ")");
// determine the best way to overwrite the old entry
if (extraBuf.length() == 0) {
// new entry is inline; if old entry wasn't, old data is
// orphaned
// do not override new offset value since data is inline
log.debug("overwriteIFDValue: new entry is inline");
}
else if (entry.getValueOffset() + entry.getValueCount() *
entry.getType().getBytesPerElement() == raf.length())
{
// old entry was already at EOF; overwrite it
newOffset = entry.getValueOffset();
log.debug("overwriteIFDValue: old entry is at EOF");
}
else if (newCount <= entry.getValueCount()) {
// new entry is as small or smaller than old entry;
// overwrite it
newOffset = entry.getValueOffset();
log.debug("overwriteIFDValue: new entry is <= old entry");
}
else {
// old entry was elsewhere; append to EOF, orphaning old
// entry
newOffset = raf.length();
log.debug("overwriteIFDValue: old entry will be orphaned");
}
// overwrite old entry
out.seek(offsets[ifd] + (bigTiff ? 8 : 2) + bytesPerEntry * i + 2);
out.writeShort(newType);
writeIntValue(out, newCount);
writeIntValue(out, newOffset);
if (extraBuf.length() > 0) {
out.seek(newOffset);
out.write(extraBuf.getByteBuffer(), 0, newCount);
}
return;
}
}
throw new FormatException("Tag not found (" + IFD.getIFDTagName(tag) + ")");
}
/** Convenience method for overwriting a file's first ImageDescription. */
public void overwriteComment(final RandomAccessInputStream in,
final Object value) throws FormatException, IOException
{
overwriteIFDValue(in, 0, IFD.IMAGE_DESCRIPTION, value);
}
// -- Helper methods --
/**
* Coverts a list to a primitive array.
*
* @param l The list of <code>Long</code> to convert.
* @return A primitive array of type <code>long[]</code> with the values from
* </code>l</code>.
*/
private long[] toPrimitiveArray(final List<Long> l) {
final long[] toReturn = new long[l.size()];
for (int i = 0; i < l.size(); i++) {
toReturn[i] = l.get(i);
}
return toReturn;
}
/**
* Write the given value to the given RandomAccessOutputStream. If the
* 'bigTiff' flag is set, then the value will be written as an 8 byte long;
* otherwise, it will be written as a 4 byte integer.
*/
private void writeIntValue(final RandomAccessOutputStream out,
final long offset) throws IOException
{
if (bigTiff) {
out.writeLong(offset);
}
else {
out.writeInt((int) offset);
}
}
/**
* Makes a valid IFD.
*
* @param ifd The IFD to handle.
* @param pixelType The pixel type.
* @param nChannels The number of channels.
*/
private void makeValidIFD(final IFD ifd, final int pixelType,
final int nChannels)
{
final int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
final int bps = 8 * bytesPerPixel;
final int[] bpsArray = new int[nChannels];
Arrays.fill(bpsArray, bps);
ifd.putIFDValue(IFD.BITS_PER_SAMPLE, bpsArray);
if (FormatTools.isFloatingPoint(pixelType)) {
ifd.putIFDValue(IFD.SAMPLE_FORMAT, 3);
}
if (ifd.getIFDValue(IFD.COMPRESSION) == null) {
ifd.putIFDValue(IFD.COMPRESSION, TiffCompression.UNCOMPRESSED.getCode());
}
final boolean indexed =
nChannels == 1 && ifd.getIFDValue(IFD.COLOR_MAP) != null;
final PhotoInterp pi =
indexed ? PhotoInterp.RGB_PALETTE : nChannels == 1
? PhotoInterp.BLACK_IS_ZERO : PhotoInterp.RGB;
ifd.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, pi.getCode());
ifd.putIFDValue(IFD.SAMPLES_PER_PIXEL, nChannels);
if (ifd.get(IFD.X_RESOLUTION) == null) {
ifd.putIFDValue(IFD.X_RESOLUTION, new TiffRational(1, 1));
}
if (ifd.get(IFD.Y_RESOLUTION) == null) {
ifd.putIFDValue(IFD.Y_RESOLUTION, new TiffRational(1, 1));
}
if (ifd.get(IFD.SOFTWARE) == null) {
ifd.putIFDValue(IFD.SOFTWARE, "OME Bio-Formats");
}
if (ifd.get(IFD.ROWS_PER_STRIP) == null) {
ifd.putIFDValue(IFD.ROWS_PER_STRIP, new long[] { 1 });
}
if (ifd.get(IFD.IMAGE_DESCRIPTION) == null) {
ifd.putIFDValue(IFD.IMAGE_DESCRIPTION, "");
}
}
} |
package net.apnic.whowas;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.apnic.whowas.history.*;
import net.apnic.whowas.intervaltree.IntervalTree;
import net.apnic.whowas.rdap.*;
import net.apnic.whowas.types.IP;
import net.apnic.whowas.types.IpInterval;
import net.apnic.whowas.types.Parsing;
import net.apnic.whowas.types.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
@RestController
@CrossOrigin(origins = "*")
@EnableConfigurationProperties({ WebController.ServerNotices.class })
public class WebController {
private final static Logger LOGGER = LoggerFactory.getLogger(WebController.class);
private final IntervalTree<IP, ObjectHistory, IpInterval> intervalTree;
private final ObjectIndex objectIndex;
private final BiFunction<Object, HttpServletRequest, TopLevelObject> makeResponse;
@Autowired
WebController(IntervalTree<IP, ObjectHistory, IpInterval> intervalTree, ObjectIndex objectIndex, BiFunction<Object, HttpServletRequest, TopLevelObject> responseMaker) {
this.intervalTree = intervalTree;
this.objectIndex = objectIndex;
this.makeResponse = responseMaker;
} |
package net.ghostrealms.cmd;
import net.ghostrealms.UUIDLib;
import net.md_5.bungee.api.ChatColor;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import java.text.NumberFormat;
import java.util.Locale;
public class PayCommand implements CommandExecutor {
private Economy econ = null;
public PayCommand(Economy econ) {
this.econ = econ;
}
@Override
public boolean onCommand(CommandSender cmdsender, Command cmd, String label, String[] args) {
double amount;
if(args.length == 2) {
try {
amount = Double.parseDouble(args[1]);
} catch (RuntimeException ex) {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.RED + "Please specify a number for an amount.");
return false;
}
if(amount == 0) {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.RED + "Please specify a number for an amount.");
return true;
} else if(amount < 1) {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.GOLD + "Nice try.. Can't send a Negative Amount!");
return true;
}
OfflinePlayer sender = (OfflinePlayer) cmdsender;
OfflinePlayer receiver = Bukkit.getOfflinePlayer(UUIDLib.getID(args[0]));
if(!econ.hasAccount(receiver)) {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.YELLOW + "That user does not have an account.");
return false;
}
if(!econ.has(sender, amount)) {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.RED + "Insufficient funds.");
return false;
}
econ.depositPlayer(receiver, amount);
econ.withdrawPlayer(sender, amount);
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.YELLOW + "You sent " + ChatColor.GREEN
+ prettyPrint(amount) + ChatColor.YELLOW + " to " + receiver.getName());
if(receiver.isOnline()) {
Player pl = Bukkit.getPlayer(receiver.getUniqueId());
pl.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.YELLOW + "You Received " + ChatColor.GREEN +
prettyPrint(amount) + ChatColor.YELLOW + " from " + sender.getName());
return true;
}
return true;
} else {
cmdsender.sendMessage(ChatColor.GRAY + "[Realms] " + ChatColor.RED + "Oops. Wrong Usage! Try" +
ChatColor.YELLOW + " /pay <user> <amount>");
return false;
}
}
public String prettyPrint(double num) {
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
return econ.format(num).replace(".00", "");
}
} |
package net.imagej.ops.create.img;
import net.imglib2.Dimensions;
import net.imglib2.Interval;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.img.ImgView;
import net.imglib2.type.Type;
import net.imglib2.view.Views;
/**
* Utility methods for working with {@link Img} objects.
*
* @author Curtis Rueden
*/
public final class Imgs {
private Imgs() {
// NB: Prevent instantiation of utility class.
}
/**
* Creates an {@link Img}.
*
* @param factory The {@link ImgFactory} to use to create the image.
* @param dims The dimensional bounds of the newly created image. If the given
* bounds are an {@link Interval}, the resultant {@link Img} will
* have the same min/max as that {@link Interval} as well (see
* {@link #adjustMinMax} for details).
* @param type The component type of the newly created image.
* @return the newly created {@link Img}
*/
public static <T extends Type<T>> Img<T> create(final ImgFactory<T> factory,
final Dimensions dims, final T type)
{
return Imgs.adjustMinMax(factory.imgFactory(type).create(dims), dims);
}
/**
* Adjusts the given {@link Img} to match the bounds of the specified
* {@link Interval}.
*
* @param img An image whose min/max bounds might need adjustment.
* @param minMax An {@link Interval} whose min/max bounds to use when
* adjusting the image. If the provided {@code minMax} object is not
* an {@link Interval}, no adjustment is performed.
* @return A wrapped version of the input {@link Img} with bounds adjusted to
* match the provided {@link Interval}, if any; or the input image
* itself if no adjustment was needed/possible.
*/
public static <T extends Type<T>> Img<T> adjustMinMax(final Img<T> img,
final Object minMax)
{
if (!(minMax instanceof Interval)) return img;
final Interval interval = (Interval) minMax;
final long[] min = new long[interval.numDimensions()];
interval.min(min);
for (int d = 0; d < min.length; d++) {
if (min[d] != 0) {
return ImgView.wrap(Views.translate(img, min), img.factory());
}
}
return img;
}
} |
package net.imagej.updater;
import static net.imagej.updater.util.UpdaterUtil.prettyPrintTimestamp;
import java.awt.Frame;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import net.imagej.updater.Conflicts.Conflict;
import net.imagej.updater.Conflicts.Resolution;
import net.imagej.updater.Diff.Mode;
import net.imagej.updater.FileObject.Action;
import net.imagej.updater.FileObject.Status;
import net.imagej.updater.FileObject.Version;
import net.imagej.updater.FilesCollection.Filter;
import net.imagej.updater.util.Downloadable;
import net.imagej.updater.util.Downloader;
import net.imagej.updater.util.Progress;
import net.imagej.updater.util.StderrProgress;
import net.imagej.updater.util.UpdaterUserInterface;
import net.imagej.updater.util.UpdaterUtil;
import org.scijava.log.LogService;
import org.scijava.util.AppUtils;
import org.scijava.util.FileUtils;
import org.scijava.util.IteratorPlus;
import org.scijava.util.POM;
/**
* This is the command-line interface into the ImageJ Updater.
*
* @author Johannes Schindelin
*/
public class CommandLine {
protected static LogService log = UpdaterUtil.getLogService();
protected FilesCollection files;
protected Progress progress;
private FilesCollection.DependencyMap dependencyMap;
private boolean checksummed = false;
/**
* Determines whether die() should exit or throw a RuntimeException.
*/
private boolean standalone;
@Deprecated
public CommandLine() {
this(AppUtils.getBaseDirectory("ij.dir", CommandLine.class, "updater"), 80);
}
public CommandLine(final File ijDir, final int columnCount) {
this(ijDir, columnCount, null);
}
public CommandLine(final File ijDir, final int columnCount,
final Progress progress) {
this.progress = progress == null ? new StderrProgress(columnCount)
: progress;
files = new FilesCollection(log, ijDir);
}
private void ensureChecksummed() {
if (checksummed) {
return;
}
String warnings;
try {
warnings = files.downloadIndexAndChecksum(progress);
} catch (final Exception e) {
log.debug(e);
throw die("Received exception: " + e.getMessage());
}
if (!warnings.equals("")) {
log.warn(warnings);
}
checksummed = true;
}
protected class FileFilter implements Filter {
protected Set<String> fileNames;
public FileFilter(final List<String> files) {
if (files != null && files.size() > 0) {
fileNames = new HashSet<String>();
for (final String file : files)
fileNames.add(FileObject.getFilename(file, true));
}
}
@Override
public boolean matches(final FileObject file) {
if (!file.isUpdateablePlatform(files)) {
return false;
}
if (fileNames != null
&& !fileNames.contains(file.getFilename(true))) {
return false;
}
return file.getStatus() != Status.OBSOLETE_UNINSTALLED;
}
}
public void diff(final List<String> list) {
ensureChecksummed();
final Diff diff = new Diff(System.out, files.util);
Mode mode = Mode.CLASS_FILE_DIFF;
while (list.size() > 0 && list.get(0).startsWith("
final String option = list.remove(0);
mode = Mode.valueOf(option.substring(2).replace('-', '_')
.toUpperCase());
}
for (final FileObject file : files.filter(new FileFilter(list)))
try {
final String filename = file.getLocalFilename(false);
final URL remote = new URL(files.getURL(file));
final URL local = files.prefix(filename).toURI().toURL();
diff.showDiff(filename, remote, local, mode);
} catch (final IOException e) {
log.error(e);
}
}
public void listCurrent(final List<String> list) {
ensureChecksummed();
for (final FileObject file : files.filter(new FileFilter(list)))
System.out.println(file.filename + "-" + file.getTimestamp());
}
public void list(final List<String> list, Filter filter) {
ensureChecksummed();
if (filter == null) {
filter = new FileFilter(list);
} else {
filter = files.and(new FileFilter(list), filter);
}
files.sort();
for (final FileObject file : files.filter(filter)) {
System.out.println(file.filename + "\t(" + file.getStatus() + ")\t"
+ file.getTimestamp());
}
}
public void list(final List<String> list) {
list(list, null);
}
public void listUptodate(final List<String> list) {
list(list, files.is(Status.INSTALLED));
}
public void listNotUptodate(final List<String> list) {
list(list,
files.not(files.oneOf(new Status[] { Status.OBSOLETE,
Status.INSTALLED, Status.LOCAL_ONLY })));
}
public void listUpdateable(final List<String> list) {
list(list, files.is(Status.UPDATEABLE));
}
public void listModified(final List<String> list) {
list(list, files.is(Status.MODIFIED));
}
public void listLocalOnly(final List<String> list) {
list(list, files.is(Status.LOCAL_ONLY));
}
public void listFromSite(final List<String> sites) {
if (sites.size() != 1)
throw die("Usage: list-from-site <name>");
list(null, files.isUpdateSite(sites.get(0)));
}
public void listShadowed(final List<String> list) {
ensureChecksummed();
final FileFilter filter = new FileFilter(list);
files.sort();
final List<String> overridden = new ArrayList<String>();
for (final FileObject file : files.filter(filter)) {
if (!file.overridesOtherUpdateSite()) continue;
for (final Map.Entry<String, FileObject> entry : file.overriddenUpdateSites
.entrySet())
{
final FileObject other = entry.getValue();
if (other != null && other.current != null) {
overridden.add(entry.getKey());
}
}
if (overridden.isEmpty()) continue;
System.out.println(file.filename + "\t(" + file.getStatus() + ")\t" +
file.updateSite + " overrides " + overridden);
overridden.clear();
}
}
public void show(final List<String> list) {
for (final String filename : list) {
show(filename);
}
}
public void show(final String filename) {
ensureChecksummed();
final FileObject file = files.get(filename);
if (file == null) {
log.error("File not found: " + filename);
} else {
show(file);
}
}
public void show(final FileObject file) {
ensureChecksummed();
if (dependencyMap == null) {
dependencyMap = files.getDependencies(files, false);
}
System.out.println();
System.out.println("File: " + file.getFilename(true));
if (!file.getFilename(true).equals(file.localFilename)) {
System.out.println("(Local filename: " + file.localFilename + ")");
}
String description = file.description;
if (description != null && description.length() > 0) {
description = "\t" + (description.replaceAll("\n", "\n\t"));
System.out.println("Description:\n" + description);
}
System.out.println("Update site: " + file.updateSite);
if (file.current == null) {
System.out.println("Removed from update site");
} else {
System.out.println("URL: " + files.getURL(file));
System.out.println("checksum: " + file.current.checksum
+ ", timestamp: " + file.current.timestamp);
}
if (file.localChecksum != null
&& (file.current == null || !file.localChecksum
.equals(file.current.checksum))) {
System.out.println("Local checksum: "
+ file.localChecksum
+ " ("
+ (file.hasPreviousVersion(file.localChecksum) ? ""
: "NOT a ") + "previous version)");
}
final StringBuilder builder = new StringBuilder();
for (final FileObject dependency : file.getFileDependencies(files,
false)) {
if (builder.length() > 0)
builder.append(", ");
builder.append(dependency.getFilename(true));
}
if (builder.length() > 0) {
System.out.println("Dependencies: " + builder.toString());
}
final FilesCollection dependencees = getDependencees(file);
if (dependencees != null && !dependencees.isEmpty()) {
builder.setLength(0);
for (final FileObject dependencee : dependencees) {
if (builder.length() > 0)
builder.append(", ");
builder.append(dependencee.getFilename(true));
}
if (builder.length() > 0) {
System.out.println("Have '" + file.getFilename(true)
+ "' as dependency: " + builder.toString());
}
}
final File jarFile = files.prefix(file.localFilename != null ? file.localFilename : file.filename);
if (jarFile.exists()) {
final Map<String, String> map = new LinkedHashMap<String, String>();
try {
final JarFile jar = new JarFile(jarFile);
final Manifest manifest = jar.getManifest();
final Attributes attrs = manifest == null ? null : manifest
.getMainAttributes();
final String commit = attrs == null ? null : attrs
.getValue("Implementation-Build");
if (commit != null)
map.put("Commit", commit);
JarEntry pomEntry = null;
for (final JarEntry entry : new IteratorPlus<JarEntry>(
jar.entries())) {
if (!entry.getName().endsWith("/pom.xml"))
continue;
if (pomEntry == null) {
pomEntry = entry;
} else {
System.out.println("Warning: Ignoring extra pom.xml: "
+ entry.getName() + " in " + jarFile);
}
}
if (pomEntry != null)
try {
final POM pom = new POM(jar.getInputStream(pomEntry));
final String url = pom.getProjectURL();
if (url != null)
map.put("Project URL", url);
final String scm = pom.cdata("//project/scm/url");
if (scm != null) {
if (commit != null
&& scm.matches("https?://github.com/[^/]*/[^/]*/?")) {
map.put("Commit URL", scm + "/commit/" + commit);
map.put("Compare URL", scm + "/compare/" + commit + "...master");
}
map.put("Project SCM URL", scm);
}
final String issues = pom
.cdata("//project/issueManagement/url");
if (issues != null)
map.put("Project Issue Tracker", issues);
final String ci = pom
.cdata("//project/ciManagement/url");
if (ci != null)
map.put("Jenkins Job URL", ci);
} catch (Exception e) {
log.debug(e);
System.out.println("Error parsing POM: "
+ e.getMessage());
}
jar.close();
} catch (IOException e) {
System.out.println("Could not get manifest: " + e.getMessage());
}
if (map.isEmpty()) {
System.out.println("No manifest/POM information contained in "
+ jarFile.getName());
} else {
System.out.println("Manifest/POM information for "
+ file.getBaseName() + ":");
for (final Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("\t" + entry.getKey() + ": "
+ entry.getValue());
}
}
}
}
public void history(final List<String> list) {
ensureChecksummed();
class History extends TreeMap<Long, Set<FileObject>> implements
Comparator<FileObject>
{
public void add(final FileObject file) {
if (file.current != null) {
add(file.current.timestamp, file);
}
for (final Version version : file.previous) {
add(version.timestamp, file);
}
}
public void add(final long timestamp, final FileObject file) {
Set<FileObject> set = get(timestamp);
if (set == null) {
set = new TreeSet<FileObject>(this);
put(timestamp, set);
}
set.add(file);
}
@Override
public int compare(FileObject a, FileObject b) {
return a.getFilename(true).compareTo(b.getFilename(true));
}
}
final History history = new History();
for (final FileObject file : files.filter(new FileFilter(list))) {
if (file.getStatus() == Status.LOCAL_ONLY) continue;
history.add(file);
}
for (final Entry<Long, Set<FileObject>> entry : history.descendingMap()
.entrySet())
{
final long timestamp = entry.getKey();
final Set<FileObject> files = entry.getValue();
System.out.println("" + prettyPrintTimestamp(timestamp));
for (final FileObject file : files) {
System.out.println("\t" + file.getFilename(timestamp));
}
}
}
private FilesCollection getDependencees(final FileObject file) {
if (dependencyMap == null)
dependencyMap = files.getDependencies(files, false);
return dependencyMap.get(file);
}
class OneFile implements Downloadable {
FileObject file;
OneFile(final FileObject file) {
this.file = file;
}
@Override
public File getDestination() {
return files.prefix(file.filename);
}
@Override
public String getURL() {
return files.getURL(file);
}
@Override
public long getFilesize() {
return file.filesize;
}
@Override
public String toString() {
return file.filename;
}
}
public void download(final FileObject file) {
ensureChecksummed();
try {
new Downloader(progress, files.util).start(new OneFile(file));
if (file.executable && !files.util.platform.startsWith("win")) {
try {
Runtime.getRuntime().exec(
new String[] { "chmod", "0755",
files.prefix(file.filename).getPath() });
} catch (final Exception e) {
e.printStackTrace();
throw die("Could not mark " + file.filename
+ " as executable");
}
}
log.info("Installed " + file.filename);
} catch (final IOException e) {
log.error("IO error downloading " + file.filename, e);
}
}
public void delete(final FileObject file) {
if (new File(file.filename).delete()) {
log.info("Deleted " + file.filename);
} else {
log.error("Failed to delete " + file.filename);
}
}
public void update(final List<String> list) {
update(list, false);
}
public void update(final List<String> list, final boolean force) {
update(list, force, false);
}
public void update(final List<String> list, final boolean force,
final boolean pristine) {
ensureChecksummed();
if (list.size() > 0) {
for (final FileObject file : files) {
if (file.getStatus() == Status.NEW
&& file.getAction() == Action.INSTALL) {
file.setAction(files, Action.NEW);
}
}
}
try {
for (final FileObject file : files.filter(new FileFilter(list))) {
if (file.getStatus() == Status.LOCAL_ONLY) {
if (pristine)
file.setAction(files, Action.UNINSTALL);
} else if (file.isObsolete()) {
if (file.getStatus() == Status.OBSOLETE) {
log.info("Removing " + file.filename);
file.stageForUninstall(files);
} else if (file.getStatus() == Status.OBSOLETE_MODIFIED) {
if (force || pristine) {
file.stageForUninstall(files);
log.info("Removing " + file.filename);
} else {
log.warn("Skipping obsolete, but modified "
+ file.filename);
}
}
} else if (file.getStatus() != Status.INSTALLED
&& !file.stageForUpdate(files, force)) {
log.warn("Skipping " + file.filename);
}
// remove obsolete versions in pristine mode
if (pristine) {
final File correctVersion = files.prefix(file);
final File[] versions = FileUtils.getAllVersions(
correctVersion.getParentFile(),
correctVersion.getName());
if (versions != null) {
for (final File version : versions) {
if (!version.equals(correctVersion)) {
log.info("Deleting obsolete version " + version);
if (!version.delete()) {
log.error("Could not delete " + version
+ "!");
}
}
}
}
}
}
resolveConflicts(false);
final Installer installer = new Installer(files, progress);
installer.start();
installer.moveUpdatedIntoPlace();
files.write();
} catch (final Exception e) {
if (e.getMessage().indexOf("conflicts") >= 0) {
log.error("Could not update due to conflicts:");
for (final Conflict conflict : new Conflicts(files).getConflicts(false))
{
log.error(conflict.getFilename() + ": " + conflict.getConflict());
}
} else {
log.error("Error updating", e);
}
}
}
public void revertUnrealChanges(final List<String> list) {
ensureChecksummed();
boolean simulate = false;
if (list != null && list.size() > 0 && "--simulate".equals(list.get(0))) {
simulate = true;
list.remove(0);
}
int count = 0;
for (final FileObject file : files.filter(new FileFilter(list))) {
switch (file.getStatus()) {
case MODIFIED:
case UPDATEABLE:
break;
case INSTALLED:
case LOCAL_ONLY:
case NEW:
case NOT_INSTALLED:
case OBSOLETE:
case OBSOLETE_MODIFIED:
case OBSOLETE_UNINSTALLED:
// do nothing
continue;
}
if (file.filename.endsWith(".dll")) {
try {
final DllFile dll = new DllFile(files.prefix(file));
try {
final URL url = new URL(files.getURL(file));
if (!dll.equals(url.openConnection())) continue;
}
finally {
dll.close();
}
}
catch (Throwable t) {
// print exception, but ignore otherwise
log.warn(t);
continue;
}
if (simulate) {
System.out.println("Would overwrite " + file.filename);
}
else {
file.setAction(files, Action.UPDATE);
}
count++;
}
}
if (count == 0) {
System.err.println("Nothing to do!");
}
else if (simulate) {
System.out.println("Would overwrite " + count + " file(s)");
}
else try {
final Installer installer = new Installer(files, progress);
installer.start();
installer.moveUpdatedIntoPlace();
files.write();
}
catch (Throwable t) {
log.error(t);
}
}
public void downgrade(final List<String> list) {
if (standalone) {
final Console console = System.console();
if (console == null) {
throw die("Downgrading is only allowed interactively");
}
final List<String> answers = Arrays.asList("Yours, and yours alone", "Obama's", "San Andreas'");
final String correct = answers.get(0);
Collections.shuffle(answers);
String answer = console.readLine("Downgrading is not accurate, due to lack of accurate metadata\n" +
"In particular, when files have been shadowed/unshadowed or marked obsolete,\n" +
"the result of a downgrade is guaranteed to be inaccurate.\n\n" +
"If you do not want an inaccurate time, now is the time to quit.\n\n" +
"Otherwise, please answer the following question accurately:\n" +
"Whose fault is it if anything goes wrong with this downgrade?\n\n" +
"\t1) %s\n\t2) %s\n\t3) %s\n", answers.toArray()).trim();
if (answer.matches("[0-9]+")) try {
answer = answers.get(Integer.parseInt(answer) - 1);
}
catch (final NumberFormatException e) {
// ignore
}
if (!correct.equals(answer)) {
throw die("Absolutely not.");
}
}
boolean simulate = false;
if (list.size() > 0 && "--simulate".equals(list.get(0))) {
simulate = true;
list.remove(0);
}
if (list.size() < 1) {
throw die("What date?");
}
final String timestampString = list.remove(0);
final long timestamp = Long.parseLong(timestampString);
ensureChecksummed();
int count = 0;
for (final FileObject file : files.filter(new FileFilter(list))) {
if (file.getStatus() == Status.LOCAL_ONLY) continue;
if (file.current != null && file.current.timestamp <= timestamp) {
if (!file.current.checksum.equals(file.localChecksum)) {
if (simulate) {
System.out.println("Would update/install " + file.current.filename);
}
else {
file.setStatus(Status.UPDATEABLE);
file.setFirstValidAction(files, Action.UPDATE, Action.INSTALL);
}
count++;
}
continue;
}
String result = null;
String checksum = null;
long matchedTimestamp = 0;
for (final Version version : file.previous) {
if (timestamp >= version.timestamp && version.timestamp > matchedTimestamp) {
result = version.filename;
checksum = version.checksum;
matchedTimestamp = version.timestamp;
}
}
if (checksum == null) {
if (file.localChecksum != null) {
if (simulate) {
System.out.println("Would uninstall " + file.getLocalFilename(false));
}
else {
file.setAction(files, Action.UNINSTALL);
}
count++;
}
}
else if (!result.equals(file.filename) || !checksum.equals(file.localChecksum)) {
if (simulate) {
System.out.println("Would update/install " + result);
}
else {
if (file.current == null) {
file.current = new Version(checksum, matchedTimestamp);
}
else {
file.current.checksum = checksum;
file.current.timestamp = matchedTimestamp;
}
file.filename = file.current.filename = result;
file.filesize = -1;
file.setStatus(Status.UPDATEABLE);
file.setFirstValidAction(files, Action.UPDATE, Action.INSTALL);
}
count++;
}
}
if (count == 0) {
System.err.println("Nothing to do!");
}
else if (!simulate) try {
resolveConflicts(false);
final Installer installer = new Installer(files, progress);
installer.start();
installer.moveUpdatedIntoPlace();
files.write();
} catch (final Exception e) {
if (e.getMessage().indexOf("conflicts") >= 0) {
log.error("Could not update due to conflicts:");
for (final Conflict conflict : new Conflicts(files).getConflicts(false))
{
log.error(conflict.getFilename() + ": " + conflict.getConflict());
}
} else {
log.error("Error updating", e);
}
}
}
public void upload(final List<String> list) {
if (list == null) {
throw die("Which files do you mean to upload?");
}
boolean forceUpdateSite = false, forceShadow = false, simulate = false, forgetMissingDeps = false;
String updateSite = null;
while (list.size() > 0 && list.get(0).startsWith("-")) {
final String option = list.remove(0);
if ("--update-site".equals(option) || "--site".equals(option)) {
if (list.size() < 1) {
throw die("Missing name for --update-site");
}
updateSite = list.remove(0);
forceUpdateSite = true;
} else if ("--simulate".equals(option)) {
simulate = true;
} else if ("--force-shadow".equals(option)) {
forceShadow = true;
} else if ("--forget-missing-dependencies".equals(option)) {
forgetMissingDeps = true;
} else {
throw die("Unknown option: " + option);
}
}
if (list.size() == 0) {
throw die("Which files do you mean to upload?");
}
if (forceShadow && updateSite == null) {
throw die("Need an explicit update site with --force-shadow");
}
ensureChecksummed();
int count = 0;
for (final String name : list) {
final FileObject file = files.get(name);
if (file == null) {
throw die("No file '" + name + "' found!");
}
if (file.getStatus() == Status.INSTALLED && (file.localFilename == null || file.localFilename.equals(file.filename))) {
if (forceShadow && !updateSite.equals(file.updateSite)) {
// TODO: add overridden update site
file.updateSite = updateSite;
file.setStatus(Status.MODIFIED);
log.info("Uploading (force-shadow) '" + name
+ "' to site '" + updateSite + "'");
} else {
log.info("Skipping up-to-date " + name);
continue;
}
}
handleLauncherForUpload(file);
if (updateSite == null) {
updateSite = file.updateSite;
if (updateSite == null) {
updateSite = file.updateSite = chooseUploadSite(name);
}
if (updateSite == null) {
throw die("Canceled");
}
} else if (file.updateSite == null) {
log.info("Uploading new file '" + name + "' to site '"
+ updateSite + "'");
file.updateSite = updateSite;
} else if (!file.updateSite.equals(updateSite)) {
if (forceUpdateSite) {
file.updateSite = updateSite;
} else {
throw die("Cannot upload to multiple update sites ("
+ list.get(0) + " to " + updateSite + " and "
+ name + " to " + file.updateSite + ")");
}
}
if (file.getStatus() == Status.NOT_INSTALLED
|| file.getStatus() == Status.NEW) {
log.info("Removing file '" + name + "'");
file.setAction(files, Action.REMOVE);
} else {
if (simulate) {
log.info("Would upload '" + name + "'");
}
if (file.localFilename != null && !file.localFilename.equals(file.filename)) {
file.addPreviousVersion(file.current.checksum, file.current.timestamp, file.filename);
}
file.setAction(files, Action.UPLOAD);
}
count++;
}
if (count == 0) {
log.info("Nothing to upload");
return;
}
if (updateSite != null
&& files.getUpdateSite(updateSite, false) == null) {
throw die("Unknown update site: '" + updateSite + "'");
}
if (forgetMissingDeps) {
for (final Conflict conflict : new Conflicts(files)
.getConflicts(true)) {
final String message = conflict.getConflict();
if (!message.startsWith("Depends on ")
|| !message.endsWith(" which is about to be removed.")) {
continue;
}
log.info("Breaking dependency: " + conflict);
for (final Resolution resolution : conflict.getResolutions()) {
if (resolution.getDescription().startsWith("Break")) {
resolution.resolve();
break;
}
}
}
}
if (simulate) {
final Iterable<Conflict> conflicts = new Conflicts(files)
.getConflicts(true);
if (Conflicts.needsFeedback(conflicts)) {
log.error("Unresolved upload conflicts!\n\n"
+ UpdaterUtil.join("\n", conflicts));
} else {
log.info("Would upload/remove " + count + " to/from "
+ getLongUpdateSiteName(updateSite));
}
final String errors = files.checkConsistency();
if (errors != null) {
log.error(errors);
}
return;
}
final String errors = files.checkConsistency();
if (errors != null) {
throw die(errors);
}
log.info("Uploading to " + getLongUpdateSiteName(updateSite));
upload(updateSite);
}
public void uploadCompleteSite(final List<String> list) {
if (list == null) {
throw die("Which files do you mean to upload?");
}
boolean ignoreWarnings = false, forceShadow = false, simulate = false;
while (list.size() > 0 && list.get(0).startsWith("-")) {
final String option = list.remove(0);
if ("--force".equals(option)) {
ignoreWarnings = true;
} else if ("--force-shadow".equals(option)) {
forceShadow = true;
} else if ("--simulate".equals(option)) {
simulate = true;
} else if ("--platforms".equals(option)) {
if (list.size() == 0) {
throw die("Need a comma-separated list of platforms with --platform");
}
files.util.setUpdateablePlatforms(list.remove(0).split(","));
} else {
throw die("Unknown option: " + option);
}
}
if (list.size() != 1) {
throw die("Which files do you mean to upload?");
}
final String updateSite = list.get(0);
ensureChecksummed();
if (files.getUpdateSite(updateSite, false) == null) {
throw die("Unknown update site '" + updateSite + "'");
}
int removeCount = 0, uploadCount = 0, warningCount = 0;
for (final FileObject file : files) {
if (!file.isUpdateablePlatform(files)) {
continue;
}
final String name = file.filename;
handleLauncherForUpload(file);
switch (file.getStatus()) {
case OBSOLETE:
case OBSOLETE_MODIFIED:
if (forceShadow) {
file.updateSite = updateSite;
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would upload " + file.filename);
}
uploadCount++;
} else if (ignoreWarnings && updateSite.equals(file.updateSite)) {
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would re-upload " + file.filename);
}
uploadCount++;
} else {
log.warn("Obsolete '" + name + "' still installed!");
warningCount++;
}
break;
case UPDATEABLE:
case MODIFIED:
if (!forceShadow && !updateSite.equals(file.updateSite)) {
log.warn("'" + name + "' of update site '"
+ file.updateSite + "' is not up-to-date!");
warningCount++;
continue;
}
//$FALL-THROUGH$
case LOCAL_ONLY:
file.updateSite = updateSite;
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would upload new "
+ (file.getStatus() == Status.LOCAL_ONLY ? ""
: "version of ")
+ file.getLocalFilename(true));
}
uploadCount++;
break;
case NEW:
case NOT_INSTALLED:
// special: keep tools-1.4.2.jar, needed for ImageJ 1.x
if ("ImageJ".equals(updateSite)
&& file.getFilename(true).equals("jars/tools.jar")) {
break;
}
if (!file.isUpdateablePlatform(files)) break;
file.setAction(files, Action.REMOVE);
if (simulate) {
log.info("Would mark " + file.filename + " obsolete");
}
removeCount++;
break;
case INSTALLED:
case OBSOLETE_UNINSTALLED:
// leave these alone
break;
}
}
// remove all obsolete dependencies of the same upload site
for (final FileObject file : files.forUpdateSite(updateSite)) {
if (!file.willBeUpToDate()) {
continue;
}
for (final FileObject dependency : file.getFileDependencies(files,
false)) {
if (dependency.willNotBeInstalled()
&& updateSite.equals(dependency.updateSite)) {
file.removeDependency(dependency.getFilename(false));
}
}
if (ignoreWarnings) {
final List<String> obsoleteDependencies = new ArrayList<String>();
for (final Dependency dependency : file.getDependencies()) {
final FileObject dep = files.get(dependency.filename);
if (dep != null && dep.isObsolete()) {
obsoleteDependencies.add(dependency.filename);
}
}
for (final String filename : obsoleteDependencies) {
file.removeDependency(filename);
}
}
}
if (!ignoreWarnings && warningCount > 0) {
throw die("Use --force to ignore warnings and upload anyway");
}
if (removeCount == 0 && uploadCount == 0) {
log.info("Nothing to upload");
return;
}
if (simulate) {
final Iterable<Conflict> conflicts = new Conflicts(files)
.getConflicts(true);
if (Conflicts.needsFeedback(conflicts)) {
log.error("Unresolved upload conflicts!\n\n"
+ UpdaterUtil.join("\n", conflicts));
} else {
log.info("Would upload " + uploadCount + " (removing "
+ removeCount + ") to "
+ getLongUpdateSiteName(updateSite));
}
final String errors = files.checkConsistency();
if (errors != null) {
log.error(errors);
}
return;
}
log.info("Uploading " + uploadCount + " (removing " + removeCount
+ ") to " + getLongUpdateSiteName(updateSite));
upload(updateSite);
}
private void handleLauncherForUpload(final FileObject file) {
if (file.getStatus() == Status.LOCAL_ONLY
&& files.util.isLauncher(file.filename)) {
file.executable = true;
file.addPlatform(UpdaterUtil.platformForLauncher(file.filename));
for (final String fileName : new String[] { "jars/imagej-launcher.jar" }) {
final FileObject dependency = files.get(fileName);
if (dependency != null) {
file.addDependency(files, dependency);
}
}
}
}
private void upload(final String updateSite) {
resolveConflicts(true);
FilesUploader uploader = null;
try {
uploader = new FilesUploader(null, files, updateSite, progress);
if (!uploader.login())
throw die("Login failed!");
uploader.upload(progress);
files.write();
} catch (final Throwable e) {
final String message = e.getMessage();
if (message != null && message.indexOf("conflicts") >= 0) {
log.error("Could not upload due to conflicts:");
for (final Conflict conflict : new Conflicts(files)
.getConflicts(true)) {
log.error(conflict.getFilename() + ": "
+ conflict.getConflict());
}
} else {
e.printStackTrace();
throw die("Error during upload: " + e);
}
if (uploader != null)
uploader.logout();
}
}
private void resolveConflicts(final boolean forUpload) {
final Console console = System.console();
final Conflicts conflicts = new Conflicts(files);
for (;;) {
final Iterable<Conflict> list = conflicts.getConflicts(forUpload);
if (!Conflicts.needsFeedback(list)) {
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
log.info((filename != null ? filename + ": " : "")
+ conflict.getConflict());
}
return;
}
if (console == null) {
final StringBuilder builder = new StringBuilder();
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
builder.append((filename != null ? filename + ": " : "")
+ conflict.getConflict() + "\n");
}
throw die("There are conflicts:\n" + builder);
}
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
if (filename != null) {
console.printf("File '%s':\n", filename);
}
console.printf("%s\n", conflict.getConflict());
if (conflict.getResolutions().length == 0) {
continue;
}
console.printf("\nResolutions:\n");
final Resolution[] resolutions = conflict.getResolutions();
for (int i = 0; i < resolutions.length; i++) {
console.printf("% 3d %s\n", i + 1,
resolutions[i].getDescription());
}
for (;;) {
final String answer = console.readLine("\nResolution? ");
if (answer == null || answer.toLowerCase().startsWith("x")) {
throw die("Aborted");
}
try {
final int index = Integer.parseInt(answer);
if (index > 0 && index <= resolutions.length) {
resolutions[index - 1].resolve();
break;
}
console.printf(
"Invalid choice: %d (must be between 1 and %d)",
index, resolutions.length);
} catch (final NumberFormatException e) {
console.printf("Invalid answer: %s\n", answer);
}
}
}
}
}
public String chooseUploadSite(final String file) {
final List<String> names = new ArrayList<String>();
final List<String> options = new ArrayList<String>();
for (final String name : files.getUpdateSiteNames(false)) {
final UpdateSite updateSite = files.getUpdateSite(name, true);
if (updateSite.getUploadDirectory() == null
|| updateSite.getUploadDirectory().equals("")) {
continue;
}
names.add(name);
options.add(getLongUpdateSiteName(name));
}
if (names.size() == 0) {
log.error("No uploadable sites found");
return null;
}
final String message = "Choose upload site for file '" + file + "'";
final int index = UpdaterUserInterface.get().optionDialog(message,
message, options.toArray(new String[options.size()]), 0);
return index < 0 ? null : names.get(index);
}
public String getLongUpdateSiteName(final String name) {
final UpdateSite site = files.getUpdateSite(name, true);
String host = site.getHost();
if (host == null || host.equals("")) {
host = "";
} else {
if (host.startsWith("webdav:")) {
final int colon = host.indexOf(':', 8);
if (colon > 0) {
host = host.substring(0, colon) + ":<password>";
}
}
host += ":";
}
return name + " (" + host + site.getUploadDirectory() + ")";
}
public void listUpdateSites(Collection<String> args) {
ensureChecksummed();
if (args == null || args.size() == 0)
args = files.getUpdateSiteNames(true);
for (final String name : args) {
final UpdateSite site = files.getUpdateSite(name, true);
System.out.print(name + (site.isActive() ? "" : " (DISABLED)")
+ ": " + site.getURL());
if (site.getUploadDirectory() == null)
System.out.println();
else
System.out.println(" (upload host: " + site.getHost()
+ ", upload directory: " + site.getUploadDirectory()
+ ")");
}
}
public void addOrEditUploadSite(final List<String> args, final boolean add) {
if (args.size() != 2 && args.size() != 4)
throw die("Usage: " + (add ? "add" : "edit")
+ "-update-site <name> <url> [<host> <upload-directory>]");
addOrEditUploadSite(args.get(0), args.get(1),
args.size() > 2 ? args.get(2) : null,
args.size() > 3 ? args.get(3) : null, add);
}
public void addOrEditUploadSite(final String name, final String url,
final String sshHost, final String uploadDirectory,
final boolean add) {
ensureChecksummed();
final UpdateSite site = files.getUpdateSite(name, true);
if (site == null || add) {
if (site != null)
throw die("Site '" + name + "' was already added!");
files.addUpdateSite(name, url, sshHost, uploadDirectory, 0l);
} else {
site.setURL(url);
site.setHost(sshHost);
site.setUploadDirectory(uploadDirectory);
site.setActive(true);
}
try {
files.write();
} catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
throw die("Could not write local file database");
}
}
public void removeUploadSite(final List<String> names) {
if (names == null || names.size() < 1) {
throw die("Which update-site do you want to remove, exactly?");
}
removeUploadSite(names.toArray(new String[names.size()]));
}
public void removeUploadSite(final String... names) {
ensureChecksummed();
for (final String name : names) {
files.removeUpdateSite(name);
}
try {
files.write();
} catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
throw die("Could not write local file database");
}
}
@Deprecated
public static CommandLine getInstance() {
try {
return new CommandLine();
} catch (final Exception e) {
e.printStackTrace();
log.error("Could not parse db.xml.gz: " + e.getMessage());
throw new RuntimeException(e);
}
}
private static List<String> makeList(final String[] list, int start) {
final List<String> result = new ArrayList<String>();
while (start < list.length)
result.add(list[start++]);
return result;
}
/**
* Print an error message and exit the process with an error.
*
* Note: Java has no "noreturn" annotation, but you can always write:
* <code>throw die(<message>)</code> to make the Java compiler understand.
*
* @param message
* the error message
* @return a dummy return value to be able to use "throw die(...)" to shut
* up the compiler
*/
private RuntimeException die(final String message) {
if (standalone) {
log.error(message);
System.exit(1);
}
return new RuntimeException(message);
}
public void usage() {
final StringBuilder diffOptions = new StringBuilder();
diffOptions.append("[ ");
for (final Mode mode : Mode.values()) {
if (diffOptions.length() > 2) {
diffOptions.append(" | ");
}
diffOptions.append("
+ mode.toString().toLowerCase().replace(' ', '-'));
}
diffOptions.append(" ]");
throw die("Usage: imagej.updater.ui.CommandLine <command>\n"
+ "\n"
+ "Commands:\n"
+ "\tdiff "
+ diffOptions
+ " [<files>]\n"
+ "\tlist [<files>]\n"
+ "\tlist-uptodate [<files>]\n"
+ "\tlist-not-uptodate [<files>]\n"
+ "\tlist-updateable [<files>]\n"
+ "\tlist-modified [<files>]\n"
+ "\tlist-current [<files>]\n"
+ "\tlist-local-only [<files>]\n"
+ "\tlist-shadowed [<files>]\n"
+ "\tlist-from-site <name>\n"
+ "\tshow [<files>]\n"
+ "\tupdate [<files>]\n"
+ "\tupdate-force [<files>]\n"
+ "\tupdate-force-pristine [<files>]\n"
+ "\trevert-unreal-changes [<files>]\n"
+ "\tupload [--simulate] [--[update-]site <name>] [--force-shadow] [--forget-missing-dependencies] [<files>]\n"
+ "\tupload-complete-site [--simulate] [--force] [--force-shadow] [--platforms <platform>[,<platform>...]] <name>\n"
+ "\tlist-update-sites [<nick>...]\n"
+ "\tadd-update-site <nick> <url> [<host> <upload-directory>]\n"
+ "\tedit-update-site <nick> <url> [<host> <upload-directory>]");
}
public static void main(final String... args) {
if (System.getProperty("imagej.dir") == null) {
final String ijDir = System.getProperty("ij.dir");
if (ijDir != null) System.setProperty("imagej.dir", ijDir);
else {
final String fijiDir = System.getProperty("fiji.dir");
if (fijiDir != null) System.setProperty("imagej.dir", fijiDir);
}
}
try {
main(AppUtils.getBaseDirectory("imagej.dir", CommandLine.class, "updater"), 79, null, true, args);
} catch (final RuntimeException e) {
log.error(e);
System.exit(1);
} catch (final Exception e) {
log.error("Could not parse db.xml.gz", e);
System.exit(1);
}
}
public static void main(final File ijDir, final int columnCount,
final String... args) {
main(ijDir, columnCount, null, args);
}
public static void main(final File ijDir, final int columnCount,
final Progress progress, final String... args) {
main(ijDir, columnCount, progress, false, args);
}
private static void main(final File ijDir, final int columnCount,
final Progress progress, final boolean standalone,
final String[] args) {
String http_proxy = System.getenv("http_proxy");
if (http_proxy != null && http_proxy.startsWith("http:
final int colon = http_proxy.indexOf(':', 7);
final int slash = http_proxy.indexOf('/', 7);
int port = 80;
if (colon < 0) {
http_proxy = slash < 0 ? http_proxy.substring(7) : http_proxy
.substring(7, slash);
} else {
port = Integer.parseInt(slash < 0 ? http_proxy
.substring(colon + 1) : http_proxy.substring(colon + 1,
slash));
http_proxy = http_proxy.substring(7, colon);
}
System.setProperty("http.proxyHost", http_proxy);
System.setProperty("http.proxyPort", "" + port);
} else {
UpdaterUtil.useSystemProxies();
}
Authenticator.setDefault(new ConsoleAuthenticator());
setUserInterface();
final CommandLine instance = new CommandLine(ijDir, columnCount,
progress);
instance.standalone = standalone;
if (args.length == 0) {
instance.usage();
}
final String command = args[0];
if (command.equals("diff")) {
instance.diff(makeList(args, 1));
} else if (command.equals("list")) {
instance.list(makeList(args, 1));
} else if (command.equals("list-current")) {
instance.listCurrent(makeList(args, 1));
} else if (command.equals("list-uptodate")) {
instance.listUptodate(makeList(args, 1));
} else if (command.equals("list-not-uptodate")) {
instance.listNotUptodate(makeList(args, 1));
} else if (command.equals("list-updateable")) {
instance.listUpdateable(makeList(args, 1));
} else if (command.equals("list-modified")) {
instance.listModified(makeList(args, 1));
} else if (command.equals("list-local-only")) {
instance.listLocalOnly(makeList(args, 1));
} else if (command.equals("list-from-site")) {
instance.listFromSite(makeList(args, 1));
} else if (command.equals("list-shadowed")) {
instance.listShadowed(makeList(args, 1));
} else if (command.equals("show")) {
instance.show(makeList(args, 1));
} else if (command.equals("update")) {
instance.update(makeList(args, 1));
} else if (command.equals("update-force")) {
instance.update(makeList(args, 1), true);
} else if (command.equals("update-force-pristine")) {
instance.update(makeList(args, 1), true, true);
} else if (command.equals("revert-unreal-changes")) {
instance.revertUnrealChanges(makeList(args, 1));
} else if (command.equals("upload")) {
instance.upload(makeList(args, 1));
} else if (command.equals("upload-complete-site")) {
instance.uploadCompleteSite(makeList(args, 1));
} else if (command.equals("list-update-sites")) {
instance.listUpdateSites(makeList(args, 1));
} else if (command.equals("add-update-site")) {
instance.addOrEditUploadSite(makeList(args, 1), true);
} else if (command.equals("edit-update-site")) {
instance.addOrEditUploadSite(makeList(args, 1), false);
} else if (command.equals("remove-update-site")) {
instance.removeUploadSite(makeList(args, 1));
// hidden commands, i.e. not for public consumption
} else if (command.equals("history")) {
instance.history(makeList(args, 1));
} else if (command.equals("downgrade")) {
instance.downgrade(makeList(args, 1));
} else {
instance.usage();
}
}
protected static class ConsoleAuthenticator extends Authenticator {
protected Console console = System.console();
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (console == null) {
throw new RuntimeException(
"Need a console for user interaction!");
}
final String user = console
.readLine(" \r" + getRequestingPrompt() + "\nUser: ");
final char[] password = console.readPassword("Password: ");
return new PasswordAuthentication(user, password);
}
}
protected static void setUserInterface() {
UpdaterUserInterface.set(new ConsoleUserInterface());
}
protected static class ConsoleUserInterface extends UpdaterUserInterface {
protected Console console = System.console();
protected int count;
@Override
public String getPassword(final String message) {
if (console == null) {
throw new RuntimeException(
"Password prompt requires interactive operation!");
}
System.out.print(message + ": ");
return new String(console.readPassword());
}
@Override
public boolean promptYesNo(final String title, final String message) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
System.err.print(title + ": " + message);
final String line = console.readLine();
return line.startsWith("y") || line.startsWith("Y");
}
public void showPrompt(String prompt) {
if (!prompt.endsWith(": ")) {
prompt += ": ";
}
System.err.print(prompt);
}
public String getUsername(final String prompt) {
if (console == null) {
throw new RuntimeException(
"Username prompt requires interactive operation!");
}
showPrompt(prompt);
return console.readLine();
}
public int askChoice(final String[] options) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
for (int i = 0; i < options.length; i++)
System.err.println("" + (i + 1) + ": " + options[i]);
for (;;) {
System.err.print("Choice? ");
final String answer = console.readLine();
if (answer.equals("")) {
return -1;
}
try {
return Integer.parseInt(answer) - 1;
} catch (final Exception e) { /* ignore */
}
}
}
@Override
public void error(final String message) {
log.error(message);
}
@Override
public void info(final String message, final String title) {
log.info(title + ": " + message);
}
@Override
public void log(final String message) {
log.info(message);
}
@Override
public void debug(final String message) {
log.debug(message);
}
@Override
public OutputStream getOutputStream() {
return System.out;
}
@Override
public void showStatus(final String message) {
log(message);
}
@Override
public void handleException(final Throwable exception) {
exception.printStackTrace();
}
@Override
public boolean isBatchMode() {
return false;
}
@Override
public int optionDialog(final String message, final String title,
final Object[] options, final int def) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
for (int i = 0; i < options.length; i++)
System.err.println("" + (i + 1) + ") " + options[i]);
for (;;) {
System.out.print("Your choice (default: " + def + ": "
+ options[def] + ")? ");
final String line = console.readLine();
if (line.equals("")) {
return def;
}
try {
final int option = Integer.parseInt(line);
if (option > 0 && option <= options.length) {
return option - 1;
}
} catch (final NumberFormatException e) {
// ignore
}
}
}
@Override
public String getPref(final String key) {
return null;
}
@Override
public void setPref(final String key, final String value) {
log("Ignoring setting '" + key + "'");
}
@Override
public void savePreferences() { /* do nothing */
}
@Override
public void openURL(final String url) throws IOException {
log("Please open " + url + " in your browser");
}
@Override
public String getString(final String title) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
System.out.print(title + ": ");
return console.readLine();
}
@Override
public void addWindow(final Frame window) { }
@Override
public void removeWindow(final Frame window) { }
}
} |
package net.sknv.nkmod;
import net.minecraft.block.Block;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntityType;
import net.minecraftforge.common.extensions.IForgeContainerType;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.sknv.nkmod.blocks.machines.GrinderContainer;
import net.sknv.nkmod.blocks.machines.GrinderTile;
import net.sknv.nkmod.blocks.machines.ReactionChamberContainer;
import net.sknv.nkmod.blocks.machines.ReactionChamberTile;
import net.sknv.nkmod.blocks.machines.base.MachineBlock;
import net.sknv.nkmod.blocks.NkOreBlock;
import net.sknv.nkmod.items.NkBlockItem;
import net.sknv.nkmod.items.NkItem;
public class RegistryHandler {
// create DeferredRegister object
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Naschkatze.MODID);
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Naschkatze.MODID);
private static final DeferredRegister<TileEntityType<?>> TILES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, Naschkatze.MODID);
private static final DeferredRegister<ContainerType<?>> CONTAINERS = DeferredRegister.create(ForgeRegistries.CONTAINERS, Naschkatze.MODID);
public static void init() {
// attach DeferredRegister to the event bus
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
TILES.register(FMLJavaModLoadingContext.get().getModEventBus());
CONTAINERS.register(FMLJavaModLoadingContext.get().getModEventBus());
}
// register blocks
public static final RegistryObject<Block> URANINITE_ORE = BLOCKS.register("uraninite_ore", () -> new NkOreBlock(2,3));
// How to add MachineBlocks
// Create XXBlockContainer extends AbstractMachineContainer, register here
// Create XXBlockTile extends AbstractMachineTile, register here
// Register block here with () -> new MachineBlock(XXBlockTile::new)
// Register BlockItem
// Register screen on ClientSetup with ClientSetupMachineScreenFactory<>("textures/gui/xx_gui.png")
/*
* Traditionally:
* Block -> Tile
* Tile -> Container
* ClientSetup registers Container <-> Screen
* */
// todo: document machine blocks abstract classes and interfaces
// todo: make wrapper method to add machines that adds Block, Tile, Container, BlockItem automatically.
public static final RegistryObject<Block> GRINDER = BLOCKS.register("grinder", () -> new MachineBlock(GrinderTile::new));
public static final RegistryObject<Block> REACTIONCHAMBER = BLOCKS.register("reaction_chamber", () -> new MachineBlock(ReactionChamberTile::new));
// register block items
public static final RegistryObject<Item> URANINITE_ORE_ITEM = ITEMS.register("uraninite_ore", () -> new NkBlockItem(URANINITE_ORE.get()));
public static final RegistryObject<Item> GRINDER_ITEM = ITEMS.register("grinder", () -> new NkBlockItem(GRINDER.get()));
public static final RegistryObject<Item> REACTIONCHAMBER_ITEM = ITEMS.register("reaction_chamber", () -> new NkBlockItem(REACTIONCHAMBER.get()));
// register block TEs
public static final RegistryObject<TileEntityType<GrinderTile>> GRINDER_TILE = TILES.register("grinder", () -> TileEntityType.Builder.create(GrinderTile::new, GRINDER.get()).build(null));
public static final RegistryObject<TileEntityType<ReactionChamberTile>> REACTIONCHAMBER_TILE = TILES.register("reaction_chamber", () -> TileEntityType.Builder.create(ReactionChamberTile::new, REACTIONCHAMBER.get()).build(null));
// register block containers
public static final RegistryObject<ContainerType<GrinderContainer>> GRINDER_CONTAINER = CONTAINERS.register("grinder", () -> IForgeContainerType.create((windowId, inv, data) -> new GrinderContainer(windowId, inv.player.getEntityWorld(), data.readBlockPos(), inv, inv.player)));
public static final RegistryObject<ContainerType<ReactionChamberContainer>> REACTIONCHAMBER_CONTAINER = CONTAINERS.register("reaction_chamber", () -> IForgeContainerType.create((windowId, inv, data) -> new ReactionChamberContainer(windowId, inv.player.getEntityWorld(), data.readBlockPos(), inv, inv.player)));
// register items
public static final RegistryObject<Item> CRUSHED_URANINITE = ITEMS.register("crushed_uraninite", NkItem::new);
public static final RegistryObject<Item> YELLOWCAKE = ITEMS.register("yellowcake", NkItem::new);
public static final RegistryObject<Item> URANIUM_INGOT = ITEMS.register("uranium_ingot", NkItem::new);
public static final RegistryObject<Item> UO2_INGOT = ITEMS.register("uo2_ingot", NkItem::new);
public static final RegistryObject<Item> GRAPHITE_INGOT = ITEMS.register("graphite_ingot", NkItem::new);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.