answer
stringlengths 17
10.2M
|
|---|
package com.notlob.jgrid.renderer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import com.notlob.jgrid.Grid;
import com.notlob.jgrid.Grid.GroupRenderStyle;
import com.notlob.jgrid.model.Column;
import com.notlob.jgrid.model.Row;
import com.notlob.jgrid.styles.CellStyle;
import com.notlob.jgrid.styles.ContentStyle;
/**
* Responsible for painting the grid widget.
*
* @author Stef
*/
public class GridRenderer<T> extends Renderer<T> implements PaintListener {
// Passed to each renderer during a control paint event.
protected final RenderContext rc;
// Used to render cells.
protected final CellRenderer<T> cellRenderer;
// Used to render rows of columns.
protected final RowRenderer<T> rowRenderer;
// Used for in-line (rather than column-based) group rows.
protected final GroupRowRenderer<T> groupRowRenderer;
// Used to render the selected cells.
protected final SelectionRenderer<T> selectionRenderer;
// Set to represent the header cell when a column is being dragged to re-locate.
protected Image columnDragImage;
// Double-buffering image. Used as a key for the setData method.
private final static String DATA__DOUBLE_BUFFER_IMAGE = "double-buffer-image"; //$NON-NLS-1$
// The references below are recycled objects - to avoid GC churn.
// Used to set each row's bounds.
protected final Rectangle rowBounds;
// Used to align the 'no data' message within the control bounds.
protected final Point contentLocation;
// Used to render the grid's borderlines.
protected final Rectangle borderBounds;
public GridRenderer(final Grid<T> grid) {
super(grid);
rc = new RenderContext(grid);
cellRenderer = createCellRenderer();
rowRenderer = createRowRenderer();
groupRowRenderer = createGroupRowRenderer();
selectionRenderer = createSelectionRenderer();
contentLocation = new Point(0, 0);
rowBounds = new Rectangle(0, 0, 0, 0);
borderBounds = new Rectangle(0, 0, 0, 0);
}
protected CellRenderer<T> createCellRenderer() {
return new CellRenderer<T>(grid);
}
protected RowRenderer<T> createRowRenderer() {
return new RowRenderer<T>(grid, cellRenderer);
}
protected GroupRowRenderer<T> createGroupRowRenderer() {
return new GroupRowRenderer<T>(grid, cellRenderer);
}
protected SelectionRenderer<T> createSelectionRenderer() {
return new SelectionRenderer<T>(grid);
}
public Column getGroupColumnForX(final GC gc, final Row<T> row, final int x, final boolean header) {
rc.setGC(gc);
setDefaultRowBounds(gc, row);
return groupRowRenderer.getGroupColumnForX(rc, x, header, row, rowBounds);
}
public int getGroupColumnX(final GC gc, final Column findColumn, final Row<T> row) {
rc.setGC(gc);
setDefaultRowBounds(gc, row);
return groupRowRenderer.getGroupColumnX(rc, findColumn, row, rowBounds);
}
public Rectangle getExpandImageBounds(final GC gc, final Row<T> row) {
rc.setGC(gc);
setDefaultRowBounds(gc, row);
return groupRowRenderer.getExpandImageBounds(rc, row, rowBounds);
}
protected void setDefaultRowBounds(final GC gc, final Row<T> row) {
rowBounds.x = styleRegistry.getCellSpacingHorizontal();
rowBounds.y = viewport.getViewportArea(gc).y + viewport.getRowY(gc, row);
rowBounds.width = grid.getClientArea().width - grid.getClientArea().x;
rowBounds.height = grid.getRowHeight(row);
}
public Point getTextExtent(final String text, final GC gc, final FontData fontData) {
rc.setGC(gc);
return super.getTextExtent(text, rc, fontData);
}
@Override
public void paintControl(final PaintEvent e) {
GC gc = null;
rc.setAnimationPending(false);
try {
if (grid.getLabelProvider() == null) {
throw new IllegalArgumentException("There's no IGridLabelProvider on the grid.");
}
if (grid.getContentProvider() == null) {
throw new IllegalArgumentException("There's no IGridContentProvider on the grid.");
}
// Double-buffer the paint event.
Image image = (Image) grid.getData(DATA__DOUBLE_BUFFER_IMAGE);
if ((image == null) || (image.getBounds().width != grid.getSize().x) || (image.getBounds().height != grid.getSize().y)) {
// If the old image no longer fits the bounds, trash it.
if (image != null) {
image.dispose();
}
// Store the double-buffer image in the data of the canvas.
image = new Image(grid.getDisplay(), grid.getSize().x, grid.getSize().y);
grid.setData(DATA__DOUBLE_BUFFER_IMAGE, image);
}
// Set-up a GC for this paint event.
gc = new GC(image);
gc.setBackground(getColour(styleRegistry.getBackgroundColour()));
gc.fillRectangle(grid.getClientArea());
gc.setAntialias(SWT.ON);
gc.setTextAntialias(SWT.ON);
// Ensure our RC has this GC. Nicey.
rc.setGC(gc);
if (gridModel != null && !gridModel.getColumns().isEmpty()) {
// Calculate the viewport ranges.
viewport.calculateVisibleCellRange(gc);
// Paint the grid and cell backgrounds.
rc.setRenderPass(RenderPass.BACKGROUND);
paintRows(rc);
selectionRenderer.paintSelectionRegion(rc);
// Paint the grid and cell foregrounds.
rc.setRenderPass(RenderPass.FOREGROUND);
paintRows(rc);
selectionRenderer.paintSelectionRegion(rc);
// Paint a drag image if we're dragging a column.
paintColumnDragImage(rc);
}
if (gridModel.getRows().isEmpty()) {
// Paint the 'no data' message. Note the filter check has to compensate for the CollapseGroupFilter. Naff.
final String text = grid.getEmptyMessage() == null ? (grid.getFilters().size() > 1 ? getDefaultFiltersHiddenDataMessage() : getDefaultNoDataMessage()) : grid.getEmptyMessage();
final CellStyle cellStyle = styleRegistry.getNoDataStyle();
final Point point = getTextExtent(text, rc, cellStyle.getFontData());
final Rectangle bounds = viewport.getViewportArea(gc);
final Rectangle oldBounds = gc.getClipping();
gc.setAlpha(cellStyle.getForegroundOpacity());
gc.setFont(getFont(cellStyle.getFontData()));
gc.setForeground(getColour(cellStyle.getForeground()));
align(point.x, point.y, bounds, contentLocation, cellStyle.getTextAlignment());
gc.setClipping(bounds);
gc.drawText(text, contentLocation.x, contentLocation.y, SWT.DRAW_TRANSPARENT);
gc.setClipping(oldBounds);
}
// Paint a main border if required (column header outer-top border can be used for the top border along the grid).
borderBounds.x = grid.getClientArea().x;
borderBounds.y = grid.getClientArea().y;
borderBounds.width = grid.getClientArea().width - 1;
borderBounds.height = grid.getClientArea().height - 1;
setCorners(borderBounds, topLeft, topRight, bottomRight, bottomLeft);
paintBorderLine(gc, styleRegistry.getMainBorderLeft(), topLeft, bottomLeft);
paintBorderLine(gc, styleRegistry.getMainBorderRight(), topRight, bottomRight);
paintBorderLine(gc, styleRegistry.getMainBorderTop(), topLeft, topRight);
paintBorderLine(gc, styleRegistry.getMainBorderBottom(), bottomLeft, bottomRight);
// Paint the image to the real GC now.
e.gc.drawImage(image, 0, 0);
// Schedule another paint if we're animating.
if (rc.isAnimationPending()) {
grid.getDisplay().timerExec(ANIMATION_INTERVAL, new Runnable() {
@Override
public void run() {
if (!grid.isDisposed()) {
for (Row<T> row : grid.getRows()) {
if (row.getFrame() != -1) {
row.setFrame(row.getFrame() + row.getAnimation().getIncrement());
}
}
grid.redraw();
}
}
});
}
} catch (final Throwable t) {
if (!rc.isErrorLogged()) {
// Print the error to the std err and ensure we only do this once to avoid log fillage.
System.err.println(String.format("Failed to paint control: %s", t.getMessage()));
t.printStackTrace(System.err);
rc.setErrorLogged(true);
}
} finally {
if (gc != null) {
gc.dispose();
}
}
}
/**
* Iterate over the header row(s) then body rows and render each row in turn.
*/
protected void paintRows(final RenderContext rc) {
final GC gc = rc.getGC();
final Rectangle viewportArea = viewport.getViewportArea(gc);
// Set-up the initial row's bounds.
rowBounds.x = styleRegistry.getCellSpacingHorizontal();
rowBounds.y = styleRegistry.getCellSpacingVertical();
rowBounds.width = grid.getClientArea().width - grid.getClientArea().x;
// Paint the column header row(s).
if (grid.isShowColumnHeaders()) {
final Row<T> row = gridModel.getColumnHeaderRow();
rowBounds.height = grid.getRowHeight(row);
rowRenderer.paintRow(rc, rowBounds, row);
}
// Paint the main rows (including the row number column and the pinned columns).
rc.setAlternate(false);
rowBounds.y = viewportArea.y + styleRegistry.getCellSpacingVertical();
for (int rowIndex=viewport.getFirstRowIndex(); rowIndex<viewport.getLastVisibleRowIndex(); rowIndex++) {
final Row<T> row = gridModel.getRows().get(rowIndex);
rowBounds.height = grid.getRowHeight(row);
if (gridModel.isParentRow(row) && (grid.getGroupRenderStyle() == GroupRenderStyle.INLINE)) {
// Paint the group row, by using the groupBy columns from left-to-right.
groupRowRenderer.paintRow(rc, rowBounds, row);
} else {
// Just paint the row like any normal row - with columns.
rowRenderer.paintRow(rc, rowBounds, row);
}
// Advance any row animation.
if (row.getAnimation() != null) {
row.getAnimation().postAnimate(rc, row);
}
// Move the bounds down for the next row.
rowBounds.y += (rowBounds.height + styleRegistry.getCellSpacingVertical());
// If there's a next row, and it's in the same group, don't flip the alternate background.
final int nextIndex = rowIndex + 1;
if (!((nextIndex < viewport.getLastRowIndex()) && (nextIndex < gridModel.getRows().size()) && (gridModel.isSameGroup(row, gridModel.getRows().get(nextIndex))))) {
rc.setAlternate(!rc.isAlternate());
}
}
}
/**
* If there's a column being repositioned with the mouse, render a 'drag image' representing the column
* header at the mouse location.
*/
protected void paintColumnDragImage(final RenderContext rc) {
final Column column = grid.getMouseHandler().getRepositioningColumn();
if ((column == null) && (columnDragImage != null)) {
// If we're not dragging then dispose any previous image.
columnDragImage.dispose();
columnDragImage = null;
} else if (column != null) {
final GC gc = rc.getGC();
if (columnDragImage == null) {
// Create a column drag image.
final CellStyle cellStyle = styleRegistry.getCellStyle(column, gridModel.getColumnHeaderRow());
final int height = grid.getRowHeight(gridModel.getColumnHeaderRow());
columnDragImage = new Image(grid.getDisplay(), column.getWidth(), height);
final Rectangle dragImageBounds = new Rectangle(columnDragImage.getBounds().x, columnDragImage.getBounds().y, columnDragImage.getBounds().width - 1, columnDragImage.getBounds().height - 1);
// Create a new GC to create an image of the column header in and back-up the actual GC.
final RenderContext imageRC = new RenderContext(grid);
final GC imageGC = new GC(columnDragImage);
imageRC.setGC(imageGC);
// Render the column header to the imageGC.
imageRC.setRenderPass(RenderPass.BACKGROUND);
cellRenderer.paintCell(imageRC, dragImageBounds, column, gridModel.getColumnHeaderRow(), cellStyle);
imageRC.setRenderPass(RenderPass.FOREGROUND);
cellRenderer.paintCell(imageRC, dragImageBounds, column, gridModel.getColumnHeaderRow(), cellStyle);
// Restore the original GC and clean-up the image GC.
imageGC.dispose();
}
// Render the column drag image at the mouses location on the main GC.
final Point mouseLocation = grid.toControl(new Point(
grid.getDisplay().getCursorLocation().x - (columnDragImage.getBounds().width / 2),
grid.getDisplay().getCursorLocation().y));
gc.setAlpha(220);
gc.drawImage(columnDragImage, mouseLocation.x, mouseLocation.y);
}
}
protected String getDefaultFiltersHiddenDataMessage() {
return "No data matches your filter criteria.";
}
protected String getDefaultNoDataMessage() {
return "There is no data to display.";
}
public boolean isPaintingPinned() {
return rc.isPaintingPinned();
}
public int getMinimumWidth(final GC gc, final Column column) {
// Get the column header style and caption.
int minWidth = getCellMinimumWidth(gc, column, gridModel.getColumnHeaderRow());
// Iterate over each cell in the column getting style, content, images, padding, text extents, etc....
for (Row<T> row : grid.getRows()) {
minWidth = Math.max(minWidth, getCellMinimumWidth(gc, column, row));
}
// Don't allow auto-resize to zap a column out of existence.
return Math.max(minWidth, 5);
}
protected int getCellMinimumWidth(final GC gc, final Column column, final Row<T> row) {
final CellStyle cellStyle = styleRegistry.getCellStyle(column, row);
gc.setFont(getFont(cellStyle.getFontData()));
// Include cell padding.
int width = cellStyle.getPaddingLeft() + cellStyle.getPaddingRight();
// Ensure the standard image can also fit.
if (cellStyle.getContentStyle() != ContentStyle.TEXT) {
width += (16 + cellStyle.getPaddingImageText());
}
// Include any text in the width.
if (cellStyle.getContentStyle() != ContentStyle.IMAGE) {
final String text = cellRenderer.getCellText(column, row);
final Point point = getTextExtent(text, gc, cellStyle.getFontData());
width += point.x;
}
return width;
}
}
|
package br.com.navita.mobile.domain;
import java.io.Serializable;
import java.util.List;
public class MobileBean implements Serializable{
private static final long serialVersionUID = 1L;
public MobileBean() {
resultCode = 0;
}
protected String token;
protected Integer resultCode;
protected String message;
protected List<?> list;
protected Object object;
protected Long processingTime;
public Long getProcessingTime() {
return processingTime;
}
public void setProcessingTime(Long processingTime) {
this.processingTime = processingTime;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Integer getResultCode() {
return resultCode;
}
public void setResultCode(Integer resultCode) {
this.resultCode = resultCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
|
package org.togglz.console;
import com.floreysoft.jmte.Engine;
import org.togglz.core.Togglz;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
public abstract class RequestHandlerBase implements RequestHandler {
protected void writeResponse(RequestEvent event, String body) throws IOException {
HttpServletResponse response = event.getResponse();
Map<String, Object> model = new HashMap<>();
model.put("content", body);
model.put("serverInfo", event.getContext().getServerInfo());
model.put("togglzTitle", Togglz.getNameWithVersion());
if (event.getContext().getServletContextName() != null) {
model.put("displayName", event.getContext().getServletContextName());
}
String template = getResourceAsString("template.html");
String result = new Engine().transform(template, model);
response.setContentType("text/html");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(result.getBytes(UTF_8));
response.flushBuffer();
}
protected String getResourceAsString(String name) throws IOException {
InputStream stream = loadResource(name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
copy(stream, bos);
return new String(bos.toByteArray(), UTF_8);
}
protected InputStream loadResource(String name) {
String templateName = RequestHandler.class.getPackage().getName().replace('.', '/') + "/" + name;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return classLoader.getResourceAsStream(templateName);
}
protected void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
}
}
|
package org.zstack.console;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.header.AbstractService;
import org.zstack.header.console.*;
import org.zstack.header.core.Completion;
import org.zstack.header.core.FutureCompletion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HypervisorType;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.identity.SessionLogoutExtensionPoint;
import org.zstack.header.managementnode.ManagementNodeChangeListener;
import org.zstack.header.managementnode.ManagementNodeInventory;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.vm.*;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: frank
* Time: 11:51 PM
* To change this template use File | Settings | File Templates.
*/
public class ConsoleManagerImpl extends AbstractService implements ConsoleManager, VmInstanceMigrateExtensionPoint, ManagementNodeChangeListener,
VmReleaseResourceExtensionPoint, SessionLogoutExtensionPoint {
private static CLogger logger = Utils.getLogger(ConsoleManagerImpl.class);
@Autowired
private CloudBus bus;
@Autowired
private DatabaseFacade dbf;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private ThreadFacade thdf;
private Map<String, ConsoleBackend> consoleBackends = new HashMap<String, ConsoleBackend>();
private Map<String, ConsoleHypervisorBackend> consoleHypervisorBackends = new HashMap<String, ConsoleHypervisorBackend>();
private String useBackend;
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof ConsoleProxyAgentMessage) {
passThrough(msg);
} else if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
}
private void passThrough(Message msg) {
getBackend().handleMessage(msg);
}
private void handleLocalMessage(Message msg) {
bus.dealWithUnknownMessage(msg);
}
private void handleApiMessage(APIMessage msg) {
if (msg instanceof APIRequestConsoleAccessMsg) {
handle((APIRequestConsoleAccessMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(final APIRequestConsoleAccessMsg msg) {
final APIRequestConsoleAccessEvent evt = new APIRequestConsoleAccessEvent(msg.getId());
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return String.format("request-console-for-vm-%s", msg.getVmInstanceUuid());
}
@Override
public void run(final SyncTaskChain chain) {
VmInstanceVO vmvo = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
ConsoleBackend bkd = getBackend();
bkd.grantConsoleAccess(msg.getSession(), VmInstanceInventory.valueOf(vmvo), new ReturnValueCompletion<ConsoleInventory>(chain) {
@Override
public void success(ConsoleInventory returnValue) {
if (!"0.0.0.0".equals(CoreGlobalProperty.CONSOLE_PROXY_OVERRIDDEN_IP) &&
!"".equals(CoreGlobalProperty.CONSOLE_PROXY_OVERRIDDEN_IP)) {
returnValue.setHostname(CoreGlobalProperty.CONSOLE_PROXY_OVERRIDDEN_IP);
} else {
returnValue.setHostname(CoreGlobalProperty.UNIT_TEST_ON ? "127.0.0.1" : Platform.getManagementServerIp());
}
evt.setInventory(returnValue);
bus.publish(evt);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(errorCode);
evt.setSuccess(false);
bus.publish(evt);
chain.next();
}
});
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
@Override
public String getId() {
return bus.makeLocalServiceId(ConsoleConstants.SERVICE_ID);
}
private void populateExtensions() {
for (ConsoleBackend bkd : pluginRgty.getExtensionList(ConsoleBackend.class)) {
ConsoleBackend old = consoleBackends.get(bkd.getConsoleBackendType());
if (old != null) {
throw new CloudRuntimeException(String.format("duplicate ConsoleBackend[%s, %s] for type[%s]",
bkd.getClass().getName(), old.getClass().getName(), old.getConsoleBackendType()));
}
consoleBackends.put(bkd.getConsoleBackendType(), bkd);
}
for (ConsoleHypervisorBackend bkd : pluginRgty.getExtensionList(ConsoleHypervisorBackend.class)) {
ConsoleHypervisorBackend old = consoleHypervisorBackends.get(bkd.getConsoleBackendHypervisorType().toString());
if (old != null) {
throw new CloudRuntimeException(String.format("duplicate ConsoleHypervisorBackend[%s, %s] for type[%s]",
bkd.getClass().getName(), old.getClass().getName(), bkd.getConsoleBackendHypervisorType()));
}
consoleHypervisorBackends.put(bkd.getConsoleBackendHypervisorType().toString(), bkd);
}
}
@Override
public boolean start() {
populateExtensions();
clean();
return true;
}
private void clean() {
try {
final String ip = Platform.getManagementServerIp();
deleteConsoleProxyByManagementNode(ip);
} catch (Throwable th) {
logger.warn("clean up console proxy failed", th);
}
}
@Override
public boolean stop() {
return true;
}
private ConsoleBackend getBackend() {
ConsoleBackend bkd = consoleBackends.get(useBackend);
if (bkd == null) {
throw new CloudRuntimeException(String.format("no plugin registered ConsoleBackend[type:%s]", useBackend));
}
return bkd;
}
public void setUseBackend(String useBackend) {
this.useBackend = useBackend;
}
@Override
public ConsoleHypervisorBackend getHypervisorConsoleBackend(HypervisorType type) {
ConsoleHypervisorBackend bkd = consoleHypervisorBackends.get(type.toString());
if (bkd == null) {
throw new CloudRuntimeException(String.format("cannot find ConsoleHypervisorBackend[type:%s]", type.toString()));
}
return bkd;
}
@Override
public ConsoleBackend getConsoleBackend() {
return getBackend();
}
@Override
public void preMigrateVm(VmInstanceInventory inv, String destHostUuid) {
}
@Override
public void beforeMigrateVm(VmInstanceInventory inv, String destHostUuid) {
}
@Override
public void afterMigrateVm(VmInstanceInventory inv, String srcHostUuid) {
ConsoleBackend bkd = getBackend();
FutureCompletion completion = new FutureCompletion(null);
bkd.deleteConsoleSession(inv, completion);
try {
synchronized (completion) {
completion.wait(1500);
}
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
}
}
@Override
public void failedToMigrateVm(VmInstanceInventory inv, String destHostUuid, ErrorCode reason) {
}
@Override
public void releaseVmResource(VmInstanceSpec spec, final Completion completion) {
ConsoleBackend bkd = getBackend();
bkd.deleteConsoleSession(spec.getVmInventory(), new Completion(completion) {
@Override
public void success() {
completion.success();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(errorCode.toString());
completion.success();
}
});
}
@Override
public void sessionLogout(final SessionInventory session) {
ConsoleBackend bkd = getBackend();
bkd.deleteConsoleSession(session, new NoErrorCompletion() {
@Override
public void done() {
logger.debug(String.format("deleted all console proxy opened by the session[uuid:%s]", session.getUuid()));
}
});
}
@Transactional
private void deleteConsoleProxyByManagementNode(final String managementHostName) {
String sql = "delete from ConsoleProxyVO q where q.proxyHostname = :managementHostName";
Query q = dbf.getEntityManager().createQuery(sql);
q.setParameter("managementHostName", managementHostName);
q.executeUpdate();
}
public void cleanupNode(ManagementNodeInventory inv) {
logger.debug(String.format("Management node[uuid:%s] left, will clean the record in ConsoleProxyVO", inv.getUuid()));
deleteConsoleProxyByManagementNode(inv.getHostName());
}
@Override
public void nodeLeft(ManagementNodeInventory inv) {
cleanupNode(inv);
}
@Override
public void iAmDead(ManagementNodeInventory inv) {
cleanupNode(inv);
}
@Override
public void nodeJoin(ManagementNodeInventory inv) {
}
@Override
public void iJoin(ManagementNodeInventory inv) {
}
}
|
package edu.pdx.cs410J.chances;
import edu.pdx.cs410J.AbstractAppointmentBook;
import edu.pdx.cs410J.AppointmentBookParser;
import edu.pdx.cs410J.ParserException;
import java.io.File;
/**
* @author chancesnow
*/
public class TextParser implements AppointmentBookParser
{
private File file;
public TextParser(String filePath)
{
file = new File(filePath);
if (!file.exists() || !file.isDirectory()) {
file = null;
}
}
@Override
public AbstractAppointmentBook parse() throws ParserException
{
return null;
}
}
|
package se.llbit.tinytemplate.test;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Test;
import se.llbit.tinytemplate.TemplateParser.SyntaxError;
import se.llbit.tinytemplate.TinyTemplate;
@SuppressWarnings("javadoc")
public class TestTinyTemplate {
@Test
public void testUndefinedTemplate() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("");
assertEquals("", tt.expand("test"));
assertFalse("expand returns false if the template was not expanded",
tt.expand("test", new PrintStream(new ByteArrayOutputStream())));
}
@Test
public void testSimple_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("test [[hello]]");
assertEquals("hello", tt.expand("test"));
assertTrue("expand returns true if the template was expanded",
tt.expand("test", new PrintStream(new ByteArrayOutputStream())));
}
@Test
public void testSimple_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo [[]]");
assertEquals("", tt.expand("foo"));
assertTrue("expand returns true if the template was expanded",
tt.expand("foo", new PrintStream(new ByteArrayOutputStream())));
}
/**
* Multiple templates in one "file"
* @throws SyntaxError
*/
@Test
public void testSimple_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo [[ baa ]] bar [[ faa ]]");
assertEquals(" baa ", tt.expand("foo"));
assertEquals(" faa ", tt.expand("bar"));
}
/**
* Very many special characters can be used in template names
* @throws SyntaxError
*/
@Test
public void testSimple_4() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("$(%)!}@{ [[=)]]");
assertEquals("=)", tt.expand("$(%)!}@{"));
}
/**
* Newlines in template body
* @throws SyntaxError
*/
@Test
public void testSimple_5() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"x= [[\n" +
"z\r" +
"\r\n" +
"]]");
String nl = System.getProperty("line.separator");
assertEquals(nl + "z" + nl + nl, tt.expand("x"));
}
/**
* Newlines in template body
* @throws SyntaxError
*/
@Test
public void testSimple_6() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo =\n" +
"[[void a() {\n" +
" baa;\n" +
"}\n" +
"\n" +
"void b() {\n" +
" boo(hoo);\n" +
"}]]");
String nl = System.getProperty("line.separator");
assertEquals(
"void a() {" + nl +
" baa;" + nl +
"}" + nl +
nl +
"void b() {" + nl +
" boo(hoo);" + nl +
"}", tt.expand("foo"));
}
/**
* Missing template name
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_1() throws SyntaxError {
new TinyTemplate("[[]]");
}
/**
* Missing template name
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_2() throws SyntaxError {
new TinyTemplate(" = [[]]");
}
/**
* Missing end of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_3() throws SyntaxError {
new TinyTemplate("x = [[ ");
}
/**
* Missing end of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_4() throws SyntaxError {
new TinyTemplate("x = [[ ]");
}
/**
* Missing start of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_5() throws SyntaxError {
new TinyTemplate("x = ]]");
}
/**
* Missing start of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_6() throws SyntaxError {
new TinyTemplate("x = [ ]]");
}
/**
* Double brackets not allowed inside template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_7() throws SyntaxError {
new TinyTemplate("x = [[ [[ ]]");
}
/**
* Double brackets not allowed inside template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_8() throws SyntaxError {
new TinyTemplate("x = [[ ]] ]]");
}
/**
* Missing template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_9() throws SyntaxError {
new TinyTemplate("x = ");
}
/**
* Missing template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_10() throws SyntaxError {
new TinyTemplate("x");
}
/**
* Tests a template variable
* @throws SyntaxError
*/
@Test
public void testVariable_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("test = [[$hello]]");
tt.bind("hello", "hej");
assertEquals("hej", tt.expand("test"));
}
/**
* Tests an unbound variable
* @throws SyntaxError
*/
@Test
public void testVariable_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("test = [[x $hello y]]");
assertEquals("x <unbound variable hello> y", tt.expand("test"));
}
/**
* Double dollar signs escape to a single dollar sign
* @throws SyntaxError
*/
@Test
public void testVariable_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("test = [[ $$ not a variable ]]");
assertEquals(" $ not a variable ", tt.expand("test"));
}
/**
* Java identifier characters and periods can be used in variable names
* parenthesized.
* @throws SyntaxError
*/
@Test
public void testVariable_4() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$(_.00wat1..)]]");
tt.bind("_.00wat1..", "batman");
assertEquals("batman", tt.expand("foo"));
}
/**
* Line endings in variable expansions are preserved as-is if the
* expansion is not indented
* @throws SyntaxError
*/
@Test
public void testVariable_5() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[$block]]");
tt.bind("block",
"{\n" +
" hello\r" +
" you\r\n" +
"}");
assertEquals(
"{\n" +
" hello\r" +
" you\r\n" +
"}", tt.expand("foo"));
}
/**
* Line endings in variable expansions are replaced by the current
* system's default line ending when the expansion is indented
* @throws SyntaxError
*/
@Test
public void testVariable_6() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[ x$block]]");
tt.bind("block",
"{\n" +
" hello\r" +
" you\r\n" +
"}");
String nl = System.getProperty("line.separator");
assertEquals(
" x{" + nl +
" hello" + nl +
" you" + nl +
" }", tt.expand("foo"));
}
/**
* Attribute evaluation calls the attribute method on the context object
* @throws SyntaxError
*/
@Test
public void testAttribute_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[#toString]]");
tt.pushContext("the string");
assertEquals("the string", tt.expand("foo"));
}
/**
* Attempting to evaluate an attribute on an object with no such method
* @throws SyntaxError
*/
@Test
public void testAttribute_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[#imaginaryMethod]]");
tt.pushContext("the string");
assertEquals("<failed to eval imaginaryMethod; reason: no such method>", tt.expand("foo"));
}
/**
* Attempting to evaluate attribute without context
* @throws SyntaxError
*/
@Test
public void testAttribute_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo = [[#imaginaryMethod]]");
assertEquals("<failed to eval imaginaryMethod; reason: no context>", tt.expand("foo"));
}
/**
* Multiple assign are allowed between template name and template body
* @throws SyntaxError
*/
@Test
public void testMultiAssign_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test == \n" +
"== ==== = ===== [[$hello]]");
tt.bind("hello", "hej");
assertEquals("hej", tt.expand("test"));
}
/**
* Multiple template names are allowed for each template
* @throws SyntaxError
*/
@Test
public void testSynonyms_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test == foo = = = bar [[$hello]]");
tt.bind("hello", "hej");
assertEquals("hej", tt.expand("test"));
assertEquals("hej", tt.expand("foo"));
assertEquals("hej", tt.expand("bar"));
}
/**
* Multiple template names are allowed for each template
* @throws SyntaxError
*/
@Test
public void testSynonyms_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test foo bar [[$hello]]");
tt.bind("hello", "hej");
assertEquals("hej", tt.expand("test"));
assertEquals("hej", tt.expand("foo"));
assertEquals("hej", tt.expand("bar"));
}
@Test
public void testComment_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"# line comment\n" +
"test = [[$hello]]");
tt.bind("hello", "hej");
assertEquals("hej", tt.expand("test"));
}
@Test
public void testComment_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo=[[x]]# comment\n" +
"# test = [[y]]");
assertEquals("", tt.expand("test"));
assertEquals("x", tt.expand("foo"));
}
@Test
public void testComment_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo=[[## not a comment]]");
assertEquals("hash signs inside a template body are not comments",
"# not a comment", tt.expand("foo"));
}
@Test
public void testIndentation_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo = \n" +
"[[void m() {\n" +
" \n" +
" 2 \n" +
" ]]");
tt.setIndentation("\t");
String nl = System.getProperty("line.separator");
assertEquals(
"void m() {" + nl +
"\t" + nl +
"\t\t2 " + nl +
"\t\t\t\t", tt.expand("foo"));
}
/**
* Expansions can be correctly indented, but the indentation inside the
* expansion is not touched.
* @throws SyntaxError
*/
@Test
public void testIndentationExpansion_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo = \n" +
"[[ $block]]");
tt.bind("block",
"{\n" +
" hello\n" +
" you\n" +
"}");
tt.setIndentation(" ");
String nl = System.getProperty("line.separator");
assertEquals(
" {" + nl +
" hello" + nl +
" you" + nl +
" }", tt.expand("foo"));
}
}
|
package dk.itu.smdp.group2.questionnaire.model;
import java.util.ArrayList;
import dk.itu.smdp.group2.R;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class ChoiceQuestion extends Question{
private int min,max;
private int numChecked = 0;
private ArrayList<Tuple<String,String>> options;
// results
private View root;
private RadioGroup radiogroup = null;
private ArrayList<CheckBox> checkboxes = null;
public ChoiceQuestion(String question, String description, boolean optional, int minSelections, int maxSelections){
super(question,description,optional);
min = minSelections;
max = maxSelections;
options = new ArrayList<Tuple<String,String>>();
}
public void addOption(String id, String text){
options.add(new Tuple<String,String>(id, text));
}
public boolean containsID(String id){
return getValueForID(id) == null;
}
public boolean isIDChosen(String id) {
//TODO: Made the assumption that both key and value are unique.
String value = getValueForID(id);
if(radiogroup != null){
return ((RadioButton)radiogroup.findViewById(radiogroup.getCheckedRadioButtonId())).getText().equals(value);
}else{ // checkbox
for(CheckBox cb : checkboxes){
if(cb.isChecked() && cb.getText().equals(value))
return true;
}
return false;
}
}
@Override
public View generateView() {
// inflate and fetch objects
root = this.getParent().getActivity().getLayoutInflater().inflate(R.layout.question_choice, null);
TextView title = (TextView) root.findViewById(R.id.tvChoiceTitle);
TextView desc = (TextView) root.findViewById(R.id.tvChoiceDesc);
TextView select = (TextView) root.findViewById(R.id.tvChoiceSelec);
LinearLayout options = (LinearLayout) root.findViewById(R.id.svsChoiceLL);
// set values
title.setText(this.getQuestion() + (this.isOptional() ? "" : " *"));
desc.setText(this.getDescription());
if(getDescription() == null || getDescription().length() == 0) desc.setVisibility(View.GONE);
// create options (dynamically because it is only checkbox/radio)
if(min == 1 && max == 1){ // radio
select.setVisibility(View.GONE);
radiogroup = new RadioGroup(getParent().getActivity());
for(Tuple<String,String> kv : this.options){
RadioButton rb = new RadioButton(getParent().getActivity());
rb.setText(kv.getSecond());
radiogroup.addView(rb);
// Put listener
rb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// make questions visible/invisible if they have this as condition
getParent().checkConditions();
}
});
}
options.addView(radiogroup);
}else{ // checkbox
select.setText("Select between "+min+" and "+max+" options");
checkboxes = new ArrayList<CheckBox>();
for(Tuple<String,String> kv : this.options){
final CheckBox cb = new CheckBox(getParent().getActivity());
cb.setText(kv.getSecond());
// Put listener
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
numChecked += isChecked ? 1 : -1;
// uncheck again if too many
if(isChecked && numChecked > max){
cb.setChecked(false);
numChecked
}else{
// make questions visible/invisible if they have this as condition
getParent().checkConditions();
}
}
});
options.addView(cb);
checkboxes.add(cb);
}
}
return root;
}
@Override
public String generateTextResult() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isAnswered() {
if(radiogroup != null){
return radiogroup.getCheckedRadioButtonId() != -1;
}else{
int selected = countChecked(checkboxes);
return selected >= min && selected <= max;
}
}
@Override
public void setVisible(boolean visible) {
root.setVisibility(visible ? View.VISIBLE : View.GONE);
}
// PRIVATE HELPERS
private class Tuple<T,V>{
private T t;
private V v;
public Tuple(T t, V v){
this.t = t;
this.v = v;
}
public T getFirst(){return t;}
public V getSecond(){return v;}
}
private String getValueForID(String id){
for(Tuple<String,String> t : options){
if(t.getFirst().equals(id))
return t.getSecond();
}
return null;
}
private int countChecked(ArrayList<CheckBox> arr){
int count = 0;
for(CheckBox cb : arr){
count += cb.isChecked() ? 1 : 0;
}
return count;
}
}
|
package soot.jimple.toolkits.callgraph;
import soot.*;
import soot.jimple.*;
import soot.options.CGOptions;
import soot.options.SparkOptions;
import java.util.*;
import soot.toolkits.scalar.Pair;
import soot.util.*;
import soot.util.queue.*;
/** Resolves virtual calls.
* @author Ondrej Lhotak
*/
public final class VirtualCalls
{
private SparkOptions options = new SparkOptions( PhaseOptions.v().getPhaseOptions("cg.spark") );
public VirtualCalls( Singletons.Global g ) {
}
public static VirtualCalls v() { return G.v().soot_jimple_toolkits_callgraph_VirtualCalls(); }
private final LargeNumberedMap<Type, SmallNumberedMap<SootMethod>> typeToVtbl =
new LargeNumberedMap<Type, SmallNumberedMap<SootMethod>>( Scene.v().getTypeNumberer() );
public SootMethod resolveSpecial( SpecialInvokeExpr iie, NumberedString subSig, SootMethod container ) {
SootMethod target = iie.getMethod();
/* cf. JVM spec, invokespecial instruction */
if( Scene.v().getOrMakeFastHierarchy()
.canStoreType( container.getDeclaringClass().getType(),
target.getDeclaringClass().getType() )
&& container.getDeclaringClass().getType() !=
target.getDeclaringClass().getType()
&& !target.getName().equals( "<init>" )
&& subSig != sigClinit ) {
return resolveNonSpecial(
container.getDeclaringClass().getSuperclass().getType(),
subSig );
} else {
return target;
}
}
public SootMethod resolveNonSpecial( RefType t, NumberedString subSig ) {
SmallNumberedMap<SootMethod> vtbl = typeToVtbl.get( t );
if( vtbl == null ) {
typeToVtbl.put( t, vtbl =
new SmallNumberedMap<SootMethod>( Scene.v().getMethodNumberer() ) );
}
SootMethod ret = vtbl.get( subSig );
if( ret != null ) return ret;
SootClass cls = t.getSootClass();
SootMethod m = cls.getMethodUnsafe( subSig );
if( m != null ) {
if( m.isConcrete() || m.isNative() || m.isPhantom() ) {
ret = m;
}
} else {
if( cls.hasSuperclass() ) {
ret = resolveNonSpecial( cls.getSuperclass().getType(), subSig );
}
}
vtbl.put( subSig, ret );
return ret;
}
private final Map<Type,List<Type>> baseToSubTypes = new HashMap<Type,List<Type>>();
private final Map<Pair<Type, NumberedString>, List<Type>> baseToPossibleSubTypes = new HashMap<Pair<Type,NumberedString>, List<Type>>();
public void resolve( Type t, Type declaredType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets ) {
resolve(t, declaredType, null, subSig, container, targets);
}
public void resolve( Type t, Type declaredType, Type sigType, NumberedString subSig, SootMethod container, ChunkedQueue<SootMethod> targets ) {
if( declaredType instanceof ArrayType ) declaredType = RefType.v("java.lang.Object");
if( sigType instanceof ArrayType ) sigType = RefType.v("java.lang.Object");
if( t instanceof ArrayType ) t = RefType.v( "java.lang.Object" );
if( declaredType != null && !Scene.v().getOrMakeFastHierarchy()
.canStoreType( t, declaredType ) ) {
return;
}
if( sigType != null && !Scene.v().getOrMakeFastHierarchy()
.canStoreType( t, sigType ) ) {
return;
}
if( t instanceof RefType ) {
SootMethod target = resolveNonSpecial( (RefType) t, subSig );
if( target != null ) targets.add( target );
} else if( t instanceof AnySubType ) {
if (options.library() == SparkOptions.library_name_resolution) {
RefType base = ((AnySubType) t).getBase();
Pair<Type, NumberedString> pair = new Pair<Type, NumberedString>(base, subSig);
List<Type> types = baseToPossibleSubTypes.get(pair);
if (types != null) {
for(Type st : types) {
if (!Scene.v().getOrMakeFastHierarchy().canStoreType( st, declaredType)) {
resolve( st, st, sigType, subSig, container, targets); //TODO
} else {
resolve (st, declaredType, sigType, subSig, container, targets);
}
}
return;
}
baseToPossibleSubTypes.put(pair, types = new ArrayList<Type>());
types.add(base);
Chain<SootClass> classes = Scene.v().getClasses();
for(SootClass sc : classes) {
for(SootMethod sm : sc.getMethods()) {
if(sm.isConcrete() && sm.getSubSignature().equals(subSig.getString())) {
Type st = sc.getType();
if (!Scene.v().getOrMakeFastHierarchy().canStoreType( st, declaredType)) {
resolve( st, st, sigType, subSig, container, targets); //TODO
} else {
resolve (st, declaredType, sigType, subSig, container, targets);
}
types.add(st);
}
}
}
} else {
RefType base = ((AnySubType)t).getBase();
List<Type> subTypes = baseToSubTypes.get(base);
if( subTypes != null ) {
for( Iterator<Type> stIt = subTypes.iterator(); stIt.hasNext(); ) {
final Type st = stIt.next();
resolve( st, declaredType, sigType, subSig, container, targets );
}
return;
}
baseToSubTypes.put(base, subTypes = new ArrayList<Type>() );
subTypes.add(base);
LinkedList<SootClass> worklist = new LinkedList<SootClass>();
HashSet<SootClass> workset = new HashSet<SootClass>();
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
SootClass cl = base.getSootClass();
if( workset.add( cl ) ) worklist.add( cl );
while( !worklist.isEmpty() ) {
cl = worklist.removeFirst();
if( cl.isInterface() ) {
for( Iterator<SootClass> cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext(); ) {
final SootClass c = cIt.next();
if( workset.add( c ) ) worklist.add( c );
}
} else {
if( cl.isConcrete() ) {
resolve( cl.getType(), declaredType, sigType, subSig, container, targets );
subTypes.add(cl.getType());
}
for( Iterator<SootClass> cIt = fh.getSubclassesOf( cl ).iterator(); cIt.hasNext(); ) {
final SootClass c = cIt.next();
if( workset.add( c ) ) worklist.add( c );
}
}
}
}
} else if( t instanceof NullType ) {
} else {
throw new RuntimeException( "oops "+t );
}
}
public final NumberedString sigClinit =
Scene.v().getSubSigNumberer().findOrAdd("void <clinit>()");
public final NumberedString sigStart =
Scene.v().getSubSigNumberer().findOrAdd("void start()");
public final NumberedString sigRun =
Scene.v().getSubSigNumberer().findOrAdd("void run()");
}
|
package sqlancer.mysql.gen;
import java.util.ArrayList;
import java.util.List;
import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.gen.UntypedExpressionGenerator;
import sqlancer.mysql.MySQLGlobalState;
import sqlancer.mysql.MySQLSchema.MySQLColumn;
import sqlancer.mysql.MySQLSchema.MySQLRowValue;
import sqlancer.mysql.ast.MySQLBetweenOperation;
import sqlancer.mysql.ast.MySQLBinaryComparisonOperation;
import sqlancer.mysql.ast.MySQLBinaryComparisonOperation.BinaryComparisonOperator;
import sqlancer.mysql.ast.MySQLBinaryLogicalOperation;
import sqlancer.mysql.ast.MySQLBinaryLogicalOperation.MySQLBinaryLogicalOperator;
import sqlancer.mysql.ast.MySQLBinaryOperation;
import sqlancer.mysql.ast.MySQLBinaryOperation.MySQLBinaryOperator;
import sqlancer.mysql.ast.MySQLCastOperation;
import sqlancer.mysql.ast.MySQLCollate;
import sqlancer.mysql.ast.MySQLColumnReference;
import sqlancer.mysql.ast.MySQLComputableFunction;
import sqlancer.mysql.ast.MySQLComputableFunction.MySQLFunction;
import sqlancer.mysql.ast.MySQLConstant;
import sqlancer.mysql.ast.MySQLConstant.MySQLDoubleConstant;
import sqlancer.mysql.ast.MySQLExists;
import sqlancer.mysql.ast.MySQLExpression;
import sqlancer.mysql.ast.MySQLInOperation;
import sqlancer.mysql.ast.MySQLStringExpression;
import sqlancer.mysql.ast.MySQLUnaryPostfixOperation;
import sqlancer.mysql.ast.MySQLUnaryPrefixOperation;
import sqlancer.mysql.ast.MySQLUnaryPrefixOperation.MySQLUnaryPrefixOperator;
public class MySQLExpressionGenerator extends UntypedExpressionGenerator<MySQLExpression, MySQLColumn>{
private MySQLGlobalState state;
private MySQLRowValue rowVal;
public MySQLExpressionGenerator(MySQLGlobalState state) {
this.state = state;
}
public void setRowVal(MySQLRowValue rowVal) {
this.rowVal = rowVal;
}
private enum Actions {
COLUMN, LITERAL, UNARY_PREFIX_OPERATION, UNARY_POSTFIX, FUNCTION, BINARY_LOGICAL_OPERATOR,
BINARY_COMPARISON_OPERATION, CAST, IN_OPERATION, BINARY_OPERATION, EXISTS, BETWEEN_OPERATOR;
}
public MySQLExpression generateExpression(int depth) {
if (depth >= state.getOptions().getMaxExpressionDepth()) {
return generateLeafNode();
}
switch (Randomly.fromOptions(Actions.values())) {
case COLUMN:
return generateColumn();
case LITERAL:
return generateConstant();
case UNARY_PREFIX_OPERATION:
MySQLExpression subExpr = generateExpression(depth + 1);
MySQLUnaryPrefixOperator random = MySQLUnaryPrefixOperator.getRandom();
if (random == MySQLUnaryPrefixOperator.MINUS) {
throw new IgnoreMeException();
}
return new MySQLUnaryPrefixOperation(subExpr, random);
case UNARY_POSTFIX:
return new MySQLUnaryPostfixOperation(generateExpression(depth + 1),
Randomly.fromOptions(MySQLUnaryPostfixOperation.UnaryPostfixOperator.values()),
Randomly.getBoolean());
case FUNCTION:
return getFunction(depth + 1);
case BINARY_LOGICAL_OPERATOR:
return new MySQLBinaryLogicalOperation(generateExpression(depth + 1),
generateExpression(depth + 1), MySQLBinaryLogicalOperator.getRandom());
case BINARY_COMPARISON_OPERATION:
return new MySQLBinaryComparisonOperation(generateExpression(depth + 1),
generateExpression(depth + 1), BinaryComparisonOperator.getRandom());
case CAST:
return new MySQLCastOperation(generateExpression(depth + 1), MySQLCastOperation.CastType.getRandom());
case IN_OPERATION:
MySQLExpression expr = generateExpression(depth + 1);
List<MySQLExpression> rightList = new ArrayList<>();
for (int i = 0; i < 1 + Randomly.smallNumber(); i++) {
rightList.add(generateExpression(depth + 1));
}
return new MySQLInOperation(expr, rightList, Randomly.getBoolean());
case BINARY_OPERATION:
if (true) {
throw new IgnoreMeException();
}
return new MySQLBinaryOperation(generateExpression(depth + 1), generateExpression(depth + 1),
MySQLBinaryOperator.getRandom());
case EXISTS:
return getExists(depth + 1);
case BETWEEN_OPERATOR:
return new MySQLBetweenOperation(generateExpression(depth + 1), generateExpression(depth + 1),
generateExpression(depth + 1));
default:
throw new AssertionError();
}
}
private MySQLExpression getExists(int depth) {
if (Randomly.getBoolean()) {
return new MySQLExists(new MySQLStringExpression("SELECT 1", MySQLConstant.createTrue()));
} else {
return new MySQLExists(new MySQLStringExpression("SELECT 1 wHERE FALSE", MySQLConstant.createFalse()));
}
}
private MySQLExpression getFunction(int depth) {
MySQLFunction func = MySQLFunction.getRandomFunction();
int nrArgs = func.getNrArgs();
if (func.isVariadic()) {
nrArgs += Randomly.smallNumber();
}
MySQLExpression[] args = new MySQLExpression[nrArgs];
for (int i = 0; i < args.length; i++) {
args[i] = generateExpression(depth + 1);
}
return new MySQLComputableFunction(func, args);
}
private enum ConstantType {
INT, NULL, STRING, DOUBLE;
}
@Override
public MySQLExpression generateConstant() {
switch (Randomly.fromOptions(ConstantType.values())) {
case INT:
return MySQLConstant.createIntConstant((int) state.getRandomly().getInteger());
case NULL:
return MySQLConstant.createNullConstant();
case STRING:
String string = state.getRandomly().getString();
if (string.startsWith("\n")) {
throw new IgnoreMeException();
}
if (string.startsWith("-0") || string.startsWith("0.")) {
throw new IgnoreMeException();
}
MySQLConstant createStringConstant = MySQLConstant.createStringConstant(string);
// if (Randomly.getBoolean()) {
// return new MySQLCollate(createStringConstant, Randomly.fromOptions("ascii_bin", "binary"));
if (string.startsWith("1e")) {
throw new IgnoreMeException();
}
return createStringConstant;
case DOUBLE:
double val = state.getRandomly().getDouble();
if (Math.abs(val) <= 1 && val != 0) {
throw new IgnoreMeException();
}
return new MySQLDoubleConstant(val);
default:
throw new AssertionError();
}
}
@Override
protected MySQLExpression generateColumn() {
MySQLColumn c = Randomly.fromList(columns);
MySQLConstant val;
if (rowVal == null) {
val = null;
} else {
val = rowVal.getValues().get(c);
}
return MySQLColumnReference.create(c, val);
}
}
|
package com.github.jsonj;
import static com.github.jsonj.tools.JsonBuilder.array;
import static com.github.jsonj.tools.JsonBuilder.field;
import static com.github.jsonj.tools.JsonBuilder.fromObject;
import static com.github.jsonj.tools.JsonBuilder.object;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jsonj.tools.JsonParser;
import java.io.IOException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class ObjectMapperTest {
private ObjectMapper objectMapper;
private JsonParser parser;
@BeforeMethod
public void before() {
objectMapper = new ObjectMapper();
parser = new JsonParser();
}
@DataProvider
public Object[][] jsonElements() {
return new Object[][] {
{object(
field("meaning_of_life",42),
field("a",42.0),
field("b",true),
field("c",array(42,"foo",3.14,true,null)),
field("d",object(field("a",1)))
)},
{
array(42,"foo",3.14,true,null)
},
{
fromObject(42)
},
{
fromObject("hello world")
}
};
}
@Test(dataProvider="jsonElements")
public void shouldSurviveSerializeDeserializeAndBeEqual(JsonElement element) throws IOException {
String serialized = objectMapper.writeValueAsString(element);
assertThat(parser.parse(serialized)).isEqualTo(element);
JsonElement deSerialized = objectMapper.readValue(serialized, JsonElement.class);
assertThat(deSerialized).isEqualTo(element);
if(element.isArray()) {
JsonArray e = objectMapper.readValue(serialized, JsonArray.class);
assertThat(e).isEqualTo(element);
}
if(element.isObject()) {
JsonObject e = objectMapper.readValue(serialized, JsonObject.class);
assertThat(e).isEqualTo(element);
}
if(element.isPrimitive()) {
JsonPrimitive e = objectMapper.readValue(serialized, JsonPrimitive.class);
assertThat(e).isEqualTo(element);
}
}
}
|
package com.tfl.tests.web;
import static com.google.common.truth.Truth.assertThat;
import org.testng.annotations.Test;
import ru.yandex.qatools.allure.annotations.Issue;
import com.frameworkium.tests.internal.BaseTest;
import com.tfl.pages.web.HomePage;
import com.tfl.pages.web.JourneyPlannerResultsPage;
import com.tfl.pages.web.PlanJourneyPage;
public class PlanJourneyTest extends BaseTest {
@Issue("TFL-1")
@Test(description = "Plan a journey test")
public final void planJourneyTest() {
// Navigate to homepage
HomePage homePage = HomePage.open();
// Click the the plan journey link
PlanJourneyPage planJourneyPage = homePage.clickPlanJourneyLink();
// Plan a journey between two locations
JourneyPlannerResultsPage resultsPage = planJourneyPage.planJourney("Clapham Junction", "Oxford Circus");
// Check that the title displayed on the page is "JOURNEY RESULTS"
assertThat(resultsPage.getTitleText()).isEqualTo("JOURNEY RESULTS");
}
}
|
package javax.time.calendar;
import static org.testng.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import javax.time.CalendricalException;
import javax.time.calendar.field.DayOfMonth;
import javax.time.calendar.field.DayOfWeek;
import javax.time.calendar.field.DayOfYear;
import javax.time.calendar.field.MonthOfYear;
import javax.time.calendar.field.QuarterOfYear;
import javax.time.calendar.field.WeekOfWeekyear;
import javax.time.calendar.field.Weekyear;
import javax.time.calendar.field.Year;
import javax.time.period.MockPeriodProviderReturnsNull;
import javax.time.period.Period;
import javax.time.period.PeriodProvider;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Test LocalDate.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
@Test
public class TestLocalDate {
private static final String MIN_YEAR_STR = Integer.toString(Year.MIN_YEAR);
private static final String MAX_YEAR_STR = Integer.toString(Year.MAX_YEAR);
private LocalDate TEST_2007_07_15;
@BeforeMethod
public void setUp() {
TEST_2007_07_15 = LocalDate.date(2007, 7, 15);
}
public void test_interfaces() {
assertTrue(TEST_2007_07_15 instanceof CalendricalProvider);
assertTrue(TEST_2007_07_15 instanceof Serializable);
assertTrue(TEST_2007_07_15 instanceof Comparable);
assertTrue(TEST_2007_07_15 instanceof DateProvider);
assertTrue(TEST_2007_07_15 instanceof DateMatcher);
}
public void test_serialization() throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(TEST_2007_07_15);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
baos.toByteArray()));
assertEquals(ois.readObject(), TEST_2007_07_15);
}
public void test_immutable() {
Class<LocalDate> cls = LocalDate.class;
assertTrue(Modifier.isPublic(cls.getModifiers()));
assertTrue(Modifier.isFinal(cls.getModifiers()));
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
assertTrue(Modifier.isPrivate(field.getModifiers()));
assertTrue(Modifier.isFinal(field.getModifiers()));
}
}
public void factory_date_objects() {
assertEquals(TEST_2007_07_15, LocalDate.date(Year.isoYear(2007), MonthOfYear.JULY, DayOfMonth.dayOfMonth(15)));
}
public void factory_date_objects_leapYear() {
LocalDate test_2008_02_29 = LocalDate.date(Year.isoYear(2008), MonthOfYear.FEBRUARY, DayOfMonth.dayOfMonth(29));
assertEquals(test_2008_02_29.getYear(), Year.isoYear(2008));
assertEquals(test_2008_02_29.getMonthOfYear(), MonthOfYear.FEBRUARY);
assertEquals(test_2008_02_29.getDayOfMonth(), DayOfMonth.dayOfMonth(29));
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_date_objects_nullYear() {
LocalDate.date(null, MonthOfYear.JULY, DayOfMonth.dayOfMonth(15));
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_date_objects_nullMonth() {
LocalDate.date(Year.isoYear(2007), null, DayOfMonth.dayOfMonth(15));
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_date_objects_nullDay() {
LocalDate.date(Year.isoYear(2007), MonthOfYear.JULY, null);
}
@Test(expectedExceptions=InvalidCalendarFieldException.class)
public void factory_date_objects_nonleapYear() {
LocalDate.date(Year.isoYear(2007), MonthOfYear.FEBRUARY, DayOfMonth.dayOfMonth(29));
}
@Test(expectedExceptions=InvalidCalendarFieldException.class)
public void factory_date_objects_dayTooBig() {
LocalDate.date(Year.isoYear(2007), MonthOfYear.APRIL, DayOfMonth.dayOfMonth(31));
}
public void factory_date_intsMonth() {
assertEquals(TEST_2007_07_15, LocalDate.date(2007, MonthOfYear.JULY, 15));
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_intsMonth_dayTooLow() {
LocalDate.date(2007, MonthOfYear.JANUARY, 0);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_intsMonth_dayTooHigh() {
LocalDate.date(2007, MonthOfYear.JANUARY, 32);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_factory_date_intsMonth_nullMonth() {
LocalDate.date(2007, null, 30);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_intsMonth_yearTooLow() {
LocalDate.date(Integer.MIN_VALUE, MonthOfYear.JANUARY, 1);
}
public void factory_date_ints() {
assertEquals(TEST_2007_07_15.getYear(), Year.isoYear(2007));
assertEquals(TEST_2007_07_15.getMonthOfYear(), MonthOfYear.JULY);
assertEquals(TEST_2007_07_15.getDayOfMonth(), DayOfMonth.dayOfMonth(15));
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_ints_dayTooLow() {
LocalDate.date(2007, 1, 0);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_ints_dayTooHigh() {
LocalDate.date(2007, 1, 32);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_ints_monthTooLow() {
LocalDate.date(2007, 0, 1);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_ints_monthTooHigh() {
LocalDate.date(2007, 13, 1);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_factory_date_ints_yearTooLow() {
LocalDate.date(Integer.MIN_VALUE, 1, 1);
}
public void factory_date_DateProvider() {
assertSame(LocalDate.date(TEST_2007_07_15), TEST_2007_07_15);
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_date_DateProvider_null() {
LocalDate.date(null);
}
@Test(expectedExceptions=NullPointerException.class)
public void factory_date_DateProvider_null_toLocalDate() {
LocalDate.date(new MockDateProviderReturnsNull());
}
// Since plusDays/minusDays actually depends on MJDays, it cannot be used for testing
private LocalDate next(LocalDate date) {
int newDayOfMonth = date.getDayOfMonth().getValue() + 1;
if (newDayOfMonth <= date.getMonthOfYear().lengthInDays(date.getYear())) {
return date.withDayOfMonth(newDayOfMonth);
}
date = date.withDayOfMonth(1);
if (date.getMonthOfYear() == MonthOfYear.DECEMBER) {
date = date.with(date.getYear().next());
}
return date.with(date.getMonthOfYear().next());
}
private LocalDate previous(LocalDate date) {
int newDayOfMonth = date.getDayOfMonth().getValue() - 1;
if (newDayOfMonth > 0) {
return date.withDayOfMonth(newDayOfMonth);
}
date = date.with(date.getMonthOfYear().previous());
if (date.getMonthOfYear() == MonthOfYear.DECEMBER) {
date = date.with(date.getYear().previous());
}
return date.with(date.getMonthOfYear().getLastDayOfMonth(date.getYear()));
}
public void factory_fromModifiedJulianDays() {
LocalDate test = LocalDate.date(0, 1, 1);
for (int i = -678941; i < 700000; i++) {
assertEquals(LocalDate.fromModifiedJulianDays(i), test);
test = next(test);
}
test = LocalDate.date(0, 1, 1);
for (int i = -678941; i > -2000000; i
assertEquals(LocalDate.fromModifiedJulianDays(i), test);
test = previous(test);
}
assertEquals(LocalDate.fromModifiedJulianDays(40587), LocalDate.date(1970, 1, 1));
assertEquals(LocalDate.fromModifiedJulianDays(-678942), LocalDate.date(-1, 12, 31));
}
public void test_getChronology() {
assertSame(ISOChronology.INSTANCE, TEST_2007_07_15.getChronology());
}
public void test_isSupported() {
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.yearRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.quarterOfYearRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.monthOfYearRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.monthOfQuarterRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.dayOfMonthRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.dayOfWeekRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.dayOfYearRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.weekOfMonthRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.weekOfWeekyearRule()));
assertTrue(TEST_2007_07_15.isSupported(ISOChronology.weekyearRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.hourOfDayRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.minuteOfHourRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.secondOfMinuteRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.nanoOfSecondRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.hourOfAmPmRule()));
assertFalse(TEST_2007_07_15.isSupported(ISOChronology.amPmOfDayRule()));
assertFalse(TEST_2007_07_15.isSupported(null));
}
public void test_get() {
assertEquals(TEST_2007_07_15.get(ISOChronology.yearRule()), TEST_2007_07_15.getYear().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.quarterOfYearRule()), TEST_2007_07_15.getMonthOfYear().getQuarterOfYear().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.monthOfYearRule()), TEST_2007_07_15.getMonthOfYear().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.monthOfQuarterRule()), TEST_2007_07_15.getMonthOfYear().getMonthOfQuarter());
assertEquals(TEST_2007_07_15.get(ISOChronology.dayOfMonthRule()), TEST_2007_07_15.getDayOfMonth().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.dayOfWeekRule()), TEST_2007_07_15.getDayOfWeek().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.dayOfYearRule()), TEST_2007_07_15.getDayOfYear().getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.weekOfWeekyearRule()), WeekOfWeekyear.weekOfWeekyear(TEST_2007_07_15).getValue());
assertEquals(TEST_2007_07_15.get(ISOChronology.weekyearRule()), Weekyear.weekyear(TEST_2007_07_15).getValue());
}
@Test(expectedExceptions=UnsupportedCalendarFieldException.class)
public void test_get_unsupported() {
TEST_2007_07_15.get(ISOChronology.hourOfDayRule());
}
@DataProvider(name="sampleDates")
Object[][] provider_sampleDates() {
return new Object[][] {
{2008, 7, 5},
{2007, 7, 5},
{2006, 7, 5},
{2005, 7, 5},
{2004, 1, 1},
{-1, 1, 2},
};
}
// get*()
@Test(dataProvider="sampleDates")
public void test_getYearMonth(int y, int m, int d) {
assertEquals(LocalDate.date(y, m, d).getYearMonth(), YearMonth.yearMonth(y, m));
}
@Test(dataProvider="sampleDates")
public void test_getMonthDay(int y, int m, int d) {
assertEquals(LocalDate.date(y, m, d).getMonthDay(), MonthDay.monthDay(m, d));
}
@Test(dataProvider="sampleDates")
public void test_get(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
assertEquals(a.getYear(), Year.isoYear(y));
assertEquals(a.getMonthOfYear(), MonthOfYear.monthOfYear(m));
assertEquals(a.getDayOfMonth(), DayOfMonth.dayOfMonth(d));
}
@Test(dataProvider="sampleDates")
public void test_getDOY(int y, int m, int d) {
Year year = Year.isoYear(y);
LocalDate a = LocalDate.date(y, m, d);
int total = 0;
for (int i = 1; i < m; i++) {
total += MonthOfYear.monthOfYear(i).lengthInDays(year);
}
int doy = total + d;
assertEquals(a.getDayOfYear(), DayOfYear.dayOfYear(doy));
}
// getDayOfWeek()
public void test_getDayOfWeek() {
DayOfWeek dow = DayOfWeek.MONDAY;
Year year = Year.isoYear(2007);
for (MonthOfYear month : MonthOfYear.values()) {
int length = month.lengthInDays(year);
for (int i = 1; i <= length; i++) {
LocalDate d = LocalDate.date(year, month, DayOfMonth.dayOfMonth(i));
assertSame(d.getDayOfWeek(), dow);
dow = dow.next();
}
}
}
// with()
public void test_with() {
DateAdjuster dateAdjuster = DateAdjusters.lastDayOfMonth();
assertEquals(TEST_2007_07_15.with(dateAdjuster), dateAdjuster.adjustDate(TEST_2007_07_15));
}
@Test(expectedExceptions=NullPointerException.class)
public void test_with_null() {
TEST_2007_07_15.with((DateAdjuster) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_with_null_adjustDate() {
TEST_2007_07_15.with(new MockDateAdjusterReturnsNull());
}
// withYear()
public void test_withYear_int_normal() {
LocalDate t = TEST_2007_07_15.withYear(2008);
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_withYear_int_noChange() {
LocalDate t = TEST_2007_07_15.withYear(2007);
assertSame(t, TEST_2007_07_15);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_withYear_int_invalid() {
TEST_2007_07_15.withYear(Year.MIN_YEAR - 1);
}
public void test_withYear_int_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).withYear(2007);
LocalDate expected = LocalDate.date(2007, 2, 28);
assertEquals(t, expected);
}
public void test_withYear_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.withYear(2008, DateResolvers.strict());
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_withYear_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.withYear(2007, DateResolvers.strict());
assertSame(t, TEST_2007_07_15);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_withYear_int_DateResolver_invalid() {
TEST_2007_07_15.withYear(Year.MIN_YEAR - 1, DateResolvers.nextValid());
}
public void test_withYear_int_DateResolver_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).withYear(2007, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 3, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_withYear_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.withYear(2008, new MockDateResolverReturnsNull());
}
@Test(expectedExceptions=InvalidCalendarFieldException.class)
public void test_withYear_int_DateResolver_adjustDay_invalid() {
LocalDate.date(2008, 2, 29).withYear(2007, DateResolvers.strict());
}
// withMonthOfYear()
public void test_withMonthOfYear_int_normal() {
LocalDate t = TEST_2007_07_15.withMonthOfYear(1);
assertEquals(t, LocalDate.date(2007, 1, 15));
}
public void test_withMonthOfYear_int_noChange() {
LocalDate t = TEST_2007_07_15.withMonthOfYear(7);
assertSame(t, TEST_2007_07_15);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_withMonthOfYear_int_invalid() {
TEST_2007_07_15.withMonthOfYear(13);
}
public void test_withMonthOfYear_int_adjustDay() {
LocalDate t = LocalDate.date(2007, 12, 31).withMonthOfYear(11);
LocalDate expected = LocalDate.date(2007, 11, 30);
assertEquals(t, expected);
}
public void test_withMonthOfYear_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.withMonthOfYear(1, DateResolvers.strict());
assertEquals(t, LocalDate.date(2007, 1, 15));
}
public void test_withMonthOfYear_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.withMonthOfYear(7, DateResolvers.strict());
assertSame(t, TEST_2007_07_15);
}
@Test(expectedExceptions=IllegalCalendarFieldValueException.class)
public void test_withMonthOfYear_int_DateResolver_invalid() {
TEST_2007_07_15.withMonthOfYear(13, DateResolvers.nextValid());
}
public void test_withMonthOfYear_int_DateResolver_adjustDay() {
LocalDate t = LocalDate.date(2007, 12, 31).withMonthOfYear(11, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 12, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_withMonthOfYear_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.withMonthOfYear(1, new MockDateResolverReturnsNull());
}
@Test(expectedExceptions=InvalidCalendarFieldException.class)
public void test_withMonthOfYear_int_DateResolver_adjustDay_invalid() {
LocalDate.date(2007, 12, 31).withMonthOfYear(11, DateResolvers.strict());
}
// withDayOfMonth()
public void test_withDayOfMonth_normal() {
LocalDate t = TEST_2007_07_15.withDayOfMonth(1);
assertEquals(t, LocalDate.date(2007, 7, 1));
}
public void test_withDayOfMonth_noChange() {
LocalDate t = TEST_2007_07_15.withDayOfMonth(15);
assertSame(t, TEST_2007_07_15);
}
@Test(expectedExceptions=InvalidCalendarFieldException.class)
public void test_withDayOfMonth_invalid() {
LocalDate.date(2007, 11, 30).withDayOfMonth(31);
}
// plus(PeriodProvider)
public void test_plus_PeriodProvider() {
PeriodProvider provider = Period.period(1, 2, 3, 4, 5, 6, 7);
LocalDate t = TEST_2007_07_15.plus(provider);
assertEquals(t, LocalDate.date(2008, 9, 18));
}
public void test_plus_PeriodProvider_timeIgnored() {
PeriodProvider provider = Period.period(1, 2, 3, Integer.MAX_VALUE, 5, 6, 7);
LocalDate t = TEST_2007_07_15.plus(provider);
assertEquals(t, LocalDate.date(2008, 9, 18));
}
public void test_plus_PeriodProvider_zero() {
LocalDate t = TEST_2007_07_15.plus(Period.ZERO);
assertSame(t, TEST_2007_07_15);
}
public void test_plus_PeriodProvider_previousValidResolver_oneMonth() {
PeriodProvider provider = Period.months(1);
LocalDate t = LocalDate.date(2008, 1, 31).plus(provider);
assertEquals(t, LocalDate.date(2008, 2, 29));
}
public void test_plus_PeriodProvider_previousValidResolver_oneMonthOneDay() {
PeriodProvider provider = Period.yearsMonthsDays(0, 1, 1);
LocalDate t = LocalDate.date(2008, 1, 31).plus(provider);
assertEquals(t, LocalDate.date(2008, 3, 1));
}
// public void test_plus_PeriodProvider_previousValidResolver_oneMonthMinusOneDay() {
// PeriodProvider provider = Period.yearsMonthsDays(0, 1, -1);
// LocalDate t = LocalDate.date(2008, 1, 31).plus(provider);
// assertEquals(t, LocalDate.date(2008, 2, 29)); // TODO: what is the correct result
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PeriodProvider_null() {
TEST_2007_07_15.plus((PeriodProvider) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PeriodProvider_badProvider() {
TEST_2007_07_15.plus(new MockPeriodProviderReturnsNull());
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plus_PeriodProvider_invalidTooLarge() {
PeriodProvider provider = Period.years(1);
LocalDate.date(Year.MAX_YEAR, 1, 1).plus(provider);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plus_PeriodProvider_invalidTooSmall() {
PeriodProvider provider = Period.years(-1);
LocalDate.date(Year.MIN_YEAR, 1, 1).plus(provider);
}
// plusYears()
public void test_plusYears_int_normal() {
LocalDate t = TEST_2007_07_15.plusYears(1);
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_plusYears_int_noChange() {
LocalDate t = TEST_2007_07_15.plusYears(0);
assertSame(t, TEST_2007_07_15);
}
public void test_plusYears_int_negative() {
LocalDate t = TEST_2007_07_15.plusYears(-1);
assertEquals(t, LocalDate.date(2006, 7, 15));
}
public void test_plusYears_int_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).plusYears(1);
LocalDate expected = LocalDate.date(2009, 2, 28);
assertEquals(t, expected);
}
public void test_plusYears_int_invalidTooLarge() {
try {
LocalDate.date(Year.MAX_YEAR, 1, 1).plusYears(1);
fail();
} catch (CalendricalException ex) {
String actual = Long.toString(((long) Year.MAX_YEAR) + 1);
assertEquals(ex.getMessage(), "Year " + actual + " exceeds the supported year range");
}
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plusYears_int_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusYears(-1);
}
public void test_plusYears_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.plusYears(1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_plusYears_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.plusYears(0, DateResolvers.nextValid());
assertSame(t, TEST_2007_07_15);
}
public void test_plusYears_int_DateResolver_negative() {
LocalDate t = TEST_2007_07_15.plusYears(-1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2006, 7, 15));
}
public void test_plusYears_int_DateResolver_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).plusYears(1, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2009, 3, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_plusYears_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.plusYears(1, new MockDateResolverReturnsNull());
}
public void test_plusYears_int_DateResolver_invalidTooLarge() {
try {
LocalDate.date(Year.MAX_YEAR, 1, 1).plusYears(1, DateResolvers.nextValid());
fail();
} catch (CalendricalException ex) {
long year = ((long) Year.MAX_YEAR) + 1;
assertEquals(ex.getMessage(), "Year " + year + " exceeds the supported year range");
}
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plusYears_int_DateResolver_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusYears(-1, DateResolvers.nextValid());
}
// plusMonths()
public void test_plusMonths_int_normal() {
LocalDate t = TEST_2007_07_15.plusMonths(1);
assertEquals(t, LocalDate.date(2007, 8, 15));
}
public void test_plusMonths_int_noChange() {
LocalDate t = TEST_2007_07_15.plusMonths(0);
assertSame(t, TEST_2007_07_15);
}
public void test_plusMonths_int_overYears() {
LocalDate t = TEST_2007_07_15.plusMonths(25);
assertEquals(t, LocalDate.date(2009, 8, 15));
}
public void test_plusMonths_int_negative() {
LocalDate t = TEST_2007_07_15.plusMonths(-1);
assertEquals(t, LocalDate.date(2007, 6, 15));
}
public void test_plusMonths_int_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.plusMonths(-7);
assertEquals(t, LocalDate.date(2006, 12, 15));
}
public void test_plusMonths_int_negativeOverYears() {
LocalDate t = TEST_2007_07_15.plusMonths(-31);
assertEquals(t, LocalDate.date(2004, 12, 15));
}
public void test_plusMonths_int_adjustDayFromLeapYear() {
LocalDate t = LocalDate.date(2008, 2, 29).plusMonths(12);
LocalDate expected = LocalDate.date(2009, 2, 28);
assertEquals(t, expected);
}
public void test_plusMonths_int_adjustDayFromMonthLength() {
LocalDate t = LocalDate.date(2007, 3, 31).plusMonths(1);
LocalDate expected = LocalDate.date(2007, 4, 30);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusMonths_int_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 1).plusMonths(1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusMonths_int_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusMonths(-1);
}
public void test_plusMonths_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.plusMonths(1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2007, 8, 15));
}
public void test_plusMonths_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.plusMonths(0, DateResolvers.nextValid());
assertSame(t, TEST_2007_07_15);
}
public void test_plusMonths_int_DateResolver_overYears() {
LocalDate t = TEST_2007_07_15.plusMonths(25, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2009, 8, 15));
}
public void test_plusMonths_int_DateResolver_negative() {
LocalDate t = TEST_2007_07_15.plusMonths(-1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2007, 6, 15));
}
public void test_plusMonths_int_DateResolver_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.plusMonths(-7, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2006, 12, 15));
}
public void test_plusMonths_int_DateResolver_negativeOverYears() {
LocalDate t = TEST_2007_07_15.plusMonths(-31, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2004, 12, 15));
}
public void test_plusMonths_int_DateResolver_adjustDayFromLeapYear() {
LocalDate t = LocalDate.date(2008, 2, 29).plusMonths(12, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2009, 3, 1);
assertEquals(t, expected);
}
public void test_plusMonths_int_DateResolver_adjustDayFromMonthLength() {
LocalDate t = LocalDate.date(2007, 3, 31).plusMonths(1, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 5, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_plusMonths_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.plusMonths(1, new MockDateResolverReturnsNull());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusMonths_int_DateResolver_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 1).plusMonths(1, DateResolvers.nextValid());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusMonths_int_DateResolver_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusMonths(-1, DateResolvers.nextValid());
}
// plusWeeks()
@DataProvider(name="samplePlusWeeksSymmetry")
Object[][] provider_samplePlusWeeksSymmetry() {
return new Object[][] {
{LocalDate.date(-1, 1, 1)},
{LocalDate.date(-1, 2, 28)},
{LocalDate.date(-1, 3, 1)},
{LocalDate.date(-1, 12, 31)},
{LocalDate.date(0, 1, 1)},
{LocalDate.date(0, 2, 28)},
{LocalDate.date(0, 2, 29)},
{LocalDate.date(0, 3, 1)},
{LocalDate.date(0, 12, 31)},
{LocalDate.date(2007, 1, 1)},
{LocalDate.date(2007, 2, 28)},
{LocalDate.date(2007, 3, 1)},
{LocalDate.date(2007, 12, 31)},
{LocalDate.date(2008, 1, 1)},
{LocalDate.date(2008, 2, 28)},
{LocalDate.date(2008, 2, 29)},
{LocalDate.date(2008, 3, 1)},
{LocalDate.date(2008, 12, 31)},
{LocalDate.date(2099, 1, 1)},
{LocalDate.date(2099, 2, 28)},
{LocalDate.date(2099, 3, 1)},
{LocalDate.date(2099, 12, 31)},
{LocalDate.date(2100, 1, 1)},
{LocalDate.date(2100, 2, 28)},
{LocalDate.date(2100, 3, 1)},
{LocalDate.date(2100, 12, 31)},
};
}
@Test(dataProvider="samplePlusWeeksSymmetry")
public void test_plusWeeks_symmetry(LocalDate reference) {
for (int weeks = 0; weeks < 365 * 8; weeks++) {
LocalDate t = reference.plusWeeks(weeks).plusWeeks(-weeks);
assertEquals(t, reference);
t = reference.plusWeeks(-weeks).plusWeeks(weeks);
assertEquals(t, reference);
}
}
public void test_plusWeeks_normal() {
LocalDate t = TEST_2007_07_15.plusWeeks(1);
assertEquals(t, LocalDate.date(2007, 7, 22));
}
public void test_plusWeeks_noChange() {
LocalDate t = TEST_2007_07_15.plusWeeks(0);
assertSame(t, TEST_2007_07_15);
}
public void test_plusWeeks_overMonths() {
LocalDate t = TEST_2007_07_15.plusWeeks(9);
assertEquals(t, LocalDate.date(2007, 9, 16));
}
public void test_plusWeeks_overYears() {
LocalDate t = LocalDate.date(2006, 7, 16).plusWeeks(52);
assertEquals(t, TEST_2007_07_15);
}
public void test_plusWeeks_overLeapYears() {
LocalDate t = TEST_2007_07_15.plusYears(-1).plusWeeks(104);
assertEquals(t, LocalDate.date(2008, 7, 12));
}
public void test_plusWeeks_negative() {
LocalDate t = TEST_2007_07_15.plusWeeks(-1);
assertEquals(t, LocalDate.date(2007, 7, 8));
}
public void test_plusWeeks_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.plusWeeks(-28);
assertEquals(t, LocalDate.date(2006, 12, 31));
}
public void test_plusWeeks_negativeOverYears() {
LocalDate t = TEST_2007_07_15.plusWeeks(-104);
assertEquals(t, LocalDate.date(2005, 7, 17));
}
public void test_plusWeeks_maximum() {
LocalDate t = LocalDate.date(Year.MAX_YEAR, 12, 24).plusWeeks(1);
LocalDate expected = LocalDate.date(Year.MAX_YEAR, 12, 31);
assertEquals(t, expected);
}
public void test_plusWeeks_minimum() {
LocalDate t = LocalDate.date(Year.MIN_YEAR, 1, 8).plusWeeks(-1);
LocalDate expected = LocalDate.date(Year.MIN_YEAR, 1, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusWeeks_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 25).plusWeeks(1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusWeeks_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 7).plusWeeks(-1);
}
// plusDays()
@DataProvider(name="samplePlusDaysSymmetry")
Object[][] provider_samplePlusDaysSymmetry() {
return new Object[][] {
{LocalDate.date(-1, 1, 1)},
{LocalDate.date(-1, 2, 28)},
{LocalDate.date(-1, 3, 1)},
{LocalDate.date(-1, 12, 31)},
{LocalDate.date(0, 1, 1)},
{LocalDate.date(0, 2, 28)},
{LocalDate.date(0, 2, 29)},
{LocalDate.date(0, 3, 1)},
{LocalDate.date(0, 12, 31)},
{LocalDate.date(2007, 1, 1)},
{LocalDate.date(2007, 2, 28)},
{LocalDate.date(2007, 3, 1)},
{LocalDate.date(2007, 12, 31)},
{LocalDate.date(2008, 1, 1)},
{LocalDate.date(2008, 2, 28)},
{LocalDate.date(2008, 2, 29)},
{LocalDate.date(2008, 3, 1)},
{LocalDate.date(2008, 12, 31)},
{LocalDate.date(2099, 1, 1)},
{LocalDate.date(2099, 2, 28)},
{LocalDate.date(2099, 3, 1)},
{LocalDate.date(2099, 12, 31)},
{LocalDate.date(2100, 1, 1)},
{LocalDate.date(2100, 2, 28)},
{LocalDate.date(2100, 3, 1)},
{LocalDate.date(2100, 12, 31)},
};
}
@Test(dataProvider="samplePlusDaysSymmetry")
public void test_plusDays_symmetry(LocalDate reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDate t = reference.plusDays(days).plusDays(-days);
assertEquals(t, reference);
t = reference.plusDays(-days).plusDays(days);
assertEquals(t, reference);
}
}
public void test_plusDays_normal() {
LocalDate t = TEST_2007_07_15.plusDays(1);
assertEquals(t, LocalDate.date(2007, 7, 16));
}
public void test_plusDays_noChange() {
LocalDate t = TEST_2007_07_15.plusDays(0);
assertSame(t, TEST_2007_07_15);
}
public void test_plusDays_overMonths() {
LocalDate t = TEST_2007_07_15.plusDays(62);
assertEquals(t, LocalDate.date(2007, 9, 15));
}
public void test_plusDays_overYears() {
LocalDate t = LocalDate.date(2006, 7, 14).plusDays(366);
assertEquals(t, TEST_2007_07_15);
}
public void test_plusDays_overLeapYears() {
LocalDate t = TEST_2007_07_15.plusYears(-1).plusDays(365 + 366);
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_plusDays_negative() {
LocalDate t = TEST_2007_07_15.plusDays(-1);
assertEquals(t, LocalDate.date(2007, 7, 14));
}
public void test_plusDays_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.plusDays(-196);
assertEquals(t, LocalDate.date(2006, 12, 31));
}
public void test_plusDays_negativeOverYears() {
LocalDate t = TEST_2007_07_15.plusDays(-730);
assertEquals(t, LocalDate.date(2005, 7, 15));
}
public void test_plusDays_maximum() {
LocalDate t = LocalDate.date(Year.MAX_YEAR, 12, 30).plusDays(1);
LocalDate expected = LocalDate.date(Year.MAX_YEAR, 12, 31);
assertEquals(t, expected);
}
public void test_plusDays_minimum() {
LocalDate t = LocalDate.date(Year.MIN_YEAR, 1, 2).plusDays(-1);
LocalDate expected = LocalDate.date(Year.MIN_YEAR, 1, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusDays_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 31).plusDays(1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_plusDays_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusDays(-1);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plusDays_overflowTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 31).plusDays(Long.MAX_VALUE);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_plusDays_overflowTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).plusDays(Long.MIN_VALUE);
}
// minus(PeriodProvider)
public void test_minus_PeriodProvider() {
PeriodProvider provider = Period.period(1, 2, 3, 4, 5, 6, 7);
LocalDate t = TEST_2007_07_15.minus(provider);
assertEquals(t, LocalDate.date(2006, 5, 12));
}
public void test_minus_PeriodProvider_timeIgnored() {
PeriodProvider provider = Period.period(1, 2, 3, Integer.MAX_VALUE, 5, 6, 7);
LocalDate t = TEST_2007_07_15.minus(provider);
assertEquals(t, LocalDate.date(2006, 5, 12));
}
public void test_minus_PeriodProvider_zero() {
LocalDate t = TEST_2007_07_15.minus(Period.ZERO);
assertSame(t, TEST_2007_07_15);
}
public void test_minus_PeriodProvider_previousValidResolver_oneMonth() {
PeriodProvider provider = Period.months(1);
LocalDate t = LocalDate.date(2008, 3, 31).minus(provider);
assertEquals(t, LocalDate.date(2008, 2, 29));
}
// public void test_minus_PeriodProvider_previousValidResolver_oneMonthOneDay() {
// PeriodProvider provider = Period.yearsMonthsDays(0, 1, 1);
// LocalDate t = LocalDate.date(2008, 3, 31).minus(provider);
// assertEquals(t, LocalDate.date(2008, 2, 29)); // TODO: what is the correct result here
@Test(expectedExceptions=NullPointerException.class)
public void test_minus_PeriodProvider_null() {
TEST_2007_07_15.minus((PeriodProvider) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_minus_PeriodProvider_badProvider() {
TEST_2007_07_15.minus(new MockPeriodProviderReturnsNull());
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minus_PeriodProvider_invalidTooLarge() {
PeriodProvider provider = Period.years(-1);
LocalDate.date(Year.MAX_YEAR, 1, 1).minus(provider);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minus_PeriodProvider_invalidTooSmall() {
PeriodProvider provider = Period.years(1);
LocalDate.date(Year.MIN_YEAR, 1, 1).minus(provider);
}
// minusYears()
public void test_minusYears_int_normal() {
LocalDate t = TEST_2007_07_15.minusYears(1);
assertEquals(t, LocalDate.date(2006, 7, 15));
}
public void test_minusYears_int_noChange() {
LocalDate t = TEST_2007_07_15.minusYears(0);
assertSame(t, TEST_2007_07_15);
}
public void test_minusYears_int_negative() {
LocalDate t = TEST_2007_07_15.minusYears(-1);
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_minusYears_int_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).minusYears(1);
LocalDate expected = LocalDate.date(2007, 2, 28);
assertEquals(t, expected);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minusYears_int_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 1, 1).minusYears(-1);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minusYears_int_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).minusYears(1);
}
public void test_minusYears_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.minusYears(1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2006, 7, 15));
}
public void test_minusYears_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.minusYears(0, DateResolvers.nextValid());
assertSame(t, TEST_2007_07_15);
}
public void test_minusYears_int_DateResolver_negative() {
LocalDate t = TEST_2007_07_15.minusYears(-1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2008, 7, 15));
}
public void test_minusYears_int_DateResolver_adjustDay() {
LocalDate t = LocalDate.date(2008, 2, 29).minusYears(1, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 3, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_minusYears_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.minusYears(1, new MockDateResolverReturnsNull());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusYears_int_DateResolver_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 1, 1).minusYears(-1, DateResolvers.nextValid());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusYears_int_DateResolver_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).minusYears(1, DateResolvers.nextValid());
}
// minusMonths()
public void test_minusMonths_int_normal() {
LocalDate t = TEST_2007_07_15.minusMonths(1);
assertEquals(t, LocalDate.date(2007, 6, 15));
}
public void test_minusMonths_int_noChange() {
LocalDate t = TEST_2007_07_15.minusMonths(0);
assertSame(t, TEST_2007_07_15);
}
public void test_minusMonths_int_overYears() {
LocalDate t = TEST_2007_07_15.minusMonths(25);
assertEquals(t, LocalDate.date(2005, 6, 15));
}
public void test_minusMonths_int_negative() {
LocalDate t = TEST_2007_07_15.minusMonths(-1);
assertEquals(t, LocalDate.date(2007, 8, 15));
}
public void test_minusMonths_int_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.minusMonths(-7);
assertEquals(t, LocalDate.date(2008, 2, 15));
}
public void test_minusMonths_int_negativeOverYears() {
LocalDate t = TEST_2007_07_15.minusMonths(-31);
assertEquals(t, LocalDate.date(2010, 2, 15));
}
public void test_minusMonths_int_adjustDayFromLeapYear() {
LocalDate t = LocalDate.date(2008, 2, 29).minusMonths(12);
LocalDate expected = LocalDate.date(2007, 2, 28);
assertEquals(t, expected);
}
public void test_minusMonths_int_adjustDayFromMonthLength() {
LocalDate t = LocalDate.date(2007, 3, 31).minusMonths(1);
LocalDate expected = LocalDate.date(2007, 2, 28);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusMonths_int_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 1).minusMonths(-1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusMonths_int_invalidTooSmall() {
LocalDate t = LocalDate.date(Year.MIN_YEAR, 1, 1).minusMonths(1);
}
public void test_minusMonths_int_DateResolver_normal() {
LocalDate t = TEST_2007_07_15.minusMonths(1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2007, 6, 15));
}
public void test_minusMonths_int_DateResolver_noChange() {
LocalDate t = TEST_2007_07_15.minusMonths(0, DateResolvers.nextValid());
assertSame(t, TEST_2007_07_15);
}
public void test_minusMonths_int_DateResolver_overYears() {
LocalDate t = TEST_2007_07_15.minusMonths(25, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2005, 6, 15));
}
public void test_minusMonths_int_DateResolver_negative() {
LocalDate t = TEST_2007_07_15.minusMonths(-1, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2007, 8, 15));
}
public void test_minusMonths_int_DateResolver_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.minusMonths(-7, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2008, 2, 15));
}
public void test_minusMonths_int_DateResolver_negativeOverYears() {
LocalDate t = TEST_2007_07_15.minusMonths(-31, DateResolvers.nextValid());
assertEquals(t, LocalDate.date(2010, 2, 15));
}
public void test_minusMonths_int_DateResolver_adjustDayFromLeapYear() {
LocalDate t = LocalDate.date(2008, 2, 29).minusMonths(12, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 3, 1);
assertEquals(t, expected);
}
public void test_minusMonths_int_DateResolver_adjustDayFromMonthLength() {
LocalDate t = LocalDate.date(2007, 3, 31).minusMonths(1, DateResolvers.nextValid());
LocalDate expected = LocalDate.date(2007, 3, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_minusMonths_int_DateResolver_null_adjustDay() {
TEST_2007_07_15.minusMonths(1, new MockDateResolverReturnsNull());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusMonths_int_DateResolver_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 1).minusMonths(-1, DateResolvers.nextValid());
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusMonths_int_DateResolver_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).minusMonths(1, DateResolvers.nextValid());
}
// minusWeeks()
@DataProvider(name="sampleMinusWeeksSymmetry")
Object[][] provider_sampleMinusWeeksSymmetry() {
return new Object[][] {
{LocalDate.date(-1, 1, 1)},
{LocalDate.date(-1, 2, 28)},
{LocalDate.date(-1, 3, 1)},
{LocalDate.date(-1, 12, 31)},
{LocalDate.date(0, 1, 1)},
{LocalDate.date(0, 2, 28)},
{LocalDate.date(0, 2, 29)},
{LocalDate.date(0, 3, 1)},
{LocalDate.date(0, 12, 31)},
{LocalDate.date(2007, 1, 1)},
{LocalDate.date(2007, 2, 28)},
{LocalDate.date(2007, 3, 1)},
{LocalDate.date(2007, 12, 31)},
{LocalDate.date(2008, 1, 1)},
{LocalDate.date(2008, 2, 28)},
{LocalDate.date(2008, 2, 29)},
{LocalDate.date(2008, 3, 1)},
{LocalDate.date(2008, 12, 31)},
{LocalDate.date(2099, 1, 1)},
{LocalDate.date(2099, 2, 28)},
{LocalDate.date(2099, 3, 1)},
{LocalDate.date(2099, 12, 31)},
{LocalDate.date(2100, 1, 1)},
{LocalDate.date(2100, 2, 28)},
{LocalDate.date(2100, 3, 1)},
{LocalDate.date(2100, 12, 31)},
};
}
@Test(dataProvider="sampleMinusWeeksSymmetry")
public void test_minusWeeks_symmetry(LocalDate reference) {
for (int weeks = 0; weeks < 365 * 8; weeks++) {
LocalDate t = reference.minusWeeks(weeks).minusWeeks(-weeks);
assertEquals(t, reference);
t = reference.minusWeeks(-weeks).minusWeeks(weeks);
assertEquals(t, reference);
}
}
public void test_minusWeeks_normal() {
LocalDate t = TEST_2007_07_15.minusWeeks(1);
assertEquals(t, LocalDate.date(2007, 7, 8));
}
public void test_minusWeeks_noChange() {
LocalDate t = TEST_2007_07_15.minusWeeks(0);
assertSame(t, TEST_2007_07_15);
}
public void test_minusWeeks_overMonths() {
LocalDate t = TEST_2007_07_15.minusWeeks(9);
assertEquals(t, LocalDate.date(2007, 5, 13));
}
public void test_minusWeeks_overYears() {
LocalDate t = LocalDate.date(2008, 7, 13).minusWeeks(52);
assertEquals(t, TEST_2007_07_15);
}
public void test_minusWeeks_overLeapYears() {
LocalDate t = TEST_2007_07_15.minusYears(-1).minusWeeks(104);
assertEquals(t, LocalDate.date(2006, 7, 18));
}
public void test_minusWeeks_negative() {
LocalDate t = TEST_2007_07_15.minusWeeks(-1);
assertEquals(t, LocalDate.date(2007, 7, 22));
}
public void test_minusWeeks_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.minusWeeks(-28);
assertEquals(t, LocalDate.date(2008, 1, 27));
}
public void test_minusWeeks_negativeOverYears() {
LocalDate t = TEST_2007_07_15.minusWeeks(-104);
assertEquals(t, LocalDate.date(2009, 7, 12));
}
public void test_minusWeeks_maximum() {
LocalDate t = LocalDate.date(Year.MAX_YEAR, 12, 24).minusWeeks(-1);
LocalDate expected = LocalDate.date(Year.MAX_YEAR, 12, 31);
assertEquals(t, expected);
}
public void test_minusWeeks_minimum() {
LocalDate t = LocalDate.date(Year.MIN_YEAR, 1, 8).minusWeeks(1);
LocalDate expected = LocalDate.date(Year.MIN_YEAR, 1, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusWeeks_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 25).minusWeeks(-1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusWeeks_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 7).minusWeeks(1);
}
// minusDays()
@DataProvider(name="sampleMinusDaysSymmetry")
Object[][] provider_sampleMinusDaysSymmetry() {
return new Object[][] {
{LocalDate.date(-1, 1, 1)},
{LocalDate.date(-1, 2, 28)},
{LocalDate.date(-1, 3, 1)},
{LocalDate.date(-1, 12, 31)},
{LocalDate.date(0, 1, 1)},
{LocalDate.date(0, 2, 28)},
{LocalDate.date(0, 2, 29)},
{LocalDate.date(0, 3, 1)},
{LocalDate.date(0, 12, 31)},
{LocalDate.date(2007, 1, 1)},
{LocalDate.date(2007, 2, 28)},
{LocalDate.date(2007, 3, 1)},
{LocalDate.date(2007, 12, 31)},
{LocalDate.date(2008, 1, 1)},
{LocalDate.date(2008, 2, 28)},
{LocalDate.date(2008, 2, 29)},
{LocalDate.date(2008, 3, 1)},
{LocalDate.date(2008, 12, 31)},
{LocalDate.date(2099, 1, 1)},
{LocalDate.date(2099, 2, 28)},
{LocalDate.date(2099, 3, 1)},
{LocalDate.date(2099, 12, 31)},
{LocalDate.date(2100, 1, 1)},
{LocalDate.date(2100, 2, 28)},
{LocalDate.date(2100, 3, 1)},
{LocalDate.date(2100, 12, 31)},
};
}
@Test(dataProvider="sampleMinusDaysSymmetry")
public void test_minusDays_symmetry(LocalDate reference) {
for (int days = 0; days < 365 * 8; days++) {
LocalDate t = reference.minusDays(days).minusDays(-days);
assertEquals(t, reference);
t = reference.minusDays(-days).minusDays(days);
assertEquals(t, reference);
}
}
public void test_minusDays_normal() {
LocalDate t = TEST_2007_07_15.minusDays(1);
assertEquals(t, LocalDate.date(2007, 7, 14));
}
public void test_minusDays_noChange() {
LocalDate t = TEST_2007_07_15.minusDays(0);
assertSame(t, TEST_2007_07_15);
}
public void test_minusDays_overMonths() {
LocalDate t = TEST_2007_07_15.minusDays(62);
assertEquals(t, LocalDate.date(2007, 5, 14));
}
public void test_minusDays_overYears() {
LocalDate t = LocalDate.date(2008, 7, 16).minusDays(367);
assertEquals(t, TEST_2007_07_15);
}
public void test_minusDays_overLeapYears() {
LocalDate t = TEST_2007_07_15.plusYears(2).minusDays(365 + 366);
assertEquals(t, TEST_2007_07_15);
}
public void test_minusDays_negative() {
LocalDate t = TEST_2007_07_15.minusDays(-1);
assertEquals(t, LocalDate.date(2007, 7, 16));
}
public void test_minusDays_negativeAcrossYear() {
LocalDate t = TEST_2007_07_15.minusDays(-169);
assertEquals(t, LocalDate.date(2007, 12, 31));
}
public void test_minusDays_negativeOverYears() {
LocalDate t = TEST_2007_07_15.minusDays(-731);
assertEquals(t, LocalDate.date(2009, 7, 15));
}
public void test_minusDays_maximum() {
LocalDate t = LocalDate.date(Year.MAX_YEAR, 12, 30).minusDays(-1);
LocalDate expected = LocalDate.date(Year.MAX_YEAR, 12, 31);
assertEquals(t, expected);
}
public void test_minusDays_minimum() {
LocalDate t = LocalDate.date(Year.MIN_YEAR, 1, 2).minusDays(1);
LocalDate expected = LocalDate.date(Year.MIN_YEAR, 1, 1);
assertEquals(t, expected);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusDays_invalidTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 31).minusDays(-1);
}
@Test(expectedExceptions={CalendricalException.class})
public void test_minusDays_invalidTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).minusDays(1);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minusDays_overflowTooLarge() {
LocalDate.date(Year.MAX_YEAR, 12, 31).minusDays(Long.MIN_VALUE);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_minusDays_overflowTooSmall() {
LocalDate.date(Year.MIN_YEAR, 1, 1).minusDays(Long.MAX_VALUE);
}
// matches()
public void test_matches() {
assertTrue(TEST_2007_07_15.matches(Year.isoYear(2007)));
assertFalse(TEST_2007_07_15.matches(Year.isoYear(2006)));
assertTrue(TEST_2007_07_15.matches(QuarterOfYear.Q3));
assertFalse(TEST_2007_07_15.matches(QuarterOfYear.Q2));
assertTrue(TEST_2007_07_15.matches(MonthOfYear.JULY));
assertFalse(TEST_2007_07_15.matches(MonthOfYear.JUNE));
assertTrue(TEST_2007_07_15.matches(DayOfMonth.dayOfMonth(15)));
assertFalse(TEST_2007_07_15.matches(DayOfMonth.dayOfMonth(14)));
assertTrue(TEST_2007_07_15.matches(DayOfWeek.SUNDAY));
assertFalse(TEST_2007_07_15.matches(DayOfWeek.MONDAY));
}
// toLocalDate()
@Test(dataProvider="sampleDates")
public void test_toLocalDate(int year, int month, int day) {
LocalDate t = LocalDate.date(year, month, day);
assertSame(t.toLocalDate(), t);
}
// toCalendrical()
@Test(dataProvider="sampleDates")
public void test_toCalendrical(int year, int month, int day) {
LocalDate t = LocalDate.date(year, month, day);
assertEquals(t.toCalendrical(), Calendrical.calendrical(t, null, null, null));
}
// toModifiedJulianDays()
public void test_toMJDays() {
LocalDate test = LocalDate.date(0, 1, 1);
for (int i = -678941; i < 700000; i++) {
assertEquals(test.toModifiedJulianDays(), i);
test = next(test);
}
test = LocalDate.date(0, 1, 1);
for (int i = -678941; i > -2000000; i
assertEquals(test.toModifiedJulianDays(), i);
test = previous(test);
}
assertEquals(LocalDate.date(1858, 11, 17).toModifiedJulianDays(), 0);
assertEquals(LocalDate.date(1, 1, 1).toModifiedJulianDays(), -678575);
assertEquals(LocalDate.date(1995, 9, 27).toModifiedJulianDays(), 49987);
assertEquals(LocalDate.date(1970, 1, 1).toModifiedJulianDays(), 40587);
assertEquals(LocalDate.date(-1, 12, 31).toModifiedJulianDays(), -678942);
}
public void test_toMJDays_fromMJDays_symmetry() {
LocalDate test = LocalDate.date(0, 1, 1);
for (int i = -678941; i < 700000; i++) {
assertEquals(LocalDate.fromModifiedJulianDays(test.toModifiedJulianDays()), test);
test = next(test);
}
test = LocalDate.date(0, 1, 1);
for (int i = -678941; i > -2000000; i
assertEquals(LocalDate.fromModifiedJulianDays(test.toModifiedJulianDays()), test);
test = previous(test);
}
}
// compareTo()
public void test_comparisons() {
doTest_comparisons_LocalDate(
LocalDate.date(Year.MIN_YEAR, 1, 1),
LocalDate.date(Year.MIN_YEAR, 12, 31),
LocalDate.date(-1, 1, 1),
LocalDate.date(-1, 12, 31),
LocalDate.date(0, 1, 1),
LocalDate.date(0, 12, 31),
LocalDate.date(1, 1, 1),
LocalDate.date(1, 12, 31),
LocalDate.date(2006, 1, 1),
LocalDate.date(2006, 12, 31),
LocalDate.date(2007, 1, 1),
LocalDate.date(2007, 12, 31),
LocalDate.date(2008, 1, 1),
LocalDate.date(2008, 2, 29),
LocalDate.date(2008, 12, 31),
LocalDate.date(Year.MAX_YEAR, 1, 1),
LocalDate.date(Year.MAX_YEAR, 12, 31)
);
}
void doTest_comparisons_LocalDate(LocalDate... localDates) {
for (int i = 0; i < localDates.length; i++) {
LocalDate a = localDates[i];
for (int j = 0; j < localDates.length; j++) {
LocalDate b = localDates[j];
if (i < j) {
assertTrue(a.compareTo(b) < 0, a + " <=> " + b);
assertEquals(a.isBefore(b), true, a + " <=> " + b);
assertEquals(a.isAfter(b), false, a + " <=> " + b);
assertEquals(a.equals(b), false, a + " <=> " + b);
} else if (i > j) {
assertTrue(a.compareTo(b) > 0, a + " <=> " + b);
assertEquals(a.isBefore(b), false, a + " <=> " + b);
assertEquals(a.isAfter(b), true, a + " <=> " + b);
assertEquals(a.equals(b), false, a + " <=> " + b);
} else {
assertEquals(a.compareTo(b), 0, a + " <=> " + b);
assertEquals(a.isBefore(b), false, a + " <=> " + b);
assertEquals(a.isAfter(b), false, a + " <=> " + b);
assertEquals(a.equals(b), true, a + " <=> " + b);
}
}
}
}
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
TEST_2007_07_15.compareTo(null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_isBefore_ObjectNull() {
TEST_2007_07_15.isBefore(null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_isAfter_ObjectNull() {
TEST_2007_07_15.isAfter(null);
}
@Test(expectedExceptions=ClassCastException.class)
@SuppressWarnings("unchecked")
public void compareToNonLocalDate() {
Comparable c = TEST_2007_07_15;
c.compareTo(new Object());
}
// equals()
@Test(dataProvider="sampleDates")
public void test_equals_true(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m, d);
assertEquals(a.equals(b), true);
}
@Test(dataProvider="sampleDates")
public void test_equals_false_year_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y + 1, m, d);
assertEquals(a.equals(b), false);
}
@Test(dataProvider="sampleDates")
public void test_equals_false_month_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m + 1, d);
assertEquals(a.equals(b), false);
}
@Test(dataProvider="sampleDates")
public void test_equals_false_day_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m, d + 1);
assertEquals(a.equals(b), false);
}
public void test_equals_itself_true() {
assertEquals(TEST_2007_07_15.equals(TEST_2007_07_15), true);
}
public void test_equals_string_false() {
assertEquals(TEST_2007_07_15.equals("2007-07-15"), false);
}
public void test_equals_null_false() {
assertEquals(TEST_2007_07_15.equals(null), false);
}
// hashCode()
@Test(dataProvider="sampleDates")
public void test_hashCode(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
assertEquals(a.hashCode(), a.hashCode());
LocalDate b = LocalDate.date(y, m, d);
assertEquals(a.hashCode(), b.hashCode());
}
// toString()
@DataProvider(name="sampleToString")
Object[][] provider_sampleToString() {
return new Object[][] {
{2008, 7, 5, "2008-07-05"},
{2007, 12, 31, "2007-12-31"},
{999, 12, 31, "0999-12-31"},
{-1, 1, 2, "-0001-01-02"},
};
}
@Test(dataProvider="sampleToString")
public void test_toString(int y, int m, int d, String expected) {
LocalDate t = LocalDate.date(y, m, d);
String str = t.toString();
assertEquals(str, expected);
}
// matchesDate()
@Test(dataProvider="sampleDates")
public void test_matchesDate_true(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m, d);
assertEquals(a.matchesDate(b), true);
}
@Test(dataProvider="sampleDates")
public void test_matchesDate_false_year_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y + 1, m, d);
assertEquals(a.matchesDate(b), false);
}
@Test(dataProvider="sampleDates")
public void test_matchesDate_false_month_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m + 1, d);
assertEquals(a.matchesDate(b), false);
}
@Test(dataProvider="sampleDates")
public void test_matchesDate_false_day_differs(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
LocalDate b = LocalDate.date(y, m, d + 1);
assertEquals(a.matchesDate(b), false);
}
public void test_matchesDate_itself_true() {
assertEquals(TEST_2007_07_15.matchesDate(TEST_2007_07_15), true);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_matchesDate_null() {
TEST_2007_07_15.matchesDate(null);
}
// adjustDate()
@Test(dataProvider="sampleDates")
public void test_adjustDate(int y, int m, int d) {
LocalDate a = LocalDate.date(y, m, d);
assertSame(a.adjustDate(TEST_2007_07_15), a);
assertSame(TEST_2007_07_15.adjustDate(a), TEST_2007_07_15);
}
public void test_adjustDate_same() {
assertSame(LocalDate.date(2007, 7, 15).adjustDate(TEST_2007_07_15), TEST_2007_07_15);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_adjustDate_null() {
TEST_2007_07_15.adjustDate(null);
}
}
|
package kodkod.test.unit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import kodkod.ast.Formula;
import kodkod.engine.Solution.Outcome;
import kodkod.engine.Solver;
import kodkod.engine.satlab.ResolutionTrace;
import kodkod.engine.satlab.SATFactory;
import kodkod.engine.satlab.SATProver;
import kodkod.engine.satlab.SATSolver;
import kodkod.instance.Bounds;
import kodkod.util.ints.Ints;
import org.junit.Test;
import kodkod.test.util.Solvers;
import kodkod.examples.alloy.CeilingsAndFloors;
/**
* A test that loads multiple native solvers into memory.
*
* @author Emian Torlak
*/
public class NativeSolverTest {
private static final List<SATFactory> solvers = Solvers.allAvailableSolvers();
private final Formula formula;
private final Bounds bounds;
public NativeSolverTest() {
final CeilingsAndFloors prob = new CeilingsAndFloors();
this.formula = prob.checkBelowTooDoublePrime();
this.bounds = prob.bounds(6, 6);
}
@Test
public void testEmptyCNF() {
for(SATFactory factory : solvers) {
assertTrue(factory.instance().solve());
}
}
@Test
public void testEmptyClauseCNF() {
for(SATFactory factory : solvers) {
final SATSolver solver = factory.instance();
solver.addClause(new int[0]);
assertFalse(solver.solve());
}
}
@Test
public void testProofOfEmptyClauseCNF() {
for(SATFactory factory : solvers) {
if (!factory.prover()) continue;
final SATProver solver = (SATProver) factory.instance();
solver.addClause(new int[0]);
assertFalse(solver.solve());
final ResolutionTrace proof = solver.proof();
assertEquals(1, proof.size());
assertEquals(Ints.singleton(0), proof.core());
assertEquals(Ints.EMPTY_SET, proof.resolvents());
assertEquals(0, proof.get(0).size());
}
}
@Test
public void testProofOfNthEmptyClauseCNF() {
for(SATFactory factory : solvers) {
if (!factory.prover()) continue;
final SATProver solver = (SATProver) factory.instance();
solver.addVariables(1);
solver.addClause(new int[]{1});
solver.addVariables(1);
solver.addClause(new int[]{-2});
solver.addVariables(2);
solver.addClause(new int[]{2, 3, 4});
solver.addClause(new int[0]);
solver.addClause(new int[]{4});
solver.addClause(new int[]{3});
assertFalse(solver.solve());
final ResolutionTrace proof = solver.proof();
assertEquals(4, proof.size());
assertEquals(Ints.singleton(3), proof.core());
assertEquals(Ints.EMPTY_SET, proof.resolvents());
assertEquals(0, proof.get(3).size());
}
}
@Test
public void testProofOfLastEmptyClauseCNF() {
for(SATFactory factory : solvers) {
if (!factory.prover()) continue;
final SATProver solver = (SATProver) factory.instance();
solver.addVariables(1);
solver.addClause(new int[]{1});
solver.addVariables(1);
solver.addClause(new int[]{-2});
solver.addVariables(2);
solver.addClause(new int[]{2, 3, 4});
solver.addClause(new int[0]);
assertFalse(solver.solve());
final ResolutionTrace proof = solver.proof();
assertEquals(4, proof.size());
assertEquals(Ints.singleton(3), proof.core());
assertEquals(Ints.EMPTY_SET, proof.resolvents());
assertEquals(0, proof.get(3).size());
}
}
@Test(expected=IllegalArgumentException.class)
public void testPlingelingBadThreadInput() {
final SATFactory pl = SATFactory.plingeling(0, true);
solveWith(pl);
}
@Test
public void testPlingelingOneThread() {
if (!SATFactory.available(SATFactory.plingeling())) return;
final SATFactory pl = SATFactory.plingeling(1,null);
assertEquals(Outcome.UNSATISFIABLE, solveWith(pl));
}
@Test
public void testPlingelingPortfolio() {
if (!SATFactory.available(SATFactory.plingeling())) return;
final SATFactory pl = SATFactory.plingeling(null,true);
assertEquals(Outcome.UNSATISFIABLE, solveWith(pl));
}
@Test
public void testPlingelingThreeThreadsPortfolio() {
if (!SATFactory.available(SATFactory.plingeling())) return;
final SATFactory pl = SATFactory.plingeling(3,true);
assertEquals(Outcome.UNSATISFIABLE, solveWith(pl));
}
// @Test
// public void testLingelingIncremental() {
// final SATSolver solver = SATFactory.Lingeling.instance();
// solver.addVariables(1);
// solver.addClause(new int[]{1});
// assertTrue(solver.solve());
// solver.addVariables(1);
// solver.addClause(new int[]{-2});
// assertTrue(solver.solve());
// solver.addVariables(8);
// solver.addClause(new int[]{2, 9, 10});
// assertTrue(solver.solve());
// solver.addClause(new int[0]);
// solver.addClause(new int[]{7, 8, 10});
// assertFalse(solver.solve());
// solver.addClause(new int[]{-3, 5});
// assertFalse(solver.solve());
// @Test
// public void testLingelingRetrieveModel() {
// final SATSolver solver = SATFactory.Lingeling.instance();
// solver.addVariables(1);
// solver.addClause(new int[]{1});
// assertTrue(solver.solve());
// solver.addVariables(1);
// solver.addClause(new int[]{-2});
// assertTrue(solver.solve());
// solver.addVariables(18);
// solver.addClause(new int[]{2, 9, 10});
// assertTrue(solver.solve());
// try {
// for(int i = 1; i <= 20; i++)
// solver.valueOf(i);
// fail(ia.getMessage());
// try {
// solver.valueOf(21);
// // do nothing
@Test
public void testMultipleSolvers() {
final List<Callable<Outcome>> calls = new ArrayList<Callable<Outcome>>();
for(SATFactory factory : solvers) {
calls.add(callSolver(factory));
}
final ExecutorService exec = Executors.newFixedThreadPool(calls.size());
try {
final List<Future<Outcome>> out = exec.invokeAll(calls);
assertEquals(calls.size(), out.size());
for(Future<Outcome> result : out) {
assertEquals(Outcome.UNSATISFIABLE, result.get());
}
} catch (InterruptedException e) {
fail("Unexpected interruption");
} catch (ExecutionException e) {
fail("Unexpected execution exception");
}
}
private Callable<Outcome> callSolver(final SATFactory factory) {
return new Callable<Outcome>() {
public Outcome call() throws Exception {
return solveWith(factory);
}
};
}
private Outcome solveWith(SATFactory factory) {
final Solver solver = new Solver();
solver.options().setSolver(factory);
return solver.solve(formula, bounds).outcome();
}
}
|
package linenux.command;
import static linenux.helpers.Assert.assertChangeBy;
import static linenux.helpers.Assert.assertNoChange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.LocalDateTime;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import linenux.command.parser.ReminderArgumentParser;
import linenux.command.result.CommandResult;
import linenux.model.Reminder;
import linenux.model.Schedule;
import linenux.model.Task;
/**
* JUnit test for remind command.
*/
public class RemindCommandTest {
private Schedule schedule;
private RemindCommand remindCommand;
private Task todo;
private Task deadline;
private Task event;
@Before
public void setupRemindCommand() {
ArrayList<Task> tasks = new ArrayList<>();
todo = new Task("Todo");
deadline = new Task("Deadline", LocalDateTime.of(2016, 1, 1, 1, 0));
event = new Task("Event", LocalDateTime.of(2016, 1, 1, 1, 0), LocalDateTime.of(2016, 1, 1, 13, 0));
tasks.add(todo);
tasks.add(deadline);
tasks.add(event);
this.schedule = new Schedule(tasks);
this.remindCommand = new RemindCommand(this.schedule);
}
/**
* Test that respondTo detects various versions of the commands. It should return true even if
* the format of the arguments are invalid.
*/
@Test
public void testRespondToRemindCommand() {
assertTrue(this.remindCommand.respondTo("remind"));
assertTrue(this.remindCommand.respondTo("remind task"));
assertTrue(this.remindCommand.respondTo("remind task t/2016-01-01"));
assertTrue(this.remindCommand.respondTo("remind task t/2016-01-01 n/notes"));
}
/**
* Test respondTo is case-insensitive.
*/
@Test
public void testCaseInsensitiveRemindCommand() {
assertTrue(this.remindCommand.respondTo("ReMiNd task t/2016-01-01"));
}
/**
* Test that respondTo will return false for commands not related to adding reminders.
*/
@Test
public void testNotRespondToOtherCommands() {
assertFalse(this.remindCommand.respondTo("notremind"));
}
/**
* Test that executing adding reminder without notes to a To-Do should return correct result
*/
@Test
public void testExecuteAddReminderWithoutNotesToToDo() {
assertChangeBy(() -> this.todo.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Todo t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = this.todo.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
}
/**
* Test that executing adding reminder with notes to a To-Do should return correct result
*/
@Test
public void testExecuteAddReminderWithNotesToToDo() {
assertChangeBy(() -> this.todo.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Todo t/2000-01-01 05:00PM n/Attend Workshop"));
ArrayList<Reminder> reminders = this.todo.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test that executing adding reminder with notes in different order to a To-Do should return correct result
*/
@Test
public void testExecuteAddReminderWithDiffParamOrderToToDo() {
assertChangeBy(() -> this.todo.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Todo n/Attend Workshop t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = todo.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test that executing adding reminder without notes to a Deadline should return correct result
*/
@Test
public void testExecuteAddReminderWithoutNotesToDeadline() {
assertChangeBy(() -> this.deadline.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Deadline t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = this.deadline.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
}
/**
* Test that executing adding reminder with notes to a Deadline should return correct result
*/
@Test
public void testExecuteAddReminderWithNotesToDeadline() {
assertChangeBy(() -> this.deadline.getReminders().size(),
1,
() -> this.remindCommand.execute("remind deadline t/2000-01-01 05:00PM n/Attend Workshop"));
ArrayList<Reminder> reminders = this.deadline.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test that executing adding reminder with notes in different order to a Deadline should return correct result
*/
@Test
public void testExecuteAddReminderWithDiffParamOrderToDeadline() {
assertChangeBy(() -> this.deadline.getReminders().size(),
1,
() -> this.remindCommand.execute("remind deadline n/Attend Workshop t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = this.deadline.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test that executing adding reminder without notes to a Event should return correct result
*/
@Test
public void testExecuteAddReminderWithoutNotesToEvent() {
assertChangeBy(() -> this.event.getReminders().size(),
1,
() -> this.remindCommand.execute("remind event t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = this.event.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
}
/**
* Test that executing adding reminder with notes to a Event should return correct result
*/
@Test
public void testExecuteAddReminderWithNotesToEvent() {
assertChangeBy(() -> this.event.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Event t/2000-01-01 05:00PM n/Attend Workshop"));
ArrayList<Reminder> reminders = this.event.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test that executing adding reminder with notes in different order to a Event should return correct result
*/
@Test
public void testExecuteAddReminderWithDiffParamOrderToEvent() {
assertChangeBy(() -> this.event.getReminders().size(),
1,
() -> this.remindCommand.execute("remind Event n/Attend Workshop t/2000-01-01 05:00PM"));
ArrayList<Reminder> reminders = this.event.getReminders();
Reminder addedReminder = reminders.get(reminders.size() - 1);
assertEquals(LocalDateTime.of(2000, 1, 1, 17, 0), addedReminder.getTimeOfReminder());
assertEquals("Attend Workshop", addedReminder.getNote());
}
/**
* Test the result when no task name is given to search.
*/
@Test
public void testTimeWithoutTaskNameCommandResult() {
CommandResult result = assertNoChange(() -> this.todo.getReminders().size(),
() -> this.remindCommand.execute("remind t/2011-01-01 05:00PM"));
assertEquals(expectedInvalidArgumentMessage(), result.getFeedback());
}
/**
* Test the result when no task name is given to search + not affected by optional field notes.
*/
@Test
public void testTimeWithoutTaskNameWithNotesCommandResult() {
CommandResult result = assertNoChange(() -> this.todo.getReminders().size(),
() -> this.remindCommand.execute("remind t/2011-01-01 05:00PM n/Attend Workshop"));
assertEquals(expectedInvalidArgumentMessage(), result.getFeedback());
}
/**
* Test the result when no time is given for the reminder.
*/
@Test
public void testTaskNameWithoutTimeCommandResult() {
CommandResult result = assertNoChange(() -> this.todo.getReminders().size(),
() -> this.remindCommand.execute("remind todo"));
assertEquals("Cannot create reminder without date.", result.getFeedback());
}
/**
* Test the result when no time is given for the reminder + not affected by optional field Notes
*/
@Test
public void testTaskNameWithoutTimeWithNotesCommandResult() {
CommandResult result = assertNoChange(() -> this.todo.getReminders().size(),
() -> this.remindCommand.execute("remind todo n/Attend Workshop"));
assertEquals("Cannot create reminder without date.", result.getFeedback());
}
/**
* Test the result when time is invalid
*/
@Test
public void testInvalidTimeCommandResult() {
CommandResult result = assertNoChange(() -> this.todo.getReminders().size(),
() -> this.remindCommand.execute("remind todo t/tomorrow"));
assertEquals("Cannot parse \"tomorrow\".", result.getFeedback());
}
private String expectedInvalidArgumentMessage() {
return "Invalid arguments.\n\n" + ReminderArgumentParser.ARGUMENT_FORMAT;
}
}
|
package org.animotron.operator;
import org.animotron.ATest;
import org.animotron.Expression;
import org.animotron.exception.EBuilderTerminated;
import org.animotron.operator.query.ALL;
import org.animotron.operator.relation.HAVE;
import org.animotron.operator.relation.IS;
import org.animotron.operator.relation.USE;
import org.junit.Test;
import java.io.IOException;
import static org.animotron.Expression._;
import static org.animotron.Expression.text;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class AllUseTest extends ATest {
@Test
public void simple_all_Use() throws EBuilderTerminated, IOException, InterruptedException {
new Expression(
_(THE._, "A", _(IS._, "S"), _(HAVE._, "X", text("α")))
);
new Expression(
_(THE._, "B", _(IS._, "A"), _(HAVE._, "Y", text("β")))
);
new Expression(
_(THE._, "C", _(IS._, "B"), _(HAVE._, "Z", text("γ")), _(HAVE._, "X", text("αα")))
);
new Expression (
_(THE._, "s", _(ALL._, "S"))
);
Expression b = new Expression(
_(THE._, "b", _(AN._, "s", _(USE._, "B")))
);
assertAnimo(b, "<the:b><the:s><the:B><is:A/><have:Y>β</have:Y></the:B><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C></the:s></the:b>");
Expression c = new Expression(
_(THE._, "c", _(AN._, "s", _(USE._, "C")))
);
assertAnimo(c, "<the:c><the:s><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C></the:s></the:c>");
}
@Test
public void simple_all_Use_1() throws EBuilderTerminated, IOException, InterruptedException {
new Expression(
_(THE._, "A", _(IS._, "S"), _(HAVE._, "X", text("α")))
);
new Expression(
_(THE._, "B", _(IS._, "A"), _(HAVE._, "Y", text("β")))
);
new Expression(
_(THE._, "C", _(IS._, "B"), _(HAVE._, "Z", text("γ")), _(HAVE._, "X", text("αα")))
);
new Expression (
_(THE._, "s", _(ALL._, "S"))
);
new Expression (
_(THE._, "ub", _(USE._, "B"))
);
new Expression (
_(THE._, "uc", _(USE._, "C"))
);
Expression b = new Expression(
_(THE._, "b", _(AN._, "s", _(AN._, "ub")))
);
assertAnimo(b, "<the:b><the:s><the:B><is:A/><have:Y>β</have:Y></the:B><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C></the:s></the:b>");
Expression c = new Expression(
_(THE._, "c", _(AN._, "s", _(AN._, "uc")))
);
assertAnimo(c, "<the:c><the:s><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C></the:s></the:c>");
}
@Test
public void complex_all_Use() throws EBuilderTerminated, IOException, InterruptedException {
new Expression(
_(THE._, "A", _(IS._, "S"), _(HAVE._, "X", text("α")))
);
new Expression(
_(THE._, "B", _(IS._, "A"), _(HAVE._, "Y", text("β")))
);
new Expression(
_(THE._, "B1", _(IS._, "B"), _(HAVE._, "Y", text("ββ")))
);
new Expression(
_(THE._, "C", _(IS._, "B"), _(HAVE._, "Z", text("γ")), _(HAVE._, "X", text("αα")))
);
new Expression(
_(THE._, "C1", _(IS._, "C"), _(HAVE._, "Z", text("γγ")), _(HAVE._, "X", text("ααα")))
);
new Expression (
_(THE._, "s", _(ALL._, "S"))
);
Expression b = new Expression(
_(THE._, "b", _(AN._, "s", _(USE._, "B")))
);
assertAnimo(b, "<the:b><the:s><the:B><is:A/><have:Y>β</have:Y></the:B><the:B1><is:B/><have:Y>ββ</have:Y></the:B1></the:s></the:b>");
Expression c = new Expression(
_(THE._, "c", _(AN._, "s", _(USE._, "C")))
);
assertAnimo(c, "<the:c><the:s><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C><the:C1><is:C/><have:Z>γγ</have:Z><have:X>ααα</have:X></the:C1></the:s></the:c>");
}
@Test
public void complex_all_Use_1() throws EBuilderTerminated, IOException, InterruptedException {
new Expression(
_(THE._, "A", _(IS._, "S"), _(HAVE._, "X", text("α")))
);
new Expression(
_(THE._, "B", _(IS._, "A"), _(HAVE._, "Y", text("β")))
);
new Expression(
_(THE._, "B1", _(IS._, "B"), _(HAVE._, "Y", text("ββ")))
);
new Expression(
_(THE._, "C", _(IS._, "B"), _(HAVE._, "Z", text("γ")), _(HAVE._, "X", text("αα")))
);
new Expression(
_(THE._, "C1", _(IS._, "C"), _(HAVE._, "Z", text("γγ")), _(HAVE._, "X", text("ααα")))
);
new Expression (
_(THE._, "s", _(ALL._, "S"))
);
new Expression (
_(THE._, "ub", _(USE._, "B"))
);
new Expression (
_(THE._, "uc", _(USE._, "C"))
);
Expression b = new Expression(
_(THE._, "b", _(AN._, "s", _(AN._, "ub")))
);
assertAnimo(b, "<the:b><the:s><the:B><is:A/><have:Y>β</have:Y></the:B><the:B1><is:B/><have:Y>ββ</have:Y></the:B1></the:s></the:b>");
Expression c = new Expression(
_(THE._, "c", _(AN._, "s", _(AN._, "uc")))
);
assertAnimo(c, "<the:c><the:s><the:C><is:B/><have:Z>γ</have:Z><have:X>αα</have:X></the:C><the:C1><is:C/><have:Z>γγ</have:Z><have:X>ααα</have:X></the:C1></the:s></the:c>");
}
}
|
package org.it4y.net.link;
import junit.framework.Assert;
import org.it4y.util.Counter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
public class LinkManagerTest {
private final Logger log= LoggerFactory.getLogger(LinkManager.class);
private LinkManager startLinkManager(LinkNotification.EventType aType,LinkNotification.EventAction aAction,LinkNotification aListener) throws Exception {
LinkManager lm=new LinkManager();
Assert.assertNotNull(lm);
//register event listener if we want
if (aListener != null) {
LinkNotification x=lm.registerListener(aAction,aType,aListener);
Assert.assertEquals(x,aListener);
}
//run it
lm.start();
//wait so thread can start
Thread.sleep(100);
Assert.assertTrue(lm.isRunning());
Assert.assertTrue(lm.isDaemon());
Assert.assertTrue(lm.isAlive());
int retry=0;
//we need to wait until linkmanager has all the data
while(!lm.isReady() & retry < 20) {
Thread.sleep(100);
retry++;
}
Assert.assertTrue("Timeout waiting link manager",lm.isReady());
return lm;
}
private LinkManager startLinkManager() throws Exception {
return startLinkManager(null,null,null);
}
private void stopLinkManager(LinkManager lm) throws Exception {
lm.halt();
//wait so thread can start
Thread.sleep(200);
Assert.assertTrue(!lm.isReady());
Assert.assertTrue(!lm.isRunning());
}
@Test
public void testLinkManager() throws Exception {
LinkManager lm=startLinkManager();
stopLinkManager(lm);
}
@Test
public void testDefaulGateway() throws Exception {
//this test should always work when there is a normal network setup
LinkManager lm=startLinkManager();
//Get default gateway
Assert.assertNotNull(lm.getDefaultGateway());
lm.halt();
}
@Test
public void testfindbyInterfaceName() throws Exception {
//this test should always work when there is a normal network setup
LinkManager lm=startLinkManager();
//Get lo interface
NetworkInterface lo=lm.findByInterfaceName("lo");
Assert.assertNotNull(lo);
log.info("{}",lo);
//this is only correct for lo interface
Assert.assertNotNull(lo.getIpv4AddressAsInetAddress());
Assert.assertTrue(lo.getMtu() > 0);
Assert.assertEquals("lo", lo.getName());
Assert.assertEquals(0x0100007f,lo.getIpv4Address()&0xffffffff);
Assert.assertTrue(lo.getMtu()>0);
Assert.assertTrue(lo.isLowerUP());
Assert.assertTrue(lo.isUP());
Assert.assertTrue(lo.isLoopBack());
Assert.assertTrue(!lo.isPoint2Point());
Assert.assertTrue(lo.isActive());
lm.halt();
}
@Test
public void testfindbyInterfaceIndex() throws Exception {
//this test should always work when there is a normal network setup
LinkManager lm=startLinkManager();
//Get lo interface
NetworkInterface lo=lm.findByInterfaceIndex(1);
Assert.assertNotNull(lo);
Assert.assertEquals(1,lo.getIndex());
lm.halt();
}
@Test
public void testConcurrentFindbyName() throws Exception{
final LinkManager lm=startLinkManager();
final Counter readcnt=new Counter();
final Counter wrtcnt=new Counter();
//we need access to internal wlock lock for simulating write locks
Field privateLock = LinkManager.class.getDeclaredField("wlock");
privateLock.setAccessible(true);
final Lock wlock=(Lock)privateLock.get(lm);
log.info("running concurrent access...");
log.info("# of cpu: {}",Runtime.getRuntime().availableProcessors());
ExecutorService es= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*4);
//Run 40 jobs on the linkmanager requesting all links concurrently
for (int i=0;i<100;i++) {
//start some read access
for (final String net : lm.getInterfaceList()) {
es.submit(new Runnable() {
@Override
public void run() {
readcnt.inc();
NetworkInterface x=lm.findByInterfaceName(net);
Assert.assertNotNull(x);
Assert.assertEquals(net,x.getName());
}
});
//and long locking write access
if ((i % 3) == 0) {
es.submit(new Runnable() {
@Override
public void run() {
wrtcnt.inc();
wlock.lock();
try {
//do something usefull while holding the lock
Thread.sleep(20);
} catch (InterruptedException ignore) {
} finally {
wlock.unlock();
}
}
});
}
}
}
Thread.sleep(500);
//All read/write locks are executed multible times
log.info("Read locks: {}",readcnt.getCount());
log.info("Write locks: {}",wrtcnt.getCount());
Assert.assertTrue(readcnt.getCount()>1);
Assert.assertTrue(wrtcnt.getCount()>1);
//if it is not thread save, we don't get here
lm.halt();
}
@Test
public void testLinkMessagesNotification() throws Exception {
final Counter cnt=new Counter();
final LinkManager lm=startLinkManager(LinkNotification.EventType.Link, LinkNotification.EventAction.All, new LinkNotification() {
@Override
public void onEvent(EventAction action, EventType type, NetworkInterface network) {
cnt.inc();
Assert.assertEquals(action, EventAction.New);
Assert.assertEquals(type, EventType.Link);
}
@Override
public void onStateChanged(NetworkInterface network) {
cnt.inc();
}
});
Assert.assertTrue(cnt.getCount() > 0);
//if it is not thread save, we don't get here
lm.halt();
}
@Test
public void testAddressMessagesNotification() throws Exception {
final Counter cnt=new Counter();
final LinkManager lm=startLinkManager(LinkNotification.EventType.Address, LinkNotification.EventAction.All, new LinkNotification() {
@Override
public void onEvent(EventAction action, EventType type, NetworkInterface network) {
cnt.inc();
Assert.assertEquals(action, EventAction.Update);
Assert.assertEquals(type, EventType.Address);
}
@Override
public void onStateChanged(NetworkInterface network) {
cnt.inc();
}
});
Assert.assertTrue(cnt.getCount() > 0);
//if it is not thread save, we don't get here
lm.halt();
}
@Test
public void testRouteMessagesNotification() throws Exception {
final Counter cnt=new Counter();
final LinkManager lm=startLinkManager(LinkNotification.EventType.Routing, LinkNotification.EventAction.All, new LinkNotification() {
@Override
public void onEvent(EventAction action, EventType type, NetworkInterface network) {
cnt.inc();
Assert.assertEquals(action, EventAction.Update);
Assert.assertEquals(type, EventType.Routing);
}
@Override
public void onStateChanged(NetworkInterface network) {
}
});
Assert.assertTrue(cnt.getCount() > 0);
//if it is not thread save, we don't get here
lm.halt();
}
@Test
public void testLinkStateMessagesNotification() throws Exception {
final Counter cnt=new Counter();
final LinkManager lm=startLinkManager(LinkNotification.EventType.All, LinkNotification.EventAction.All, new LinkNotification() {
@Override
public void onEvent(EventAction action, EventType type, NetworkInterface network) {
}
@Override
public void onStateChanged(NetworkInterface network) {
cnt.inc();
Assert.assertTrue(network.isUP());
Assert.assertTrue(network.isActive());
}
});
//we should always have lo up
Assert.assertTrue(cnt.getCount() >= 1);
//if it is not thread save, we don't get here
lm.halt();
}
@Test
public void testUnregisterNotification() throws Exception {
final LinkManager lm=startLinkManager();
LinkNotification noti=new LinkNotification() {
@Override
public void onEvent(EventAction action, EventType type, NetworkInterface network) {
}
@Override
public void onStateChanged(NetworkInterface network) {
}
};
lm.registerListener(LinkNotification.EventAction.All, LinkNotification.EventType.All, noti);
lm.unRegisterListener(noti);
}
}
|
package org.jtrfp.trcl.pool;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Queue;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.jtrfp.trcl.pool.IndexPool.GrowthBehavior;
import org.jtrfp.trcl.pool.IndexPool.OutOfIndicesException;
public class IndexPoolTest extends TestCase {
public void testPop() {
final IndexPool subject = new IndexPool();
for(int i=0; i<500; i++)
assertEquals(i, subject.pop());
}
public void testPopOrException() {
final IndexPool subject = new IndexPool();
subject.setHardLimit(500);
for(int i=0; i<500; i++)
assertEquals(i, subject.pop());
try {
subject.popOrException();
fail("Failed to throw expected OutOfIndicesException.");
} catch (OutOfIndicesException e) {}//Good.
}
public void testPopCollectionOfIntegerInt() {
final IndexPool subject = new IndexPool();
final ArrayList<Integer>dest = new ArrayList<Integer>();
subject.pop(dest, 512);
for(int i=0; i<512; i++)
assertEquals(Integer.valueOf(i), dest.get(i));
assertEquals(512,dest.size());
}
public void testFree() {
final IndexPool subject = new IndexPool();
for(int i=0; i<500; i++)
assertEquals(i, subject.pop());
for(int i=0; i<250; i++)
subject.free(i);
for(int i=0; i<250; i++)
assertEquals(i, subject.pop());
assertEquals(500,subject.pop());
}
public void testSetGrowthBehavior() {
final IndexPool subject = new IndexPool();
assertEquals(1, subject.getMaxCapacity());
subject.setGrowthBehavior(new GrowthBehavior(){
@Override
public int grow(int previousMaxCapacity) {
return previousMaxCapacity+1;
}
public int shrink(int minDesiredCapacity){
return minDesiredCapacity;
}});
subject.pop();
subject.pop();
assertEquals(2, subject.getMaxCapacity());
subject.pop();
assertEquals(3, subject.getMaxCapacity());
}
public void testPopConsecutive() {
final IndexPool subject = new IndexPool();
assertEquals(0, subject.popConsecutive(4));
assertEquals(4, subject.popConsecutive(4));
}
public void testGetMaxCapacity() {
final IndexPool subject = new IndexPool();
for(int i=0; i<60; i++)
subject.pop();
//With default doubling growth, power-of-two behavior expected.
assertEquals(64, subject.getMaxCapacity());
}
public void testGetHardLimit() {
final IndexPool subject= new IndexPool();
subject.setHardLimit(5);
assertEquals(5,subject.getHardLimit());
}
public void testFreeCollectionOfIntegersInt(){
final IndexPool subject = new IndexPool();
final ArrayList<Integer>dest = new ArrayList<Integer>();
subject.pop(dest, 512);
subject.free(dest);
assertEquals(0, subject.pop());
}
public void testGetUsedIndices(){
final IndexPool subject = new IndexPool();
Queue<Integer> indices = subject.getUsedIndices();
subject.pop();
final ArrayList<Integer> dest = new ArrayList<Integer>();
subject.pop(dest, 2);
assertNotNull(indices);
assertEquals(3,indices.size());
Iterator<Integer> it = indices.iterator();
assertEquals(0, (int)it.next());
assertEquals(1, (int)it.next());
assertEquals(2, (int)it.next());
assertEquals(1, (int)dest.get(0));
assertEquals(2, (int)dest.get(1));
}//end testGetUsedIndices()
public void testCompact(){
final IndexPool subject = new IndexPool();
subject.pop();
subject.pop();
subject.pop();
subject.free(0);
subject.free(1);
// f f 2
assertEquals(2, subject.getFreeIndices().size());
assertEquals(1, subject.getUsedIndices().size());
subject.compact();
// f f 2
assertEquals(2, subject.getFreeIndices().size());
assertEquals(1, subject.getUsedIndices().size());
assertEquals(0,subject.pop());
subject.free(2);
// 0 f f
assertEquals(2, subject.getFreeIndices().size());
assertEquals(1, subject.getUsedIndices().size());
subject.compact();
assertEquals(0, subject.getFreeIndices().size());
assertEquals(1, subject.getUsedIndices().size());
}
}//end IndexPoolTest
|
package org.komamitsu.fluency;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.komamitsu.fluency.buffer.PackedForwardBuffer;
import org.komamitsu.fluency.buffer.TestableBuffer;
import org.komamitsu.fluency.flusher.AsyncFlusher;
import org.komamitsu.fluency.flusher.Flusher;
import org.komamitsu.fluency.flusher.SyncFlusher;
import org.komamitsu.fluency.sender.MockTCPSender;
import org.komamitsu.fluency.sender.MultiSender;
import org.komamitsu.fluency.sender.RetryableSender;
import org.komamitsu.fluency.sender.Sender;
import org.komamitsu.fluency.sender.TCPSender;
import org.komamitsu.fluency.sender.failuredetect.FailureDetector;
import org.komamitsu.fluency.sender.failuredetect.PhiAccrualFailureDetectStrategy;
import org.komamitsu.fluency.sender.heartbeat.TCPHeartbeater;
import org.komamitsu.fluency.sender.retry.ExponentialBackOffRetryStrategy;
import org.msgpack.value.MapValue;
import org.msgpack.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;
@RunWith(Theories.class)
public class FluencyTest
{
private static final Logger LOG = LoggerFactory.getLogger(FluencyTest.class);
private static final int SMALL_BUF_SIZE = 4 * 1024 * 1024;
private static final String TMPDIR = System.getProperty("java.io.tmpdir");
@DataPoints
public static final Options[] OPTIONS = {
new Options(false, false, false, false, false), // Normal
new Options(true, false, false, false, false), // Failover
new Options(false, true, false, true, false), // File backup + Ack response
new Options(false, false, true, false, false), // Close instead of flush
new Options(false, false, false, true, false), // Ack response
new Options(false, false, false, false, true), // Small buffer
new Options(true, false, false, false, true), // Failover + Small buffer
new Options(false, false, true, false, true), // Close instead of flush + Small buffer
new Options(false, false, false, true, true), // Ack response + Small buffer
new Options(true, false, true, false, false), // Failover + Close instead of flush
new Options(false, true, true, true, false), // File backup + Ack response + Close instead of flush
new Options(false, false, true, true, false) // Ack response + Close instead of flush
};
public static class Options
{
private final boolean failover;
private final boolean fileBackup;
private final boolean closeInsteadOfFlush;
private final boolean ackResponse;
private final boolean smallBuffer;
public Options(boolean failover, boolean fileBackup, boolean closeInsteadOfFlush, boolean ackResponse, boolean smallBuffer)
{
this.failover = failover;
this.fileBackup = fileBackup;
this.closeInsteadOfFlush = closeInsteadOfFlush;
this.ackResponse = ackResponse;
this.smallBuffer = smallBuffer;
}
@Override
public String toString()
{
return "Options{" +
"failover=" + failover +
", fileBackup=" + fileBackup +
", closeInsteadOfFlush=" + closeInsteadOfFlush +
", ackResponse=" + ackResponse +
", smallBuffer=" + smallBuffer +
'}';
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Options options = (Options) o;
if (failover != options.failover) {
return false;
}
if (fileBackup != options.fileBackup) {
return false;
}
if (closeInsteadOfFlush != options.closeInsteadOfFlush) {
return false;
}
if (ackResponse != options.ackResponse) {
return false;
}
return smallBuffer == options.smallBuffer;
}
@Override
public int hashCode()
{
int result = (failover ? 1 : 0);
result = 31 * result + (fileBackup ? 1 : 0);
result = 31 * result + (closeInsteadOfFlush ? 1 : 0);
result = 31 * result + (ackResponse ? 1 : 0);
result = 31 * result + (smallBuffer ? 1 : 0);
return result;
}
}
@Test
public void testDefaultFluency()
throws IOException
{
{
Fluency fluency = null;
try {
fluency = Fluency.defaultFluency();
assertThat(fluency.getBuffer(), instanceOf(PackedForwardBuffer.class));
PackedForwardBuffer buffer = (PackedForwardBuffer) fluency.getBuffer();
assertThat(buffer.getMaxBufferSize(), is(512 * 1024 * 1024L));
assertThat(buffer.getFileBackupDir(), is(nullValue()));
assertThat(buffer.bufferFormatType(), is("packed_forward"));
assertThat(buffer.getChunkExpandRatio(), is(2f));
assertThat(buffer.getChunkRetentionSize(), is(4 * 1024 * 1024));
assertThat(buffer.getChunkInitialSize(), is(1 * 1024 * 1024));
assertThat(buffer.getChunkRetentionTimeMillis(), is(400));
assertThat(buffer.isAckResponseMode(), is(false));
assertThat(fluency.getFlusher(), instanceOf(AsyncFlusher.class));
AsyncFlusher flusher = (AsyncFlusher) fluency.getFlusher();
assertThat(flusher.isTerminated(), is(false));
assertThat(flusher.getFlushIntervalMillis(), is(600));
assertThat(flusher.getWaitUntilBufferFlushed(), is(60));
assertThat(flusher.getWaitUntilTerminated(), is(60));
assertThat(flusher.getSender(), instanceOf(RetryableSender.class));
RetryableSender retryableSender = (RetryableSender) flusher.getSender();
assertThat(retryableSender.getRetryStrategy(), instanceOf(ExponentialBackOffRetryStrategy.class));
ExponentialBackOffRetryStrategy retryStrategy = (ExponentialBackOffRetryStrategy) retryableSender.getRetryStrategy();
assertThat(retryStrategy.getMaxRetryCount(), is(7));
assertThat(retryStrategy.getBaseIntervalMillis(), is(400));
assertThat(retryableSender.getBaseSender(), instanceOf(TCPSender.class));
TCPSender sender = (TCPSender) retryableSender.getBaseSender();
assertThat(sender.getHost(), is("127.0.0.1"));
assertThat(sender.getPort(), is(24224));
assertThat(sender.getConnectionTimeoutMilli(), is(5000));
assertThat(sender.getReadTimeoutMilli(), is(5000));
FailureDetector failureDetector = sender.getFailureDetector();
assertThat(failureDetector, is(nullValue()));
}
finally {
if (fluency != null) {
fluency.close();
}
}
}
{
Fluency.defaultFluency(12345).close();
Fluency.defaultFluency("333.333.333.333", 12345).close();
Fluency.defaultFluency(Arrays.asList(new InetSocketAddress(43210))).close();
Fluency.Config config = new Fluency.Config();
config.setFlushIntervalMillis(200).setMaxBufferSize(Long.MAX_VALUE).setSenderMaxRetryCount(99);
Fluency.defaultFluency(config).close();
Fluency.defaultFluency(12345, config).close();
Fluency.defaultFluency("333.333.333.333", 12345, config).close();
Fluency.defaultFluency(Arrays.asList(new InetSocketAddress(43210)), config).close();
}
{
Fluency fluency = null;
try {
String tmpdir = System.getProperty("java.io.tmpdir");
assertThat(tmpdir, is(notNullValue()));
Fluency.Config config =
new Fluency.Config()
.setFlushIntervalMillis(200)
.setMaxBufferSize(Long.MAX_VALUE)
.setBufferChunkInitialSize(7 * 1024 * 1024)
.setBufferChunkRetentionSize(13 * 1024 * 1024)
.setSenderMaxRetryCount(99)
.setAckResponseMode(true)
.setWaitUntilBufferFlushed(42)
.setWaitUntilFlusherTerminated(24)
.setFileBackupDir(tmpdir);
fluency = Fluency.defaultFluency(
Arrays.asList(
new InetSocketAddress("333.333.333.333", 11111),
new InetSocketAddress("444.444.444.444", 22222)), config);
assertThat(fluency.getBuffer(), instanceOf(PackedForwardBuffer.class));
PackedForwardBuffer buffer = (PackedForwardBuffer) fluency.getBuffer();
assertThat(buffer.getMaxBufferSize(), is(Long.MAX_VALUE));
assertThat(buffer.getFileBackupDir(), is(tmpdir));
assertThat(buffer.bufferFormatType(), is("packed_forward"));
assertThat(buffer.getChunkRetentionTimeMillis(), is(400));
assertThat(buffer.getChunkExpandRatio(), is(2f));
assertThat(buffer.getChunkInitialSize(), is(7 * 1024 * 1024));
assertThat(buffer.getChunkRetentionSize(), is(13 * 1024 * 1024));
assertThat(buffer.isAckResponseMode(), is(true));
assertThat(fluency.getFlusher(), instanceOf(AsyncFlusher.class));
AsyncFlusher flusher = (AsyncFlusher) fluency.getFlusher();
assertThat(flusher.isTerminated(), is(false));
assertThat(flusher.getFlushIntervalMillis(), is(200));
assertThat(flusher.getWaitUntilBufferFlushed(), is(42));
assertThat(flusher.getWaitUntilTerminated(), is(24));
assertThat(flusher.getSender(), instanceOf(RetryableSender.class));
RetryableSender retryableSender = (RetryableSender) flusher.getSender();
assertThat(retryableSender.getRetryStrategy(), instanceOf(ExponentialBackOffRetryStrategy.class));
ExponentialBackOffRetryStrategy retryStrategy = (ExponentialBackOffRetryStrategy) retryableSender.getRetryStrategy();
assertThat(retryStrategy.getMaxRetryCount(), is(99));
assertThat(retryStrategy.getBaseIntervalMillis(), is(400));
assertThat(retryableSender.getBaseSender(), instanceOf(MultiSender.class));
MultiSender multiSender = (MultiSender) retryableSender.getBaseSender();
assertThat(multiSender.getSenders().size(), is(2));
assertThat(multiSender.getSenders().get(0), instanceOf(TCPSender.class));
{
TCPSender sender = (TCPSender) multiSender.getSenders().get(0);
assertThat(sender.getHost(), is("333.333.333.333"));
assertThat(sender.getPort(), is(11111));
assertThat(sender.getConnectionTimeoutMilli(), is(5000));
assertThat(sender.getReadTimeoutMilli(), is(5000));
FailureDetector failureDetector = sender.getFailureDetector();
assertThat(failureDetector.getFailureIntervalMillis(), is(3 * 1000));
assertThat(failureDetector.getFailureDetectStrategy(), instanceOf(PhiAccrualFailureDetectStrategy.class));
assertThat(failureDetector.getHeartbeater(), instanceOf(TCPHeartbeater.class));
assertThat(failureDetector.getHeartbeater().getHost(), is("333.333.333.333"));
assertThat(failureDetector.getHeartbeater().getPort(), is(11111));
assertThat(failureDetector.getHeartbeater().getIntervalMillis(), is(1000));
}
{
TCPSender sender = (TCPSender) multiSender.getSenders().get(1);
assertThat(sender.getHost(), is("444.444.444.444"));
assertThat(sender.getPort(), is(22222));
assertThat(sender.getConnectionTimeoutMilli(), is(5000));
assertThat(sender.getReadTimeoutMilli(), is(5000));
FailureDetector failureDetector = sender.getFailureDetector();
assertThat(failureDetector.getFailureIntervalMillis(), is(3 * 1000));
assertThat(failureDetector.getFailureDetectStrategy(), instanceOf(PhiAccrualFailureDetectStrategy.class));
assertThat(failureDetector.getHeartbeater(), instanceOf(TCPHeartbeater.class));
assertThat(failureDetector.getHeartbeater().getHost(), is("444.444.444.444"));
assertThat(failureDetector.getHeartbeater().getPort(), is(22222));
assertThat(failureDetector.getHeartbeater().getIntervalMillis(), is(1000));
}
}
finally {
if (fluency != null) {
fluency.close();
}
}
}
}
@Test
public void testIsTerminated()
throws IOException, InterruptedException
{
Sender sender = new MockTCPSender(24224);
TestableBuffer.Config bufferConfig = new TestableBuffer.Config();
{
Flusher.Instantiator flusherConfig = new AsyncFlusher.Config();
Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
assertFalse(fluency.isTerminated());
fluency.close();
TimeUnit.SECONDS.sleep(1);
assertTrue(fluency.isTerminated());
}
{
Flusher.Instantiator flusherConfig = new SyncFlusher.Config();
Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
assertFalse(fluency.isTerminated());
fluency.close();
TimeUnit.SECONDS.sleep(1);
assertTrue(fluency.isTerminated());
}
}
@Test
public void testGetAllocatedBufferSize()
throws IOException
{
Fluency fluency = new Fluency.Builder(new MockTCPSender(24224)).
setBufferConfig(new TestableBuffer.Config()).
setFlusherConfig(new AsyncFlusher.Config()).
build();
assertThat(fluency.getAllocatedBufferSize(), is(0L));
Map<String, Object> map = new HashMap<String, Object>();
map.put("comment", "hello world");
for (int i = 0; i < 10000; i++) {
fluency.emit("foodb.bartbl", map);
}
assertThat(fluency.getAllocatedBufferSize(), is(TestableBuffer.ALLOC_SIZE * 10000L));
}
@Test
public void testWaitUntilFlusherTerminated()
throws IOException, InterruptedException
{
{
Sender sender = new MockTCPSender(24224);
TestableBuffer.Config bufferConfig = new TestableBuffer.Config().setWaitBeforeCloseMillis(2000);
AsyncFlusher.Config flusherConfig = new AsyncFlusher.Config().setWaitUntilTerminated(0);
Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
fluency.close();
assertThat(fluency.waitUntilFlusherTerminated(1), is(false));
}
{
Sender sender = new MockTCPSender(24224);
TestableBuffer.Config bufferConfig = new TestableBuffer.Config().setWaitBeforeCloseMillis(2000);
AsyncFlusher.Config flusherConfig = new AsyncFlusher.Config().setWaitUntilTerminated(0);
Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
fluency.close();
assertThat(fluency.waitUntilFlusherTerminated(3), is(true));
}
}
@Test
public void testWaitUntilFlushingAllBuffer()
throws IOException, InterruptedException
{
{
Sender sender = new MockTCPSender(24224);
TestableBuffer.Config bufferConfig = new TestableBuffer.Config();
Flusher.Instantiator flusherConfig = new AsyncFlusher.Config().setFlushIntervalMillis(2000);
Fluency fluency = null;
try {
fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
assertThat(fluency.waitUntilAllBufferFlushed(3), is(true));
}
finally {
if (fluency != null) {
fluency.close();
}
}
}
{
Sender sender = new MockTCPSender(24224);
TestableBuffer.Config bufferConfig = new TestableBuffer.Config();
Flusher.Instantiator flusherConfig = new AsyncFlusher.Config().setFlushIntervalMillis(2000);
Fluency fluency = null;
try {
fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
assertThat(fluency.waitUntilAllBufferFlushed(1), is(false));
}
finally {
if (fluency != null) {
fluency.close();
}
}
}
}
interface FluencyFactory
{
Fluency generate(List<Integer> localPort)
throws IOException;
}
private Sender getSingleTCPSender(int port)
{
return new TCPSender.Config().setPort(port).createInstance();
}
private Sender getDoubleTCPSender(int firstPort, int secondPort)
{
return new MultiSender.Config(
Arrays.<Sender.Instantiator>asList(
new TCPSender.Config()
.setPort(firstPort)
.setHeartbeaterConfig(new TCPHeartbeater.Config().setPort(firstPort)),
new TCPSender.Config()
.setPort(secondPort)
.setHeartbeaterConfig(new TCPHeartbeater.Config().setPort(secondPort))
)).createInstance();
}
@Theory
public void testFluencyUsingAsyncFlusher(final Options options)
throws Exception
{
testFluencyBase(new FluencyFactory()
{
@Override
public Fluency generate(List<Integer> localPorts)
throws IOException
{
Sender sender;
int fluentdPort = localPorts.get(0);
if (options.failover) {
int secondaryFluentdPort = localPorts.get(1);
sender = getDoubleTCPSender(fluentdPort, secondaryFluentdPort);
}
else {
sender = getSingleTCPSender(fluentdPort);
}
PackedForwardBuffer.Config bufferConfig = new PackedForwardBuffer.Config();
if (options.ackResponse) {
bufferConfig.setAckResponseMode(true);
}
if (options.smallBuffer) {
bufferConfig.setMaxBufferSize(SMALL_BUF_SIZE);
}
if (options.fileBackup) {
bufferConfig.setFileBackupDir(TMPDIR).setFileBackupPrefix("testFluencyUsingAsyncFlusher" + options.hashCode());
}
Flusher.Instantiator flusherConfig = new AsyncFlusher.Config();
return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
}
}, options);
}
@Theory
public void testFluencyUsingSyncFlusher(final Options options)
throws Exception
{
testFluencyBase(new FluencyFactory()
{
@Override
public Fluency generate(List<Integer> localPorts)
throws IOException
{
Sender sender;
int fluentdPort = localPorts.get(0);
if (options.failover) {
int secondaryFluentdPort = localPorts.get(1);
sender = getDoubleTCPSender(fluentdPort, secondaryFluentdPort);
}
else {
sender = getSingleTCPSender(fluentdPort);
}
PackedForwardBuffer.Config bufferConfig = new PackedForwardBuffer.Config();
if (options.ackResponse) {
bufferConfig.setAckResponseMode(true);
}
if (options.smallBuffer) {
bufferConfig.setMaxBufferSize(SMALL_BUF_SIZE);
}
if (options.fileBackup) {
bufferConfig.setFileBackupDir(TMPDIR).setFileBackupPrefix("testFluencyUsingSyncFlusher" + options.hashCode());
}
Flusher.Instantiator flusherConfig = new SyncFlusher.Config();
return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
}
}, options);
}
private void testFluencyBase(final FluencyFactory fluencyFactory, final Options options)
throws Exception
{
LOG.info("testFluencyBase starts: options={}", options);
final ArrayList<Integer> localPorts = new ArrayList<Integer>();
final MockFluentdServer fluentd = new MockFluentdServer();
fluentd.start();
final MockFluentdServer secondaryFluentd = new MockFluentdServer(fluentd);
secondaryFluentd.start();
TimeUnit.MILLISECONDS.sleep(200);
localPorts.add(fluentd.getLocalPort());
localPorts.add(secondaryFluentd.getLocalPort());
final AtomicReference<Fluency> fluency = new AtomicReference<Fluency>(fluencyFactory.generate(localPorts));
if (options.fileBackup) {
fluency.get().clearBackupFiles();
}
final int maxNameLen = 200;
final HashMap<Integer, String> nameLenTable = new HashMap<Integer, String>(maxNameLen);
for (int i = 1; i <= maxNameLen; i++) {
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < i; j++) {
stringBuilder.append('x');
}
nameLenTable.put(i, stringBuilder.toString());
}
final AtomicLong ageEventsSum = new AtomicLong();
final AtomicLong nameEventsLength = new AtomicLong();
final AtomicLong tag0EventsCounter = new AtomicLong();
final AtomicLong tag1EventsCounter = new AtomicLong();
final AtomicLong tag2EventsCounter = new AtomicLong();
final AtomicLong tag3EventsCounter = new AtomicLong();
try {
final Random random = new Random();
int concurrency = 10;
final int reqNum = 6000;
long start = System.currentTimeMillis();
final CountDownLatch latch = new CountDownLatch(concurrency);
final AtomicBoolean shouldFailOver = new AtomicBoolean(true);
final AtomicBoolean shouldStopFluentd = new AtomicBoolean(true);
final AtomicBoolean shouldStopFluency = new AtomicBoolean(true);
final CountDownLatch fluentdCloseWaitLatch = new CountDownLatch(concurrency);
final CountDownLatch fluencyCloseWaitLatch = new CountDownLatch(concurrency);
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < concurrency; i++) {
es.execute(new Runnable()
{
@Override
public void run()
{
for (int i = 0; i < reqNum; i++) {
if (Thread.currentThread().isInterrupted()) {
LOG.info("Interrupted...");
break;
}
if (options.failover) {
if (i == reqNum / 2) {
if (shouldFailOver.getAndSet(false)) {
LOG.info("Failing over...");
try {
secondaryFluentd.stop();
}
catch (IOException e) {
LOG.warn("Failed to stop secondary fluentd", e);
}
}
}
}
else if (options.fileBackup) {
if (i == reqNum / 2) {
if (shouldStopFluentd.getAndSet(false)) {
LOG.info("Stopping Fluentd...");
try {
fluentd.stop();
secondaryFluentd.stop();
}
catch (IOException e) {
LOG.warn("Failed to stop Fluentd", e);
}
}
fluentdCloseWaitLatch.countDown();
try {
assertTrue(fluentdCloseWaitLatch.await(20, TimeUnit.SECONDS));
}
catch (InterruptedException e) {
LOG.warn("Interrupted", e);
}
if (shouldStopFluency.getAndSet(false)) {
LOG.info("Stopping Fluency...");
try {
fluency.get().close();
TimeUnit.SECONDS.sleep(2);
}
catch (Exception e) {
LOG.warn("Failed to stop Fluency", e);
}
LOG.info("Restarting Fluentd...");
try {
fluentd.start();
secondaryFluentd.start();
TimeUnit.MILLISECONDS.sleep(200);
LOG.info("Restarting Fluency...");
fluency.set(fluencyFactory.generate(Arrays.asList(fluentd.getLocalPort(), secondaryFluentd.getLocalPort())));
TimeUnit.SECONDS.sleep(2);
}
catch (Exception e) {
LOG.warn("Failed to restart Fluentd", e);
}
}
fluencyCloseWaitLatch.countDown();
try {
assertTrue(fluencyCloseWaitLatch.await(20, TimeUnit.SECONDS));
}
catch (InterruptedException e) {
LOG.warn("Interrupted", e);
}
}
}
int tagNum = i % 4;
final String tag = String.format("foodb%d.bartbl%d", tagNum, tagNum);
switch (tagNum) {
case 0:
tag0EventsCounter.incrementAndGet();
break;
case 1:
tag1EventsCounter.incrementAndGet();
break;
case 2:
tag2EventsCounter.incrementAndGet();
break;
case 3:
tag3EventsCounter.incrementAndGet();
break;
default:
throw new RuntimeException("Never reach here");
}
int rand = random.nextInt(maxNameLen);
final Map<String, Object> hashMap = new HashMap<String, Object>();
String name = nameLenTable.get(rand + 1);
nameEventsLength.addAndGet(name.length());
hashMap.put("name", name);
rand = random.nextInt(100);
int age = rand;
ageEventsSum.addAndGet(age);
hashMap.put("age", age);
hashMap.put("comment", "hello, world");
hashMap.put("rate", 1.23);
try {
Exception exception = null;
for (int retry = 0; retry < 10; retry++) {
try {
fluency.get().emit(tag, hashMap);
exception = null;
break;
}
catch (Exception e) {
exception = e;
try {
TimeUnit.SECONDS.sleep(1);
}
catch (InterruptedException e1) {
}
}
}
if (exception != null) {
throw exception;
}
}
catch (Exception e) {
LOG.warn("Exception occurred", e);
}
}
latch.countDown();
}
});
}
for (int i = 0; i < 60; i++) {
if (latch.await(1, TimeUnit.SECONDS)) {
break;
}
}
assertEquals(0, latch.getCount());
if (options.closeInsteadOfFlush) {
fluency.get().close();
}
else {
fluency.get().flush();
fluency.get().waitUntilAllBufferFlushed(20);
}
fluentd.stop();
secondaryFluentd.stop();
TimeUnit.MILLISECONDS.sleep(1000);
if (options.failover) {
assertThat(fluentd.connectCounter.get(), is(greaterThan(0L)));
assertThat(fluentd.connectCounter.get(), is(lessThanOrEqualTo(10L)));
assertThat(fluentd.closeCounter.get(), is(greaterThan(0L)));
assertThat(fluentd.closeCounter.get(), is(lessThanOrEqualTo(10L)));
}
else {
assertThat(fluentd.connectCounter.get(), is(greaterThan(0L)));
assertThat(fluentd.connectCounter.get(), is(lessThanOrEqualTo(2L)));
assertThat(fluentd.closeCounter.get(), is(greaterThan(0L)));
assertThat(fluentd.closeCounter.get(), is(lessThanOrEqualTo(2L)));
}
assertEquals((long) concurrency * reqNum, fluentd.ageEventsCounter.get());
assertEquals(ageEventsSum.get(), fluentd.ageEventsSum.get());
assertEquals((long) concurrency * reqNum, fluentd.nameEventsCounter.get());
assertEquals(nameEventsLength.get(), fluentd.nameEventsLength.get());
assertEquals(tag0EventsCounter.get(), fluentd.tag0EventsCounter.get());
assertEquals(tag1EventsCounter.get(), fluentd.tag1EventsCounter.get());
assertEquals(tag2EventsCounter.get(), fluentd.tag2EventsCounter.get());
assertEquals(tag3EventsCounter.get(), fluentd.tag3EventsCounter.get());
System.out.println(System.currentTimeMillis() - start);
}
finally {
fluency.get().close();
fluentd.stop();
secondaryFluentd.stop();
}
}
private static class MockFluentdServer
extends AbstractFluentdServer
{
private final AtomicLong connectCounter;
private final AtomicLong ageEventsCounter;
private final AtomicLong ageEventsSum;
private final AtomicLong nameEventsCounter;
private final AtomicLong nameEventsLength;
private final AtomicLong tag0EventsCounter;
private final AtomicLong tag1EventsCounter;
private final AtomicLong tag2EventsCounter;
private final AtomicLong tag3EventsCounter;
private final AtomicLong closeCounter;
private final long startTimestamp;
public MockFluentdServer()
throws IOException
{
connectCounter = new AtomicLong();
ageEventsCounter = new AtomicLong();
ageEventsSum = new AtomicLong();
nameEventsCounter = new AtomicLong();
nameEventsLength = new AtomicLong();
tag0EventsCounter = new AtomicLong();
tag1EventsCounter = new AtomicLong();
tag2EventsCounter = new AtomicLong();
tag3EventsCounter = new AtomicLong();
closeCounter = new AtomicLong();
startTimestamp = System.currentTimeMillis() / 1000;
}
public MockFluentdServer(MockFluentdServer base)
throws IOException
{
connectCounter = base.connectCounter;
ageEventsCounter = base.ageEventsCounter;
ageEventsSum = base.ageEventsSum;
nameEventsCounter = base.nameEventsCounter;
nameEventsLength = base.nameEventsLength;
tag0EventsCounter = base.tag0EventsCounter;
tag1EventsCounter = base.tag1EventsCounter;
tag2EventsCounter = base.tag2EventsCounter;
tag3EventsCounter = base.tag3EventsCounter;
closeCounter = base.closeCounter;
startTimestamp = System.currentTimeMillis() / 1000;
}
@Override
protected EventHandler getFluentdEventHandler()
{
return new EventHandler()
{
@Override
public void onConnect(SocketChannel accpetSocketChannel)
{
connectCounter.incrementAndGet();
}
@Override
public void onReceive(String tag, long timestampMillis, MapValue data)
{
if (tag.equals("foodb0.bartbl0")) {
tag0EventsCounter.incrementAndGet();
}
else if (tag.equals("foodb1.bartbl1")) {
tag1EventsCounter.incrementAndGet();
}
else if (tag.equals("foodb2.bartbl2")) {
tag2EventsCounter.incrementAndGet();
}
else if (tag.equals("foodb3.bartbl3")) {
tag3EventsCounter.incrementAndGet();
}
else {
throw new IllegalArgumentException("Unexpected tag: tag=" + tag);
}
assertTrue(startTimestamp <= timestampMillis && timestampMillis < startTimestamp + 60 * 1000);
assertEquals(4, data.size());
for (Map.Entry<Value, Value> kv : data.entrySet()) {
String key = kv.getKey().asStringValue().toString();
Value val = kv.getValue();
if (key.equals("comment")) {
assertEquals("hello, world", val.toString());
}
else if (key.equals("rate")) {
assertEquals(1.23, val.asFloatValue().toFloat(), 0.000001);
}
else if (key.equals("name")) {
nameEventsCounter.incrementAndGet();
nameEventsLength.addAndGet(val.asRawValue().asString().length());
}
else if (key.equals("age")) {
ageEventsCounter.incrementAndGet();
ageEventsSum.addAndGet(val.asIntegerValue().asInt());
}
}
}
@Override
public void onClose(SocketChannel accpetSocketChannel)
{
closeCounter.incrementAndGet();
}
};
}
}
private static class EmitTask
implements Callable<Void>
{
private final Fluency fluency;
private final String tag;
private final Map<String, Object> data;
private final int count;
private EmitTask(Fluency fluency, String tag, Map<String, Object> data, int count)
{
this.fluency = fluency;
this.tag = tag;
this.data = data;
this.count = count;
}
@Override
public Void call()
{
for (int i = 0; i < count; i++) {
try {
fluency.emit(tag, data);
}
catch (IOException e) {
e.printStackTrace();
try {
TimeUnit.MILLISECONDS.sleep(500);
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return null;
}
}
private static class StuckSender
extends StubSender
{
private final CountDownLatch latch;
public StuckSender(CountDownLatch latch)
{
this.latch = latch;
}
@Override
public void send(ByteBuffer data)
throws IOException
{
try {
latch.await();
}
catch (InterruptedException e) {
FluencyTest.LOG.warn("Interrupted in send()", e);
}
}
@Override
public boolean isAvailable()
{
return true;
}
}
@Test
public void testBufferFullException()
throws IOException
{
final CountDownLatch latch = new CountDownLatch(1);
Sender stuckSender = new StuckSender(latch);
try {
PackedForwardBuffer.Config bufferConfig = new PackedForwardBuffer.Config().setChunkInitialSize(64).setMaxBufferSize(256);
Fluency fluency = new Fluency.Builder(stuckSender).setBufferConfig(bufferConfig).build();
Map<String, Object> event = new HashMap<String, Object>();
event.put("name", "xxxx");
for (int i = 0; i < 7; i++) {
fluency.emit("tag", event);
}
try {
fluency.emit("tag", event);
assertTrue(false);
}
catch (BufferFullException e) {
assertTrue(true);
}
}
finally {
latch.countDown();
}
}
public static class Foo {
public String s;
}
public static class FooSerializer extends StdSerializer<Foo> {
public final AtomicBoolean serialized;
protected FooSerializer(AtomicBoolean serialized)
{
super(Foo.class);
this.serialized = serialized;
}
@Override
public void serialize(Foo value, JsonGenerator gen, SerializerProvider provider)
throws IOException
{
gen.writeStartObject();
gen.writeStringField("s", "Foo:" + value.s);
gen.writeEndObject();
serialized.set(true);
}
}
@Test
public void testBufferWithJacksonModule()
throws IOException
{
AtomicBoolean serialized = new AtomicBoolean();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Foo.class, new FooSerializer(serialized));
PackedForwardBuffer.Config bufferConfig = new PackedForwardBuffer
.Config()
.setChunkInitialSize(64)
.setMaxBufferSize(256)
.setJacksonModules(Collections.<Module>singletonList(simpleModule));
Fluency fluency = new Fluency.Builder(new TCPSender.Config()
.createInstance())
.setBufferConfig(bufferConfig)
.build();
Map<String, Object> event = new HashMap<String, Object>();
Foo foo = new Foo();
foo.s = "Hello";
event.put("foo", foo);
fluency.emit("tag", event);
assertThat(serialized.get(), is(true));
}
// @Test
public void testWithRealFluentd()
throws Exception
{
int concurrency = 4;
int reqNum = 1000000;
Fluency fluency = Fluency.defaultFluency();
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("name", "komamitsu");
data.put("age", 42);
data.put("comment", "hello, world");
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<Void>> futures = new ArrayList<Future<Void>>();
try {
for (int i = 0; i < concurrency; i++) {
futures.add(executorService.submit(new EmitTask(fluency, "foodb.bartbl", data, reqNum)));
}
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
}
finally {
fluency.close();
}
}
// @Test
public void testWithRealMultipleFluentd()
throws IOException, InterruptedException, TimeoutException, ExecutionException
{
int concurrency = 4;
int reqNum = 1000000;
/*
MultiSender sender = new MultiSender(Arrays.asList(new TCPSender(24224), new TCPSender(24225)));
Buffer.Config bufferConfig = new PackedForwardBuffer.Config().setMaxBufferSize(128 * 1024 * 1024).setAckResponseMode(true);
Flusher.Config flusherConfig = new AsyncFlusher.Config().setFlushIntervalMillis(200);
Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
*/
Fluency fluency = Fluency.defaultFluency(
Arrays.asList(new InetSocketAddress(24224), new InetSocketAddress(24225)),
new Fluency.Config().setAckResponseMode(true));
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("name", "komamitsu");
data.put("age", 42);
data.put("comment", "hello, world");
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<Void>> futures = new ArrayList<Future<Void>>();
try {
for (int i = 0; i < concurrency; i++) {
futures.add(executorService.submit(new EmitTask(fluency, "foodb.bartbl", data, reqNum)));
}
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
}
finally {
fluency.close();
}
}
// @Test
public void testWithRealFluentdWithFileBackup()
throws ExecutionException, TimeoutException, IOException, InterruptedException
{
int concurrency = 4;
int reqNum = 1000000;
Fluency fluency = Fluency.defaultFluency(
new Fluency.Config()
// Fluency might use a lot of buffer for loaded backup files.
// So it'd better increase max buffer size
.setMaxBufferSize(512 * 1024 * 1024L)
.setFileBackupDir(System.getProperty("java.io.tmpdir")));
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("name", "komamitsu");
data.put("age", 42);
data.put("comment", "hello, world");
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<Void>> futures = new ArrayList<Future<Void>>();
try {
for (int i = 0; i < concurrency; i++) {
futures.add(executorService.submit(new EmitTask(fluency, "foodb.bartbl", data, reqNum)));
}
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
}
finally {
fluency.close();
}
}
}
|
package org.mvel2.tests.core;
import org.mvel2.MVEL;
import java.util.HashMap;
/**
* Tests to ensure MVEL fails when it should.
*/
public class FailureTests extends AbstractTest {
public void testBadParserConstruct() {
try {
test("a = 0; a =+++ 5;");
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail() {
try {
MVEL.eval("i = 0; i < 99 dksadlka", new HashMap());
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail2() {
try {
MVEL.compileExpression("i = 0; i < 99 dksadlka");
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail3() {
try {
MVEL.compileExpression("def foo() { 'bar' }; foo(123);");
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail4() {
try {
MVEL.eval("hour zzz", createTestMap());
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail5() {
try {
MVEL.eval("[");
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testShouldFail6() {
try {
MVEL.eval("new int[] {1.5}");
}
catch (Exception e) {
return;
}
assertTrue(false);
}
}
|
package org.oakgp.util;
import static org.junit.Assert.assertEquals;
import static org.oakgp.TestUtils.createConstant;
import static org.oakgp.TestUtils.createVariable;
import static org.oakgp.TestUtils.readNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.oakgp.node.Node;
public class NodeComparatorTest {
private static final NodeComparator COMPARATOR = new NodeComparator();
@Test
public void testCompareVariables() {
assertOrdered(createVariable(0), createVariable(1));
}
@Test
public void testCompareConstants() {
assertOrdered(createConstant(3), createConstant(7));
}
@Test
public void testCompareFunctions() {
// ordering of function nodes is a bit arbitrary (relies on hashCode of Operator class name and arguments)
// the important thing is that it is consistent
assertOrdered(readNode("(- 1 1)"), readNode("(+ 1 1)"));
assertOrdered(readNode("(* 3 3)"), readNode("(* 3 4)"));
}
@Test
public void testCompareConstantsToVariables() {
assertOrdered(createConstant(7), createVariable(3));
assertOrdered(createConstant(3), createVariable(7));
}
@Test
public void testCompareConstantsToFunctions() {
assertOrdered(createConstant(7), readNode("(+ 1 1)"));
}
@Test
public void testCompareVariablesToFunctions() {
assertOrdered(createVariable(7), readNode("(+ 1 1)"));
}
private void assertOrdered(Node n1, Node n2) {
assertEquals(0, COMPARATOR.compare(n1, n1));
assertEquals(-1, COMPARATOR.compare(n1, n2));
assertEquals(1, COMPARATOR.compare(n2, n1));
}
@Test
public void testSort() {
Node f1 = readNode("(+ 1 1)");
Node f2 = readNode("(- 1 1)");
Node f3 = readNode("(* 1 1)");
List<Node> nodes = new ArrayList<>();
nodes.add(f1);
nodes.add(f2);
nodes.add(readNode("-1"));
nodes.add(readNode("v1"));
nodes.add(readNode("3"));
nodes.add(f3);
nodes.add(readNode("v0"));
Collections.sort(nodes, COMPARATOR);
assertEquals("-1", nodes.get(0).toString());
assertEquals("3", nodes.get(1).toString());
assertEquals("v0", nodes.get(2).toString());
assertEquals("v1", nodes.get(3).toString());
assertEquals(f2, nodes.get(4));
assertEquals(f3, nodes.get(5));
assertEquals(f1, nodes.get(6));
}
}
|
package org.takes.facets.auth;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang.RandomStringUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.HttpException;
import org.takes.facets.forward.RsForward;
import org.takes.misc.Opt;
import org.takes.rq.RqFake;
import org.takes.rq.RqMethod;
import org.takes.rq.RqWithHeaders;
import org.takes.rs.RsPrint;
/**
* Test of {@link PsBasic}.
* @author Endrigo Antonini (teamed@endrigo.com.br)
* @version $Id$
* @since 0.20
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class PsBasicTest {
/**
* Basic Auth.
*/
private static final String AUTH_BASIC = "Authorization: Basic %s";
/**
* Valid code parameter.
*/
private static final String VALID_CODE = "?valid_code=%s";
/**
* PsBasic can handle connection with valid credential.
* @throws Exception if any error occurs
*/
@Test
public void handleConnectionWithValidCredential() throws Exception {
final String user = "john";
final Opt<Identity> identity = new PsBasic(
"RealmA",
new PsBasic.Fake(true)
).enter(
new RqWithHeaders(
new RqFake(
RqMethod.GET,
String.format(
PsBasicTest.VALID_CODE,
// @checkstyle MagicNumberCheck (1 line)
RandomStringUtils.randomAlphanumeric(10)
)
),
this.generateAuthenticateHead(user, "pass")
)
);
MatcherAssert.assertThat(identity.has(), Matchers.is(true));
MatcherAssert.assertThat(
identity.get().urn(),
CoreMatchers.equalTo(this.generateIdentityUrn(user))
);
}
/**
* PsBasic can handle connection with valid credential when.
* @throws Exception if any error occurs
*/
@Test
public void handleConnectionWithValidCredentialDefaultEntry()
throws Exception {
final String user = "johny";
final String password = "password2";
final Opt<Identity> identity = new PsBasic(
"RealmAA",
new PsBasic.Default(
"mike my%20password1 urn:basic:michael",
String.format("%s %s urn:basic:%s", user, password, user)
)
).enter(
new RqWithHeaders(
new RqFake(
RqMethod.GET,
String.format(
PsBasicTest.VALID_CODE,
// @checkstyle MagicNumberCheck (1 line)
RandomStringUtils.randomAlphanumeric(10)
)
),
this.generateAuthenticateHead(user, password)
)
);
MatcherAssert.assertThat(identity.has(), Matchers.is(true));
MatcherAssert.assertThat(
identity.get().urn(),
CoreMatchers.equalTo(this.generateIdentityUrn(user))
);
}
/**
* PsBasic can handle connection with invalid credential.
* @throws Exception If some problem inside
*/
@Test
public void handleConnectionWithInvalidCredential() throws Exception {
RsForward forward = new RsForward();
try {
new PsBasic(
"RealmB",
new PsBasic.Empty()
).enter(
new RqWithHeaders(
new RqFake(
RqMethod.GET,
String.format(
"?invalid_code=%s",
// @checkstyle MagicNumberCheck (1 line)
RandomStringUtils.randomAlphanumeric(10)
)
),
this.generateAuthenticateHead("username", "wrong")
)
);
} catch (final RsForward ex) {
forward = ex;
}
MatcherAssert.assertThat(
new RsPrint(forward).printHead(),
Matchers.allOf(
Matchers.containsString("HTTP/1.1 401 Unauthorized"),
Matchers.containsString(
"WWW-Authenticate: Basic ream=\"RealmB\""
)
)
);
}
/**
* PsBasic can handle multiple headers with valid credential.
* @throws Exception If some problem inside
*/
@Test
public void handleMultipleHeadersWithValidCredential() throws Exception {
final String user = "bill";
final Opt<Identity> identity = new PsBasic(
"RealmC",
new PsBasic.Fake(true)
).enter(
new RqWithHeaders(
new RqFake(
RqMethod.GET,
String.format(
"?multiple_code=%s",
// @checkstyle MagicNumberCheck (1 line)
RandomStringUtils.randomAlphanumeric(10)
)
),
this.generateAuthenticateHead(user, "changeit"),
"Referer: http://teamed.io/",
"Connection:keep-alive",
"Content-Encoding:gzip",
"X-Check-Cacheable:YES",
"X-Powered-By:Java/1.7"
)
);
MatcherAssert.assertThat(identity.has(), Matchers.is(true));
MatcherAssert.assertThat(
identity.get().urn(),
CoreMatchers.equalTo(this.generateIdentityUrn(user))
);
}
/**
* PsBasic can handle multiple headers with invalid content.
* @throws Exception If some problem inside
*/
@Test(expected = HttpException.class)
public void handleMultipleHeadersWithInvalidContent() throws Exception {
MatcherAssert.assertThat(
new PsBasic(
"RealmD",
new PsBasic.Fake(true)
).enter(
new RqWithHeaders(
new RqFake(
"XPTO",
"/wrong-url"
),
String.format(
"XYZ%s",
this.generateAuthenticateHead("user", "password")
),
"XYZReferer: http://teamed.io/",
"XYZConnection:keep-alive",
"XYZContent-Encoding:gzip",
"XYZX-Check-Cacheable:YES",
"XYZX-Powered-By:Java/1.7"
)
).has(),
Matchers.is(false)
);
}
/**
* Generate the identity urn.
* @param user User
* @return URN
*/
private String generateIdentityUrn(final String user) {
return String.format("urn:basic:%s", user);
}
/**
* Generate the string used on the request that store information about
* authentication.
* @param user Username
* @param pass Password
* @return Header string.
*/
private String generateAuthenticateHead(
final String user,
final String pass
) {
final String auth = String.format("%s:%s", user, pass);
final String encoded = DatatypeConverter.printBase64Binary(
auth.getBytes()
);
return String.format(PsBasicTest.AUTH_BASIC, encoded);
}
}
|
package tigase.db.jdbc;
import tigase.db.DBInitException;
import tigase.db.RepositoryFactory;
import tigase.db.TigaseDBException;
import tigase.db.UserExistsException;
import tigase.db.UserRepository;
import tigase.xmpp.BareJID;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.*;
/**
*
* @author Wojtek
*/
public class JDBCRepositoryTest {
UserRepository repo = null;
boolean initialised = false;
public JDBCRepositoryTest() {
}
@Before
public void setUp() {
HashMap map = new LinkedHashMap();
map.put( RepositoryFactory.DATA_REPO_POOL_SIZE_PROP_KEY, "2");
String repositoryURI = null;
// repositoryURI = "jdbc:mysql://localhost:3306/tigasedb?user=tigase&password=tigase&useUnicode=true&characterEncoding=UTF-8&autoCreateUser=true";
// repositoryURI = "jdbc:jtds:sqlserver://sqlserverhost:1433;databaseName=tigasedb;user=tigase;password=mypass;schema=dbo;lastUpdateCount=false;autoCreateUser=true";
// repositoryURI = "jdbc:sqlserver://sqlserverhost:1433;databaseName=tigasedb;user=tigase;password=mypass;schema=dbo;lastUpdateCount=false;autoCreateUser=true";
// repositoryURI = "jdbc:postgresql://localhost/tigasedb?user=tigase&password=tigase&useUnicode=true&characterEncoding=UTF-8&autoCreateUser=true";
// repositoryURI = "jdbc:derby:/Users/wojtek/dev/tigase/tigase-server/derbyDb";
// repositoryURI = "mongodb://localhost/tigase_test?autoCreateUser=true";
Assume.assumeNotNull(repositoryURI);
repo = new JDBCRepository();
try {
repo.initRepository( repositoryURI, map );
initialised = true;
} catch ( DBInitException ex ) {
Logger.getLogger( JDBCRepositoryTest.class.getName() ).log( Level.SEVERE, "db initialisation failed", ex );
}
Assume.assumeTrue(initialised);
}
private void getData( BareJID user ) {
if ( user == null ){
user = BareJID.bareJIDInstanceNS( "user", "domain" );
}
System.out.println( "retrieve: " + user + " / thread: " + Thread.currentThread().getName() );
try {
// repo.getData( user, "privacy", "default-list", null );
repo.addUser( user );
} catch ( UserExistsException ex ) {
System.out.println( "User exists, ignore: " + ex.getUserId() );
} catch ( TigaseDBException ex ) {
Logger.getLogger( JDBCRepositoryTest.class.getName() ).log( Level.SEVERE, null, ex );
}
}
@Test
public void testLongNode() throws InterruptedException, TigaseDBException {
BareJID user = BareJID.bareJIDInstanceNS( "user", "domain" );
repo.setData( user, "node1/node2/node3", "key", "value" );
String node3val;
node3val = repo.getData( user, "node1/node2/node3", "key" );
Assert.assertEquals("String differ from expected!", "value", node3val);
repo.removeSubnode( user, "node1" );
node3val = repo.getData( user, "node1/node2/node3", "key" );
Assert.assertNull( "Node not removed", node3val );
}
@Test
public void testGetData() throws InterruptedException {
System.out.println( "repo: " + repo );
if ( repo != null ){
LocalDateTime localNow = LocalDateTime.now();
// getData( null );
long initalDelay = 5;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 10 );
final int iter = 50;
final int threads = 10;
for ( int i = 0 ; i < threads ; i++ ) {
scheduler.scheduleAtFixedRate( new RunnableImpl( iter ), initalDelay, 100, TimeUnit.MILLISECONDS );
}
Thread.sleep( threads * 1000 );
}
}
private class RunnableImpl implements Runnable {
int count = 0;
int max = 50;
public RunnableImpl(int max) {
this.max = max;
}
@Override
public void run() {
while ( count < max ) {
count++;
BareJID user;
user = BareJID.bareJIDInstanceNS( String.valueOf( ( new Date() ).getTime() / 10 ), "domain" );
getData( user );
}
}
}
}
|
package tv.ustream.yolo.io;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileWriter;
/**
* @author bandesz
*/
public class TailerFileTest
{
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
private File testFile;
private long originalLastModified;
@Before
public void setUp() throws Exception
{
testFile = tmpFolder.newFile();
FileWriter out = new FileWriter(testFile);
out.write(String.format("content"));
out.close();
testFile.setLastModified(System.currentTimeMillis() - 10000);
originalLastModified = testFile.lastModified();
}
@Test
public void lastModifiedShouldReturnLastModified()
{
TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());
Assert.assertEquals(originalLastModified, tailerFile.lastModified());
}
@Test
public void lastModifiedShouldReturnNewLastModifiedWhenFileChanged() throws Exception
{
TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());
FileWriter out = new FileWriter(testFile);
out.write(String.format("content2"));
out.close();
Assert.assertEquals(testFile.lastModified(), tailerFile.lastModified());
}
@Test
public void lastModifiedShouldReturnSameWhenFileSizeNotChanged() throws Exception
{
TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());
testFile.setLastModified(System.currentTimeMillis());
Assert.assertEquals(originalLastModified, tailerFile.lastModified());
}
@Test
public void createShouldHandleSameFile()
{
TailerFile tailerFile = TailerFile.create(testFile);
Assert.assertEquals(testFile.getAbsolutePath(), tailerFile.getAbsolutePath());
}
}
|
package org.apache.commons.collections;
import junit.framework.*;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Tests base {@link java.util.Map} methods and contracts.
* <p>
* To use, simply extend this class, and implement
* the {@link #makeMap} method.
* <p>
* If your {@link Map} fails one of these tests by design,
* you may still use this base set of cases. Simply override the
* test case (method) your {@link Map} fails.
*
* @author Rodney Waldhoff
* @version $Id: TestMap.java,v 1.6 2002/02/21 20:08:15 morgand Exp $
*/
public abstract class TestMap extends TestObject {
public TestMap(String testName) {
super(testName);
}
/**
* Return a new, empty {@link Map} to used for testing.
*/
public abstract Map makeMap();
public Object makeObject() {
return makeMap();
}
protected Object tryToPut(Map map, Object key, Object val) {
try {
return map.put(key,val);
} catch(UnsupportedOperationException e) {
return null;
} catch(ClassCastException e) {
return null;
} catch(IllegalArgumentException e) {
return null;
} catch(NullPointerException e) {
return null;
} catch(Throwable t) {
t.printStackTrace();
fail("Map.put should only throw UnsupportedOperationException, ClassCastException, IllegalArgumentException or NullPointerException. Found " + t.toString());
return null; // never get here, since fail throws exception
}
}
/*
public void testMapContainsKey() {
// XXX finish me
}
public void testMapContainsValue() {
// XXX finish me
}
public void testMapEntrySet() {
// XXX finish me
}
public void testMapEquals() {
// XXX finish me
}
public void testMapGet() {
// XXX finish me
}
public void testMapHashCode() {
// XXX finish me
}
public void testMapIsEmpty() {
// XXX finish me
}
public void testMapKeySet() {
// XXX finish me
}
*/
public void testMapSupportsNullValues() {
if ((this instanceof TestMap.SupportsPut) == false) {
return;
}
Map map = makeMap();
map.put(new Integer(1),"foo");
assertTrue("no null values in Map",map.containsValue(null) == false);
map.put(new Integer(2),null);
assertTrue("null value in Map",map.containsValue(null));
assertTrue("key to a null value",map.containsKey(new Integer(2)));
}
public void testMultiplePuts() {
if ((this instanceof TestMap.SupportsPut) == false) {
return;
}
Map map = makeMap();
map.put(new Integer(4),"foo");
map.put(new Integer(4),"bar");
map.put(new Integer(4),"foo");
map.put(new Integer(4),"bar");
assertTrue("same key different value",map.get(new Integer(4)).equals("bar"));
}
public void testCapacity() {
if ((this instanceof TestMap.SupportsPut) == false) {
return;
}
Map map = makeMap();
map.put(new Integer(1),"foo");
map.put(new Integer(2),"foo");
map.put(new Integer(3),"foo");
map.put(new Integer(1),"foo");
assertTrue("size of Map should be 3, but was " + map.size(), map.size() == 3);
}
public void testEntrySetRemove() {
if ((this instanceof TestMap.EntrySetSupportsRemove) == false ||
(this instanceof TestMap.SupportsPut) == false) {
return;
}
Map map = makeMap();
map.put("1","1");
map.put("2","2");
map.put("3","3");
Object o = map.entrySet().iterator().next();
// remove one of the key/value pairs
Set set = map.entrySet();
set.remove(o);
assertTrue(set.size() == 2);
// try to remove it again, to make sure
// the Set is not confused by missing entries
set.remove(o);
assertTrue("size of Map should be 2, but was " + map.size(), map.size() == 2);
}
public void testEntrySetContains() {
if ((this instanceof TestMap.SupportsPut) == false) {
return;
}
Map map = makeMap();
map.put("1","1");
map.put("2","2");
map.put("3","3");
Set set = map.entrySet();
Object o = set.iterator().next();
assertTrue("entry set should contain valid element",set.contains(o));
// make a bogus entry
DefaultMapEntry entry = new DefaultMapEntry("4","4");
assertTrue("entry set should not contain a bogus element",
set.contains(entry) == false);
}
/*
// optional operation
public void testMapClear() {
// XXX finish me
}
// optional operation
public void testMapPut() {
// XXX finish me
}
// optional operation
public void testMapPutAll() {
// XXX finish me
}
// optional operation
public void testMapRemove() {
// XXX finish me
}
public void testMapSize() {
// XXX finish me
}
public void testMapValues() {
// XXX finish me
}
*/
/**
* Marker interface, indicating that a TestMap subclass
* can test put(Object,Object) operations.
*/
public interface SupportsPut {
}
public interface EntrySetSupportsRemove {
}
}
|
package org.jdesktop.swingx;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class JXLabel2VisualTest extends InteractiveTestCase {
public static void main(String[] args) throws Exception {
// setSystemLF(true);
JXLabel2VisualTest test = new JXLabel2VisualTest();
try {
test.runInteractiveTests();
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* #swingx-680 Preferred size is not set when label is rotated.
*/
public static void interactiveJXLabel() {
JFrame testFrame = new JFrame("JXLabel Test");
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JXLabel label = new JXLabel("This is some JXLabel text");
label.setTextRotation(Math.PI/4);
testFrame.setContentPane(label);
testFrame.pack();
testFrame.setLocationByPlatform(true);
testFrame.setVisible(true);
}
}
|
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.decorator.AlternateRowHighlighter;
import org.jdesktop.swingx.decorator.Filter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PatternFilter;
import org.jdesktop.swingx.decorator.PatternHighlighter;
import org.jdesktop.swingx.decorator.RolloverHighlighter;
import org.jdesktop.swingx.decorator.ShuttleSorter;
import org.jdesktop.swingx.table.ColumnHeaderRenderer;
import org.jdesktop.swingx.table.DefaultTableColumnModelExt;
import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.util.AncientSwingTeam;
/**
* Split from old JXTableUnitTest - contains "interactive"
* methods only.
*
* @author Jeanette Winzenburg
*/
public class JXTableVisualCheck extends JXTableUnitTest {
public static void main(String args[]) {
// setSystemLF(true);
JXTableVisualCheck test = new JXTableVisualCheck();
try {
// test.runInteractiveTests();
// test.runInteractiveTests("interactive.*ColumnControlColumnModel.*");
// test.runInteractiveTests("interactive.*TableHeader.*");
// test.runInteractiveTests("interactive.*Sort.*");
// test.runInteractiveTests("interactive.*RToL.*");
// test.runInteractiveTests("interactive.*RowHeight.*");
// test.runInteractiveTests("interactive.*TableMod.*");
test.runInteractiveTests("interactive.*Column.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* Issue #89-swingx: ColumnControl not updated with ComponentOrientation.
*
*/
public void interactiveRToLTableWithColumnControl() {
final JXTable table = new JXTable(createAscendingModel(0, 20));
final JScrollPane pane = new JScrollPane(table);
// table.setColumnControlVisible(true);
// pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JXFrame frame = wrapInFrame(pane, "RToLScrollPane");
Action toggleComponentOrientation = new AbstractAction("toggle orientation") {
public void actionPerformed(ActionEvent e) {
ComponentOrientation current = pane.getComponentOrientation();
if (current == ComponentOrientation.LEFT_TO_RIGHT) {
pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
} else {
pane.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
}
}
};
addAction(frame, toggleComponentOrientation);
Action toggleColumnControl = new AbstractAction("toggle column control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
addAction(frame, toggleColumnControl);
frame.setVisible(true);
}
public void interactiveTestRowHeightAndSelection() {
final JXTable table = new JXTable(sortableTableModel);
table.setRowHeightEnabled(true);
table.setRowHeight(0, table.getRowHeight() * 2);
final int column = 0;
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
ListSelectionModel model = (ListSelectionModel) e.getSource();
int selected = model.getMinSelectionIndex();
if (selected < 0) return;
System.out.println("from selection: " + table.getValueAt(selected, column));
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
System.out.println(table.getValueAt(row, column));
}
});
JFrame frame = wrapWithScrollingInFrame(table, "Accessing values (indy rowheights)");
frame.setVisible(true);
}
public void interactiveTestRowHeight() {
JXTable table = new JXTable(sortableTableModel);
table.setRowHeightEnabled(true);
table.setRowHeight(0, table.getRowHeight() * 2);
JFrame frame = wrapWithScrollingInFrame(table, "Individual rowheight");
frame.setVisible(true);
}
/**
* example mixed sorting (Jens Elkner).
*
*/
public void interactiveTestSorterPatch() {
Object[][] fourWheels = new Object[][]{
new Object[] {"Car", new Car(180f)},
new Object[] {"Porsche", new Porsche(170)},
new Object[] {"Porsche", new Porsche(170)},
new Object[] {"Porsche", new Porsche(170, false)},
new Object[] {"Tractor", new Tractor(20)},
new Object[] {"Tractor", new Tractor(10)},
};
DefaultTableModel model = new DefaultTableModel(fourWheels, new String[] {"Text", "Car"}) ;
JXTable table = new JXTable(model);
JFrame frame = wrapWithScrollingInFrame(table, "Sorter patch");
frame.setVisible(true);
}
public class Car implements Comparable<Car> {
float speed = 100;
public Car(float speed) { this.speed = speed; }
public int compareTo(Car o) {
return speed < o.speed ? -1 : speed > o.speed ? 1 : 0;
}
public String toString() {
return "Car - " + speed;
}
}
public class Porsche extends Car {
boolean hasBridgeStone = true;
public Porsche(float speed) { super(speed); }
public Porsche(float speed, boolean bridgeStone) {
this(speed);
hasBridgeStone = bridgeStone;
}
public int compareTo(Car o) {
if (o instanceof Porsche) {
return ((Porsche) o).hasBridgeStone ? 0 : 1;
}
return super.compareTo(o);
}
public String toString() {
return "Porsche - " + speed + (hasBridgeStone ? "+" : "");
}
}
public class Tractor implements Comparable<Tractor> {
float speed = 20;
public Tractor(float speed) { this.speed = speed; }
public int compareTo(Tractor o) {
return speed < o.speed ? -1 : speed > o.speed ? 1 : 0;
}
public String toString() {
return "Tractor - " + speed;
}
}
/**
* Issue #179: Sorter does not use collator if cell content is
* a String.
*
*/
public void interactiveTestLocaleSorter() {
Object[][] rowData = new Object[][] {
new Object[] { Boolean.TRUE, "aa" },
new Object[] { Boolean.FALSE, "AB" },
new Object[] { Boolean.FALSE, "AC" },
new Object[] { Boolean.TRUE, "BA" },
new Object[] { Boolean.FALSE, "BB" },
new Object[] { Boolean.TRUE, "BC" } };
String[] columnNames = new String[] { "Critical", "Task" };
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
// public Class getColumnClass(int column) {
// return column == 1 ? String.class : super.getColumnClass(column);
final JXTable table = new JXTable(model);
table.setSorter(1);
JFrame frame = wrapWithScrollingInFrame(table, "locale sorting");
frame.setVisible(true);
}
/**
* Issue #??: Problems with filters and ColumnControl
*
* - sporadic ArrayIndexOOB after sequence:
* filter(column), sort(column), hide(column), setFilter(null)
*
* - filtering invisible columns? Unclear state transitions.
*
*/
public void interactiveTestColumnControlAndFilters() {
final JXTable table = new JXTable(sortableTableModel);
// hmm bug regression with combos as editors - same in JTable
// JComboBox box = new JComboBox(new Object[] {"one", "two", "three" });
// box.setEditable(true);
// table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box));
Action toggleFilter = new AbstractAction("Toggle Filter col. 0") {
boolean hasFilters;
public void actionPerformed(ActionEvent e) {
if (hasFilters) {
table.setFilters(null);
} else {
Filter filter = new PatternFilter("e", 0, 0);
table.setFilters(new FilterPipeline(new Filter[] {filter}));
}
hasFilters = !hasFilters;
}
};
toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible ");
table.setColumnControlVisible(true);
JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters");
addAction(frame, toggleFilter);
frame.setVisible(true);
}
// public void interactiveTestColumnControlAndFiltersRowSorter() {
// final JXTable table = new JXTable(sortableTableModel);
// // hmm bug regression with combos as editors - same in JTable
//// JComboBox box = new JComboBox(new Object[] {"one", "two", "three" });
//// box.setEditable(true);
//// table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box));
// Action toggleFilter = new AbstractAction("Toggle RowFilter -contains e- ") {
// boolean hasFilters;
// public void actionPerformed(ActionEvent e) {
// if (hasFilters) {
// table.setFilters(null);
// } else {
// RowSorterFilter filter = new RowSorterFilter();
// filter.setRowFilter(RowFilter.regexFilter(".*e.*", 0));
// table.setFilters(new FilterPipeline(new Filter[] {filter}));
// hasFilters = !hasFilters;
// toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible ");
// table.setColumnControlVisible(true);
// JFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters");
// addAction(frame, toggleFilter);
// frame.setVisible(true);
/**
* Issue ??: Column control on changing column model.
*
*/
public void interactiveTestToggleTableModel() {
final DefaultTableModel tableModel = createAscendingModel(0, 20);
final JXTable table = new JXTable(tableModel);
table.setColumnControlVisible(true);
Action toggleAction = new AbstractAction("Toggle TableModel") {
public void actionPerformed(ActionEvent e) {
TableModel model = table.getModel();
table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel);
}
};
JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set columnModel -> core default");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue ??: Column control on changing column model.
*
*/
public void interactiveTestColumnControlColumnModel() {
final JXTable table = new JXTable(10, 5);
table.setColumnControlVisible(true);
Action toggleAction = new AbstractAction("Set ColumnModel") {
public void actionPerformed(ActionEvent e) {
table.setColumnModel(new DefaultTableColumnModel());
table.setModel(sortableTableModel);
setEnabled(false);
}
};
JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set columnModel -> core default");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue ??: Column control on changing column model.
*
*/
public void interactiveTestColumnControlColumnModelExt() {
final JXTable table = new JXTable();
table.setColumnModel( new DefaultTableColumnModel());
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
Action toggleAction = new AbstractAction("Set ColumnModelExt") {
public void actionPerformed(ActionEvent e) {
table.setColumnModel(new DefaultTableColumnModelExt());
table.setModel(sortableTableModel);
table.getColumnExt(0).setVisible(false);
setEnabled(false);
}
};
JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set ColumnModel -> modelExt");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue #155-swingx: vertical scrollbar policy lost.
*
*/
public void interactiveTestColumnControlConserveVerticalScrollBarPolicy() {
final JXTable table = new JXTable();
Action toggleAction = new AbstractAction("Toggle Control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
table.setModel(new DefaultTableModel(10, 5));
// table.setColumnControlVisible(true);
JScrollPane scrollPane1 = new JScrollPane(table);
scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue #11: Column control not showing with few rows.
*
*/
public void interactiveTestColumnControlFewRows() {
final JXTable table = new JXTable();
Action toggleAction = new AbstractAction("Toggle Control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* check behaviour outside scrollPane
*
*/
public void interactiveTestColumnControlWithoutScrollPane() {
final JXTable table = new JXTable();
Action toggleAction = new AbstractAction("Toggle Control") {
public void actionPerformed(ActionEvent e) {
table.setColumnControlVisible(!table.isColumnControlVisible());
}
};
toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane");
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
JXFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* check behaviour of moving into/out of scrollpane.
*
*/
public void interactiveTestToggleScrollPaneWithColumnControlOn() {
final JXTable table = new JXTable();
table.setModel(new DefaultTableModel(10, 5));
table.setColumnControlVisible(true);
final JXFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on");
Action toggleAction = new AbstractAction("Toggle ScrollPane") {
public void actionPerformed(ActionEvent e) {
Container parent = table.getParent();
boolean inScrollPane = parent instanceof JViewport;
if (inScrollPane) {
JScrollPane scrollPane = (JScrollPane) table.getParent().getParent();
frame.getContentPane().remove(scrollPane);
frame.getContentPane().add(table);
} else {
parent.remove(table);
parent.add(new JScrollPane(table));
}
frame.pack();
}
};
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* TableColumnExt: user friendly resizable
*
*/
public void interactiveTestColumnResizable() {
final JXTable table = new JXTable(sortableTableModel);
table.setColumnControlVisible(true);
int totalColumnCount = table.getColumnCount();
final TableColumnExt priorityColumn = table.getColumnExt("First Name");
JXFrame frame = wrapWithScrollingInFrame(table, "JXTable: Column with Min=Max not resizable");
Action action = new AbstractAction("Toggle MinMax of FirstName") {
public void actionPerformed(ActionEvent e) {
// user-friendly resizable flag
if (priorityColumn.getMinWidth() == priorityColumn.getMaxWidth()) {
priorityColumn.setMinWidth(50);
priorityColumn.setMaxWidth(150);
} else {
priorityColumn.setMinWidth(100);
priorityColumn.setMaxWidth(100);
}
}
};
addAction(frame, action);
frame.setVisible(true);
}
public void interactiveTestRolloverHighlight() {
JXTable table = new JXTable(sortableTableModel);
table.setRolloverEnabled(true);
table.setHighlighters(new HighlighterPipeline(new Highlighter[]
{new RolloverHighlighter(Color.YELLOW, null)} ));
JFrame frame = wrapWithScrollingInFrame(table, "rollover highlight");
frame.setVisible(true);
}
/**
* Issue #31 (swingx): clicking header must not sort if table !enabled.
*
*/
public void interactiveTestDisabledTableSorting() {
final JXTable table = new JXTable(sortableTableModel);
table.setColumnControlVisible(true);
Action toggleAction = new AbstractAction("Toggle Enabled") {
public void actionPerformed(ActionEvent e) {
table.setEnabled(!table.isEnabled());
}
};
JXFrame frame = wrapWithScrollingInFrame(table, "Disabled tabled: no sorting");
addAction(frame, toggleAction);
frame.setVisible(true);
}
/**
* Issue #191: sorting and custom renderer
* not reproducible ...
*
*/
public void interactiveTestCustomRendererSorting() {
JXTable table = new JXTable(sortableTableModel);
TableColumn column = table.getColumn("No.");
TableCellRenderer renderer = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
value = "# " + value ;
Component comp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col );
return comp;
}
};
column.setCellRenderer(renderer);
JFrame frame = wrapWithScrollingInFrame(table, "RendererSortingTest");
frame.setVisible(true); // RG: Changed from deprecated method show();
}
public void interactiveTestToggleSortingEnabled() {
final JXTable table = new JXTable(sortableTableModel);
table.setColumnControlVisible(true);
Action toggleSortableAction = new AbstractAction("Toggle Sortable") {
public void actionPerformed(ActionEvent e) {
table.setSortable(!table.isSortable());
}
};
JXFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test");
addAction(frame, toggleSortableAction);
frame.setVisible(true); // RG: Changed from deprecated method show();
}
public void interactiveTestTableSizing1() {
JXTable table = new JXTable();
table.setAutoCreateColumnsFromModel(false);
table.setModel(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()];
for (int i = 0; i < columns.length; i++) {
columns[i] = new TableColumnExt(i);
table.addColumn(columns[i]);
}
columns[0].setPrototypeValue(new Integer(0));
columns[1].setPrototypeValue("Simple String Value");
columns[2].setPrototypeValue(new Integer(1000));
columns[3].setPrototypeValue(Boolean.TRUE);
columns[4].setPrototypeValue(new Date(100));
columns[5].setPrototypeValue(new Float(1.5));
columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank",
tableModel.linkURL));
columns[7].setPrototypeValue(new Integer(3023));
columns[8].setPrototypeValue("John Doh");
columns[9].setPrototypeValue("23434 Testcase St");
columns[10].setPrototypeValue(new Integer(33333));
columns[11].setPrototypeValue(Boolean.FALSE);
table.setVisibleRowCount(12);
JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test");
frame.setVisible(true);
}
public void interactiveTestEmptyTableSizing() {
JXTable table = new JXTable(0, 5);
table.setColumnControlVisible(true);
JFrame frame = wrapWithScrollingInFrame(table, "Empty Table (0 rows)");
frame.setVisible(true);
}
public void interactiveTestTableSizing2() {
JXTable table = new JXTable();
table.setAutoCreateColumnsFromModel(false);
table.setModel(tableModel);
TableColumnExt columns[] = new TableColumnExt[6];
int viewIndex = 0;
for (int i = columns.length - 1; i >= 0; i
columns[viewIndex] = new TableColumnExt(i);
table.addColumn(columns[viewIndex++]);
}
columns[5].setHeaderValue("String Value");
columns[5].setPrototypeValue("9999");
columns[4].setHeaderValue("String Value");
columns[4].setPrototypeValue("Simple String Value");
columns[3].setHeaderValue("Int Value");
columns[3].setPrototypeValue(new Integer(1000));
columns[2].setHeaderValue("Bool");
columns[2].setPrototypeValue(Boolean.FALSE);
//columns[2].setSortable(false);
columns[1].setHeaderValue("Date");
columns[1].setPrototypeValue(new Date(0));
//columns[1].setSortable(false);
columns[0].setHeaderValue("Float");
columns[0].setPrototypeValue(new Float(5.5));
table.setRowHeight(24);
table.setRowMargin(2);
JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test");
frame.setVisible(true);
}
public void interactiveTestTableAlternateHighlighter1() {
JXTable table = new JXTable(tableModel);
table.setRowHeight(22);
table.setRowMargin(1);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true) // column 0, ascending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.
linePrinter,
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableAlternateRowHighlighter1 Test");
frame.setVisible(true);
}
public void interactiveTestTableAlternateRowHighlighter2() {
JXTable table = new JXTable(tableModel);
table.setRowHeight(22);
table.setRowMargin(1);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, false), // column 1, descending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.classicLinePrinter,
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableAlternateRowHighlighter2 Test");
frame.setVisible(true);
}
public void interactiveTestTableSorter1() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.notePadBackground,
}));
table.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad
table.setGridColor(Color.cyan.darker());
table.setRowHeight(22);
table.setRowMargin(1);
table.setShowHorizontalLines(true);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true), // column 0, ascending
new ShuttleSorter(1, true), // column 1, ascending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter1 col 0= asc, col 1 = asc");
frame.setVisible(true);
}
public void interactiveTestTableSorter2() {
JXTable table = new JXTable(sortableTableModel);
table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
table.setGridColor(Color.cyan.darker());
table.setRowHeight(22);
table.setRowMargin(1);
table.setShowHorizontalLines(true);
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, true), // column 0, ascending
new ShuttleSorter(1, false), // column 1, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter2 col 0 = asc, col 1 = desc");
frame.setVisible(true);
}
public void interactiveTestFocusedCellBackground() {
TableModel model = new AncientSwingTeam() {
public boolean isCellEditable(int row, int column) {
return column != 0;
}
};
JXTable xtable = new JXTable(model);
// BasicLookAndFeel lf;
xtable.setBackground(Highlighter.notePadBackground.getBackground()); // ledger
JTable table = new JTable(model);
table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable");
frame.setVisible(true);
}
public void interactiveTestTableSorter3() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new Highlighter(Color.orange, null),
}));
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, true), // column 1, ascending
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter3 col 1 = asc, col 0 = desc");
frame.setVisible(true);
}
public void interactiveTestTableSorter4() {
JXTable table = new JXTable(sortableTableModel);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new Highlighter(Color.orange, null),
}));
table.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(0, false), // column 0, descending
new ShuttleSorter(1, true), // column 1, ascending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TableSorter4 col 0 = des, col 1 = asc");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter1() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(1, 1));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("^A", 0, 1)
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter1 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter2() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(2, 2));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("^S", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter2 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter3() {
JXTable table = new JXTable(tableModel);
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("^S", 0, 1),
new ShuttleSorter(1, false), // column 1, descending
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter3 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter4() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(3, 3));
table.setShowGrid(true);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("^A", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter4 Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternFilter5() {
JXTable table = new JXTable(tableModel);
table.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter("^S", 0, 1),
new ShuttleSorter(0, false), // column 0, descending
new ShuttleSorter(1, true), // column 1, ascending
new ShuttleSorter(3, false), // column 3, descending
}));
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new PatternHighlighter(null, Color.red, "^S", 0, 1),
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter5 Test");
frame.setVisible(true);
}
public void interactiveTestTableViewProperties() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(15, 15));
table.setRowHeight(48);
JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test");
frame.setVisible(true);
}
public void interactiveTestTablePatternHighlighter() {
JXTable table = new JXTable(tableModel);
table.setIntercellSpacing(new Dimension(15, 15));
table.setRowHeight(48);
table.setRowHeight(0, 96);
table.setShowGrid(true);
table.setHighlighters(new HighlighterPipeline(new Highlighter[] {
new PatternHighlighter(null, Color.red, "^A", 0, 1),
}));
JFrame frame = wrapWithScrollingInFrame(table, "TablePatternHighlighter Test");
frame.setVisible(true);
}
public void interactiveTestTableColumnProperties() {
JXTable table = new JXTable();
table.setModel(tableModel);
table.getTableHeader().setBackground(Color.green);
table.getTableHeader().setForeground(Color.magenta);
table.getTableHeader().setFont(new Font("Serif", Font.PLAIN, 10));
ColumnHeaderRenderer headerRenderer = ColumnHeaderRenderer.createColumnHeaderRenderer();
headerRenderer.setHorizontalAlignment(JLabel.LEFT);
headerRenderer.setBackground(Color.blue);
headerRenderer.setForeground(Color.yellow);
headerRenderer.setIcon(new Icon() {
public int getIconWidth() {
return 12;
}
public int getIconHeight() {
return 12;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.red);
g.fillOval(0, 0, 10, 10);
}
});
headerRenderer.setIconTextGap(20);
headerRenderer.setFont(new Font("Serif", Font.BOLD, 18));
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumnExt column = table.getColumnExt(i);
if (i % 3 > 0) {
column.setHeaderRenderer(headerRenderer);
}
if (i % 2 > 0) {
TableCellRenderer cellRenderer =
table.getNewDefaultRenderer(table.getColumnClass(i));
if (cellRenderer instanceof JLabel || cellRenderer instanceof AbstractButton) {
JComponent labelCellRenderer = (JComponent)cellRenderer;
labelCellRenderer.setBackground(Color.gray);
labelCellRenderer.setForeground(Color.red);
if (cellRenderer instanceof JLabel) {
((JLabel) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER);
} else {
((AbstractButton) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER);
}
column.setCellRenderer(cellRenderer);
}
}
}
JFrame frame = wrapWithScrollingInFrame(table, "TableColumnProperties Test");
frame.setVisible(true);
}
/**
* dummy
*/
public void testDummy() {
}
}
|
package org.jdesktop.swingx;
import javax.swing.JPanel;
import org.jdesktop.test.SerializableSupport;
/**
* Test to exposed known issues of serializable.
*
* @author Jeanette Winzenburg
*/
public class SerializableIssues extends InteractiveTestCase {
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: RolloverController
*
*/
public void testTreeTable() {
JXTreeTable component = new JXTreeTable();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: TreeAdapter
*
*/
public void testTree() {
JXTree component = new JXTree();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: PainterUIResource
*
*/
public void testTitledPanel() {
JXTitledPanel component = new JXTitledPanel();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: ui delegate
*
*/
public void testTipOfTheDay() {
JXTipOfTheDay component = new JXTipOfTheDay();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: VerticalLayout
*
*/
public void testTaskPaneContainer() {
JXTaskPaneContainer component = new JXTaskPaneContainer();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: VerticalLayout
*
*/
public void testTaskPane() {
JXTaskPane component = new JXTaskPane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: rolloverController
*
*/
public void testTable() {
JXTable component = new JXTable();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: ui-delegate
*
*/
public void testStatusBar() {
JXStatusBar component = new JXStatusBar();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: EventHandler
*
*/
public void testSearchPanel() {
JXSearchPanel component = new JXSearchPanel();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable. <p>
*
* First blow: DefaultMultiThumbModel.
*
*/
public void testMultiThumbSlider() {
JXMultiThumbSlider component = new JXMultiThumbSlider();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: MultiSplitPaneLayout.
*
*/
public void testMultiSplitPane() {
JXMultiSplitPane component = new JXMultiSplitPane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: BufferedImage.
*
*/
public void testLoginPanel() {
JXLoginPane component = new JXLoginPane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: DelegatingRenderer.
*
*/
public void testList() {
JXList component = new JXList();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: internal MouseHandler
*/
public void testImagePanel() {
JXImagePanel component = new JXImagePanel();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* first blow: PainterUIResource
*/
public void testHeader() {
JXHeader component = new JXHeader();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* Frist blow: Rectangle inner class
*/
public void testGraph() {
JXGraph component = new JXGraph();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: BufferedImage
*/
public void testGradientChooser() {
JXGradientChooser component = new JXGradientChooser();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: inner class ?
*/
public void testGlassBox() {
JXGlassBox component = new JXGlassBox();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: inner class?.
*
*/
public void testFrame() {
JXFrame component = new JXFrame();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: EventHandler
*/
public void testFindPanel() {
JXFindPanel component = new JXFindPanel();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: EventHandler
*/
public void testFindBar() {
JXFindBar component = new JXFindBar();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
* First blow: ui-delegate
*/
public void testErrorPane() {
JXErrorPane component = new JXErrorPane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
*
*/
public void testEditorPane() {
JXEditorPane component = new JXEditorPane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
*
*/
public void testDialog() {
JXDialog component = new JXDialog(new JPanel());
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
*
*/
public void testDatePicker() {
JXDatePicker component = new JXDatePicker();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
*
*/
public void testColorSelectionButton() {
JXColorSelectionButton component = new JXColorSelectionButton();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
/**
* Issue #423-swingx: all descendants of JComponent must be
* serializable.<p>
*
*
*/
public void testCollapsiblePane() {
JXCollapsiblePane component = new JXCollapsiblePane();
try {
SerializableSupport.serialize(component);
} catch (Exception e) {
fail("not serializable " + e);
}
}
}
|
package br.ufba.ia.copsandrobbers.search;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
public class AStar {
//Declare constants
public static final int larguraTela = 80, alturaTela = 60, tamanhoPixel = 20, qtdeAgentes = 3;
// Constantes relacionadas ao caminho
public static final int naoTerminou = 0 ;
public static final int naoComecou = 0;
public static final int encontrado = 1, naoExiste = 2;
public static final int caminhoPassavel = 0, caminhoBloqueado = 1; // constantes referente a habilidade de andar.
public int naListaFechada = 10;
//Create needed arrays
public char[][] possibilidadeDeCaminhada = new char[larguraTela][alturaTela];
public int[] listaAberta = new int[larguraTela*alturaTela+2];
public int[][] qualLista = new int[larguraTela+1][alturaTela+1];
public int[] xAberta = new int[larguraTela*alturaTela+2];
public int[] yAberta = new int[larguraTela*alturaTela+2];
public int[][] xPai = new int[larguraTela+1][alturaTela+1];
public int[][] yPai = new int[larguraTela+1][alturaTela+1];
public int[] custoF = new int[larguraTela*alturaTela+2];
public int[][] custoG = new int[larguraTela+1][alturaTela+1];
public int[] custoH = new int[larguraTela*alturaTela+2];
public int[] tamanhoDoCaminho = new int[qtdeAgentes+1]; //armazena o tamanho do caminho encontrado para a criatura
public int[] localizacaoDoCaminho = new int[qtdeAgentes+1];
//int* arquivaCaminho [qtdeAgentes+1];
public List<Integer> arquivaCaminho[] = new List[qtdeAgentes+1];
public List<Integer[]> arquivaCaminho2 = new ArrayList<Integer[]>();
//Path reading variables
public int[] statusDoCaminho = new int[qtdeAgentes+1];
public int[] caminhoX = new int[qtdeAgentes+1];
public int[] caminhoY = new int[qtdeAgentes+1];
public void inicializarBuscadorDeCaminho()
{
for (int x = 0; x < qtdeAgentes+1; x++){
arquivaCaminho[x] = new Vector<Integer>();
arquivaCaminho2.add(new Integer[4]);
}
}
public void finalizarBuscadorDeCaminho()
{
for (int x = 0; x < qtdeAgentes+1; x++){
arquivaCaminho[x].clear();
arquivaCaminho2.set(x, null);
}
}
public int encontrarCaminho(int caminhoBuscadorID, int origemX, int origemY,
int destinoX, int destinoY)
{
int naListaAberta=0, valorXPai=0, valorYPai=0, a=0, b=0, m=0, u=0, v=0, temp=0, diagonal=0, numItemsListaAberta=0, adicionadoCustoG=0, custoGTemp = 0, path = 0, tempx, tragetoriaX, tragetoriaY, posicaoDaCelula, novoIDItemListaAberta=0;
int inicioX = origemX/tamanhoPixel;
int inicioY = origemY/tamanhoPixel;
destinoX = destinoX/tamanhoPixel;
destinoY = destinoY/tamanhoPixel;
if (inicioX == destinoX && inicioY == destinoY && localizacaoDoCaminho[caminhoBuscadorID] > 0)
return encontrado;
if (inicioX == destinoX && inicioY == destinoY && localizacaoDoCaminho[caminhoBuscadorID] == 0)
return naoExiste;
if (possibilidadeDeCaminhada[destinoX][destinoY] == caminhoBloqueado)
{
caminhoX[caminhoBuscadorID] = origemX;
caminhoY[caminhoBuscadorID] = origemY;
return naoExiste;
}
if (naListaFechada > 1000000) //Resetando queLista ocasionalmente
{
for (int x = 0; x < larguraTela; x++) {
for (int y = 0; y < alturaTela; y++)
qualLista [x][y] = 0;
}
naListaFechada = 10;
}
naListaFechada = naListaFechada+2; //alterando os valores da listaAberta(lista aberta) e onClosed list eh mais rapida do que redimensionar queLista() array;
naListaAberta = naListaFechada-1;
tamanhoDoCaminho [caminhoBuscadorID] = naoComecou;//i.e, = 0
localizacaoDoCaminho [caminhoBuscadorID] = naoComecou;//i.e, = 0
custoG[inicioX][inicioY] = 0; //resetando o quadrado inicial com o valor de G para 0
//4. Adicionando a posicao inicial listaAberta de quadrados para serem verificados.
numItemsListaAberta = 1;
listaAberta[1] = 1; //colocando este como o item do topo(e atualmente somente) da listaAberta, que eh mantida como uma heap binaria.
xAberta[1] = inicioX;
yAberta[1] = inicioY;
//5. Faca o seguinte ate que um caminho eh encontrador ou ele nao exista.
do
{
if (numItemsListaAberta != 0)
{
//7. Remova o primeiro item da listaAberta.
valorXPai = xAberta[listaAberta[1]];
valorYPai = yAberta[listaAberta[1]]; //Grave as coordenadas da celula do item
qualLista[valorXPai][valorYPai] = naListaFechada;//adicione o item para a closedList
numItemsListaAberta = numItemsListaAberta - 1;//reduzindo o numero de items da listaAberta em 1
listaAberta[1] = listaAberta[numItemsListaAberta+1];//mova o ultimo item na heap a cima para o slot
v = 1;
do
{
u = v;
if (2*u+1 <= numItemsListaAberta) //Se ambos os filhos existirem
{
//Selecione o menor dos dois filhos.
if (custoF[listaAberta[u]] >= custoF[listaAberta[2*u]])
v = 2*u;
if (custoF[listaAberta[v]] >= custoF[listaAberta[2*u+1]])
v = 2*u+1;
}
else
{
if (2*u <= numItemsListaAberta) //Se somente o filho 1 existe
{
if (custoF[listaAberta[u]] >= custoF[listaAberta[2*u]])
v = 2*u;
}
}
if (u != v)
{
temp = listaAberta[u];
listaAberta[u] = listaAberta[v];
listaAberta[v] = temp;
}
else
break; //de outro modo, saia do loop
}
while (!(Gdx.input.isKeyPressed(Keys.ESCAPE))); //Tentei isso, mas no sei como criar a varivel actualkey.
for (b = valorYPai-1; b <= valorYPai+1; b++){
for (a = valorXPai-1; a <= valorXPai+1; a++){
if (a != -1 && b != -1 && a != larguraTela && b != alturaTela){
if (qualLista[a][b] != naListaFechada) {
if (possibilidadeDeCaminhada [a][b] != caminhoBloqueado) {
diagonal = caminhoPassavel;
if (a == valorXPai-1)
{
if (b == valorYPai-1)
{
if (possibilidadeDeCaminhada[valorXPai-1][valorYPai] == caminhoBloqueado || possibilidadeDeCaminhada[valorXPai][valorYPai-1] == caminhoBloqueado) diagonal = caminhoBloqueado;
}
else if (b == valorYPai+1)
{
if (possibilidadeDeCaminhada[valorXPai][valorYPai+1] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai-1][valorYPai] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
}
else if (a == valorXPai+1)
{
if (b == valorYPai-1)
{
if (possibilidadeDeCaminhada[valorXPai][valorYPai-1] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai+1][valorYPai] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
else if (b == valorYPai+1)
{
if (possibilidadeDeCaminhada[valorXPai+1][valorYPai] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai][valorYPai+1] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
}
if (diagonal == caminhoPassavel) {
if (qualLista[a][b] != naListaAberta)
{
//Cria um item novo na listaAberta na heap binaria.
novoIDItemListaAberta = novoIDItemListaAberta + 1; //Cada novo item tem um ID unico.
m = numItemsListaAberta+1;
listaAberta[m] = novoIDItemListaAberta;// Coloque o novo item da listaAberta(atualmente ID#) na base da heap.
xAberta[novoIDItemListaAberta] = a;
yAberta[novoIDItemListaAberta] = b;//grave suas coordenadas x e y do novo item
//Calculando o custo de G
if (Math.abs(a-valorXPai) == 1 && Math.abs(b-valorYPai) == 1)
adicionadoCustoG = 14;//custo de ir pelas diagonais dos quadrados;
else
adicionadoCustoG = 10;
custoG[a][b] = custoG[valorXPai][valorYPai] + adicionadoCustoG;
//Calcular os custos H e F e o pai
custoH[listaAberta[m]] = AStar.tamanhoPixel*(Math.abs(a - destinoX) + Math.abs(b - destinoY));
custoF[listaAberta[m]] = custoG[a][b] + custoH[listaAberta[m]];
xPai[a][b] = valorXPai ; yPai[a][b] = valorYPai;
//Iniciando da base, sucessivamente comparar items pais,
//ou borbulhando todos os caminhos para o topo (se este tem o menor custo de F).
while (m != 1)
{
if (custoF[listaAberta[m]] <= custoF[listaAberta[m/2]])
{
temp = listaAberta[m/2];
listaAberta[m/2] = listaAberta[m];
listaAberta[m] = temp;
m = m/2;
}
else
break;
}
numItemsListaAberta = numItemsListaAberta+1;
qualLista[a][b] = naListaAberta;
}
//8.If adjacent cell is already on the open list, check to see if this
else //Se queLista(a,b) = naListaAberta
{
if (Math.abs(a-valorXPai) == 1 && Math.abs(b-valorYPai) == 1)
adicionadoCustoG = 14;//Custo de ir pelas diagonais
else
adicionadoCustoG = 10;
custoGTemp = custoG[valorXPai][valorYPai] + adicionadoCustoG;
if (custoGTemp < custoG[a][b])
{
xPai[a][b] = valorXPai; //troque o quadrado pai
yPai[a][b] = valorYPai;
custoG[a][b] = custoGTemp;//troque o custo de G
for (int x = 1; x <= numItemsListaAberta; x++) //olho para o item na listaAberta
{
if (xAberta[listaAberta[x]] == a && yAberta[listaAberta[x]] == b) //item encontrado
{
custoF[listaAberta[x]] = custoG[a][b] + custoH[listaAberta[x]];//troque o custo F
m = x;
while (m != 1)
{
if (custoF[listaAberta[m]] < custoF[listaAberta[m/2]])
{
temp = listaAberta[m/2];
listaAberta[m/2] = listaAberta[m];
listaAberta[m] = temp;
m = m/2;
}
else
break;
}
break; //saia para x = loop
} //Se xAberta(listaAberta(x)) = a
} //For x = 1 To numItemsListaAberta
}//If custoGTemp < custoG(a,b)
}//else If queLista(a,b) = naListaAberta
}
}
}
}
}//for (a = valorXPai-1; a <= valorXPai+1; a++){
}//for (b = valorYPai-1; b <= valorYPai+1; b++){
}//if (numItemsListaAberta != 0)
else
{
path = naoExiste; break;
}
if (qualLista[destinoX][destinoY] == naListaAberta)
{
path = encontrado; break;
}
}
while (true);
if (path == encontrado)
{
tragetoriaX = destinoX; tragetoriaY = destinoY;
do
{
tempx = xPai[tragetoriaX][tragetoriaY];
tragetoriaY = yPai[tragetoriaX][tragetoriaY];
tragetoriaX = tempx;
//Calcular o tamanho do caminho.
tamanhoDoCaminho[caminhoBuscadorID] = tamanhoDoCaminho[caminhoBuscadorID] + 1;
}
while (tragetoriaX != inicioX || tragetoriaY != inicioY);
//b.Redimensione o dataBank para o correto tamanho em bytes.
Integer[] arr = arquivaCaminho2.get(caminhoBuscadorID);
arquivaCaminho2.set(caminhoBuscadorID, Arrays.copyOf(arr, tamanhoDoCaminho[caminhoBuscadorID]*8));
// um conjunto corretamente ordenado de dados do caminho, para o primeiro passo
tragetoriaX = destinoX ; tragetoriaY = destinoY;
posicaoDaCelula = tamanhoDoCaminho[caminhoBuscadorID]*2;//Inicie do final
do
{
posicaoDaCelula = posicaoDaCelula - 2;
arquivaCaminho2.get(caminhoBuscadorID)[posicaoDaCelula] = tragetoriaX;
arquivaCaminho2.get(caminhoBuscadorID)[posicaoDaCelula+1] = tragetoriaY;
tempx = xPai[tragetoriaX][tragetoriaY];
tragetoriaY = yPai[tragetoriaX][tragetoriaY];
tragetoriaX = tempx;
}
while (tragetoriaX != inicioX || tragetoriaY != inicioY);
//11. Leia o primeiro passo dentro dos arrays caminhoX/caminhoY.
leituraDoCaminho(caminhoBuscadorID,origemX,origemY,1);
}
return path;
}
public void leituraDoCaminho(int caminhoBuscadorID,int correnteX,int correnteY, int pixelPorFrame)
{
int ID = caminhoBuscadorID;
//Se um caminho tem sido encontrado para o pathfinder ...
if (statusDoCaminho[ID] == encontrado)
{
if (localizacaoDoCaminho[ID] < tamanhoDoCaminho[ID])
{
if (localizacaoDoCaminho[ID] == 0 ||
(Math.abs(correnteX - caminhoX[ID]) < pixelPorFrame && Math.abs(correnteY - caminhoY[ID]) < pixelPorFrame))
localizacaoDoCaminho[ID] = localizacaoDoCaminho[ID] + 1;
}
//Leia o dado do caminho.
caminhoX[ID] = leituraCaminhoX(ID,localizacaoDoCaminho[ID]);
caminhoY[ID] = leituraCaminhoY(ID,localizacaoDoCaminho[ID]);
if (localizacaoDoCaminho[ID] == tamanhoDoCaminho[ID])
{
if (Math.abs(correnteX - caminhoX[ID]) < pixelPorFrame
&& Math.abs(correnteY - caminhoY[ID]) < pixelPorFrame) //Se perto o suficiente do quadrado do centro
statusDoCaminho[ID] = naoComecou;
}
}
else
{
caminhoX[ID] = correnteX;
caminhoY[ID] = correnteY;
}
}
//The following two functions read the raw path data from the arquivaCaminho.
//You can call these functions directly and skip the readPath function
//above if you want. Make sure you know what your current localizacaoDoCaminho
//atual.
// Name: ReadPathX
int leituraCaminhoX(int caminhoBuscadorID,int localizacaoDoCaminho)
{
int x = 0;
if (localizacaoDoCaminho <= tamanhoDoCaminho[caminhoBuscadorID])
{
//Le a coordenada X do patharquivaCaminho
x = arquivaCaminho2.get(caminhoBuscadorID)[localizacaoDoCaminho*2-2];
//Ajusta a coordenada para ela ficar alinhada ao inicio do quadrado.
x = (int) (tamanhoPixel*x);
}
return x;
}
// Name: ReadPathY
int leituraCaminhoY(int caminhoBuscadorID,int localizacaoDoCaminho)
{
int y = 0;
if (localizacaoDoCaminho <= tamanhoDoCaminho[caminhoBuscadorID])
{
//Le as coordenadas do arquivaCaminho.
// y = arquivaCaminho[pathfinderID].get(localizacaoDoCaminho*2-1);
y = arquivaCaminho2.get(caminhoBuscadorID)[localizacaoDoCaminho*2-1];
//Ajusta a coordenada para ela ficar alinhada ao inicio do quadrado.
y = (int) ( tamanhoPixel*y);
}
return y;
}
public int encontrarCaminhoBuscaCega(int caminhoBuscadorID, int origemX, int origemY,
int destinoX, int destinoY)
{
int naListaAberta=0, valorXPai=0, valorYPai=0, a=0, b=0, m=0, u=0, v=0, temp=0, diagonal=0, numItemsListaAberta=0, adicionadoCustoG=0, custoGTemp = 0, caminho = 0, tempx, tragetoriaX, tragetoriaY, posicaoDaCelula, novoIDItemListaAberta=0;
int inicioX = origemX/tamanhoPixel;
int inicioY = origemY/tamanhoPixel;
destinoX = destinoX/tamanhoPixel;
destinoY = destinoY/tamanhoPixel;
if (inicioX == destinoX && inicioY == destinoY && localizacaoDoCaminho[caminhoBuscadorID] > 0)
return encontrado;
if (inicioX == destinoX && inicioY == destinoY && localizacaoDoCaminho[caminhoBuscadorID] == 0)
return naoExiste;
if (possibilidadeDeCaminhada[destinoX][destinoY] == caminhoBloqueado)
{
caminhoX[caminhoBuscadorID] = origemX;
caminhoY[caminhoBuscadorID] = origemY;
return naoExiste;
}
if (naListaFechada > 1000000) //Resetando queLista ocasionalmente
{
for (int x = 0; x < larguraTela; x++) {
for (int y = 0; y < alturaTela; y++)
qualLista [x][y] = 0;
}
naListaFechada = 10;
}
naListaFechada = naListaFechada+2;
naListaAberta = naListaFechada-1;
tamanhoDoCaminho [caminhoBuscadorID] = naoComecou;//i.e, = 0
localizacaoDoCaminho [caminhoBuscadorID] = naoComecou;//i.e, = 0
custoG[inicioX][inicioY] = 0; //resetando o quadrado inicial com o valor de G para 0
numItemsListaAberta = 1;
listaAberta[1] = 1;
xAberta[1] = inicioX;
yAberta[1] = inicioY;
do
{
if (numItemsListaAberta != 0)
{
//7. Remova o primeiro item da listaAberta.
valorXPai = xAberta[listaAberta[1]];
valorYPai = yAberta[listaAberta[1]]; //Grave as coordenadas da celula do item
qualLista[valorXPai][valorYPai] = naListaFechada;//adicione o item para a closedList
numItemsListaAberta = numItemsListaAberta - 1;//reduzindo o numero de items da listaAberta em 1
listaAberta[1] = listaAberta[numItemsListaAberta+1];//mova o ultimo item na heap a cima para o slot
v = 1;
do
{
u = v;
if (2*u+1 <= numItemsListaAberta) //Se ambos os filhos existirem
{
//Selecione o menor dos dois filhos.
if (custoF[listaAberta[u]] >= custoF[listaAberta[2*u]])
v = 2*u;
if (custoF[listaAberta[v]] >= custoF[listaAberta[2*u+1]])
v = 2*u+1;
}
else
{
if (2*u <= numItemsListaAberta) //Se somente o filho 1 existe
{
if (custoF[listaAberta[u]] >= custoF[listaAberta[2*u]])
v = 2*u;
}
}
if (u != v)
{
temp = listaAberta[u];
listaAberta[u] = listaAberta[v];
listaAberta[v] = temp;
}
else
break; //de outro modo, saia do loop
}
while (!(Gdx.input.isKeyPressed(Keys.ESCAPE))); //Tentei isso, mas no sei como criar a varivel actualkey.
for (b = valorYPai-1; b <= valorYPai+1; b++){
for (a = valorXPai-1; a <= valorXPai+1; a++){
if (a != -1 && b != -1 && a != larguraTela && b != alturaTela){
if (qualLista[a][b] != naListaFechada) {
if (possibilidadeDeCaminhada [a][b] != caminhoBloqueado) {
diagonal = caminhoPassavel;
if (a == valorXPai-1)
{
if (b == valorYPai-1)
{
if (possibilidadeDeCaminhada[valorXPai-1][valorYPai] == caminhoBloqueado || possibilidadeDeCaminhada[valorXPai][valorYPai-1] == caminhoBloqueado) diagonal = caminhoBloqueado;
}
else if (b == valorYPai+1)
{
if (possibilidadeDeCaminhada[valorXPai][valorYPai+1] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai-1][valorYPai] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
}
else if (a == valorXPai+1)
{
if (b == valorYPai-1)
{
if (possibilidadeDeCaminhada[valorXPai][valorYPai-1] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai+1][valorYPai] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
else if (b == valorYPai+1)
{
if (possibilidadeDeCaminhada[valorXPai+1][valorYPai] == caminhoBloqueado
|| possibilidadeDeCaminhada[valorXPai][valorYPai+1] == caminhoBloqueado)
diagonal = caminhoBloqueado;
}
}
if (diagonal == caminhoPassavel) {
if (qualLista[a][b] != naListaAberta)
{
//Cria um item novo na listaAberta na heap binaria.
novoIDItemListaAberta = novoIDItemListaAberta + 1; //Cada novo item tem um ID unico.
m = numItemsListaAberta+1;
listaAberta[m] = novoIDItemListaAberta;// Coloque o novo item da listaAberta(atualmente ID#) na base da heap.
xAberta[novoIDItemListaAberta] = a;
yAberta[novoIDItemListaAberta] = b;//grave suas coordenadas x e y do novo item
//Calculando o custo de G
if (Math.abs(a-valorXPai) == 1 && Math.abs(b-valorYPai) == 1)
adicionadoCustoG = 14;//custo de ir pelas diagonais dos quadrados;
else
adicionadoCustoG = 10;
custoG[a][b] = 1;
//Calcular os custos H e F e o pai
custoH[listaAberta[m]] = 1;
custoF[listaAberta[m]] = custoG[a][b] + custoH[listaAberta[m]];
xPai[a][b] = valorXPai ; yPai[a][b] = valorYPai;
//Iniciando da base, sucessivamente comparar items pais,
//ou borbulhando todos os caminhos para o topo (se este tem o menor custo de F).
while (m != 1)
{
if (custoF[listaAberta[m]] <= custoF[listaAberta[m/2]])
{
temp = listaAberta[m/2];
listaAberta[m/2] = listaAberta[m];
listaAberta[m] = temp;
m = m/2;
}
else
break;
}
numItemsListaAberta = numItemsListaAberta+1;
qualLista[a][b] = naListaAberta;
}
//8.If adjacent cell is already on the open list, check to see if this
else //Se queLista(a,b) = naListaAberta
{
if (Math.abs(a-valorXPai) == 1 && Math.abs(b-valorYPai) == 1)
adicionadoCustoG = 14;//Custo de ir pelas diagonais
else
adicionadoCustoG = 10;
custoGTemp = custoG[valorXPai][valorYPai];
if (custoGTemp < custoG[a][b])
{
xPai[a][b] = valorXPai; //troque o quadrado pai
yPai[a][b] = valorYPai;
custoG[a][b] = custoGTemp;//troque o custo de G
for (int x = 1; x <= numItemsListaAberta; x++) //olho para o item na listaAberta
{
if (xAberta[listaAberta[x]] == a && yAberta[listaAberta[x]] == b) //item encontrado
{
custoF[listaAberta[x]] = custoG[a][b] + custoH[listaAberta[x]];//troque o custo F
m = x;
while (m != 1)
{
if (custoF[listaAberta[m]] < custoF[listaAberta[m/2]])
{
temp = listaAberta[m/2];
listaAberta[m/2] = listaAberta[m];
listaAberta[m] = temp;
m = m/2;
}
else
break;
}
break; //saia para x = loop
} //Se xAberta(listaAberta(x)) = a
} //For x = 1 To numItemsListaAberta
}//If custoGTemp < custoG(a,b)
}//else If queLista(a,b) = naListaAberta
}
}
}
}
}//for (a = valorXPai-1; a <= valorXPai+1; a++){
}//for (b = valorYPai-1; b <= valorYPai+1; b++){
}//if (numItemsListaAberta != 0)
else
{
caminho = naoExiste; break;
}
if (qualLista[destinoX][destinoY] == naListaAberta)
{
caminho = encontrado; break;
}
}
while (true);
if (caminho == encontrado)
{
tragetoriaX = destinoX; tragetoriaY = destinoY;
do
{
tempx = xPai[tragetoriaX][tragetoriaY];
tragetoriaY = yPai[tragetoriaX][tragetoriaY];
tragetoriaX = tempx;
//Calcular o tamanho do caminho.
tamanhoDoCaminho[caminhoBuscadorID] = tamanhoDoCaminho[caminhoBuscadorID] + 1;
}
while (tragetoriaX != inicioX || tragetoriaY != inicioY);
//b.Redimensione o dataBank para o correto tamanho em bytes.
Integer[] arr = arquivaCaminho2.get(caminhoBuscadorID);
arquivaCaminho2.set(caminhoBuscadorID, Arrays.copyOf(arr, tamanhoDoCaminho[caminhoBuscadorID]*8));
// um conjunto corretamente ordenado de dados do caminho, para o primeiro passo
tragetoriaX = destinoX ; tragetoriaY = destinoY;
posicaoDaCelula = tamanhoDoCaminho[caminhoBuscadorID]*2;//Inicie do final
do
{
posicaoDaCelula = posicaoDaCelula - 2;
arquivaCaminho2.get(caminhoBuscadorID)[posicaoDaCelula] = tragetoriaX;
arquivaCaminho2.get(caminhoBuscadorID)[posicaoDaCelula+1] = tragetoriaY;
tempx = xPai[tragetoriaX][tragetoriaY];
tragetoriaY = yPai[tragetoriaX][tragetoriaY];
tragetoriaX = tempx;
}
while (tragetoriaX != inicioX || tragetoriaY != inicioY);
//11. Leia o primeiro passo dentro dos arrays caminhoX/caminhoY.
leituraDoCaminho(caminhoBuscadorID,origemX,origemY,1);
}
return caminho;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaLineArray;
/**
* Class to process the pixel arrays
* @author Michael Deutch
*/
import java.awt.Color;
import java.util.ArrayList;
import java.awt.BasicStroke;
import java.awt.Shape;
//import java.awt.geom.GeneralPath;
import java.awt.geom.Area;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import ArmyC2.C2SD.Utilities.RendererSettings;
import java.awt.geom.Rectangle2D;
/*
* A class to calculate the symbol points for the GeneralPath objects.
* @author Michael Deutch
*/
public final class arraysupport
{
private static final double maxLength=100;
private static final double minLength=2.5;
private static final double dACP=0;
private static final String _className="arraysupport";
// protected static void setMinLength(double value)
// minLength=value;
private static void FillPoints(POINT2[] pLinePoints,
int counter,
ArrayList<POINT2>points)
{
points.clear();
for(int j=0;j<counter;j++)
{
points.add(pLinePoints[j]);
}
}
/**
* This is the interface function to CELineArray from clsRenderer2
* for non-channel types
*
* @param lineType the line type
* @param pts the client points
* @param shapes the symbol ShapeInfo objects
* @param clipBounds the rectangular clipping bounds
* @param rev the Mil-Standard-2525 revision
*/
public static ArrayList<POINT2> GetLineArray2(int lineType,
ArrayList<POINT2> pts,
ArrayList<Shape2> shapes,
Rectangle2D clipBounds,
int rev) {
ArrayList<POINT2> points = null;
try {
POINT2 pt = null;
POINT2[] pLinePoints2 = null;
POINT2[] pLinePoints = null;
int vblSaveCounter = pts.size();
//get the count from countsupport
int j = 0;
if (pLinePoints2 == null || pLinePoints2.length == 0)//did not get set above
{
pLinePoints = new POINT2[vblSaveCounter];
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y, pt.style);
}
}
//get the number of points the array will require
int vblCounter = countsupport.GetCountersDouble(lineType, vblSaveCounter, pLinePoints, clipBounds,rev);
//resize pLinePoints and fill the first vblSaveCounter elements with the original points
if(vblCounter>0)
pLinePoints = new POINT2[vblCounter];
else
{
shapes=null;
return null;
}
lineutility.InitializePOINT2Array(pLinePoints);
//safeguards added 2-17-11 after CPOF client was allowed to add points to autoshapes
if(vblSaveCounter>pts.size())
vblSaveCounter=pts.size();
if(vblSaveCounter>pLinePoints.length)
vblSaveCounter=pLinePoints.length;
for (j = 0; j < vblSaveCounter; j++) {
pt = (POINT2) pts.get(j);
pLinePoints[j] = new POINT2(pt.x, pt.y,pt.style);
}
//we have to adjust the autoshapes because they are instantiating with fewer points
points = GetLineArray2Double(lineType, pLinePoints, vblCounter, vblSaveCounter, shapes, clipBounds,rev);
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetLineArray2",
new RendererException("GetLineArray2 " + Integer.toString(lineType), exc));
}
return points;
//the caller can get points
}
/**
* A function to calculate the points for FORTL
* @param pLinePoints OUT - the points arry also used for the return points
* @param lineType
* @param vblSaveCounter the number of client points
* @return
*/
private static int GetFORTLPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, bolVertical = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
//long[] segments=null;
//long numpts2=0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
//numpts2=lineutility.BoundPointsCount(pLinePoints,vblSaveCounter);
//segments=new long[numpts2];
//lineutility.BoundPoints(ref pLinePoints,vblSaveCounter,ref segments);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
switch (lineType) {
default:
dIncrement = 20;
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if (dLengthSegment / 20 < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < dLengthSegment / 20 - 1; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 10, 0);
nCounter++;
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 10);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 3, 10);
nCounter++;
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 2, 10);
nCounter++;
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
if (pLinePoints[j].y < pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 1, 10);
nCounter++;
}
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, 10);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt1, 0, 10);
nCounter++;
}
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], 10, 0);
nCounter++;
}//end for k
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
return nCounter;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetFORTLPointsDouble",
new RendererException("GetFORTLPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static void CoordFEBADouble(
POINT2[] pLinePoints,
int vblCounter) {
try {
//declarations
int j = 0;
POINT2[] pXLinePoints = new POINT2[4 * vblCounter / 32];
POINT2[] pNewLinePoints = new POINT2[vblCounter / 32];
POINT2[] pShortLinePoints = new POINT2[2 * vblCounter / 32];
POINT2[] pArcLinePoints = new POINT2[26 * vblCounter / 32];
double dPrinter = 1.0;
//end declarations
for (j = vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pLinePoints[0]); //initialize the rest of pLinePoints
pLinePoints[j].style = 0;
}
for (j = 0; j < 4 * vblCounter / 32; j++) {
pXLinePoints[j] = new POINT2(pLinePoints[0]); //initialization only for pXLinePoints
pXLinePoints[j].style = 0;
}
for (j = 0; j < vblCounter / 32; j++) //initialize pNewLinePoints
{
pNewLinePoints[j] = new POINT2(pLinePoints[j]);
pNewLinePoints[j].style = 0;
}
for (j = 0; j < 2 * vblCounter / 32; j++) //initialize pShortLinePoints
{
pShortLinePoints[j] = new POINT2(pLinePoints[0]);
pShortLinePoints[j].style = 0;
}
for (j = 0; j < 26 * vblCounter / 32; j++) //initialize pArcLinePoints
{
pArcLinePoints[j] = new POINT2(pLinePoints[0]);
pArcLinePoints[j].style = 0;
}
//first get the X's
lineutility.GetXFEBADouble(pNewLinePoints, 10 * dPrinter, vblCounter / 32,//was 7
pXLinePoints);
for (j = 0; j < 4 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pXLinePoints[j]);
}
pLinePoints[4 * vblCounter / 32 - 1].style = 5;
for (j = 4 * vblCounter / 32; j < 6 * vblCounter / 32; j++) {
pLinePoints[j] = new POINT2(pShortLinePoints[j - 4 * vblCounter / 32]);
pLinePoints[j].style = 5; //toggle invisible lines between feba's
}
pLinePoints[6 * vblCounter / 32 - 1].style = 5;
//last, get the arcs
lineutility.GetArcFEBADouble(14.0 * dPrinter, pNewLinePoints,
vblCounter / 32,
pArcLinePoints);
for (j = 6 * vblCounter / 32; j < vblCounter; j++) {
pLinePoints[j] = new POINT2(pArcLinePoints[j - 6 * vblCounter / 32]);
}
//clean up
pXLinePoints = null;
pNewLinePoints = null;
pShortLinePoints = null;
pArcLinePoints = null;
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "CoordFEBADouble",
new RendererException("CoordFEBADouble", exc));
}
}
private static int GetATWallPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 0;
int limit = 0;
//POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
pSpikePoints[nCounter++] = new POINT2(pLinePoints[0]);
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
if (limit < 1) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = -1; k < limit; k++)//was k=0 to limit
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = new POINT2(pt0);
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0;j < nCounter;j++){
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble", exc));
}
return nCounter;
}
public static int GetInsideOutsideDouble2(POINT2 pt0,
POINT2 pt1,
POINT2[] pLinePoints,
int vblCounter,
int index,
int lineType) {
int nDirection = 0;
try {
//declarations
ref<double[]> m = new ref();
ref<double[]> m0 = new ref();
double b0 = 0;
double b2 = 0;
double b = 0;
double X0 = 0; //segment midpoint X value
double Y0 = 0; //segment midpoint Y value
double X = 0; //X value of horiz line from left intercept with current segment
double Y = 0; //Y value of vertical line from top intercept with current segment
int nInOutCounter = 0;
int j = 0, bolVertical = 0;
int bolVertical2 = 0;
int nOrientation = 0; //will use 0 for horiz line from left, 1 for vertical line from top
int extendLeft = 0;
int extendRight = 1;
int extendAbove = 2;
int extendBelow = 3;
int oppSegment=vblCounter-index-3; //used by BELT1 only
POINT2 pt2=new POINT2();
//end declarations. will use this to determine the direction
//slope of the segment
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m0);
if(m0.value==null)
return 0;
//get the midpoint of the segment
X0 = (pt0.x + pt1.x) / 2;
Y0 = (pt0.y + pt1.y) / 2;
if(lineType==TacticalLines.BELT1 && oppSegment>=0 && oppSegment<vblCounter-1)
{
//get the midpoint of the opposite segment
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
//must calculate the corresponding point on the current segment
//first get the y axis intercept of the perpendicular line for the opposite (short) segment
//calculate this line at the midpoint of the opposite (short) segment
b0=Y0+1/m0.value[0]*X0;
//the y axis intercept of the index segment
b2=pt0.y-m0.value[0]*pt0.x;
if(m0.value[0]!=0 && bolVertical!=0)
{
//calculate the intercept at the midpoint of the shorter segment
pt2=lineutility.CalcTrueIntersectDouble2(-1/m0.value[0],b0,m0.value[0],b2,1,1,0,0);
X0=pt2.x;
Y0=pt2.y;
}
if(m0.value[0]==0 && bolVertical!=0)
{
X0= ( pLinePoints[oppSegment].x+pLinePoints[oppSegment+1].x )/2;
Y0= ( pt0.y+pt1.y )/2;
}
if(bolVertical==0)
{
Y0= ( pLinePoints[oppSegment].y+pLinePoints[oppSegment+1].y )/2;
X0= ( pt0.x+pt1.x )/2;
}
}
//slope is not too small or is vertical, use left to right
if (Math.abs(m0.value[0]) >= 1 || bolVertical == 0) {
nOrientation = 0; //left to right orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j) {
//for BELT1 we only want to know if the opposing segment is to the
//left of the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j) //change 2
continue;
if ((pLinePoints[j].y <= Y0 && pLinePoints[j + 1].y >= Y0) ||
(pLinePoints[j].y >= Y0 && pLinePoints[j + 1].y <= Y0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 1 && m.value[0] == 0) //current segment is horizontal, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter
}
//current segment is vertical, it's x value must be to the left
//of the current segment X0 for the horiz line from the left to cross
if (bolVertical2 == 0) {
if (pLinePoints[j].x < X0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the X value of the intersection between the horiz line
//from the left and the current segment
//b=Y0;
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
X = (Y0 - b) / m.value[0];
if (X < X0) //the horizontal line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
} //end if
else //use top to bottom to get orientation
{
nOrientation = 1; //top down orientation
for (j = 0; j < vblCounter - 1; j++) {
if (index != j)
{
//for BELT1 we only want to know if the opposing segment is
//above the segment (index), do not check other segments
if(lineType==TacticalLines.BELT1 && oppSegment!=j)
continue;
if ((pLinePoints[j].x <= X0 && pLinePoints[j + 1].x >= X0) ||
(pLinePoints[j].x >= X0 && pLinePoints[j + 1].x <= X0)) {
bolVertical2 = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
if (bolVertical2 == 0) //current segment is vertical, this should not happen
{ //counter unaffected
nInOutCounter++;
nInOutCounter
}
//current segment is horizontal, it's y value must be above
//the current segment Y0 for the horiz line from the left to cross
if (bolVertical2 == 1 && m.value[0] == 0) {
if (pLinePoints[j].y < Y0) {
nInOutCounter++;
}
}
//current segment is not horizontal and not vertical
if (m.value[0] != 0 && bolVertical2 == 1) {
//get the Y value of the intersection between the vertical line
//from the top and the current segment
b = pLinePoints[j].y - m.value[0] * pLinePoints[j].x;
Y = m.value[0] * X0 + b;
if (Y < Y0) //the vertical line crosses the segment
{
nInOutCounter++;
}
}
} //end if
}
} //end for
}
switch (nInOutCounter % 2) {
case 0:
if (nOrientation == 0) {
nDirection = extendLeft;
} else {
nDirection = extendAbove;
}
break;
case 1:
if (nOrientation == 0) {
nDirection = extendRight;
} else {
nDirection = extendBelow;
}
break;
default:
break;
}
//reverse direction for ICING
switch(lineType)
{
case TacticalLines.ICING:
if(nDirection==extendLeft)
nDirection=extendRight;
else if(nDirection==extendRight)
nDirection=extendLeft;
else if(nDirection==extendAbove)
nDirection=extendBelow;
else if(nDirection==extendBelow)
nDirection=extendAbove;
break;
default:
break;
}
} catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetInsideOutsideDouble2",
new RendererException("GetInsideOutsideDouble2", exc));
}
return nDirection;
}
/**
* BELT1 line and others
* @param pLinePoints
* @param lineType
* @param vblSaveCounter
* @return
*/
protected static int GetZONEPointsDouble2(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0, n = 0;
int lCount = 0;
double dLengthSegment = 0;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = null, pt2 = null, pt3 = null;
POINT2[] pSpikePoints = null;
int nDirection = 0;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
double remainder=0;
//for(j=0;j<numpts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++) {
pt1 = new POINT2(pLinePoints[j]);
pt2 = new POINT2(pLinePoints[j + 1]);
//get the direction for the spikes
nDirection = GetInsideOutsideDouble2(pt1, pt2, pLinePoints, vblSaveCounter, (int) j, lineType);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
//reverse the direction for those lines with inward spikes
if (!(lineType == TacticalLines.BELT) && !(lineType == TacticalLines.BELT1) )
{
if (dLengthSegment < 20) {
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
switch (nDirection) {
case 0: //extend left
nDirection = 1; //extend right
break;
case 1: //extend right
nDirection = 0; //extend left
break;
case 2: //extend above
nDirection = 3; //extend below
break;
case 3: //extgend below
nDirection = 2; //extend above
break;
default:
break;
}
break;
default:
break;
}
n = (int) (dLengthSegment / 20);
remainder=dLengthSegment-n*20;
for (k = 0; k < n; k++)
{
if(k>0)
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20-remainder/2, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10-remainder/2, 0);//was -10
}
else
{
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20, 0);//was +0
pSpikePoints[nCounter++] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * 20 - 10, 0);//was -10
}
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], 5);
break;
case TacticalLines.STRONG:
case TacticalLines.FORT:
pt0 = new POINT2(pSpikePoints[nCounter - 1]);
break;
default:
break;
}
pSpikePoints[nCounter++] = lineutility.ExtendDirectedLine(pt1, pt2, pt0, nDirection, 10);
//nCounter++;
switch (lineType) {
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.BELT1:
case TacticalLines.ENCIRCLE:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
break;
case TacticalLines.STRONG:
pSpikePoints[nCounter] = new POINT2(pSpikePoints[nCounter - 2]);
break;
case TacticalLines.FORT:
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], 10, 0);
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pt1, pt2, pt3, nDirection, 10);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pt3);
break;
default:
break;
}
nCounter++;
//diagnostic
if(lineType==TacticalLines.ENCIRCLE)
pSpikePoints[nCounter++] = new POINT2(pSpikePoints[nCounter-4]);
}//end for k
pSpikePoints[nCounter++] = new POINT2(pLinePoints[j + 1]);
//nCounter++;
}//end for j
for (j = 0; j < nCounter; j++) {
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[j].style = 11;
}
}
if (lineType == (long) TacticalLines.OBSAREA) {
pSpikePoints[nCounter - 1].style = 12;
} else {
if(nCounter>0)
pSpikePoints[nCounter - 1].style = 5;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
if (j == nCounter - 1) {
if (lineType != (long) TacticalLines.OBSAREA) {
pLinePoints[j].style = 5;
}
}
}
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetZONEPointsDouble2",
new RendererException("GetZONEPointsDouble2", exc));
}
return nCounter;
}
private static boolean IsTurnArcReversed(POINT2[] pPoints) {
try {
if (pPoints.length < 3) {
return false;
}
POINT2[] ptsSeize = new POINT2[2];
ptsSeize[0] = new POINT2(pPoints[0]);
ptsSeize[1] = new POINT2(pPoints[1]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double d = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize[0] = new POINT2(pPoints[1]);
ptsSeize[1] = new POINT2(pPoints[0]);
lineutility.CalcClockwiseCenterDouble(ptsSeize);
double dArcReversed = lineutility.CalcDistanceDouble(ptsSeize[0], pPoints[2]);
ptsSeize = null;
if (dArcReversed > d) {
return true;
} else {
return false;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "IsTurnArcReversed",
new RendererException("IsTurnArcReversed", exc));
}
return false;
}
private static void GetIsolatePointsDouble(POINT2[] pLinePoints,
int lineType) {
try {
//declarations
boolean reverseTurn=false;
POINT2 pt0 = new POINT2(pLinePoints[0]), pt1 = new POINT2(pLinePoints[1]), pt2 = new POINT2(pLinePoints[0]);
if(pt0.x==pt1.x && pt0.y==pt1.y)
pt1.x+=1;
POINT2 C = new POINT2(), E = new POINT2(), midPt = new POINT2();
int j = 0, k = 0, l = 0;
POINT2[] ptsArc = new POINT2[26];
POINT2[] midPts = new POINT2[7];
POINT2[] trianglePts = new POINT2[21];
POINT2[] pArrowPoints = new POINT2[3], reversepArrowPoints = new POINT2[3];
double dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
double dLength = Math.abs(dRadius - 20);
if(dRadius<40)
{
dLength=dRadius/1.5;
}
double d = lineutility.MBRDistance(pLinePoints, 2);
POINT2[] ptsSeize = new POINT2[2];
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(pLinePoints[j]);
}
if (pLinePoints.length >= 3) {
savepoints[2] = new POINT2(pLinePoints[2]);
}
lineutility.InitializePOINT2Array(ptsArc);
lineutility.InitializePOINT2Array(midPts);
lineutility.InitializePOINT2Array(trianglePts);
lineutility.InitializePOINT2Array(pArrowPoints);
lineutility.InitializePOINT2Array(reversepArrowPoints);
lineutility.InitializePOINT2Array(ptsSeize);
if (d / 7 > maxLength) {
d = 7 * maxLength;
}
if (d / 7 < minLength) { //was minLength
d = 7 * minLength; //was minLength
}
//change due to outsized arrow in 6.0, 11-3-10
if(d>140)
d=140;
//calculation points for the SEIZE arrowhead
//for SEIZE calculations
POINT2[] ptsArc2 = new POINT2[26];
lineutility.InitializePOINT2Array(ptsArc2);
//end declarations
E.x = 2 * pt1.x - pt0.x;
E.y = 2 * pt1.y - pt0.y;
ptsArc[0] = new POINT2(pLinePoints[1]);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if(lineType != TacticalLines.OCCUPY)
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) d / 7, pArrowPoints, 0);
else
lineutility.GetArrowHead4Double(ptsArc[24], ptsArc[25], (int) d / 7, (int) (1.75*d) / 7, pArrowPoints, 0);
pLinePoints[25].style = 5;
switch (lineType) {
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.ISOLATE:
for (j = 1; j <= 23; j++) {
if (j % 3 == 0) {
midPts[k].x = pt0.x - (long) ((dLength / dRadius) * (pt0.x - ptsArc[j].x));
midPts[k].y = pt0.y - (long) ((dLength / dRadius) * (pt0.y - ptsArc[j].y));
midPts[k].style = 0;
trianglePts[l] = new POINT2(ptsArc[j - 1]);
l++;
trianglePts[l] = new POINT2(midPts[k]);
l++;
trianglePts[l] = new POINT2(ptsArc[j + 1]);
trianglePts[l].style = 5;
l++;
k++;
}
}
for (j = 26; j < 47; j++) {
pLinePoints[j] = new POINT2(trianglePts[j - 26]);
}
pLinePoints[46].style = 5;
for (j = 47; j < 50; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 47]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.OCCUPY:
midPt.x = (pt1.x + ptsArc[25].x) / 2;
midPt.y = (pt1.y + ptsArc[25].y) / 2;
//lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) d / 7, reversepArrowPoints, 0);
lineutility.GetArrowHead4Double(midPt, ptsArc[25], (int) d / 7, (int) (1.75*d) / 7, reversepArrowPoints, 0);
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
}
for (j = 29; j < 32; j++) {
pLinePoints[j] = new POINT2(reversepArrowPoints[j - 29]);
pLinePoints[j].style = 0;
}
break;
case TacticalLines.SECURE:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
break;
case TacticalLines.TURN:
boolean changeArc = IsTurnArcReversed(savepoints); //change 1
if (reverseTurn == true || changeArc == true) //swap the points
{
pt0.x = pt1.x;
pt0.y = pt1.y;
pt1.x = pt2.x;
pt1.y = pt2.y;
}
ptsSeize[0] = new POINT2(pt0);
ptsSeize[1] = new POINT2(pt1);
dRadius = lineutility.CalcClockwiseCenterDouble(ptsSeize);
C = new POINT2(ptsSeize[0]);
E = new POINT2(ptsSeize[1]);
ptsArc[0] = new POINT2(pt0);
ptsArc[1] = new POINT2(E);
lineutility.ArcArrayDouble(ptsArc, 0, dRadius, lineType);
for (j = 0; j < 26; j++) {
ptsArc[j].style = 0;
pLinePoints[j] = new POINT2(ptsArc[j]);
pLinePoints[j].style = 0;
}
if (changeArc == true)//if(changeArc==false) //change 1
{
lineutility.GetArrowHead4Double(ptsArc[1], pt0, (int) d / 7, (int) d / 7, pArrowPoints, 5);
} else {
lineutility.GetArrowHead4Double(ptsArc[24], pt1, (int) d / 7, (int) d / 7, pArrowPoints, 5);
}
pLinePoints[25].style = 5;
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 9;
}
pLinePoints[28].style = 10;
break;
case TacticalLines.RETAIN:
for (j = 26; j < 29; j++) {
pLinePoints[j] = new POINT2(pArrowPoints[j - 26]);
pLinePoints[j].style = 0;
}
pLinePoints[28].style = 5;
//get the extended points for retain
k = 29;
for (j = 1; j < 24; j++) {
pLinePoints[k] = new POINT2(ptsArc[j]);
pLinePoints[k].style = 0;
k++;
pLinePoints[k] = lineutility.ExtendLineDouble(pt0, ptsArc[j], (long) d / 7);
pLinePoints[k].style = 5;
k++;
}
break;
default:
break;
}
//clean up
savepoints = null;
ptsArc = null;
midPts = null;
trianglePts = null;
pArrowPoints = null;
reversepArrowPoints = null;
ptsSeize = null;
ptsArc2 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIsolatePointsDouble",
new RendererException("GetIsolatePointsDouble " + Integer.toString(lineType), exc));
}
return;
}
/**
* @deprecated
* returns the location for the Dummy Hat
* @param pLinePoints
* @return
*/
private static POINT2 getDummyHat(POINT2[]pLinePoints)
{
POINT2 pt=null;
try
{
int j=0;
double minY=Double.MAX_VALUE;
double minX=Double.MAX_VALUE,maxX=-Double.MAX_VALUE;
int index=-1;
//get the highest point
for(j=0;j<pLinePoints.length-3;j++)
{
if(pLinePoints[j].y<minY)
{
minY=pLinePoints[j].y;
index=j;
}
if(pLinePoints[j].x<minX)
minX=pLinePoints[j].x;
if(pLinePoints[j].x>maxX)
maxX=pLinePoints[j].x;
}
pt=new POINT2(pLinePoints[index]);
double deltaMaxX=0;
double deltaMinX=0;
if(pt.x+25>maxX)
{
deltaMaxX=pt.x+25-maxX;
pt.x-=deltaMaxX;
}
if(pt.x-25<minX)
{
deltaMinX=minX-(pt.x-25);
pt.x+=deltaMinX;
}
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "getDummyHat",
new RendererException("getDummyHat", exc));
}
return pt;
}
private static void AreaWithCenterFeatureDouble(POINT2[] pLinePoints,
int vblCounter,
int lineType )
{
try
{
//declarations
int k=0;
POINT2 ptCenter = new POINT2();
int fLength=4;
if(lineType==TacticalLines.AIRFIELD)
fLength=5;
double d = lineutility.MBRDistance(pLinePoints, vblCounter-fLength);
//11-18-2010
if(d>350)
d=350;
//end declarations
for (k = 0; k < vblCounter; k++) {
pLinePoints[k].style = 0;
}
switch (lineType) {
case TacticalLines.DUMMY:
if(d<20)
d=20;
if(d>60)
d=60;
POINT2 ul=new POINT2();
POINT2 lr=new POINT2();
lineutility.CalcMBRPoints(pLinePoints, vblCounter-4, ul, lr);
//ul=getDummyHat(pLinePoints);
//ul.x-=25;
POINT2 ur=new POINT2(lr);
ur.y=ul.y;
pLinePoints[vblCounter-3]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-3].x-=d/2;
pLinePoints[vblCounter-3].y-=d/5;
pLinePoints[vblCounter-2]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-2].y-=d*0.7;
pLinePoints[vblCounter-1]=lineutility.MidPointDouble(ur, ul, 0);
pLinePoints[vblCounter-1].x+=d/2;
pLinePoints[vblCounter-1].y-=d/5;
pLinePoints[vblCounter-4].style=5;
break;
case TacticalLines.AIRFIELD:
if(d<100)
d=100;
pLinePoints[vblCounter - 5] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 5].style = 5;
pLinePoints[vblCounter - 4] = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 6);
pLinePoints[vblCounter - 4].x -= d / 10; //was 20
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 3].x = pLinePoints[vblCounter - 4].x + d / 5;//was 10
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 4]);
pLinePoints[vblCounter - 2].y += d / 20;//was 40
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 3]);
pLinePoints[vblCounter - 1].y -= d / 20;//was 40
pLinePoints[vblCounter - 1].style = 0;
break;
case TacticalLines.DMA:
if(d<50)
d=50;
if (lineType == (long) TacticalLines.DMA) {
for (k = 0; k < vblCounter - 4; k++) {
pLinePoints[k].style = 14;
}
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[0]);
pLinePoints[vblCounter - 4].style = 5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
break;
case TacticalLines.DMAF:
if(d<50)
d=50;
pLinePoints[vblCounter-4].style=5;
ptCenter = lineutility.CalcCenterPointDouble(pLinePoints, vblCounter - 4);
pLinePoints[vblCounter - 3].x = ptCenter.x - d / 10;
pLinePoints[vblCounter - 3].y = ptCenter.y;
pLinePoints[vblCounter - 3].style = 18;
pLinePoints[vblCounter - 2].x = ptCenter.x;
pLinePoints[vblCounter - 2].y = ptCenter.y - d / 10;
pLinePoints[vblCounter - 2].style = 18;
pLinePoints[vblCounter - 1].x = ptCenter.x + d / 10;
pLinePoints[vblCounter - 1].y = ptCenter.y;
pLinePoints[vblCounter - 1].style = 5;
break;
default:
break;
}
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AreaWithCenterFeatureDouble",
new RendererException("AreaWithCenterFeatureDouble " + Integer.toString(lineType), exc));
}
}
private static int GetATWallPointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 0;
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dRemainder = 0, dSpikeSize = 0;
int limit = 0;
POINT2 crossPt1, crossPt2;
//end delcarations
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
switch (lineType) {
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter] = pLinePoints[0];
pSpikePoints[nCounter].style = 0;
nCounter++;
break;
default:
break;
}
for (j = 0; j < vblSaveCounter - 1; j++) {
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
switch (lineType) {
case TacticalLines.UCF:
case TacticalLines.CF:
case TacticalLines.CFG:
case TacticalLines.CFY:
dIncrement = 60;
dSpikeSize = 20;
dRemainder = dLengthSegment / dIncrement - (double) ((int) (dLengthSegment / dIncrement));
if (dRemainder < 0.75) {
limit = (int) (dLengthSegment / dIncrement);
} else {
limit = (int) (dLengthSegment / dIncrement) + 1;
}
break;
default:
dIncrement = 20;
dSpikeSize = 10;
limit = (int) (dLengthSegment / dIncrement) - 1;
break;
}
if (limit < 1) {
pSpikePoints[nCounter] = pLinePoints[j];
nCounter++;
pSpikePoints[nCounter] = pLinePoints[j + 1];
nCounter++;
continue;
}
for (k = 0; k < limit; k++) {
switch (lineType) {
case TacticalLines.CFG: //linebreak for dot
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 4, 5);
nCounter++;
//dot
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 1, 20);
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 7, 0);
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
case TacticalLines.CFY: //linebreak for crossed line
if (k > 0) {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 45, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement + 10, 5);
nCounter++;
//dot
//pSpikePoints[nCounter]=lineutility.ExtendLine2Double(pLinePoints[j+1],pLinePoints[j],-k*dIncrement-1,20);
//nCounter++;
//replace the dot with crossed line segment
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 5, 0);
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendAlongLineDouble(pSpikePoints[nCounter - 1], pLinePoints[j + 1], 10, 5);
nCounter++;
crossPt1 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 1], 2, 5, 0);
crossPt2 = lineutility.ExtendDirectedLine(pSpikePoints[nCounter - 1], pSpikePoints[nCounter - 2], pSpikePoints[nCounter - 2], 3, 5, 5);
pSpikePoints[nCounter] = crossPt1;
nCounter++;
pSpikePoints[nCounter] = crossPt2;
nCounter++;
//remainder of line
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 13, 0);
} else {
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 45, 0);
}
break;
default:
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - 30, 0);
break;
}
if (lineType == TacticalLines.CF) {
pSpikePoints[nCounter].style = 0;
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement - dSpikeSize, 0);
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter].style = 9;
}
nCounter++;
pt0 = lineutility.ExtendLineDouble(pLinePoints[j], pSpikePoints[nCounter - 1], dSpikeSize / 2);
//the spikes
if (pLinePoints[j].x > pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 2, dSpikeSize);
}
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pSpikePoints[nCounter - 1], pt0, 3, dSpikeSize);
}
if (pLinePoints[j].x == pLinePoints[j + 1].x) {
pSpikePoints[nCounter] = pt0;
if (pLinePoints[j].y < pLinePoints[j + 1].y) //extend left of line
{
pSpikePoints[nCounter].x = pt0.x - dSpikeSize;
} else //extend right of line
{
pSpikePoints[nCounter].x = pt0.x + dSpikeSize;
}
}
nCounter++;
if (lineType == TacticalLines.CF ||
lineType == TacticalLines.CFG ||
lineType == TacticalLines.CFY) {
pSpikePoints[nCounter - 1].style = 9;
}
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 2], dSpikeSize, 0);
//need an extra point for these
switch (lineType) {
case TacticalLines.CF:
pSpikePoints[nCounter].style = 10;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
pSpikePoints[nCounter].style = 10;
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j], pSpikePoints[nCounter - 3], dSpikeSize, 0);
break;
default:
break;
}
nCounter++;
}
//use the original line point for the segment end point
pSpikePoints[nCounter] = pLinePoints[j + 1];
pSpikePoints[nCounter].style = 0;
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = pSpikePoints[j];
}
pLinePoints[nCounter-1].style=5;
//clean up
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetATWallPointsDouble",
new RendererException("GetATWallPointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
private static int GetRidgePointsDouble(POINT2[] pLinePoints,
int lineType,
int vblSaveCounter) {
int nCounter = 0;
try {
//declarations
int j = 0, k = 0;
int lCount = 0;
double dLengthSegment = 0, dIncrement = 20;
ref<double[]> m = new ref();
POINT2[] pSpikePoints = null;
POINT2 pt0;
double dSpikeSize = 20;
int limit = 0;
double d = 0;
int bolVertical = 0;
//end delcarations
m.value = new double[1];
lCount = countsupport.GetFORTLCountDouble(pLinePoints, lineType, vblSaveCounter);
pSpikePoints = new POINT2[lCount];
lineutility.InitializePOINT2Array(pSpikePoints);
//for(j=0;j<numPts2-1;j++)
for (j = 0; j < vblSaveCounter - 1; j++)
{
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1], m);
dLengthSegment = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
limit = (int) (dLengthSegment / dIncrement);
if (limit < 1)
{
pSpikePoints[nCounter] = new POINT2(pLinePoints[j]);
nCounter++;
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
continue;
}
for (k = 0; k < limit; k++)
{
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -k * dIncrement, 0);
nCounter++;
d = lineutility.CalcDistanceDouble(pLinePoints[j], pSpikePoints[nCounter - 1]);
pt0 = lineutility.ExtendLineDouble(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize / 2);
//the spikes
if (bolVertical != 0) //segment is not vertical
{
if (pLinePoints[j].x < pLinePoints[j + 1].x) //extend above the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 2, dSpikeSize);
}
else //extend below the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 3, dSpikeSize);
}
}
else //segment is vertical
{
if (pLinePoints[j + 1].y < pLinePoints[j].y) //extend left of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 0, dSpikeSize);
}
else //extend right of the line
{
pSpikePoints[nCounter] = lineutility.ExtendDirectedLine(pLinePoints[j], pLinePoints[j + 1], pt0, 1, dSpikeSize);
}
}
nCounter++;
pSpikePoints[nCounter] = lineutility.ExtendLine2Double(pLinePoints[j + 1], pLinePoints[j], -d - dSpikeSize, 0);
nCounter++;
}
pSpikePoints[nCounter] = new POINT2(pLinePoints[j + 1]);
nCounter++;
}
for (j = 0; j < nCounter; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[j]);
}
for (j = nCounter; j < lCount; j++) {
pLinePoints[j] = new POINT2(pSpikePoints[nCounter - 1]);
}
//clean up
//segments=null;
pSpikePoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRidgePointsDouble",
new RendererException("GetRidgePointsDouble " + Integer.toString(lineType), exc));
}
return nCounter;
}
protected static int GetSquallDouble(POINT2[] pLinePoints,
int amplitude,
int quantity,
int length,
int numPoints)
{
int counter = 0;
try {
int j = 0, k = 0;
POINT2 StartSegPt, EndSegPt;
POINT2 savePoint1 = new POINT2(pLinePoints[0]);
POINT2 savePoint2 = new POINT2(pLinePoints[numPoints - 1]);
ref<int[]> sign = new ref();
int segQty = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints);
POINT2[] pSquallPts = new POINT2[totalQty];
POINT2[] pSquallSegPts = null;
//end declarations
lineutility.InitializePOINT2Array(pSquallPts);
sign.value = new int[1];
sign.value[0] = -1;
if (totalQty == 0) {
return 0;
}
for (j = 0; j < numPoints - 1; j++) {
//if(segments[j]!=0)
StartSegPt = new POINT2(pLinePoints[j]);
EndSegPt = new POINT2(pLinePoints[j + 1]);
segQty = countsupport.GetSquallSegQty(StartSegPt, EndSegPt, quantity, length);
if (segQty > 0)
{
pSquallSegPts = new POINT2[segQty];
lineutility.InitializePOINT2Array(pSquallSegPts);
}
else
{
pSquallPts[counter].x = StartSegPt.x;
pSquallPts[counter++].y = StartSegPt.y;
pSquallPts[counter].x = EndSegPt.x;
pSquallPts[counter++].y = EndSegPt.y;
continue;
}
sign.value[0]=-1;
lineutility.GetSquallSegment(StartSegPt, EndSegPt, pSquallSegPts, sign, amplitude, quantity, length);
for (k = 0; k < segQty; k++)
{
pSquallPts[counter].x = pSquallSegPts[k].x;
pSquallPts[counter].y = pSquallSegPts[k].y;
if (k == 0)
{
pSquallPts[counter] = new POINT2(pLinePoints[j]);
}
if (k == segQty - 1)
{
pSquallPts[counter] = new POINT2(pLinePoints[j + 1]);
}
pSquallPts[counter].style = 0;
counter++;
}
}
//load the squall points into the linepoints array
for (j = 0; j < counter; j++) {
if (j < totalQty)
{
pLinePoints[j].x = pSquallPts[j].x;
pLinePoints[j].y = pSquallPts[j].y;
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
}
if (j == counter - 1)
{
pLinePoints[j] = new POINT2(savePoint2);
}
pLinePoints[j].style = pSquallPts[j].style;
}
}
if (counter == 0)
{
for (j = 0; j < pLinePoints.length; j++)
{
if (j == 0)
{
pLinePoints[j] = new POINT2(savePoint1);
} else
{
pLinePoints[j] = new POINT2(savePoint2);
}
}
counter = pLinePoints.length;
}
//clean up
pSquallPts = null;
pSquallSegPts = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSquallDouble",
new RendererException("GetSquallDouble", exc));
}
return counter;
}
protected static int GetSevereSquall(POINT2[] pLinePoints,
int numPoints) {
int l = 0;
try
{
int quantity = 5, length = 30, j = 0, k = 0;
int totalQty = countsupport.GetSquallQty(pLinePoints, quantity, length, numPoints) + 2 * numPoints;
POINT2[] squallPts = new POINT2[totalQty];
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), pt2 = new POINT2(),
pt3 = new POINT2(), pt4 = new POINT2(), pt5 = new POINT2(), pt6 = new POINT2(),
pt7 = new POINT2(),pt8 = new POINT2();
int segQty = 0;
double dist = 0;
//end declarations
lineutility.InitializePOINT2Array(squallPts);
for (j = 0; j < numPoints - 1; j++)
{
dist = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
segQty = (int) (dist / 30);
for (k = 0; k < segQty; k++) {
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30);
pt1 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 20);
//pt0.style = 5;
pt5 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 25);
pt6 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 30);
//pt6.style=5;
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 5, 0); //extend above line
pt3 = lineutility.ExtendDirectedLine(pt0, pt5, pt5, 3, 5, 0); //extend below line
pt4 = lineutility.ExtendDirectedLine(pt0, pt6, pt6, 2, 5, 5); //extend above line
pt4.style=5;
squallPts[l++] = new POINT2(pt2);
squallPts[l++] = new POINT2(pt3);
squallPts[l++] = new POINT2(pt4);
pt7 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 5);
pt8 = lineutility.ExtendAlongLineDouble(pLinePoints[j], pLinePoints[j + 1], k * 30 + 10);
pt8.style=5;
squallPts[l++] = new POINT2(pt7);
squallPts[l++] = new POINT2(pt8);
}
//segment remainder
squallPts[l++] = new POINT2(pLinePoints[j + 1]);
pt0 = lineutility.ExtendAlongLineDouble(pLinePoints[j+1], pLinePoints[j], 5);
pt0.style=5;
squallPts[l++]=new POINT2(pt0);
}
if(l>pLinePoints.length)
l=pLinePoints.length;
for (j = 0; j < l; j++)
{
if (j < totalQty)
{
pLinePoints[j] = new POINT2(squallPts[j]);
}
else
break;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetSevereSquall",
new RendererException("GetSevereSquall", exc));
}
return l;
}
private static int GetConvergancePointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = vblCounter;
try {
int j = 0, k = 0;
//int counter=vblCounter;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
pLinePoints[vblCounter - 1].style = 5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 10);
//we don't want too small a remainder
if (d - numJags * 10 < 5)
{
numJags -= 1;
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
//the first spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 10 + 5, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 2, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
//the 2nd spike
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, (k + 1) * 10, 0);
pLinePoints[counter++] = new POINT2(tempPt);
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 5);
tempPt = lineutility.ExtendDirectedLine(pt0, tempPt, tempPt, 3, 5, 5);
pLinePoints[counter++] = new POINT2(tempPt);
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetConvergancePointsDouble",
new RendererException("GetConvergancePointsDouble", exc));
}
return counter;
}
private static int GetITDPointsDouble(POINT2[] pLinePoints, int vblCounter)
{
int counter = 0;
try {
int j = 0, k = 0;
double d = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2();
POINT2[] tempPts = new POINT2[vblCounter];
POINT2 tempPt = new POINT2();
int numJags = 0, lineStyle = 19;
//save the original points
for (j = 0; j < vblCounter; j++) {
tempPts[j] = new POINT2(pLinePoints[j]);
}
//result points begin with the original points,
//set the last one's linestyle to 5;
//pLinePoints[vblCounter-1].style=5;
for (j = 0; j < vblCounter - 1; j++)
{
pt0 = new POINT2(tempPts[j]);
pt1 = new POINT2(tempPts[j + 1]);
d = lineutility.CalcDistanceDouble(pt0, pt1);
numJags = (int) (d / 15);
//we don't want too small a remainder
if (d - numJags * 10 < 5) {
numJags -= 1;
}
if(numJags==0)
{
pt0.style=19;
pLinePoints[counter++] = new POINT2(pt0);
pt1.style=5;
pLinePoints[counter++] = new POINT2(pt1);
}
//each 10 pixel section has two spikes: one points above the line
//the other spike points below the line
for (k = 0; k < numJags; k++) {
tempPt = lineutility.ExtendAlongLineDouble(pt0, pt1, k * 15 + 5, lineStyle);
pLinePoints[counter++] = new POINT2(tempPt);
if (k < numJags - 1) {
tempPt = lineutility.ExtendAlongLineDouble(tempPt, pt1, 10, 5);
} else {
tempPt = new POINT2(tempPts[j + 1]);
tempPt.style = 5;
}
pLinePoints[counter++] = new POINT2(tempPt);
if (lineStyle == 19) {
lineStyle = 25;
} else {
lineStyle = 19;
}
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetITDPointsDouble",
new RendererException("GetITDPointsDouble", exc));
}
return counter;
}
private static int GetXPoints(int linetype, POINT2[] pOriginalLinePoints, POINT2[] XPoints, int vblCounter)
{
int xCounter=0;
try
{
int j=0,k=0;
double d=0;
POINT2 pt0,pt1,pt2,pt3=new POINT2(),pt4=new POINT2(),pt5=new POINT2(),pt6=new POINT2();
int numThisSegment=0;
double distInterval=0;
for(j=0;j<vblCounter-1;j++)
{
d=lineutility.CalcDistanceDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1]);
numThisSegment=(int)( (d-20d)/20d);
if(linetype==TacticalLines.LRO)
numThisSegment=(int)( (d-30d)/30d);
//added 4-19-12
distInterval=d/numThisSegment;
for(k=0;k<numThisSegment;k++)
{
//pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1], 10+20*k);
pt0=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j],pOriginalLinePoints[j+1], distInterval/2+distInterval*k);
pt1=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], 5);
pt2=lineutility.ExtendAlongLineDouble2(pt0,pOriginalLinePoints[j+1], -5);
pt3=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 2, 5);
pt4=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt1, pt1, 3, 5);
pt4.style=5;
pt5=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 2, 5);
pt6=lineutility.ExtendDirectedLine(pOriginalLinePoints[j], pt2, pt2, 3, 5);
pt6.style=5;
XPoints[xCounter++]=new POINT2(pt3);
XPoints[xCounter++]=new POINT2(pt6);
XPoints[xCounter++]=new POINT2(pt5);
XPoints[xCounter++]=new POINT2(pt4);
}
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetXPointsDouble",
new RendererException("GetXPointsDouble", exc));
}
return xCounter;
}
/**
* returns a 37 point ellipse
* @param ptCenter
* @param ptWidth
* @param ptHeight
* @return
*/
private static POINT2[] getEllipsePoints(POINT2 ptCenter, POINT2 ptWidth, POINT2 ptHeight)
{
POINT2[]pEllipsePoints=null;
try
{
pEllipsePoints=new POINT2[37];
int l=0;
double dFactor=0;
double a=lineutility.CalcDistanceDouble(ptCenter, ptWidth);
double b=lineutility.CalcDistanceDouble(ptCenter, ptHeight);
lineutility.InitializePOINT2Array(pEllipsePoints);
for (l = 1; l < 37; l++)
{
//dFactor = (20.0 * l) * Math.PI / 180.0;
dFactor = (10.0 * l) * Math.PI / 180.0;
pEllipsePoints[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints[l - 1].style = 0;
}
pEllipsePoints[36]=new POINT2(pEllipsePoints[0]);
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetEllipsePoints",
new RendererException("GetEllipsePoints", exc));
}
return pEllipsePoints;
}
private static int GetLVOPoints(int linetype, POINT2[] pOriginalLinePoints, POINT2[] pLinePoints, int vblCounter)
{
int lEllipseCounter = 0;
try {
//double dAngle = 0, d = 0, a = 13, b = 6, dFactor = 0;
double dAngle = 0, d = 0, a = 4, b = 8, dFactor = 0;
int lHowManyThisSegment = 0, j = 0, k = 0, l = 0, t = 0;
POINT2 ptCenter = new POINT2();
POINT2[] pEllipsePoints2 = new POINT2[37];
double distInterval=0;
//end declarations
for (j = 0; j < vblCounter - 1; j++)
{
lineutility.InitializePOINT2Array(pEllipsePoints2);
d = lineutility.CalcDistanceDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
//lHowManyThisSegment = (int) ((d - 10) / 10);
lHowManyThisSegment = (int) ((d - 20) / 20);
if(linetype==TacticalLines.LRO)
lHowManyThisSegment = (int) ((d - 30) / 30);
//added 4-19-12
distInterval=d/lHowManyThisSegment;
dAngle = lineutility.CalcSegmentAngleDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
dAngle = dAngle + Math.PI / 2;
for (k = 0; k < lHowManyThisSegment; k++)
{
//t = k;
//ptCenter=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*20+20);
ptCenter=lineutility.ExtendAlongLineDouble2(pOriginalLinePoints[j], pOriginalLinePoints[j+1], k*distInterval);
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}//end k loop
//extra ellipse on the final segment at the end of the line
if(j==vblCounter-2)
{
ptCenter=pOriginalLinePoints[j+1];
for (l = 1; l < 37; l++)
{
//dFactor = (10.0 * l) * Math.PI / 180.0;
dFactor = (20.0 * l) * Math.PI / 180.0;
pEllipsePoints2[l - 1].x = ptCenter.x + (int) (a * Math.cos(dFactor));
pEllipsePoints2[l - 1].y = ptCenter.y + (int) (b * Math.sin(dFactor));
pEllipsePoints2[l - 1].style = 0;
}
lineutility.RotateGeometryDouble(pEllipsePoints2, 36, (int) (dAngle * 180 / Math.PI));
pEllipsePoints2[36] = new POINT2(pEllipsePoints2[35]);
pEllipsePoints2[36].style = 5;
for (l = 0; l < 37; l++)
{
pLinePoints[lEllipseCounter] = new POINT2(pEllipsePoints2[l]);
lEllipseCounter++;
}
}
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetLVOPointsDouble",
new RendererException("GetLVOPointsDouble", exc));
}
return lEllipseCounter;
}
private static int GetIcingPointsDouble(POINT2[] pLinePoints, int vblCounter) {
int counter = 0;
try {
int j = 0;
POINT2[] origPoints = new POINT2[vblCounter];
int nDirection = -1;
int k = 0, numSegments = 0;
POINT2 pt0 = new POINT2(), pt1 = new POINT2(), midPt = new POINT2(), pt2 = new POINT2();
//save the original points
for (j = 0; j < vblCounter; j++) {
origPoints[j] = new POINT2(pLinePoints[j]);
}
double distInterval=0;
for (j = 0; j < vblCounter - 1; j++) {
//how many segments for this line segment?
numSegments = (int) lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1]);
numSegments /= 15; //segments are 15 pixels long
//4-19-12
distInterval=lineutility.CalcDistanceDouble(origPoints[j], origPoints[j + 1])/numSegments;
//get the direction and the quadrant
nDirection = GetInsideOutsideDouble2(origPoints[j], origPoints[j + 1], origPoints, vblCounter, j, TacticalLines.ICING);
for (k = 0; k < numSegments; k++) {
//get the parallel segment
if (k == 0) {
pt0 = new POINT2(origPoints[j]);
} else {
//pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15, 0);
pt0 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval, 0);
}
//pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 10, 5);
pt1 = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 10, 5);
//midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * 15 + 5, 0);
midPt = lineutility.ExtendAlongLineDouble(origPoints[j], origPoints[j + 1], k * distInterval + 5, 0);
//get the perpendicular segment
pt2 = lineutility.ExtendDirectedLine(origPoints[j], origPoints[j + 1], midPt, nDirection, 5, 5);
pLinePoints[counter] = new POINT2(pt0);
pLinePoints[counter + 1] = new POINT2(pt1);
pLinePoints[counter + 2] = new POINT2(midPt);
pLinePoints[counter + 3] = new POINT2(pt2);
counter += 4;
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetIcingPointsDouble",
new RendererException("GetIcingPointsDouble", exc));
}
return counter;
}
protected static int GetAnchorageDouble(POINT2[] vbPoints2, int numPts)
{
int lFlotCounter = 0;
try
{
//declarations
int j = 0, k = 0, l = 0;
int x1 = 0, y1 = 0;
int numSegPts = -1;
int lFlotCount = 0;
int lNumSegs = 0;
double dDistance = 0;
int[] vbPoints = null;
int[] points = null;
int[] points2 = null;
POINT2 pt = new POINT2();
POINT2 pt1 = new POINT2(), pt2 = new POINT2();
//end declarations
lFlotCount = flot.GetAnchorageCountDouble(vbPoints2, numPts);
vbPoints = new int[2 * numPts];
for (j = 0; j < numPts; j++)
{
vbPoints[k] = (int) vbPoints2[j].x;
k++;
vbPoints[k] = (int) vbPoints2[j].y;
k++;
}
k = 0;
ref<int[]> bFlip = new ref();
bFlip.value = new int[1];
ref<int[]> lDirection = new ref();
lDirection.value = new int[1];
ref<int[]> lLastDirection = new ref();
lLastDirection.value = new int[1];
for (l = 0; l < numPts - 1; l++)
{
//pt1=new POINT2();
//pt2=new POINT2();
pt1.x = vbPoints[2 * l];
pt1.y = vbPoints[2 * l + 1];
pt2.x = vbPoints[2 * l + 2];
pt2.y = vbPoints[2 * l + 3];
//for all segments after the first segment we shorten
//the line by 20 so the flots will not abut
if (l > 0)
{
pt1 = lineutility.ExtendAlongLineDouble(pt1, pt2, 20);
}
dDistance = lineutility.CalcDistanceDouble(pt1, pt2);
lNumSegs = (int) (dDistance / 20);
//ref<int[]> bFlip = new ref();
//bFlip.value = new int[1];
//ref<int[]> lDirection = new ref();
//lDirection.value = new int[1];
//ref<int[]> lLastDirection = new ref();
//lLastDirection.value = new int[1];
if (lNumSegs > 0) {
points2 = new int[lNumSegs * 32];
numSegPts = flot.GetAnchorageFlotSegment(vbPoints, (int) pt1.x, (int) pt1.y, (int) pt2.x, (int) pt2.y, l, points2, bFlip, lDirection, lLastDirection);
points = new int[numSegPts];
for (j = 0; j < numSegPts; j++)
{
points[j] = points2[j];
}
for (j = 0; j < numSegPts / 3; j++) //only using half the flots
{
x1 = points[k];
y1 = points[k + 1];
//z = points[k + 2];
k += 3;
if (j % 10 == 0) {
pt.x = x1;
pt.y = y1;
pt.style = 5;
}
else if ((j + 1) % 10 == 0)
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter++].y = y1;
vbPoints2[lFlotCounter++] = new POINT2(pt);
continue;
}
else
{
break;
}
}
if (lFlotCounter < lFlotCount) {
vbPoints2[lFlotCounter].x = x1;
vbPoints2[lFlotCounter].y = y1;
lFlotCounter++;
} else {
break;
}
}
k = 0;
points = null;
} else
{
if (lFlotCounter < lFlotCount)
{
vbPoints2[lFlotCounter].x = vbPoints[2 * l];
vbPoints2[lFlotCounter].y = vbPoints[2 * l + 1];
lFlotCounter++;
}
}
}
for (j = lFlotCounter - 1; j < lFlotCount; j++)
{
vbPoints2[j].style = 5;
}
//clean up
vbPoints = null;
points = null;
points2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetAnchorageDouble",
new RendererException("GetAnchorageDouble", exc));
}
return lFlotCounter;
}
private static int GetPipePoints(POINT2[] pLinePoints,
int vblCounter)
{
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2[] xPoints = new POINT2[pLinePoints.length];
int xCounter = 0;
int j=0,k=0;
for (j = 0; j < vblCounter; j++)
{
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0;
double d = 0;
lineutility.InitializePOINT2Array(xPoints);
for (j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 20);
for (k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt1.style = 5;
pt2 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 20 * k + 10);
pt2.style = 20; //for filled circle
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
xPoints[xCounter++] = new POINT2(pt2);
}
if (numSegs == 0)
{
pLinePoints[counter] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++].style=0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style=5;
}
else
{
pLinePoints[counter] = new POINT2(pLinePoints[counter - 1]);
pLinePoints[counter++].style = 0;
pLinePoints[counter] = new POINT2(pOriginalPoints[j + 1]);
pLinePoints[counter++].style = 5;
}
}
//load the circle points
for (k = 0; k < xCounter; k++)
{
pLinePoints[counter++] = new POINT2(xPoints[k]);
}
//add one more circle
pLinePoints[counter++] = new POINT2(pLinePoints[counter]);
pOriginalPoints = null;
xPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetPipePoints",
new RendererException("GetPipePoints", exc));
}
return counter;
}
private static int GetReefPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
POINT2 pt4 = new POINT2();
//POINT2 pt5=new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int numSegs = 0,direction=0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++) {
if(pOriginalPoints[j].x<pOriginalPoints[j+1].x)
direction=2;
else
direction=3;
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 40);
for (int k = 0; k < numSegs; k++) {
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * k);
pt1 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 10);
pt1 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt1, direction, 15);//was 2
pt2 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 20);
pt2 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 5);//was 2
pt3 = lineutility.ExtendAlongLineDouble2(pt0, pOriginalPoints[j + 1], 30);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt3, direction, 20);//was 2
pt4 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 40 * (k + 1));
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt4);
}
if (numSegs == 0) {
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetReefPoints",
new RendererException("GetReefPoints", exc));
}
return counter;
}
private static int GetRestrictedAreaPoints(POINT2[] pLinePoints,
int vblCounter) {
int counter = 0;
try {
POINT2[] pOriginalPoints = new POINT2[vblCounter];
POINT2 pt0 = new POINT2();
POINT2 pt1 = new POINT2();
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
for (int j = 0; j < vblCounter; j++) {
pOriginalPoints[j] = new POINT2(pLinePoints[j]);
}
int direction=0;
int numSegs = 0;
double d = 0;
for (int j = 0; j < vblCounter - 1; j++)
{
d = lineutility.CalcDistanceDouble(pOriginalPoints[j], pOriginalPoints[j + 1]);
numSegs = (int) (d / 15);
if(pOriginalPoints[j].x < pOriginalPoints[j+1].x)
direction=3;
else
direction=2;
for (int k = 0; k < numSegs; k++)
{
pt0 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k);
pt0.style = 0;
pt1 = lineutility.ExtendAlongLineDouble2(pOriginalPoints[j], pOriginalPoints[j + 1], 15 * k + 10);
pt1.style = 5;
pt2 = lineutility.MidPointDouble(pt0, pt1, 0);
//pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pOriginalPoints[j], pOriginalPoints[j + 1], pt2, direction, 10);
pt3.style = 5;
pLinePoints[counter++] = new POINT2(pt2);
pLinePoints[counter++] = new POINT2(pt3);
pLinePoints[counter++] = new POINT2(pt0);
pLinePoints[counter++] = new POINT2(pt1);
}
if (numSegs == 0)
{
pLinePoints[counter++] = new POINT2(pOriginalPoints[j]);
pLinePoints[counter++] = new POINT2(pOriginalPoints[j + 1]);
}
}
pLinePoints[counter - 1].style = 0;
pLinePoints[counter++] = new POINT2(pOriginalPoints[vblCounter - 1]);
pOriginalPoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "GetRestrictedAreaPoints",
new RendererException("GetRestrictedAreaPoints", exc));
}
return counter;
}
//there should be two linetypes depending on scale
private static int getOverheadWire(POINT2[]pLinePoints, int vblCounter)
{
int counter=0;
try
{
int j=0;
POINT2 pt=null,pt2=null;
double x=0,y=0;
ArrayList<POINT2>pts=new ArrayList();
for(j=0;j<vblCounter;j++)
{
pt=new POINT2(pLinePoints[j]);
x=pt.x;
y=pt.y;
//tower
pt2=new POINT2(pt);
pt2.y -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.y -=5;
pt2.style=5;
pts.add(pt2);
//low cross piece
pt2=new POINT2(pt);
pt2.x -=2;
pt2.y-=10;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=2;
pt2.y-=10;
pt2.style=5;
pts.add(pt2);
//high cross piece
pt2=new POINT2(pt);
pt2.x -=7;
pt2.y-=17;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x -=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=5;
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x +=7;
pt2.y-=17;
pt2.style=5;
pts.add(pt2);
//angle piece
pt2=new POINT2(pt);
pt2.y-=20;
pts.add(pt2);
pt2=new POINT2(pt);
pt2.x+=8;
pt2.y-=12;
pt2.style=5;
pts.add(pt2);
}
//connect the towers
for(j=0;j<vblCounter-1;j++)
{
pt=new POINT2(pLinePoints[j]);
pt2=new POINT2(pLinePoints[j+1]);
if(pt.x<pt2.x)
{
pt.x+=5;
pt.y -=10;
pt2.x-=5;
pt2.y-=10;
pt2.style=5;
}
else
{
pt.x-=5;
pt.y -=10;
pt2.x+=5;
pt2.y-=10;
pt2.style=5;
}
pts.add(pt);
pts.add(pt2);
}
for(j=0;j<pts.size();j++)
{
pLinePoints[j]=pts.get(j);
counter++;
}
for(j=counter;j<pLinePoints.length;j++)
pLinePoints[j]=new POINT2(pLinePoints[counter-1]);
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "GetOverheadWire",
new RendererException("GetOverheadWire", exc));
}
return counter;
}
//private static int linetype=-1; //use for BLOCK, CONTIAN
/**
* Calculates the points for the non-channel symbols.
* The points will be stored in the original POINT2 array in pixels, pLinePoints.
* The client points occupy the first vblSaveCounter positions in pLinePoints
* and will be overwritten by the symbol points.
*
* @param lineType the line type
* @param pLinePoints - OUT - an array of POINT2
* @param vblCounter the number of points allocated
* @param vblSaveCounter the number of client points
*
* @return the symbol point count
*/
private static ArrayList<POINT2> GetLineArray2Double(int lineType,
POINT2[] pLinePoints,
int vblCounter,
int vblSaveCounter,
ArrayList<Shape2>shapes,
Rectangle2D clipBounds,
int rev)
{
ArrayList<POINT2> points=new ArrayList();
try
{
String client=CELineArray.getClient();
if(pLinePoints==null || pLinePoints.length<2)
return null;
//declarations
int[] segments=null;
double dMRR=0;
int n=0,bolVertical=0;
double dExtendLength=0;
double dWidth=0;
int nQuadrant=0;
int lLinestyle=0,pointCounter=0;
ref<double[]> offsetX=new ref(),offsetY=new ref();
double b=0,b1=0,dRadius=0,d1=0,d=0,d2=0;
ref<double[]>m=new ref();
int direction=0;
int nCounter=0;
int j=0,k=0,middleSegment=-1;
double dMBR=lineutility.MBRDistance(pLinePoints,vblSaveCounter);
POINT2 pt0=new POINT2(pLinePoints[0]), //calculation points for autoshapes
pt1=new POINT2(pLinePoints[1]),
pt2=new POINT2(pLinePoints[1]),
pt3=new POINT2(pLinePoints[0]),
pt4=new POINT2(pLinePoints[0]),
pt5=new POINT2(pLinePoints[0]),
pt6=new POINT2(pLinePoints[0]),
pt7=new POINT2(pLinePoints[0]),
pt8=new POINT2(pLinePoints[0]),
ptYIntercept=new POINT2(pLinePoints[0]),
ptYIntercept1=new POINT2(pLinePoints[0]),
ptCenter=new POINT2(pLinePoints[0]);
POINT2[] pArrowPoints=new POINT2[3],
arcPts=new POINT2[26],
circlePoints=new POINT2[100],
pts=null,pts2=null;
POINT2 midpt=new POINT2(pLinePoints[0]),midpt1=new POINT2(pLinePoints[0]);
POINT2[]pOriginalLinePoints=null;
POINT2[] pUpperLinePoints = null;
POINT2[] pLowerLinePoints = null;
POINT2[] pUpperLowerLinePoints = null;
POINT2 calcPoint0=new POINT2(),
calcPoint1=new POINT2(),
calcPoint2=new POINT2(),
calcPoint3=new POINT2(),
calcPoint4=new POINT2();
POINT2 ptTemp=new POINT2(pLinePoints[0]);
int acCounter=0;
POINT2[] acPoints=new POINT2[6];
int lFlotCount=0;
//end declarations
//Bearing line and others only have 2 points
if(vblCounter>2)
pt2=new POINT2(pLinePoints[2]);
//strcpy(CurrentFunction,"GetLineArray2");
pt0.style=0;
pt1.style=0;
pt2.style=0;
//set jaggylength in clsDISMSupport before the points get bounded
//clsDISMSupport.JaggyLength = Math.Sqrt ( (pLinePoints[1].x-pLinePoints[0].x) * (pLinePoints[1].x-pLinePoints[0].x) +
// (pLinePoints[1].y-pLinePoints[0].y) * (pLinePoints[1].y-pLinePoints[0].y) );
//double saveMaxPixels=CELineArrayGlobals.MaxPixels2;
//double saveMaxPixels=2000;
ArrayList xPoints=null;
pOriginalLinePoints = new POINT2[vblSaveCounter];
for(j = 0;j<vblSaveCounter;j++)
{
pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
}
//resize the array and get the line array
//for the specified non-channel line type
switch(lineType)
{
case TacticalLines.BBS_AREA:
lineutility.getExteriorPoints(pLinePoints, vblSaveCounter, lineType, false);
acCounter=vblSaveCounter;
break;
case TacticalLines.BS_CROSS:
pt0=new POINT2(pLinePoints[0]);
pLinePoints[0]=new POINT2(pt0);
pLinePoints[0].x-=10;
pLinePoints[1]=new POINT2(pt0);
pLinePoints[1].x+=10;
pLinePoints[1].style=10;
pLinePoints[2]=new POINT2(pt0);
pLinePoints[2].y+=10;
pLinePoints[3]=new POINT2(pt0);
pLinePoints[3].y-=10;
acCounter=4;
break;
case TacticalLines.BS_RECTANGLE:
lineutility.CalcMBRPoints(pLinePoints, pLinePoints.length, pt0, pt2); //pt0=ul, pt1=lr
//pt0=new POINT2(pLinePoints[0]);
//pt2=new POINT2(pLinePoints[1]);
//pt1=new POINT2(pt0);
//pt1.y=pt2.y;
pt1=new POINT2(pt0);
pt1.x=pt2.x;
pt3=new POINT2(pt0);
pt3.y=pt2.y;
pLinePoints=new POINT2[5];
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
acCounter=5;
break;
case TacticalLines.BBS_RECTANGLE:
//double xmax=pLinePoints[0].x,xmin=pLinePoints[1].x,ymax=pLinePoints[0].y,ymin=pLinePoints[1].y;
//double xmax=pLinePoints[2].x,xmin=pLinePoints[0].x,ymax=pLinePoints[2].y,ymin=pLinePoints[0].y;
double buffer=pLinePoints[0].style;
pOriginalLinePoints=new POINT2[5];
pOriginalLinePoints[0]=new POINT2(pLinePoints[0]);
pOriginalLinePoints[1]=new POINT2(pLinePoints[1]);
pOriginalLinePoints[2]=new POINT2(pLinePoints[2]);
pOriginalLinePoints[3]=new POINT2(pLinePoints[3]);
pOriginalLinePoints[4]=new POINT2(pLinePoints[0]);
//clockwise orientation
pt0=pLinePoints[0];
pt0.x-=buffer;
pt0.y-=buffer;
pt1=pLinePoints[1];
pt1.x+=buffer;
pt1.y-=buffer;
pt2=pLinePoints[2];
pt2.x+=buffer;
pt2.y+=buffer;
pt3=pLinePoints[3];
pt3.x-=buffer;
pt3.y+=buffer;
pLinePoints=new POINT2[5];
pLinePoints[0]=new POINT2(pt0);
pLinePoints[1]=new POINT2(pt1);
pLinePoints[2]=new POINT2(pt2);
pLinePoints[3]=new POINT2(pt3);
pLinePoints[4]=new POINT2(pt0);
vblSaveCounter=5;
acCounter=5;
break;
case TacticalLines.BS_ELLIPSE:
pt0=pLinePoints[0];//the center of the ellipse
pt1=pLinePoints[1];//the width of the ellipse
pt2=pLinePoints[2];//the height of the ellipse
pLinePoints=getEllipsePoints(pt0,pt1,pt2);
acCounter=37;
break;
case TacticalLines.OVERHEAD_WIRE:
acCounter=getOverheadWire(pLinePoints,vblSaveCounter);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for(j=0;j<vblSaveCounter;j++)
{
//pLinePoints[j]=new POINT2(pOriginalLinePoints[j]);
pLinePoints[j].style=1;
}
//pLinePoints[vblSaveCounter-1].style=5;
for(j=vblSaveCounter;j<2*vblSaveCounter;j++)
{
pLinePoints[j]=new POINT2(pOriginalLinePoints[j-vblSaveCounter]);
pLinePoints[j].style=20;
}
//pLinePoints[2*vblSaveCounter-1].style=5;
acCounter=pLinePoints.length;
break;
case TacticalLines.BOUNDARY:
acCounter=pLinePoints.length;
break;
case TacticalLines.REEF:
vblCounter = GetReefPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ICE_DRIFT:
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-5], pLinePoints[vblCounter - 4], 10, 10,pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.RESTRICTED_AREA:
vblCounter=GetRestrictedAreaPoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TRAINING_AREA:
//diagnostic
dMBR=lineutility.MBRDistance(pLinePoints, vblSaveCounter);
d=20;
if(dMBR<60)
d=dMBR/4;
if(d<5)
d=5;
//end section
for (j = 0; j < vblSaveCounter; j++)
{
pLinePoints[j].style = 1;
}
pLinePoints[vblSaveCounter - 1].style = 5;
pt0 = lineutility.CalcCenterPointDouble(pLinePoints, vblSaveCounter - 1);
//lineutility.CalcCircleDouble(pt0, 20, 26, arcPts, 0);
lineutility.CalcCircleDouble(pt0, d, 26, arcPts, 0);
for (j = vblSaveCounter; j < vblSaveCounter + 26; j++)
{
pLinePoints[j] = new POINT2(arcPts[j - vblSaveCounter]);
}
pLinePoints[j-1].style = 5;
//! inside the circle
//diagnostic
if(dMBR<50)
{
//d was used as the circle radius
d*=0.6;
}
else
d=12;
//end section
pt1 = new POINT2(pt0);
pt1.y -= d;
pt1.style = 0;
pt2 = new POINT2(pt1);
pt2.y += d;
pt2.style = 5;
pt3 = new POINT2(pt2);
pt3.y += d/4;
pt3.style = 0;
pt4 = new POINT2(pt3);
pt4.y += d/4;
pLinePoints[j++] = new POINT2(pt1);
pLinePoints[j++] = new POINT2(pt2);
pLinePoints[j++] = new POINT2(pt3);
pt4.style = 5;
pLinePoints[j++] = new POINT2(pt4);
vblCounter = j;
acCounter=vblCounter;
break;
case TacticalLines.PIPE:
vblCounter=GetPipePoints(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.ANCHORAGE_AREA:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 1: //extend left
case 2: //extend below
break;
case 0: //extend right
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 1: //extend left
case 3: //extend above
break;
case 0: //extend right
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 1: //extend left
case 2: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 3: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 1: //extend left
case 3: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 0: //extend right
case 2: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = GetAnchorageDouble(pLinePoints, vblSaveCounter);
acCounter = lFlotCount;
break;
case TacticalLines.ANCHORAGE_LINE:
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
acCounter=GetAnchorageDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.LRO:
int xCount=countsupport.GetXPointsCount(lineType, pOriginalLinePoints, vblSaveCounter);
POINT2 []xPoints2=new POINT2[xCount];
int lvoCount=countsupport.GetLVOCount(lineType, pOriginalLinePoints, vblSaveCounter);
POINT2 []lvoPoints=new POINT2[lvoCount];
xCount=GetXPoints(lineType, pOriginalLinePoints,xPoints2,vblSaveCounter);
lvoCount=GetLVOPoints(lineType, pOriginalLinePoints,lvoPoints,vblSaveCounter);
for(k=0;k<xCount;k++)
{
pLinePoints[k]=new POINT2(xPoints2[k]);
}
if(xCount>0)
pLinePoints[xCount-1].style=5;
for(k=0;k<lvoCount;k++)
{
pLinePoints[xCount+k]=new POINT2(lvoPoints[k]);
}
acCounter=xCount+lvoCount;
break;
case TacticalLines.UNDERCAST:
if(pLinePoints[0].x<pLinePoints[1].x)
lineutility.ReversePointsDouble2(pLinePoints,vblSaveCounter);
lFlotCount=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.LVO:
acCounter=GetLVOPoints(lineType, pOriginalLinePoints,pLinePoints,vblSaveCounter);
break;
case TacticalLines.ICING:
vblCounter=GetIcingPointsDouble(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.MVFR:
//get the direction and quadrant of the first segment
n = GetInsideOutsideDouble2(pLinePoints[0], pLinePoints[1], pLinePoints, vblSaveCounter, 0, lineType);
nQuadrant = lineutility.GetQuadrantDouble(pLinePoints[0], pLinePoints[1]);
//if the direction and quadrant are not compatible with GetFlotDouble then
//reverse the points
switch (nQuadrant) {
case 4:
switch (n) {
case 0: //extend left
case 3: //extend below
break;
case 1: //extend right
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 1:
switch (n) {
case 0: //extend left
case 2: //extend above
break;
case 1: //extend right
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
default:
break;
}
break;
case 2:
switch (n) {
case 0: //extend left
case 3: //extend below
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 2: //extend above
break;
default:
break;
}
break;
case 3:
switch (n) {
case 0: //extend left
case 2: //extend above
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
break;
case 1: //extend right
case 3: //extend above
break;
default:
break;
}
break;
default:
break;
}
lFlotCount = flot.GetFlotDouble(pLinePoints, vblSaveCounter);
acCounter=lFlotCount;
break;
case TacticalLines.ITD:
acCounter=GetITDPointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.CONVERGANCE:
acCounter=GetConvergancePointsDouble(pLinePoints,vblSaveCounter);
break;
case TacticalLines.RIDGE:
vblCounter=GetRidgePointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.TROUGH:
case TacticalLines.INSTABILITY:
case TacticalLines.SHEAR:
//case TacticalLines.SQUALL:
//CELineArrayGlobals.MaxPixels2=saveMaxPixels+100;
vblCounter=GetSquallDouble(pLinePoints,10,6,30,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.SQUALL:
//vblCounter = GetSquallDouble(pLinePoints, 10, 6, 30, vblSaveCounter);
vblCounter=GetSevereSquall(pLinePoints,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.USF:
case TacticalLines.SFG:
case TacticalLines.SFY:
vblCounter=flot.GetSFPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.SF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.OFY:
vblCounter=flot.GetOFYPointsDouble(pLinePoints,vblSaveCounter,lineType);
acCounter=vblCounter;
break;
case TacticalLines.OCCLUDED:
case TacticalLines.UOF:
vblCounter=flot.GetOccludedPointsDouble(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
acCounter=vblCounter;
break;
case TacticalLines.WF:
case TacticalLines.UWF:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter-vblSaveCounter+j]=pOriginalLinePoints[j];
acCounter=lFlotCount+vblSaveCounter;
break;
case TacticalLines.WFG:
case TacticalLines.WFY:
lFlotCount=flot.GetFlot2Double(pLinePoints,vblSaveCounter,lineType);
acCounter=lFlotCount;
break;
case TacticalLines.CFG:
case TacticalLines.CFY:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
acCounter=vblCounter;
break;
case TacticalLines.CF:
case TacticalLines.UCF:
vblCounter=GetATWallPointsDouble(pLinePoints,lineType,vblSaveCounter);
pLinePoints[vblCounter-1].style=5;
for(j=0;j<vblSaveCounter;j++)
pLinePoints[vblCounter+j]=pOriginalLinePoints[j];
vblCounter += vblSaveCounter;
pLinePoints[vblCounter-1].style=5;
acCounter=vblCounter;
break;
case TacticalLines.IL:
case TacticalLines.PLANNED:
case TacticalLines.ESR1:
case TacticalLines.ESR2:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
d=lineutility.CalcDistanceDouble(pLinePoints[0], pt0);
pt4 = lineutility.ExtendLineDouble(pt0, pLinePoints[0], d);
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt4, pt2, pt3);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
pLinePoints[2] = new POINT2(pt3);
pLinePoints[3] = new POINT2(pt2);
switch (lineType) {
case TacticalLines.IL:
case TacticalLines.ESR2:
pLinePoints[0].style = 0;
pLinePoints[1].style = 5;
pLinePoints[2].style = 0;
break;
case TacticalLines.PLANNED:
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2].style = 1;
break;
case TacticalLines.ESR1:
pLinePoints[1].style = 5;
if (pt0.x <= pt1.x) {
if (pLinePoints[1].y <= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
} else {
if (pLinePoints[1].y >= pLinePoints[2].y) {
pLinePoints[0].style = 0;
pLinePoints[2].style = 1;
} else {
pLinePoints[0].style = 1;
pLinePoints[2].style = 0;
}
}
break;
default:
break;
}
acCounter=4;
break;
case TacticalLines.FORDSITE:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2],pt0,pt1);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
pLinePoints[2] = new POINT2(pt0);
pLinePoints[2].style = 1;
pLinePoints[3] = new POINT2(pt1);
pLinePoints[3].style = 5;
acCounter=4;
break;
case TacticalLines.ROADBLK:
pts = new POINT2[4];
for (j = 0; j < 4; j++) {
pts[j] = new POINT2(pLinePoints[j]);
}
dRadius = lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
d = lineutility.CalcDistanceToLineDouble(pLinePoints[0], pLinePoints[1], pLinePoints[2]);
//first two lines
pLinePoints[0] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], d, 0);
pLinePoints[1] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], d, 5);
pLinePoints[2] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[1], -d, 0);
pLinePoints[3] = lineutility.ExtendTrueLinePerpDouble(pts[0], pts[1], pts[0], -d, 5);
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[0], midpt, d);
//the next line
pLinePoints[4] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[5] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[5].style = 5;
//recompute the original midpt because it was moved
midpt = lineutility.MidPointDouble(pts[0], pts[1], 0);
//move the midpoint
midpt = lineutility.ExtendLineDouble(pts[1], midpt, d);
//the last line
pLinePoints[6] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, 105, dRadius / 2);
pLinePoints[7] = lineutility.ExtendAngledLine(pts[0], pts[1], midpt, -75, dRadius / 2);
pLinePoints[7].style = 5;
acCounter=8;
break;
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.PNO:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DMAF:
AreaWithCenterFeatureDouble(pLinePoints,vblCounter,lineType);
pLinePoints[vblCounter-1].style=5;
FillPoints(pLinePoints,vblCounter,points);
xPoints=lineutility.LineOfXPoints(pOriginalLinePoints);
for(j=0;j<xPoints.size();j++)
{
points.add((POINT2)xPoints.get(j));
}
acCounter=points.size();
break;
case TacticalLines.FOXHOLE:
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical==0) //line is vertical
{
if (pt0.y > pt1.y) {
direction = 0;
} else {
direction = 1;
}
}
if (bolVertical != 0 && m.value[0] <= 1) {
if (pt0.x < pt1.x) {
direction = 3;
} else {
direction = 2;
}
}
if (bolVertical != 0 && m.value[0] > 1) {
if (pt0.x < pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x < pt1.x && pt0.y < pt1.y) {
direction = 0;
}
if (pt0.x > pt1.x && pt0.y > pt1.y) {
direction = 1;
}
if (pt0.x > pt1.x && pt0.y < pt1.y) {
direction = 0;
}
}
//M. Deutch 8-19-04
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<250)
dMBR=250;
if(dMBR>500)
dMBR=500;
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, direction, dMBR / 20);
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, direction, dMBR / 20);
acCounter=4;
break;
case TacticalLines.ISOLATE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
break;
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=50;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.OCCUPY:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=32;
break;
case TacticalLines.RETAIN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=75;
break;
case TacticalLines.SECURE:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.TURN:
GetIsolatePointsDouble(pLinePoints,lineType);
acCounter=29;
break;
case TacticalLines.ENCIRCLE:
//pOriginalLinePoints=null;
//pOriginalLinePoints = new POINT2[vblSaveCounter+2];
//for(j = 0;j<vblSaveCounter;j++)
// pOriginalLinePoints[j] = new POINT2(pLinePoints[j]);
//pOriginalLinePoints[vblSaveCounter] = new POINT2(pLinePoints[0]);
//pOriginalLinePoints[vblSaveCounter+1] = new POINT2(pLinePoints[1]);
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
//for(j=0;j<vblSaveCounter+2;j++)
// pLinePoints[pointCounter+j]=new POINT2(pOriginalLinePoints[j]);
//pointCounter += vblSaveCounter+1;
//acCounter=pointCounter;
break;
case TacticalLines.BELT1:
pUpperLinePoints=new POINT2[vblSaveCounter];
pLowerLinePoints=new POINT2[vblSaveCounter];
pUpperLowerLinePoints=new POINT2[2*vblCounter];
for(j=0;j<vblSaveCounter;j++)
pLowerLinePoints[j]=new POINT2(pLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLinePoints[j]=new POINT2(pLinePoints[j]);
pUpperLinePoints = Channels.CoordIL2Double(1,pUpperLinePoints,1,vblSaveCounter,lineType,30);
pLowerLinePoints = Channels.CoordIL2Double(1,pLowerLinePoints,0,vblSaveCounter,lineType,30);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j]=new POINT2(pUpperLinePoints[j]);
for(j=0;j<vblSaveCounter;j++)
pUpperLowerLinePoints[j+vblSaveCounter]=new POINT2(pLowerLinePoints[vblSaveCounter-j-1]);
pUpperLowerLinePoints[2*vblSaveCounter]=new POINT2(pUpperLowerLinePoints[0]);
vblCounter=GetZONEPointsDouble2(pUpperLowerLinePoints,lineType,2*vblSaveCounter+1);
for(j=0;j<vblCounter;j++)
pLinePoints[j]=new POINT2(pUpperLowerLinePoints[j]);
//pLinePoints[j]=pLinePoints[0];
//vblCounter++;
acCounter=vblCounter;
break;
case TacticalLines.BELT: //change 2
case TacticalLines.ZONE:
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.STRONG:
case TacticalLines.FORT:
acCounter=GetZONEPointsDouble2(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.ATWALL:
case TacticalLines.LINE: //7-9-07
acCounter = GetATWallPointsDouble2(pLinePoints, lineType, vblSaveCounter);
break;
// case TacticalLines.ATWALL3D:
// acCounter = GetATWallPointsDouble3D(pLinePoints, lineType, vblSaveCounter);
// break;
case TacticalLines.PLD:
for(j=0;j<vblCounter;j++)
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.FEBA:
CoordFEBADouble(pLinePoints,vblCounter);
acCounter=pLinePoints.length;
break;
case TacticalLines.UAV:
case TacticalLines.MRR:
if(rev==RendererSettings.Symbology_2525Bch2_USAS_13_14)
{
dMRR=pOriginalLinePoints[0].style;
if (dMRR <= 0) {
dMRR = 1;//was 14
}
lineutility.GetSAAFRSegment(pLinePoints, lineType, dMRR,rev);
acCounter=6;
}
if(rev==RendererSettings.Symbology_2525C)
{
return GetLineArray2Double(TacticalLines.SAAFR,pLinePoints,vblCounter,vblSaveCounter,shapes,clipBounds,rev);
}
break;
case TacticalLines.MRR_USAS:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR: //added 5-4-07
case TacticalLines.SAAFR: //these have multiple segments
case TacticalLines.AC:
dMRR = dACP;
// if (dMRR <= 0) {
// dMRR = 14;
lineutility.InitializePOINT2Array(acPoints);
lineutility.InitializePOINT2Array(arcPts);
acCounter = 0;
for (j = 0; j < vblSaveCounter;j++)
if(pOriginalLinePoints[j].style<=0)
pOriginalLinePoints[j].style=1; //was 14
//get the SAAFR segments
for (j = 0; j < vblSaveCounter - 1; j++) {
//diagnostic: use style member for dMBR
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRSegment(acPoints, lineType, dMBR,rev);//was dMRR
for (k = 0; k < 6; k++)
{
pLinePoints[acCounter] = new POINT2(acPoints[k]);
acCounter++;
}
}
//get the circles
int nextCircleSize=0,currentCircleSize=0;
for (j = 0; j < vblSaveCounter-1; j++)
{
currentCircleSize=pOriginalLinePoints[j].style;
nextCircleSize=pOriginalLinePoints[j+1].style;
//draw the circle at the segment front end
arcPts[0] = new POINT2(pOriginalLinePoints[j]);
//diagnostic: use style member for dMBR
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
//draw the circle at the segment back end
arcPts[0] = new POINT2(pOriginalLinePoints[j+1]);
//dMBR=pOriginalLinePoints[j].style;
dMBR=currentCircleSize;
lineutility.CalcCircleDouble(arcPts[0], dMBR, 26, arcPts, 0);//was dMRR
arcPts[25].style = 5;
for (k = 0; k < 26; k++)
{
pLinePoints[acCounter] = new POINT2(arcPts[k]);
acCounter++;
}
}
//acPoints = null;
break;
case TacticalLines.MINED:
case TacticalLines.UXO:
acCounter=vblCounter;
break;
case TacticalLines.BEARING:
case TacticalLines.ACOUSTIC:
case TacticalLines.ELECTRO:
case TacticalLines.TORPEDO:
case TacticalLines.OPTICAL:
acCounter=vblCounter;
break;
case TacticalLines.MSDZ:
lineutility.InitializePOINT2Array(circlePoints);
pt3 = new POINT2(pLinePoints[3]);
dRadius = lineutility.CalcDistanceDouble(pt0, pt1);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[j] = new POINT2(circlePoints[j]);
}
pLinePoints[99].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt2);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[100 + j] = new POINT2(circlePoints[j]);
}
pLinePoints[199].style = 5;
dRadius = lineutility.CalcDistanceDouble(pt0, pt3);
lineutility.CalcCircleDouble(pt0, dRadius, 100,
circlePoints,0);
for(j=0; j < 100; j++) {
pLinePoints[200 + j] = new POINT2(circlePoints[j]);
}
//acCounter=300;
acCounter=vblCounter;
//FillPoints(pLinePoints,vblCounter,points);
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CONVOY:
d=lineutility.CalcDistanceDouble(pt0, pt1);
if(d<=30)
{
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
pt0 = lineutility.ExtendLine2Double(pt1, pt0, -30, 0);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 30);
lineutility.GetArrowHead4Double(pt0, pt2, 30, 30, pArrowPoints, 0);
d = lineutility.CalcDistanceDouble(pLinePoints[0], pArrowPoints[0]);
d1 = lineutility.CalcDistanceDouble(pLinePoints[3], pArrowPoints[0]);
pLinePoints[3].style = 5;
if (d < d1) {
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[4].style = 0;
pLinePoints[5] = new POINT2(pArrowPoints[0]);
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pArrowPoints[1]);
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pArrowPoints[2]);
pLinePoints[7].style = 0;
pLinePoints[8] = new POINT2(pLinePoints[3]);
} else {
pLinePoints[4] = pLinePoints[3];
pLinePoints[4].style = 0;
pLinePoints[5] = pArrowPoints[0];
pLinePoints[5].style = 0;
pLinePoints[6] = pArrowPoints[1];
pLinePoints[6].style = 0;
pLinePoints[7] = pArrowPoints[2];
pLinePoints[7].style = 0;
pLinePoints[8] = pLinePoints[0];
}
acCounter=9;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.HCONVOY:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
pt0 = new POINT2(pLinePoints[0]);
pt1 = new POINT2(pLinePoints[1]);
pt2.x = (pt0.x + pt1.x) / 2;
pt2.y = (pt0.y + pt1.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt1, pt0, m);
if (m.value[0] < 1) {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 2, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 2, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 3, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 3, 10);
} else {
pLinePoints[0] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 0, 10);
pLinePoints[1] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 0, 10);
pLinePoints[2] = lineutility.ExtendDirectedLine(pt0, pt1, pt1, 1, 10);
pLinePoints[3] = lineutility.ExtendDirectedLine(pt0, pt1, pt0, 1, 10);
}
pLinePoints[4] = new POINT2(pLinePoints[0]);
pLinePoints[5] = new POINT2(pt0);
pLinePoints[5].style = 0;
pt2 = lineutility.ExtendLineDouble(pt1, pt0, 50);
lineutility.GetArrowHead4Double(pt2, pt0, 20, 20, pArrowPoints, 0);
// for (j = 0; j < 3; j++)
// pLinePoints[j + 6] = new POINT2(pArrowPoints[j]);
// pLinePoints[8].style = 0;
// pLinePoints[9] = new POINT2(pArrowPoints[0]);
pLinePoints[6]=new POINT2(pArrowPoints[1]);
pLinePoints[7]=new POINT2(pArrowPoints[0]);
pLinePoints[8]=new POINT2(pArrowPoints[2]);
pLinePoints[8].style = 0;
pLinePoints[9] = new POINT2(pArrowPoints[1]);
acCounter=10;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.ONEWAY:
case TacticalLines.ALT:
case TacticalLines.TWOWAY:
nCounter = (int) vblSaveCounter;
pLinePoints[vblSaveCounter - 1].style = 5;
for (j = 0; j < vblSaveCounter - 1; j++) {
d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
if(d<20) //too short
continue;
pt0 = new POINT2(pLinePoints[j]);
pt1 = new POINT2(pLinePoints[j + 1]);
bolVertical = lineutility.CalcTrueSlopeDouble(pLinePoints[j], pLinePoints[j + 1],m);
d=lineutility.CalcDistanceDouble(pLinePoints[j],pLinePoints[j+1]);
pt2 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -3 * d / 4, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[j], pLinePoints[j + 1], -1 * d / 4, 5);
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 10);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 10);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 10);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 10);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
d = 10;
if (dMBR / 20 < minLength) {
d = 5;
}
lineutility.GetArrowHead4Double(pt2, pt3, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
if (lineType == (long) TacticalLines.ALT) {
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
if (lineType == (long) TacticalLines.TWOWAY) {
if (pLinePoints[j].x < pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 2, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 2, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
if (pLinePoints[j].x > pLinePoints[j + 1].x) {
if (m.value[0] < 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 3, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 3, 15);
}
if (m.value[0] >= 1) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
}
}
if (bolVertical == 0) {
if (pLinePoints[j].y > pLinePoints[j + 1].y) {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 0, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 0, 15);
} else {
pt2 = lineutility.ExtendDirectedLine(pt0, pt1, pt2, 1, 15);
pt3 = lineutility.ExtendDirectedLine(pt0, pt1, pt3, 1, 15);
}
}
pLinePoints[nCounter] = new POINT2(pt2);
nCounter++;
pLinePoints[nCounter] = new POINT2(pt3);
nCounter++;
lineutility.GetArrowHead4Double(pt3, pt2, (int) d, (int) d,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[nCounter] = new POINT2(pArrowPoints[k]);
nCounter++;
}
}
}
acCounter=nCounter;
break;
case TacticalLines.CFL:
for(j=0;j<vblCounter;j++) //dashed lines
pLinePoints[j].style=1;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKFNT: //extra three for arrow plus extra three for feint
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<20)//was 10
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], 21);//was 11
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1], 20); //was 10
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
d = dMBR;
pt0=lineutility.ExtendLineDouble(pLinePoints[vblCounter-8], pLinePoints[vblCounter - 7], 20); //was 10
pt1 = new POINT2(pLinePoints[vblCounter - 8]);
pt2 = new POINT2(pLinePoints[vblCounter - 7]);
if (d / 10 > maxLength) {
d = 10 * maxLength;
}
if (d / 10 < minLength) {
d = 10 * minLength;
}
if(d<250)
d=250;
if(d>500)
d=250;
lineutility.GetArrowHead4Double(pt1, pt2, (int) d / 10, (int) d / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = pArrowPoints[k];
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) d / 10, (int) d / 10,
pArrowPoints,18);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = pArrowPoints[k];
}
acCounter=vblCounter;
break;
case TacticalLines.FORDIF:
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pLinePoints[2], pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
for (j = 0; j < vblCounter; j++) {
pLinePoints[j].style = 1;
}
//CommandSight section
//comment 2 lines for CS
pt0 = lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
pt1 = lineutility.MidPointDouble(pLinePoints[2], pLinePoints[3], 0);
POINT2[]savepoints=new POINT2[2];
savepoints[0]=new POINT2(pt0);
savepoints[1]=new POINT2(pt1);
Boolean drawJaggies=true;
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints=lineutility.BoundOneSegment(pt0, pt1, ul, lr);
if(savepoints != null && savepoints.length>1)
{
pt0=savepoints[0];
pt1=savepoints[1];
}
else
{
savepoints=new POINT2[2];
savepoints[0]=new POINT2(pt0);
savepoints[1]=new POINT2(pt1);
drawJaggies=false;
}
midpt=lineutility.MidPointDouble(pt0, pt1, 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
}
else
{
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
}
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
//end section
}
else
{
midpt=lineutility.MidPointDouble(pLinePoints[0], pLinePoints[1], 0);
double dist0=lineutility.CalcDistanceDouble(midpt, pt0);
double dist1=lineutility.CalcDistanceDouble(midpt, pt1);
if(dist0>dist1)
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt0, pt4, pt5); //as pt2,pt3
else
lineutility.LineRelativeToLine(pLinePoints[0], pLinePoints[1], pt1, pt4, pt5); //as pt2,pt3
pLinePoints[2] = new POINT2(pt5);//was pt3
pLinePoints[3] = new POINT2(pt4);//was pt2
}
//end section
//calculate start, end points for upper and lower lines
//across the middle
pt2 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, -10, 0);
pt3 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, -10, 0);
pt4 = lineutility.ExtendLine2Double(pLinePoints[0], pt0, 10, 0);
pt5 = lineutility.ExtendLine2Double(pLinePoints[3], pt1, 10, 0);
dWidth = lineutility.CalcDistanceDouble(pt0, pt1);
pointCounter = 4;
n = 1;
pLinePoints[pointCounter] = new POINT2(pt0);
pLinePoints[pointCounter].style = 0;
pointCounter++;
//while (dExtendLength < dWidth - 20)
if(drawJaggies)
while (dExtendLength < dWidth - 10)
{
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt2, pt3, dExtendLength - dWidth, 0);
pointCounter++;
n++;
//dExtendLength = (double) n * 10;
dExtendLength = (double) n * 5;
pLinePoints[pointCounter] = lineutility.ExtendLine2Double(pt4, pt5, dExtendLength - dWidth, 0);
pointCounter++;
if(pointCounter>=pLinePoints.length-1)
break;
n++;
}
pLinePoints[pointCounter] = new POINT2(pt1);
pLinePoints[pointCounter].style = 5;
pointCounter++;
acCounter=pointCounter;
break;
case TacticalLines.ATDITCH:
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
break;
case (int)TacticalLines.ATDITCHC: //extra Points were calculated by a function
pLinePoints[0].style=9;
acCounter=lineutility.GetDitchSpikeDouble(pLinePoints,vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style=10;
break;
case TacticalLines.ATDITCHM:
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pLinePoints[0].style = 9;
acCounter = lineutility.GetDitchSpikeDouble(
pLinePoints,
vblSaveCounter,
0,lineType);
//pLinePoints[vblCounter-1].style = 20;
break;
case TacticalLines.DIRATKGND:
//reverse the points
//lineutility.ReversePointsDouble2(
//pLinePoints,
//vblSaveCounter);
//was 20
if (dMBR / 30 > maxLength) {
dMBR = 30 * maxLength;
}
if (dMBR / 30 < minLength) {
dMBR = 30 * minLength;
}
//if(dMBR<250)
// dMBR = 250;
if(dMBR<500)
dMBR = 500;
if(dMBR>750)
dMBR = 500;
//diagnostic move the line to make room for the feint
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(d<dMBR/40)
pLinePoints[1]=lineutility.ExtendLineDouble(pLinePoints[0], pLinePoints[1], dMBR/40+1);
pLinePoints[0]=lineutility.ExtendAlongLineDouble(pLinePoints[0], pLinePoints[1],dMBR/40);
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
pt0 = new POINT2(pLinePoints[vblCounter - 12]);
pt1 = new POINT2(pLinePoints[vblCounter - 11]);
pt2 = lineutility.ExtendLineDouble(pt0, pt1, dMBR / 40);
lineutility.GetArrowHead4Double(pt0, pt1, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 10 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pt0, pt2, (int) (dMBR / 13.33), (int) (dMBR / 13.33),
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 7 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 4] = new POINT2(pLinePoints[vblCounter - 10]);
pLinePoints[vblCounter - 4].style = 0;
pLinePoints[vblCounter - 3] = new POINT2(pLinePoints[vblCounter - 7]);
pLinePoints[vblCounter - 3].style = 5;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 5]);
pLinePoints[vblCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.MFLANE:
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 10,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.RAFT: //extra eight Points for hash marks either end
pt2 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 8], pLinePoints[vblCounter - 7], dMBR / 2);
pt3 = new POINT2(pLinePoints[vblCounter - 7]);
pt1 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 2);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>200)
dMBR=200;
lineutility.GetArrowHead4Double(pt2, pt3, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 6 + k] = new POINT2(pArrowPoints[k]);
}
lineutility.GetArrowHead4Double(pt1, pt0, (int) dMBR / 10, (int) dMBR / 5,
pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 3 + k] = new POINT2(pArrowPoints[k]);
}
//pLinePoints[1].style=5;
pLinePoints[vblSaveCounter - 1].style = 5;
acCounter=vblCounter;
break;
case TacticalLines.DIRATKAIR:
//added section for click-drag mode
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
for(k=vblSaveCounter-1;k>0;k
{
d += lineutility.CalcDistanceDouble(pLinePoints[k],pLinePoints[k-1]);
if(d>60)
break;
}
if(d>60)
{
middleSegment=k;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
else
{
if(vblSaveCounter<=3)
middleSegment=1;
else
middleSegment=2;
pt2=pLinePoints[middleSegment];
if(middleSegment>=1)
pt3=pLinePoints[middleSegment-1];
}
pt0 = new POINT2(pLinePoints[0]);
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(dMBR<150)
dMBR=150;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pLinePoints[vblCounter - 10], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 9 + j] = new POINT2(pArrowPoints[j]);
}
pLinePoints[vblCounter - 6].x = (pLinePoints[vblCounter - 11].x + pLinePoints[vblCounter - 10].x) / 2;
pLinePoints[vblCounter - 6].y = (pLinePoints[vblCounter - 11].y + pLinePoints[vblCounter - 10].y) / 2;
pt0 = new POINT2(pLinePoints[vblCounter - 6]);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 11], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt3, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 6 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 10], pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
if(middleSegment>=1)
{
pt0=lineutility.MidPointDouble(pt2, pt3, 0);
lineutility.GetArrowHead4Double(pt2, pt0, (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,9);
}
for(j=0; j < 3; j++) {
pLinePoints[vblCounter - 3 + j] = new POINT2(pArrowPoints[j]);
}
//this section was added to remove fill from the bow tie feature
ArrayList<POINT2> airPts=new ArrayList();
pLinePoints[middleSegment-1].style=5;
//pLinePoints[middleSegment].style=14;
if(vblSaveCounter==2)
pLinePoints[1].style=5;
for(j=0;j<vblCounter;j++)
airPts.add(new POINT2(pLinePoints[j]));
midpt=lineutility.MidPointDouble(pLinePoints[middleSegment-1], pLinePoints[middleSegment], 0);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment]);
pt1.style=5;
airPts.add(pt1);
pt0=lineutility.ExtendAlongLineDouble(midpt, pLinePoints[middleSegment-1], dMBR/20,0);
airPts.add(pt0);
pt1=new POINT2(pLinePoints[middleSegment-1]);
pt1.style=5;
airPts.add(pt1);
//re-dimension pLinePoints so that it can hold the
//the additional points required by the shortened middle segment
//which has the bow tie feature
vblCounter=airPts.size();
pLinePoints=new POINT2[airPts.size()];
for(j=0;j<airPts.size();j++)
pLinePoints[j]=new POINT2(airPts.get(j));
//end section
acCounter=vblCounter;
//FillPoints(pLinePoints,vblCounter,points);
break;
case TacticalLines.PDF:
//reverse pt0 and pt1 8-1-08
pt0 = new POINT2(pLinePoints[1]);
pt1 = new POINT2(pLinePoints[0]);
pLinePoints[0] = new POINT2(pt0);
pLinePoints[1] = new POINT2(pt1);
//end section
pts2 = new POINT2[3];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts2[2] = new POINT2(pt2);
lineutility.GetPixelsMin(pts2, 3,
offsetX,
offsetY);
if(offsetX.value[0]<0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
pLinePoints[2].style = 5;
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR < minLength) {
dMBR = 20 * minLength;
}
if(dMBR>250)
dMBR=250;
pt2 = lineutility.ExtendLineDouble(pt0, pt1, -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[3] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
pLinePoints[3].style = 0;
pLinePoints[4] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[4].style = 0;
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].y = pt2.y - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].y = pt2.y + 2;
pLinePoints[4].style = 0;
}
if (bolVertical == 0) {
pLinePoints[3] = new POINT2(pt2);
pLinePoints[3].x = pt2.x - 2;
pLinePoints[3].style = 0;
pLinePoints[4] = new POINT2(pt2);
pLinePoints[4].x = pt2.x + 2;
pLinePoints[4].style = 0;
}
pt2 = lineutility.ExtendLineDouble(pt1, pt0, -dMBR / 10);
if (bolVertical != 0 && m.value[0] != 0) {
b = pt2.y + (1 / m.value[0]) * pt2.x;
//get the Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[5] = lineutility.ExtendLineDouble(ptYIntercept, pt2, 2);
pLinePoints[5].style = 0;
pLinePoints[6] = lineutility.ExtendLineDouble(ptYIntercept, pt2, -2);
}
if (bolVertical != 0 && m.value[0] == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].y = pt2.y + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].y = pt2.y - 2;
}
if (bolVertical == 0) {
pLinePoints[5] = new POINT2(pt2);
pLinePoints[5].x = pt2.x + 2;
pLinePoints[5].style = 0;
pLinePoints[6] = new POINT2(pt2);
pLinePoints[6].x = pt2.x - 2;
}
pLinePoints[6].style = 0;
pLinePoints[7] = new POINT2(pLinePoints[3]);
pLinePoints[7].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[8 + j] = new POINT2(pArrowPoints[j]);
}
lineutility.GetArrowHead4Double(pLinePoints[1], pLinePoints[2], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(j=0; j < 3; j++) {
pLinePoints[11 + j] = new POINT2(pArrowPoints[j]);
pLinePoints[11 + j].style = 0;
}
acCounter=14;
break;
case TacticalLines.DIRATKSPT:
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if(dMBR/20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if(client.startsWith("cpof"))
{
if(dMBR<250)
dMBR=250;
}
else
{
if(dMBR<150)
dMBR=150;
}
if(dMBR>500)
dMBR=500;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 5], pLinePoints[vblCounter - 4], (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - k - 1] = new POINT2(pArrowPoints[k]);
}
acCounter=vblCounter;
break;
case TacticalLines.ABATIS:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
lineutility.GetPixelsMin(pts2, 2,
offsetX,
offsetY);
if(offsetX.value[0]<=0) {
offsetX.value[0] = offsetX.value[0] - 100;
} else {
offsetX.value[0] = 0;
}
if(dMBR>300)
dMBR=300;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
midpt.x=(pt0.x+pLinePoints[0].x) / 2;
midpt.y = (pt0.y + pLinePoints[0].y) / 2;
pLinePoints[vblCounter - 3] = new POINT2(pt0);
pLinePoints[vblCounter - 4].style = 5;
pLinePoints[vblCounter - 3].style = 0;
if (bolVertical != 0 && m.value[0] != 0) {
b = midpt.y + (1 / m.value[0]) * midpt.x; //the line equation
//get Y intercept at x=offsetX
b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
ptYIntercept.x = offsetX.value[0];
ptYIntercept.y = b1;
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, dMBR / 20);
if (pLinePoints[vblCounter - 2].y >= midpt.y) {
pLinePoints[vblCounter - 2] = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dMBR / 20);
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].y = midpt.y - dMBR / 20;
}
if (bolVertical == 0) {
pLinePoints[vblCounter - 2] = new POINT2(midpt);
pLinePoints[vblCounter - 2].x = midpt.x - dMBR / 20;
}
pLinePoints[vblCounter - 2].style = 0;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[0]);
//put the abatis feature on the front
// ArrayList<POINT2>abatisPts=new ArrayList();
// for(j=3;j<vblCounter;j++)
// abatisPts.add(new POINT2(pLinePoints[j-3]));
// abatisPts.add(0,new POINT2(pLinePoints[vblCounter-3]));
// abatisPts.add(1,new POINT2(pLinePoints[vblCounter-2]));
// abatisPts.add(2,new POINT2(pLinePoints[vblCounter-1]));
// for(j=0;j<abatisPts.size();j++)
// pLinePoints[j]=new POINT2(abatisPts.get(j));
//end section
//FillPoints(pLinePoints,vblCounter,points);
acCounter=vblCounter;
//FillPoints(pLinePoints,acCounter,points);
break;
case TacticalLines.CLUSTER:
//must use an x offset for ptYintercept because of extending from it
pts2 = new POINT2[2];
//for some reason occulus puts the points on top of one another
if(Math.abs(pt0.y-pt1.y)<1)
{
pt1.y = pt0.y +1;
}
pts2[0] = new POINT2(pt0);
pts2[1] = new POINT2(pt1);
pts = new POINT2[26];
dRadius = lineutility.CalcDistanceDouble(pt0, pt1) / 2;
midpt.x = (pt1.x + pt0.x) / 2;
midpt.y = (pt1.y + pt0.y) / 2;
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1,m);
if(bolVertical!=0 && m.value[0] != 0) //not vertical or horizontal
{
b = midpt.y + (1 / m.value[0]) * midpt.x; //normal y intercept at x=0
//we want to get the y intercept at x=offsetX
//b1 = (-1 / m.value[0]) * offsetX.value[0] + b;
//ptYIntercept.x = offsetX.value[0];
ptYIntercept.x=0;
//ptYIntercept.y = b1;
ptYIntercept.y = b;
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, dRadius);
if (pLinePoints[0].x <= pLinePoints[1].x) {
if (pt2.y >= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
} else {
if (pt2.y <= midpt.y) {
pt2 = lineutility.ExtendLineDouble(ptYIntercept, midpt, -dRadius);
}
}
}
if (bolVertical != 0 && m.value[0] == 0) //horizontal line
{
pt2 = midpt;
if (pLinePoints[0].x <= pLinePoints[1].x) {
pt2.y = midpt.y - dRadius;
} else {
pt2.y = midpt.y + dRadius;
}
}
if (bolVertical == 0) //vertical line
{
pt2 = midpt;
if (pLinePoints[0].y <= pLinePoints[1].y) {
pt2.x = midpt.x + dRadius;
} else {
pt2.x = midpt.x - dRadius;
}
}
pt1 = lineutility.ExtendLineDouble(midpt, pt2, 100);
pts[0] = new POINT2(pt2);
pts[1] = new POINT2(pt1);
lineutility.ArcArrayDouble(
pts,
0,dRadius,
lineType);
pLinePoints[0].style = 1;
pLinePoints[1].style = 5;
for (j = 0; j < 26; j++) {
pLinePoints[2 + j] = new POINT2(pts[j]);
pLinePoints[2 + j].style = 1;
}
acCounter=28;
break;
case TacticalLines.TRIP:
dRadius = lineutility.CalcDistanceToLineDouble(pt0, pt1, pt2);
bolVertical = lineutility.CalcTrueSlopeDouble(pt0, pt1, m);
if(bolVertical!=0 && m.value[0] != 0) {
b = pt1.y + 1 / m.value[0] * pt1.x;
b1 = pt2.y - m.value[0] * pt2.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
b = calcPoint1.y + 1 / m.value[0] * calcPoint1.x;
calcPoint3 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
b = calcPoint2.y + 1 / m.value[0] * calcPoint2.x;
calcPoint4 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
b = pt1.y + 1 / m.value[0] * pt1.x;
calcPoint0 = lineutility.CalcTrueIntersectDouble2(-1 / m.value[0], b, m.value[0], b1, 1, 1, pt0.x, pt0.y);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical != 0 && m.value[0] == 0) {
calcPoint0.x = pt1.x;
calcPoint0.y = pt2.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.x = calcPoint0.x + dRadius / 2;
calcPoint3.y = calcPoint0.y;
calcPoint4.x = pt1.x + dRadius;
calcPoint4.y = pt2.y;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
if (bolVertical == 0) {
calcPoint0.x = pt2.x;
calcPoint0.y = pt1.y;
calcPoint1 = lineutility.ExtendLineDouble(pt0, pt1, dRadius / 2);
//calcPoint2 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
calcPoint2 = pt2;
calcPoint3.y = calcPoint0.y + dRadius / 2;
calcPoint3.x = calcPoint0.x;
calcPoint4.y = pt1.y + dRadius;
calcPoint4.x = pt2.x;
midpt = lineutility.MidPointDouble(calcPoint1, calcPoint3, 0);
midpt1 = lineutility.MidPointDouble(calcPoint2, calcPoint4, 0);
calcPoint3 = lineutility.ExtendLineDouble(pt0, pt1, dRadius);
d = lineutility.CalcDistanceDouble(calcPoint0, calcPoint3);
calcPoint1 = lineutility.ExtendLineDouble(calcPoint0, calcPoint3, -(d - dRadius));
}
arcPts[0] = new POINT2(calcPoint1);
arcPts[1] = new POINT2(calcPoint3);
lineutility.ArcArrayDouble(
arcPts,
0,dRadius,
lineType);
pLinePoints[0].style = 5;
pLinePoints[1].style = 5;
for (k = 0; k < 26; k++) {
pLinePoints[k] = new POINT2(arcPts[k]);
}
for (k = 25; k < vblCounter; k++) {
pLinePoints[k].style = 5;
}
pLinePoints[26] = new POINT2(pt1);
dRadius = lineutility.CalcDistanceDouble(pt1, pt0);
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 - 7, 0);
pLinePoints[27] = new POINT2(midpt);
pLinePoints[27].style = 0;
midpt = lineutility.ExtendLine2Double(pt1, pt0, -dRadius / 2 + 7, 0);
pLinePoints[28] = new POINT2(midpt);
pLinePoints[29] = new POINT2(pt0);
pLinePoints[29].style = 5;
lineutility.GetArrowHead4Double(pt1, pt0, 15, 15, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[30 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 0; k < 3; k++) {
pLinePoints[30 + k].style = 5;
}
midpt = lineutility.MidPointDouble(pt0, pt1, 0);
d = lineutility.CalcDistanceDouble(pt1, calcPoint0);
//diagnostic for CS
//pLinePoints[33] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, d, 0);
//pLinePoints[34] = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, -d, 5);
pLinePoints[33]=pt2;
pt3=lineutility.PointRelativeToLine(pt0, pt1, pt0, pt2);
d=lineutility.CalcDistanceDouble(pt3, pt2);
pt4=lineutility.ExtendAlongLineDouble(pt0, pt1, d);
d=lineutility.CalcDistanceDouble(pt2, pt4);
pLinePoints[34]=lineutility.ExtendLineDouble(pt2, pt4, d);
//end section
acCounter=35;
break;
case TacticalLines.FOLLA:
d=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(client.startsWith("cpof"))
d2=20;
else
d2=30;
if(d<d2)
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(TacticalLines.DIRATKSPT, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
//reverse the points
lineutility.ReversePointsDouble2(pLinePoints, vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>150)
dMBR=150;
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -2 * dMBR / 10);
for (k = 0; k < vblCounter - 14; k++) {
pLinePoints[k].style = 18;
}
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], 5 * dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 10);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
pLinePoints[vblCounter - 12].style = 0;
pLinePoints[vblCounter - 11] = new POINT2(pArrowPoints[2]);
pLinePoints[vblCounter - 11].style = 0;
pLinePoints[vblCounter - 10] = new POINT2(pArrowPoints[0]);
pLinePoints[vblCounter - 10].style = 0;
pLinePoints[vblCounter - 9] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 9].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 10, (int) dMBR / 10, pArrowPoints, 0);
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 8 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 6].style = 0;
//diagnostic to make first point tip of arrowhead 6-14-12
//pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], 0.75 * dMBR / 10);
pt3 = lineutility.ExtendLineDouble(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], -0.75 * dMBR / 10);
pLinePoints[1]=pt3;
pLinePoints[1].style=5;
//lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (1.25 * dMBR / 10), (int) (1.25 * dMBR / 10), pArrowPoints, 0);
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pt3, (int) (dMBR / 10), (int) (dMBR / 10), pArrowPoints, 0);
//end section
for (k = 0; k < 3; k++) {
pLinePoints[vblCounter - 5 + k] = new POINT2(pArrowPoints[2 - k]);
}
pLinePoints[vblCounter - 5].style = 0;
pLinePoints[vblCounter - 2] = new POINT2(pLinePoints[vblCounter - 8]);
pLinePoints[vblCounter - 2].style = 5;
pLinePoints[vblCounter - 1] = new POINT2(pLinePoints[vblCounter - 7]);
acCounter=16;
break;
case TacticalLines.FOLSP:
if(client.startsWith("cpof"))
d2=25;
else
d2=25;
double folspDist=0;
folspDist=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
if(folspDist<d2) //was 10
{
lineType=TacticalLines.DIRATKSPT;
GetLineArray2Double(lineType, pLinePoints,5,2,shapes,clipBounds,rev);
break;
}
// else if(folspDist<d2)//was 25
// lineType=TacticalLines.FOLLA;
// GetLineArray2Double(lineType, pLinePoints,16,2,shapes,clipBounds,rev);
// for(k=0;k<pLinePoints.length;k++)
// if(pLinePoints[k].style==18)
// pLinePoints[k].style=0;
// //lineType=TacticalLines.FOLSP;
// //acCounter=16;
// break;
//end section
//reverse the points
lineutility.ReversePointsDouble2(
pLinePoints,
vblSaveCounter);
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
if(dMBR>250)
dMBR=250;
if(client.startsWith("cpof"))
{
if(folspDist<25)
dMBR=125;
if(folspDist<75)
dMBR=150;
if(folspDist<100)
dMBR=175;
if(folspDist<125)
dMBR=200;
}
else
{
dMBR*=1.5;
}
//make tail larger 6-10-11 m. Deutch
//pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 10);
pLinePoints[0] = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], -dMBR / 8.75);
pLinePoints[vblCounter - 15].style = 5;
pt0 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 4);
lineutility.GetArrowHead4Double(pt0, pLinePoints[0], (int) dMBR / 20, (int) dMBR / 20,
pArrowPoints,0);
for(k=0; k < 3; k++)
{
pLinePoints[vblCounter - 14 + k] = new POINT2(pArrowPoints[k]);
}
pLinePoints[vblCounter - 12].style = 0;
//make tail larger 6-10-11 m. Deutch
//pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 20);
pt3 = lineutility.ExtendLineDouble(pLinePoints[1], pLinePoints[0], dMBR / 15);
lineutility.GetArrowHead4Double(pt0, pt3, (int) dMBR / 20, (int) dMBR / 20, pArrowPoints,0);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 11 + k] = new POINT2(pArrowPoints[2 - k]);
pLinePoints[vblCounter - 11 + k].style = 0;
}
pLinePoints[vblCounter - 8] = new POINT2(pLinePoints[vblCounter - 14]);
pLinePoints[vblCounter - 8].style = 5;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter - 16], pLinePoints[vblCounter - 15], (int) dMBR / 20, (int) dMBR / 20,pArrowPoints,9);
for(k=0; k < 3; k++) {
pLinePoints[vblCounter - 7 + k] = new POINT2(pArrowPoints[k]);
}
for (k = 4; k > 0; k
{
pLinePoints[vblCounter - k].style = 5;
}
acCounter=12;
break;
case TacticalLines.FERRY:
lLinestyle=9;
if(dMBR/10>maxLength)
dMBR=10*maxLength;
if(dMBR/10<minLength)
dMBR=10*minLength;
if(dMBR>250)
dMBR=250;
lineutility.GetArrowHead4Double(pLinePoints[vblCounter-8],pLinePoints[vblCounter-7],(int)dMBR/10,(int)dMBR/10,pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-6+k]=new POINT2(pArrowPoints[k]);
lineutility.GetArrowHead4Double(pLinePoints[1],pLinePoints[0],(int)dMBR/10,(int)dMBR/10, pArrowPoints,lLinestyle);
for(k=0;k<3;k++)
pLinePoints[vblCounter-3+k]=new POINT2(pArrowPoints[k]);
acCounter=8;
break;
case TacticalLines.NAVIGATION:
pt3 = lineutility.ExtendLine2Double(pt1, pt0, -10, 0);
pt4 = lineutility.ExtendLine2Double(pt0, pt1, -10, 0);
pt5 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, 10, 0);
pt6 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt3, -10, 0);
pt7 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, 10, 0);
pt8 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, pt4, -10, 0);
if (pt5.y < pt6.y) {
pLinePoints[0] = new POINT2(pt5);
} else {
pLinePoints[0] = new POINT2(pt6);
}
if (pt7.y > pt8.y) {
pLinePoints[3] = new POINT2(pt7);
} else {
pLinePoints[3] = new POINT2(pt8);
}
pLinePoints[1] = new POINT2(pt0);
pLinePoints[2] = new POINT2(pt1);
acCounter=4;
break;
case TacticalLines.FORTL:
acCounter=GetFORTLPointsDouble(pLinePoints,lineType,vblSaveCounter);
break;
// case TacticalLines.HOLD:
// case TacticalLines.BRDGHD:
// lineutility.ReorderPoints(pLinePoints);
// acCounter=pLinePoints.length;
// FillPoints(pLinePoints,acCounter,points);
// break;
case TacticalLines.CANALIZE:
acCounter = DISMSupport.GetDISMCanalizeDouble(pLinePoints,lineType);
break;
case TacticalLines.BREACH:
acCounter=DISMSupport.GetDISMBreachDouble( pLinePoints,lineType);
break;
case TacticalLines.SCREEN:
case TacticalLines.GUARD:
case TacticalLines.COVER:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SCREEN_REVC: //works for 3 or 4 points
case TacticalLines.GUARD_REVC:
case TacticalLines.COVER_REVC:
acCounter=DISMSupport.GetDISMCoverDoubleRevC(pLinePoints,lineType,vblSaveCounter);
break;
case TacticalLines.SARA:
acCounter=DISMSupport.GetDISMCoverDouble(pLinePoints,lineType);
//reorder pLinePoints
POINT2[]saraPts=new POINT2[16];
for(j=0;j<4;j++)
saraPts[j]=pLinePoints[j];
for(j=4;j<8;j++)
saraPts[j]=pLinePoints[j+4]; //8-11
for(j=8;j<12;j++)
saraPts[j]=pLinePoints[j-4];
for(j=12;j<16;j++)
saraPts[j]=pLinePoints[j]; //12-15
pLinePoints=saraPts;
//acCounter=14;
break;
case TacticalLines.DISRUPT:
acCounter=DISMSupport.GetDISMDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.CONTAIN:
acCounter=DISMSupport.GetDISMContainDouble(pLinePoints,lineType);
break;
case TacticalLines.PENETRATE:
DISMSupport.GetDISMPenetrateDouble(pLinePoints,lineType);
acCounter=7;
break;
case TacticalLines.MNFLDBLK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.BLOCK:
DISMSupport.GetDISMBlockDouble2(
pLinePoints,
lineType);
acCounter=4;
break;
case TacticalLines.LINTGT:
case TacticalLines.LINTGTS:
case TacticalLines.FPF:
acCounter=DISMSupport.GetDISMLinearTargetDouble(pLinePoints, lineType, vblCounter);
break;
case TacticalLines.GAP:
case TacticalLines.ASLTXING:
case TacticalLines.BRIDGE: //change 1
DISMSupport.GetDISMGapDouble(
pLinePoints,
lineType);
acCounter=12;
break;
case TacticalLines.MNFLDDIS:
acCounter=DISMSupport.GetDISMMinefieldDisruptDouble(pLinePoints,lineType);
break;
case TacticalLines.SPTBYFIRE:
acCounter=DISMSupport.GetDISMSupportByFireDouble(pLinePoints,lineType);
break;
case TacticalLines.ATKBYFIRE:
acCounter=DISMSupport.GetDISMATKBYFIREDouble(pLinePoints,lineType);
break;
case TacticalLines.BYIMP:
acCounter=DISMSupport.GetDISMByImpDouble(pLinePoints,lineType);
break;
case TacticalLines.CLEAR:
acCounter=DISMSupport.GetDISMClearDouble(pLinePoints,lineType);
break;
case TacticalLines.BYDIF:
acCounter=DISMSupport.GetDISMByDifDouble(pLinePoints,lineType,clipBounds);
break;
case TacticalLines.SEIZE:
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,0);
break;
case TacticalLines.SEIZE_REVC: //works for 3 or 4 points
double radius=0;
if(rev==RendererSettings.Symbology_2525C)
{
radius=lineutility.CalcDistanceDouble(pLinePoints[0], pLinePoints[1]);
pLinePoints[1]=new POINT2(pLinePoints[3]);
pLinePoints[2]=new POINT2(pLinePoints[2]);
}
acCounter=DISMSupport.GetDISMSeizeDouble(pLinePoints,lineType,radius);
break;
case TacticalLines.FIX:
case TacticalLines.MNFLDFIX:
acCounter = DISMSupport.GetDISMFixDouble(pLinePoints, lineType,clipBounds);
break;
case TacticalLines.RIP:
acCounter = DISMSupport.GetDISMRIPDouble(pLinePoints,lineType);
break;
case TacticalLines.DELAY:
case TacticalLines.WITHDRAW:
case TacticalLines.WDRAWUP:
case TacticalLines.RETIRE:
//reverse the points
//lineutility.ReversePointsDouble2(ref pLinePoints, vblSaveCounter);
acCounter=DISMSupport.GetDelayGraphicEtcDouble(pLinePoints);
break;
case TacticalLines.EASY:
acCounter=DISMSupport.GetDISMEasyDouble(pLinePoints,lineType);
break;
case TacticalLines.DECEIVE:
DISMSupport.GetDISMDeceiveDouble(pLinePoints);
acCounter=4;
break;
case TacticalLines. BYPASS:
acCounter=DISMSupport.GetDISMBypassDouble(pLinePoints,lineType);
break;
case TacticalLines.PAA_RECTANGULAR:
DISMSupport.GetDISMPAADouble(pLinePoints,lineType);
acCounter=5;
break;
case TacticalLines.AMBUSH:
acCounter=DISMSupport.AmbushPointsDouble(pLinePoints);
break;
case TacticalLines.FLOT:
acCounter=flot.GetFlotDouble(pLinePoints,vblSaveCounter);
break;
default:
acCounter=vblSaveCounter;
break;
}
//diagnostic
//lineutility.WriteFile(Double.toString(pLinePoints[0].x)+" to "+Double.toString(pLinePoints[1].x));
//end diagnostic
//Fill points
//and/or return points if shapes is null
switch(lineType)
{
case TacticalLines.BOUNDARY:
FillPoints(pLinePoints,acCounter,points);
return points;
case TacticalLines.CONTAIN:
case TacticalLines.BLOCK:
//case TacticalLines.DMAF: //points are already filled for DMAF
case TacticalLines.COVER:
case TacticalLines.SCREEN: //note: screen, cover, guard are getting their modifiers before the call to getlinearray
case TacticalLines.GUARD:
case TacticalLines.COVER_REVC:
case TacticalLines.SCREEN_REVC:
case TacticalLines.GUARD_REVC:
//case TacticalLines.DUMMY: //commented 5-3-10
case TacticalLines.PAA_RECTANGULAR:
case TacticalLines.FOLSP:
case TacticalLines.FOLLA:
//add these for rev c 3-12-12
case TacticalLines.BREACH:
case TacticalLines.BYPASS:
case TacticalLines.CANALIZE:
case TacticalLines.CLEAR:
case TacticalLines.DISRUPT:
case TacticalLines.FIX:
case TacticalLines.ISOLATE:
case TacticalLines.OCCUPY:
case TacticalLines.PENETRATE:
case TacticalLines.RETAIN:
case TacticalLines.SECURE:
case TacticalLines.SEIZE:
case TacticalLines.SEIZE_REVC:
case TacticalLines.BS_RECTANGLE:
case TacticalLines.BBS_RECTANGLE:
//add these
case TacticalLines.AIRFIELD:
case TacticalLines.DMA:
case TacticalLines.DUMMY:
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.MSDZ:
case TacticalLines.CONVOY:
case TacticalLines.HCONVOY:
case TacticalLines.MFLANE:
case TacticalLines.DIRATKAIR:
case TacticalLines.ABATIS:
FillPoints(pLinePoints,acCounter,points);
break;
default:
//if shapes is null then it is a non-CPOF client, dependent upon pixels
//instead of shapes
if(shapes==null)
{
FillPoints(pLinePoints,acCounter,points);
return points;
}
break;
}
//the shapes require pLinePoints
//if the shapes are null then it is a non-CPOF client,
if(shapes==null)
return points;
Shape2 shape=null;
Shape gp=null;
Shape2 redShape=null,blueShape=null,paleBlueShape=null,whiteShape=null;
Shape2 redFillShape=null,blueFillShape=null,blackShape=null;
BasicStroke blueStroke,paleBlueStroke;
Area blueArea=null;
Area paleBlueArea=null;
Area whiteArea=null;
boolean beginLine=true;
Polygon poly=null;
//a loop for the outline shapes
switch(lineType)
{
case TacticalLines.BBS_AREA:
case TacticalLines.BBS_RECTANGLE:
// for(j=0;j<vblSaveCounter-1;j++)
// shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
// shape.moveTo(pOriginalLinePoints[j]);
// shape.lineTo(pLinePoints[j]);
// shape.lineTo(pLinePoints[j+1]);
// shape.lineTo(pOriginalLinePoints[j+1]);
// shape.lineTo(pOriginalLinePoints[j]);
// shapes.add(shape);
// //shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pLinePoints[0]);
for(j=0;j<vblSaveCounter;j++)
shape.lineTo(pLinePoints[j]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pOriginalLinePoints[0]);
for(j=1;j<vblSaveCounter;j++)
shape.lineTo(pOriginalLinePoints[j]);
shapes.add(shape);
break;
case TacticalLines.DIRATKGND:
//create two shapes. the first shape is for the line
//the second shape is for the arrow
//renderer will know to use a skinny stroke for the arrow shape
//the line shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
shape.moveTo(pLinePoints[0]);
for(j=0;j<acCounter-10;j++)
{
//shape.lineTo(pLinePoints[j].x,pLinePoints[j].y);
shape.lineTo(pLinePoints[j]);
}
shapes.add(shape);
//the arrow shape
shape =new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[acCounter-10].x,pLinePoints[acCounter-10].y);
shape.moveTo(pLinePoints[acCounter-10]);
for(j=9;j>0;j
{
if(pLinePoints[acCounter-j-1].style == 5)
{
//shape.moveTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.moveTo(pLinePoints[acCounter-j]);
}
else
{
//shape.lineTo(pLinePoints[acCounter-j].x,pLinePoints[acCounter-j].y);
shape.lineTo(pLinePoints[acCounter-j]);
}
}
//shape.lineTo(pLinePoints[acCounter-1].x,pLinePoints[acCounter-1].y);
shapes.add(shape);
break;
// case TacticalLines.BBS_LINE:
// Shape2 outerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//line color
// Shape2 innerShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//fill color
// BasicStroke wideStroke=new BasicStroke(pLinePoints[0].style);
// BasicStroke thinStroke=new BasicStroke(pLinePoints[0].style-1);
// for(k=0;k<vblSaveCounter;k++)
// if(k==0)
// outerShape.moveTo(pLinePoints[k]);
// innerShape.moveTo(pLinePoints[k]);
// else
// outerShape.lineTo(pLinePoints[k]);
// innerShape.lineTo(pLinePoints[k]);
// outerShape.setStroke(wideStroke);
// innerShape.setStroke(thinStroke);
// shapes.add(outerShape);
// shapes.add(innerShape);
// break;
case TacticalLines.DEPTH_AREA:
paleBlueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
paleBlueShape.setFillColor(new Color(153,204,255));
paleBlueStroke=new BasicStroke(28);
blueShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
blueShape.setFillColor(new Color(30,144,255));
blueStroke=new BasicStroke(14);
whiteShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//use for symbol
whiteShape.setFillColor(Color.WHITE);
poly=new Polygon();
for(k=0;k<vblSaveCounter;k++)
{
poly.addPoint((int)pLinePoints[k].x, (int)pLinePoints[k].y);
if(k==0)
whiteShape.moveTo(pLinePoints[k]);
else
whiteShape.lineTo(pLinePoints[k]);
}
whiteArea=new Area(poly);
blueArea=new Area(blueStroke.createStrokedShape(poly));
blueArea.intersect(whiteArea);
blueShape.setShape(lineutility.createStrokedShape(blueArea));
paleBlueArea=new Area(paleBlueStroke.createStrokedShape(poly));
paleBlueArea.intersect(whiteArea);
paleBlueShape.setShape(lineutility.createStrokedShape(paleBlueArea));
shapes.add(whiteShape);
shapes.add(paleBlueShape);
shapes.add(blueShape);
break;
case TacticalLines.TRAINING_AREA:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for outline
redShape.set_Style(1);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);//use for symbol
blueShape.set_Style(0);
redShape.moveTo(pLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
redShape.lineTo(pLinePoints[k]);
//blueShape.moveTo(pLinePoints[vblSaveCounter]);
beginLine=true;
for(k=vblSaveCounter;k<acCounter;k++)
{
if(pLinePoints[k].style==0)
{
if(beginLine)
{
blueShape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
blueShape.lineTo(pLinePoints[k]);
}
if(pLinePoints[k].style==5)
{
blueShape.lineTo(pLinePoints[k]);
beginLine=true;
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.ITD:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.GREEN);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFY:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//flots and spikes (triangles)
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
//blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
//blackShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//red and blue short segments (between the flots)
for(k=0;k<vblCounter-1;k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SFG:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23) //red flots
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
}
shapes.add(redFillShape); //1-3-12
}
if(pLinePoints[k].style==24)//blue spikes red outline
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //1-3-12
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
shapes.add(blueFillShape); //1-3-12
redShape.moveTo(pLinePoints[k-2]);
redShape.lineTo(pLinePoints[k-1]);
redShape.lineTo(pLinePoints[k]);
}
}
//the corners
for(k=0;k<vblSaveCounter;k++)
{
if(k==0)
{
d=50;
redShape.moveTo(pOriginalLinePoints[0]);
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[0], pOriginalLinePoints[1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[0], pOriginalLinePoints[1], d);
redShape.lineTo(pt0);
}
else if(k>0 && k<vblSaveCounter-1)
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k-1]);
if(d1<d)
d=d1;
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k-1],d);
pt1=pOriginalLinePoints[k];
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[k], pOriginalLinePoints[k+1]);
if(d1<d)
d=d1;
pt2=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[k],pOriginalLinePoints[k+1],d);
redShape.moveTo(pt0);
redShape.lineTo(pt1);
redShape.lineTo(pt2);
}
else //last point
{
d=50;
d1=lineutility.CalcDistanceDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2]);
if(d1<d)
d=d1;
redShape.moveTo(pOriginalLinePoints[vblSaveCounter-1]);
pt0=lineutility.ExtendAlongLineDouble(pOriginalLinePoints[vblSaveCounter-1], pOriginalLinePoints[vblSaveCounter-2], d);
redShape.lineTo(pt0);
}
}
//add the shapes
//shapes.add(redFillShape); //1-3-12
//shapes.add(blueFillShape);
shapes.add(redShape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==22)
{
POINT2[] CirclePoints=new POINT2[8];
redShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
redShape.setFillColor(Color.RED);
if(redShape !=null && redShape.getShape() != null)
shapes.add(redShape);
}
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
blueShape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
blueShape.setFillColor(Color.BLUE);
if(blueShape !=null && blueShape.getShape() != null)
shapes.add(blueShape);
}
}
break;
case TacticalLines.USF:
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
beginLine=true;
//int color=0;//red
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==19 && pLinePoints[k+1].style==19)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
//color=0;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==5)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==25 && pLinePoints[k+1].style==25)
{
blueShape.moveTo(pLinePoints[k]);
blueShape.lineTo(pLinePoints[k+1]);
//color=1;
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
redShape.moveTo(pLinePoints[k]);
redShape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(redShape);
shapes.add(blueShape);
break;
case TacticalLines.SF:
blackShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blackShape.setLineColor(Color.BLACK);
redShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
redShape.setLineColor(Color.RED);
blueShape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
blueShape.setLineColor(Color.BLUE);
//blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
//blueFillShape.setFillColor(Color.BLUE);
//redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);
//redFillShape.setFillColor(Color.RED);
//color=0;
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==23)
{
redFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL);//12-30-11
redFillShape.setFillColor(Color.RED);
redFillShape.moveTo(pLinePoints[k-9]);
blackShape.moveTo(pLinePoints[k-9]);
for(int l=k-8;l<=k;l++)
{
redFillShape.lineTo(pLinePoints[l]);
blackShape.lineTo(pLinePoints[l]);
}
redFillShape.lineTo(pLinePoints[k-9]); //12-30-11
shapes.add(redFillShape); //12-30-11
}
if(pLinePoints[k].style==24)
{
blueFillShape=new Shape2(Shape2.SHAPE_TYPE_FILL); //12-30-11
blueFillShape.setFillColor(Color.BLUE);
blueFillShape.moveTo(pLinePoints[k-2]);
blueFillShape.lineTo(pLinePoints[k-1]);
blueFillShape.lineTo(pLinePoints[k]);
blueFillShape.lineTo(pLinePoints[k-2]);
shapes.add(blueFillShape); //12-30-11
blackShape.moveTo(pLinePoints[k-2]);
blackShape.lineTo(pLinePoints[k-1]);
blackShape.lineTo(pLinePoints[k]);
}
}
//the corners
blackShape.moveTo(pOriginalLinePoints[0]);
for(k=1;k<vblSaveCounter;k++)
blackShape.lineTo(pOriginalLinePoints[k]);
//shapes.add(redFillShape); //12-30-11
//shapes.add(blueFillShape);
shapes.add(redShape);
shapes.add(blueShape);
shapes.add(blackShape);
break;
case TacticalLines.WFG:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
//the dots
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.FOLLA:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1); //dashed line
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(0); //dashed line
//shape.moveTo(pLinePoints[2]);
for(j=2;j<vblCounter;j++)
{
if(pLinePoints[j-1].style != 5)
shape.lineTo(pLinePoints[j]);
else
shape.moveTo(pLinePoints[j]);
}
shapes.add(shape);
break;
case TacticalLines.CFG:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 3, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.moveTo(pLinePoints[0].x,pLinePoints[0].y);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==9)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
d=lineutility.CalcDistanceDouble(pLinePoints[k], pLinePoints[k+1]);
pt0=lineutility.ExtendAlongLineDouble(pLinePoints[k], pLinePoints[k+1], d-5);
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pt0.x,pt0.y);
shape.lineTo(pt0);
}
if(pLinePoints[k].style==0 && k==acCounter-2)
{
//shape.moveTo(pLinePoints[k].x,pLinePoints[k].y);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k+1].x,pLinePoints[k+1].y);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.PIPE:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter-1; k++)
{
if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
}
shapes.add(shape);
break;
case TacticalLines.OVERHEAD_WIRE_LS:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 5, 8, CirclePoints, 9);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==1)
{
if(k==0)
{
shape.moveTo(pLinePoints[k]);
}
else
shape.lineTo(pLinePoints[k]);
}
}
shapes.add(shape);
break;
case TacticalLines.ATDITCHM:
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==20)
{
POINT2[] CirclePoints=new POINT2[8];
shape=lineutility.CalcCircleShape(pLinePoints[k], 4, 8, CirclePoints, 9);//was 3
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
continue;
}
if(k<acCounter-2)
{
if(pLinePoints[k].style!=0 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==10)
{
shape.moveTo(pLinePoints[k]);
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
//use shapes instead of pixels
// if(shape==null)
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// if(beginLine)
// if(k==0)
// shape.set_Style(pLinePoints[k].style);
// shape.moveTo(pLinePoints[k]);
// beginLine=false;
// else
// //diagnostic 1-8-13
// if(k<acCounter-1)
// if(pLinePoints[k].style==5)
// shape.moveTo(pLinePoints[k]);
// continue;
// //end section
// shape.lineTo(pLinePoints[k]);
// //diagnostic 1-8-13
// //if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
// if(pLinePoints[k].style==10)
// beginLine=true;
// if(pLinePoints[k+1].style==20)
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
if(k<acCounter-2)
{
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==0)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==0)
{
shape.lineTo(pLinePoints[k+1]);
}
else if(pLinePoints[k].style==0 && pLinePoints[k+1].style==5)
{
shape.lineTo(pLinePoints[k+1]);
shapes.add(shape);
}
}
}//end for
break;
case TacticalLines.DIRATKFNT:
//the solid lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18)
continue;
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k>0) //doubled points with linestyle=5
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
continue;//shape.lineTo(pLinePoints[k]);
if(k==0)
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==vblCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
//the dashed lines
for (k = 0; k < vblCounter; k++)
{
if(pLinePoints[k].style==18 && pLinePoints[k-1].style == 5)
{
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
//shape.set_Style(pLinePoints[k].style);
shape.set_Style(1);
shape.moveTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==18 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
}
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==18)
{
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
}
else
continue;
}
break;
case TacticalLines.ESR1:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[2].style);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
//if(shape !=null && shape.get_Shape() != null)
shapes.add(shape);
break;
case TacticalLines.DUMMY: //commented 5-3-10
//first shape is the original points
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.set_Style(1);
// shape.moveTo(pLinePoints[acCounter-1]);
// shape.lineTo(pLinePoints[acCounter-2]);
// shape.lineTo(pLinePoints[acCounter-3]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(shape);
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for (k = 0; k < acCounter-3; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
if(k==0)
shape.set_Style(pLinePoints[k].style);
//if(k>0) //doubled points with linestyle=5
// if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5)
// shape.lineTo(pLinePoints[k]);
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-4) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(1);
shape.moveTo(pLinePoints[acCounter-1]);
shape.lineTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-3]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMA:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[vblCounter-3]);
shape.set_Style(1);
shape.lineTo(pLinePoints[vblCounter-2]);
shape.lineTo(pLinePoints[vblCounter-1]);
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.FORDIF:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[0].style);
shape.moveTo(pLinePoints[0]);
shape.lineTo(pLinePoints[1]);
shape.moveTo(pLinePoints[2]);
shape.lineTo(pLinePoints[3]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(pLinePoints[4].style);
shape.moveTo(pLinePoints[4]);
for(k=5;k<acCounter;k++)
{
if(pLinePoints[k-1].style != 5)
shape.lineTo(pLinePoints[k]);
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
break;
case TacticalLines.DMAF:
//first shape is the original points
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.set_Style(points.get(0).style);
shape.moveTo(points.get(0));
for(k=1;k<vblCounter-3;k++)
{
shape.lineTo(points.get(k));
}
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//next shape is the center feature
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(points.get(vblCounter-3));
shape.set_Style(1);
shape.lineTo(points.get(vblCounter-2));
shape.lineTo(points.get(vblCounter-1));
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
//add a shape to outline the center feature in case fill is opaque
//and the same color so that the fill obscures the feature
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
//last shape are the xpoints
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
beginLine=true;
for(k=vblCounter;k<points.size();k++)
{
if(beginLine)
{
if(k==0)
shape.set_Style(points.get(k).style);
if(k>0) //doubled points with linestyle=5
if(points.get(k).style==5 && points.get(k-1).style==5)
shape.lineTo(points.get(k));
shape.moveTo(points.get(k));
beginLine=false;
}
else
{
shape.lineTo(points.get(k));
if(points.get(k).style==5 || points.get(k).style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==points.size()-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}
break;
case TacticalLines.AIRFIELD:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for (k = 1; k < acCounter-5; k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[acCounter-4]);
shape.lineTo(pLinePoints[acCounter-3]);
shape.moveTo(pLinePoints[acCounter-2]);
shape.lineTo(pLinePoints[acCounter-1]);
shapes.add(shape);
//we need an extra shape to outline the center feature
//in case there is opaque fill that obliterates it
// gp=shape.getShape();
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.setShape(gp);
// shapes.add(1,shape);
break;
case TacticalLines.MIN_POINTS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[0]);
for(k=1;k<pLinePoints.length;k++)
shape.lineTo(pLinePoints[k]);
shapes.add(shape);
break;
default:
for (k = 0; k < acCounter; k++)
{
//use shapes instead of pixels
if(shape==null)
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
if(beginLine)
{
//if(pLinePoints[k].style==5)
// continue;
if(k==0)
shape.set_Style(pLinePoints[k].style);
if(k>0) //doubled points with linestyle=5
{
if(pLinePoints[k].style==5 && pLinePoints[k-1].style==5 && k< acCounter-1)
continue;
else if(pLinePoints[k].style==5 && pLinePoints[k-1].style==10)
continue;
}
if(k==0 && pLinePoints.length>1)
if(pLinePoints[k].style==5 && pLinePoints[k+1].style==5)
continue;
shape.moveTo(pLinePoints[k]);
beginLine=false;
}
else
{
shape.lineTo(pLinePoints[k]);
if(pLinePoints[k].style==5 || pLinePoints[k].style==10)
{
beginLine=true;
//unless there are doubled points with style=5
}
}
if(k==acCounter-1) //non-LC should only have one shape
{
if(shape !=null && shape.getShape() != null)
shapes.add(shape);
}
}//end for
break;
}//end switch
//a loop for arrowheads with fill
//these require a separate shape for fill
switch(lineType)
{
case TacticalLines.AC:
case TacticalLines.SAAFR:
case TacticalLines.MRR:
case TacticalLines.MRR_USAS:
case TacticalLines.UAV:
case TacticalLines.UAV_USAS:
case TacticalLines.LLTR:
for (j = 0; j < vblSaveCounter - 1; j++) {
dMBR=pOriginalLinePoints[j].style;
acPoints[0] = new POINT2(pOriginalLinePoints[j]);
acPoints[1] = new POINT2(pOriginalLinePoints[j + 1]);
lineutility.GetSAAFRFillSegment(acPoints, dMBR);//was dMRR
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(acPoints[0]);
shape.lineTo(acPoints[1]);
shape.lineTo(acPoints[2]);
shape.lineTo(acPoints[3]);
shapes.add(0,shape);
}
break;
case TacticalLines.BELT1://requires non-decorated fill shape
shape =new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.moveTo(pUpperLinePoints[0]);
for(j=1;j<pUpperLinePoints.length;j++)
{
shape.lineTo(pUpperLinePoints[j]);
//lineutility.SegmentLineShape(pUpperLinePoints[j], pUpperLinePoints[j+1], shape);
}
shape.lineTo(pLowerLinePoints[pLowerLinePoints.length-1]);
for(j=pLowerLinePoints.length-1;j>=0;j
{
shape.lineTo(pLowerLinePoints[j]);
//lineutility.SegmentLineShape(pLowerLinePoints[j], pLowerLinePoints[j-1], shape);
}
shape.lineTo(pUpperLinePoints[0]);
shapes.add(0,shape);
break;
case TacticalLines.DIRATKAIR:
//added this section to not fill the bow tie and instead
//add a shape to close what had been the bow tie fill areas with
//a line segment for each one
int outLineCounter=0;
POINT2[]ptOutline=new POINT2[4];
for (k = 0; k < acCounter; k++)
{
if(pLinePoints[k].style==10)
{
//shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.moveTo(pLinePoints[k-2]);
shape.lineTo(pLinePoints[k]);
if(shape !=null && shape.getShape() != null)
shapes.add(1,shape);
//collect these four points
ptOutline[outLineCounter++]=pLinePoints[k-2];
ptOutline[outLineCounter++]=pLinePoints[k];
}
}//end for
//build a shape from the to use as outline for the feature
//if fill alpha is high
// shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
// shape.moveTo(ptOutline[0]);
// shape.lineTo(ptOutline[1]);
// shape.lineTo(ptOutline[3]);
// shape.lineTo(ptOutline[2]);
// shape.lineTo(ptOutline[0]);
// if(shape !=null && shape.getShape() != null)
// shapes.add(0,shape);
break;
case TacticalLines.OFY:
case TacticalLines.OCCLUDED:
case TacticalLines.WF:
case TacticalLines.WFG:
case TacticalLines.WFY:
case TacticalLines.CF:
case TacticalLines.CFY:
case TacticalLines.CFG:
//case TacticalLines.SF:
//case TacticalLines.SFY:
//case TacticalLines.SFG:
case TacticalLines.SARA:
case TacticalLines.FERRY:
case TacticalLines.EASY:
case TacticalLines.BYDIF:
case TacticalLines.BYIMP:
case TacticalLines.FOLSP:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
case TacticalLines.MNFLDFIX:
case TacticalLines.TURN:
case TacticalLines.MNFLDDIS:
//POINT2 initialFillPt=null;
for (k = 0; k < acCounter; k++)
{
if(k==0)
{
if(pLinePoints[k].style==9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
}
else
{
if(pLinePoints[k].style==9 && pLinePoints[k-1].style != 9)
{
shape=new Shape2(Shape2.SHAPE_TYPE_FILL);
shape.set_Style(pLinePoints[k].style);
shape.moveTo(pLinePoints[k]);
//need to capture the initial fill point
//initialFillPt=new POINT2(pLinePoints[k]);
}
if(pLinePoints[k].style==9 && pLinePoints[k-1].style==9) //9,9,...,9,10
{
shape.lineTo(pLinePoints[k]);
}
}
if(pLinePoints[k].style==10)
{
shape.lineTo(pLinePoints[k]);
//if(lineType==TacticalLines.SARA)
//shape.lineTo(pLinePoints[k-2]);
if(shape !=null && shape.getShape() != null)
{
//must line to the initial fill point to close the shape
//this is a requirement for the java linear ring (map3D java client)
//if(initialFillPt != null)
//shape.lineTo(initialFillPt);
shapes.add(0,shape);
//initialFillPt=null;
}
}
}//end for
break;
default:
break;
}
//CELineArray.add_Shapes(shapes);
//clean up
pArrowPoints=null;
arcPts=null;
circlePoints=null;
pOriginalLinePoints=null;
pts2=null;
pts=null;
segments=null;
pUpperLinePoints=null;
pLowerLinePoints=null;
pUpperLowerLinePoints=null;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className, "GetLineArray2Double",
new RendererException("GetLineArray2Dboule " + Integer.toString(lineType), exc));
}
return points;
}
}
|
package imagej.ext.module;
import imagej.ext.module.ui.WidgetStyle;
import imagej.util.ClassUtils;
import imagej.util.NumberUtils;
import imagej.util.Prefs;
import imagej.util.StringMaker;
import java.util.List;
/**
* Abstract superclass of {@link ModuleItem} implementations.
*
* @author Curtis Rueden
*/
public abstract class AbstractModuleItem<T> implements ModuleItem<T> {
private final ModuleInfo info;
private MethodRef initializerRef;
private MethodRef callbackRef;
public AbstractModuleItem(final ModuleInfo info) {
this.info = info;
}
// -- Object methods --
@Override
public String toString() {
final StringMaker sm = new StringMaker();
sm.append("label", getLabel());
sm.append("description", getDescription());
sm.append("visibility", getVisibility(), ItemVisibility.NORMAL);
sm.append("required", isRequired());
sm.append("persisted", isPersisted());
sm.append("persistKey", getPersistKey());
sm.append("callback", getCallback());
sm.append("widgetStyle", getWidgetStyle(), WidgetStyle.DEFAULT);
sm.append("min", getMinimumValue());
sm.append("max", getMaximumValue());
sm.append("stepSize", getStepSize(), NumberUtils.toNumber("1", getType()));
sm.append("columnCount", getColumnCount(), 6);
sm.append("choices", getChoices());
return getName() + ": " + sm.toString();
}
// -- ModuleItem methods --
@Override
public ItemIO getIOType() {
return ItemIO.INPUT;
}
@Override
public boolean isInput() {
final ItemIO ioType = getIOType();
return ioType == ItemIO.INPUT || ioType == ItemIO.BOTH;
}
@Override
public boolean isOutput() {
final ItemIO ioType = getIOType();
return ioType == ItemIO.OUTPUT || ioType == ItemIO.BOTH;
}
@Override
public ItemVisibility getVisibility() {
return ItemVisibility.NORMAL;
}
@Override
public boolean isAutoFill() {
return true;
}
@Override
public boolean isRequired() {
return false;
}
@Override
public boolean isPersisted() {
return true;
}
@Override
public String getPersistKey() {
return null;
}
/**
* Returns the persisted value of a ModuleItem. Returns null if nothing has
* been persisted. It is the API user's responsibility to check the return
* value for null.
*/
@Override
public T loadValue() {
// if there is nothing to load from persistence return nothing
if (!isPersisted()) return null;
final String sValue;
final String persistKey = getPersistKey();
if (persistKey == null || persistKey.isEmpty()) {
final Class<?> prefClass = getDelegateClass();
final String prefKey = getName();
sValue = Prefs.get(prefClass, prefKey);
}
else sValue = Prefs.get(persistKey);
// if persisted value has never been set before return null
if (sValue == null) return null;
return ClassUtils.convert(sValue, getType());
}
@Override
public void saveValue(final T value) {
if (!isPersisted()) return;
final String sValue = value == null ? "" : value.toString();
// do not persist if object cannot be converted back from a string
if (!ClassUtils.canCast(sValue, getType())) return;
final String persistKey = getPersistKey();
if (persistKey == null || persistKey.isEmpty()) {
final Class<?> prefClass = getDelegateClass();
final String prefKey = getName();
Prefs.put(prefClass, prefKey, sValue);
}
else Prefs.put(persistKey, sValue);
}
@Override
public String getInitializer() {
return null;
}
@Override
public void initialize(final Module module) {
if (initializerRef == null) {
initializerRef =
new MethodRef(info.getDelegateClassName(), getInitializer());
}
initializerRef.execute(module.getDelegateObject());
}
@Override
public String getCallback() {
return null;
}
@Override
public void callback(final Module module) {
if (callbackRef == null) {
callbackRef = new MethodRef(info.getDelegateClassName(), getCallback());
}
callbackRef.execute(module.getDelegateObject());
}
@Override
public WidgetStyle getWidgetStyle() {
return WidgetStyle.DEFAULT;
}
@Override
public T getMinimumValue() {
return null;
}
@Override
public T getMaximumValue() {
return null;
}
@Override
public Number getStepSize() {
if (!ClassUtils.isNumber(getType())) return null;
return NumberUtils.toNumber("1", getType());
}
@Override
public int getColumnCount() {
return 6;
}
@Override
public List<T> getChoices() {
return null;
}
@Override
public T getValue(final Module module) {
final Object result;
if (isInput()) result = module.getInput(getName());
else if (isOutput()) result = module.getOutput(getName());
else result = null;
@SuppressWarnings("unchecked")
final T value = (T) result;
return value;
}
@Override
public void setValue(final Module module, final T value) {
if (isInput()) module.setInput(getName(), value);
if (isOutput()) module.setOutput(getName(), value);
}
// -- BasicDetails methods --
@Override
public String getName() {
return null;
}
@Override
public String getLabel() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public void setName(final String name) {
throw new UnsupportedOperationException();
}
@Override
public void setLabel(final String description) {
throw new UnsupportedOperationException();
}
@Override
public void setDescription(final String description) {
throw new UnsupportedOperationException();
}
// -- Helper methods --
private Class<?> getDelegateClass() {
return ClassUtils.loadClass(info.getDelegateClassName());
}
}
|
package com.segment.analytics;
import com.bugsnag.android.Bugsnag;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(RobolectricTestRunner.class) @Config(emulateSdk = 18, manifest = Config.NONE)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest(Bugsnag.class)
public class BugsnagTest extends IntegrationExam {
@Rule public PowerMockRule rule = new PowerMockRule();
BugsnagIntegrationAdapter adapter;
@Before @Override public void setUp() {
super.setUp();
PowerMockito.mockStatic(Bugsnag.class);
adapter = new BugsnagIntegrationAdapter();
}
@Test public void initialize() throws InvalidConfigurationException {
adapter.initialize(context, new JsonMap().putValue("apiKey", "foo").putValue("useSSL", true));
verifyStatic();
Bugsnag.register(context, "foo");
Bugsnag.setUseSSL(true);
}
@Test
public void onActivityCreated() {
when(activity.getLocalClassName()).thenReturn("foo");
adapter.onActivityCreated(activity, bundle);
verifyStatic();
Bugsnag.setContext("foo");
Bugsnag.onActivityCreate(activity);
}
@Test public void onActivityResumed() {
adapter.onActivityResumed(activity);
verifyStatic();
Bugsnag.onActivityResume(activity);
}
@Test public void onActivityPaused() {
adapter.onActivityPaused(activity);
verifyStatic();
Bugsnag.onActivityPause(activity);
}
@Test public void onActivityDestroyed() {
adapter.onActivityDestroyed(activity);
verifyStatic();
Bugsnag.onActivityDestroy(activity);
}
@Test public void activityLifecycle() {
adapter.onActivityStopped(activity);
adapter.onActivitySaveInstanceState(activity, bundle);
adapter.onActivityStarted(activity);
verifyStatic();
verifyNoMoreInteractions(Bugsnag.class);
}
@Test public void identify() {
traits.putUserId("foo").putEmail("bar").putName("baz");
adapter.identify(identifyPayload("foo"));
verifyStatic();
Bugsnag.setUser("foo", "bar", "baz");
Bugsnag.addToTab("User", "userId", "foo");
Bugsnag.addToTab("User", "email", "bar");
Bugsnag.addToTab("User", "name", "baz");
}
}
|
package com.alienshots.ludum.asset.texture;
import com.alienshots.ludum.component.SawComponent;
import com.alienshots.ludum.component.PlayerComponent;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
public class GameScreenAtlas {
public static final GameScreenAtlas instance = new GameScreenAtlas();
private final Map<Class<?>, String> regionNameTemplateLookup = new HashMap<>();
private Texture sourceImage;
private TextureAtlas textureAtlas;
public GameScreenAtlas() {
sourceImage = new Texture("badlogic.jpg");
textureAtlas = new TextureAtlas();
initNameTemplateLookup();
initAtlasRegions();
}
private void initNameTemplateLookup() {
regionNameTemplateLookup.put(PlayerComponent.class, "player%s_%s");
regionNameTemplateLookup.put(SawComponent.class, "component%s_%s");
}
private void initAtlasRegions() {
initPlayerRegions();
initSawRegions();
}
private void initPlayerRegions() {
String baseName = "player";
textureAtlas.addRegion(baseName + "1_1", sourceImage, 0, 0, 30, 30);
textureAtlas.addRegion(baseName + "1_2", sourceImage, 50, 50, 30, 30);
}
private void initSawRegions() {
String baseName = "saw";
textureAtlas.addRegion(baseName + "1_1", sourceImage, 100, 100, 30, 30);
textureAtlas.addRegion(baseName + "1_2", sourceImage, 150, 150, 30, 30);
textureAtlas.addRegion(baseName + "1_3", sourceImage, 200, 200, 30, 30);
textureAtlas.addRegion(baseName + "1_4", sourceImage, 250, 250, 30, 30);
textureAtlas.addRegion(baseName + "1_5", sourceImage, 300, 300, 30, 30);
textureAtlas.addRegion(baseName + "1_6", sourceImage, 350, 350, 30, 30);
textureAtlas.addRegion(baseName + "1_7", sourceImage, 400, 400, 30, 30);
}
public TextureRegion getScreenTexture(Class<?> tagClass, AtlasCoordinates coords) {
String regionName = String.format(regionNameTemplateLookup.get(tagClass), coords.getLevel(), coords.getColumn());
return textureAtlas.findRegion(regionName);
}
public void dispose() {
sourceImage.dispose();
}
// Indices start at 1
@AllArgsConstructor
@Getter
@Setter
public static class AtlasCoordinates {
private int level;
private int column;
}
}
|
package org.mskcc.cbio.portal.dao;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mskcc.cbio.portal.util.DatabaseProperties;
/**
* Data source that self-initializes based on cBioPortal configuration.
*/
public class JdbcDataSource extends BasicDataSource {
public JdbcDataSource () {
DatabaseProperties dbProperties = DatabaseProperties.getInstance();
String host = dbProperties.getDbHost();
String userName = dbProperties.getDbUser();
String password = dbProperties.getDbPassword();
String database = dbProperties.getDbName();
String url ="jdbc:mysql://" + host + "/" + database +
"?user=" + userName + "&password=" + password +
"&zeroDateTimeBehavior=convertToNull";
// Set up poolable data source
this.setDriverClassName("com.mysql.jdbc.Driver");
this.setUsername(userName);
this.setPassword(password);
this.setUrl(url);
// By pooling/reusing PreparedStatements, we get a major performance gain
this.setPoolPreparedStatements(true);
// these are the values cbioportal has been using in their production
// context.xml files when using jndi
this.setMaxTotal(500);
this.setMaxIdle(30);
this.setMaxWaitMillis(10000);
this.setMinEvictableIdleTimeMillis(30000);
this.setTestOnBorrow(true);
this.setValidationQuery("SELECT 1");
}
}
|
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge.
/**
* This is only generated once! It will never be overwritten.
* You can (and have to!) safely modify it by hand.
*/
package org.phoenixctms.ctsms.domain;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import org.hibernate.Query;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.phoenixctms.ctsms.enumeration.DBModule;
import org.phoenixctms.ctsms.query.CriteriaUtil;
import org.phoenixctms.ctsms.query.QueryUtil;
import org.phoenixctms.ctsms.query.SubCriteriaMap;
import org.phoenixctms.ctsms.util.CommonUtil;
import org.phoenixctms.ctsms.vo.AuthenticationTypeVO;
import org.phoenixctms.ctsms.vo.CriteriaInstantVO;
import org.phoenixctms.ctsms.vo.PSFVO;
import org.phoenixctms.ctsms.vo.StaffOutVO;
import org.phoenixctms.ctsms.vo.UserInVO;
import org.phoenixctms.ctsms.vo.UserInheritedVO;
import org.phoenixctms.ctsms.vo.UserOutVO;
import org.phoenixctms.ctsms.vo.UserSettingsInVO;
import org.phoenixctms.ctsms.vocycle.DeferredVO;
import org.phoenixctms.ctsms.vocycle.UserReflexionGraph;
import org.springframework.dao.DataAccessResourceFailureException;
/**
* @see User
*/
public class UserDaoImpl
extends UserDaoBase {
private org.hibernate.Criteria createUserCriteria() {
org.hibernate.Criteria userCriteria = this.getSession().createCriteria(User.class);
return userCriteria;
}
@Override
protected long handleGetChildrenCount(Long userId) throws Exception {
org.hibernate.Criteria userCriteria = createUserCriteria();
userCriteria.add(Restrictions.eq("parent.id", userId.longValue()));
return (Long) userCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
@Override
protected Collection<User> handleFindByCriteria(CriteriaInstantVO criteria, PSFVO psf) throws Exception {
Query query = QueryUtil.createSearchQuery(
criteria,
DBModule.USER_DB,
psf,
this.getSessionFactory(),
this.getCriterionTieDao(),
this.getCriterionPropertyDao(),
this.getCriterionRestrictionDao());
return query.list();
}
@Override
protected Collection<User> handleFindByIdDepartment(Long userId,
Long departmentId, PSFVO psf) throws Exception {
org.hibernate.Criteria userCriteria = createUserCriteria();
SubCriteriaMap criteriaMap = new SubCriteriaMap(User.class, userCriteria);
CriteriaUtil.applyIdDepartmentCriterion(userCriteria, userId, departmentId);
CriteriaUtil.applyPSFVO(criteriaMap, psf);
return userCriteria.list();
}
/**
* @throws Exception
* @inheritDoc
*/
@Override
protected Collection<User> handleFindByIdentity(Long identityId, PSFVO psf) throws Exception {
org.hibernate.Criteria userCriteria = createUserCriteria();
SubCriteriaMap criteriaMap = new SubCriteriaMap(User.class, userCriteria);
if (identityId != null) {
userCriteria.add(Restrictions.eq("identity.id", identityId.longValue()));
}
CriteriaUtil.applyPSFVO(criteriaMap, psf);
return userCriteria.list();
}
@Override
protected long handleGetCountByCriteria(CriteriaInstantVO criteria, PSFVO psf) throws Exception {
return QueryUtil.getSearchQueryResultCount(
criteria,
DBModule.USER_DB,
psf,
this.getSessionFactory(),
this.getCriterionTieDao(),
this.getCriterionPropertyDao(),
this.getCriterionRestrictionDao());
}
private void loadDeferredStaffOutVOs(HashMap<Class, HashMap<Long, Object>> voMap) {
HashMap<Long, Object> staffVOMap = voMap.get(StaffOutVO.class);
StaffDao staffDao = this.getStaffDao();
if (staffVOMap != null) {
Iterator<Entry<Long, Object>> staffVOMapIt = (new HashSet<Entry<Long, Object>>(staffVOMap.entrySet())).iterator();
while (staffVOMapIt.hasNext()) {
Entry<Long, Object> staffVO = staffVOMapIt.next();
DeferredVO deferredVO = (DeferredVO) staffVO.getValue();
if (deferredVO.isDeferred()) {
deferredVO.setDeferred(false);
staffDao.toStaffOutVO(staffDao.load(staffVO.getKey()), (StaffOutVO) deferredVO.getVo(), voMap, staffVOMap.size(), 0, 0);
}
}
}
}
/**
* Retrieves the entity object that is associated with the specified value object
* from the object store. If no such entity object exists in the object store,
* a new, blank entity is created
*/
private User loadUserFromUserInVO(UserInVO userInVO) {
User user = null;
Long id = userInVO.getId();
if (id != null) {
user = this.load(id);
}
if (user == null) {
user = User.Factory.newInstance();
}
return user;
}
/**
* Retrieves the entity object that is associated with the specified value object
* from the object store. If no such entity object exists in the object store,
* a new, blank entity is created
*/
private User loadUserFromUserOutVO(UserOutVO userOutVO) {
throw new UnsupportedOperationException("out value object to recursive entity not supported");
}
/**
* @inheritDoc
*/
@Override
public UserInVO toUserInVO(final User entity) {
return super.toUserInVO(entity);
}
/**
* @inheritDoc
*/
@Override
public void toUserInVO(
User source,
UserInVO target) {
super.toUserInVO(source, target);
Department department = source.getDepartment();
Staff identity = source.getIdentity();
User parent = source.getParent();
if (department != null) {
target.setDepartmentId(department.getId());
}
if (identity != null) {
target.setIdentityId(identity.getId());
}
if (parent != null) {
target.setParentId(parent.getId());
}
}
/**
* @inheritDoc
*/
@Override
public UserOutVO toUserOutVO(final User entity) {
return super.toUserOutVO(entity);
}
/**
* @inheritDoc
*/
@Override
public void toUserOutVO(
User source,
UserOutVO target) {
HashMap<Class, HashMap<Long, Object>> voMap = new HashMap<Class, HashMap<Long, Object>>();
(new UserReflexionGraph(this, this.getDepartmentDao())).toVOHelper(source, target, voMap);
loadDeferredStaffOutVOs(voMap);
}
@Override
public void toUserOutVO(
User source,
UserOutVO target, HashMap<Class, HashMap<Long, Object>> voMap) {
(new UserReflexionGraph(this, this.getDepartmentDao())).toVOHelper(source, target, voMap);
loadDeferredStaffOutVOs(voMap);
}
@Override
public void toUserOutVO(
User source,
UserOutVO target, HashMap<Class, HashMap<Long, Object>> voMap, Integer... maxInstances) {
(new UserReflexionGraph(this, this.getDepartmentDao(), maxInstances)).toVOHelper(source, target, voMap);
loadDeferredStaffOutVOs(voMap);
}
@Override
public void toUserOutVO(
User source,
UserOutVO target, Integer... maxInstances) {
HashMap<Class, HashMap<Long, Object>> voMap = new HashMap<Class, HashMap<Long, Object>>();
(new UserReflexionGraph(this, this.getDepartmentDao(), maxInstances)).toVOHelper(source, target, voMap);
loadDeferredStaffOutVOs(voMap);
}
/**
* @inheritDoc
*/
@Override
public User userInVOToEntity(UserInVO userInVO) {
User entity = this.loadUserFromUserInVO(userInVO);
this.userInVOToEntity(userInVO, entity, true);
return entity;
}
/**
* @inheritDoc
*/
@Override
public void userInVOToEntity(
UserInVO source,
User target,
boolean copyIfNull) {
super.userInVOToEntity(source, target, copyIfNull);
Long departmentId = source.getDepartmentId();
Long identityId = source.getIdentityId();
Long parentId = source.getParentId();
if (departmentId != null) {
Department department = this.getDepartmentDao().load(departmentId);
target.setDepartment(department);
department.addUsers(target);
} else if (copyIfNull) {
Department department = target.getDepartment();
target.setDepartment(null);
if (department != null) {
department.removeUsers(target);
}
}
if (identityId != null) {
Staff identity = this.getStaffDao().load(identityId);
target.setIdentity(identity);
identity.addAccounts(target);
} else if (copyIfNull) {
Staff identity = target.getIdentity();
target.setIdentity(null);
if (identity != null) {
identity.removeAccounts(target);
}
}
if (parentId != null) {
if (target.getParent() != null) {
target.getParent().removeChildren(target);
}
User parent = this.load(parentId);
target.setParent(parent);
parent.addChildren(target);
} else if (copyIfNull) {
User parent = target.getParent();
target.setParent(null);
if (parent != null) {
parent.removeChildren(target);
}
}
Collection inheritedProperties;
if ((inheritedProperties = source.getInheritedProperties()).size() > 0 || copyIfNull) {
target.setInheritedPropertyList(UserReflexionGraph.toInheritedPropertyList(inheritedProperties));
}
Collection inheritedPermissionProfileGroups;
if ((inheritedPermissionProfileGroups = source.getInheritedPermissionProfileGroups()).size() > 0 || copyIfNull) {
target.setInheritedPermissionProfileGroupList(UserReflexionGraph.toInheritedPermissionProfileGroupList(inheritedPermissionProfileGroups));
}
}
/**
* @inheritDoc
*/
@Override
public User userOutVOToEntity(UserOutVO userOutVO) {
User entity = this.loadUserFromUserOutVO(userOutVO);
this.userOutVOToEntity(userOutVO, entity, true);
return entity;
}
/**
* @inheritDoc
*/
@Override
public void userOutVOToEntity(
UserOutVO source,
User target,
boolean copyIfNull) {
super.userOutVOToEntity(source, target, copyIfNull);
StaffOutVO identityVO = source.getIdentity();
UserOutVO parentVO = source.getParent();
AuthenticationTypeVO authMethodVO = source.getAuthMethod();
if (identityVO != null) {
Staff identity = this.getStaffDao().staffOutVOToEntity(identityVO);
target.setIdentity(identity);
identity.addAccounts(target);
} else if (copyIfNull) {
Staff identity = target.getIdentity();
target.setIdentity(null);
if (identity != null) {
identity.removeAccounts(target);
}
}
if (authMethodVO != null) {
target.setAuthMethod(authMethodVO.getMethod());
} else if (copyIfNull) {
target.setAuthMethod(null);
}
if (parentVO != null) {
if (target.getParent() != null) {
target.getParent().removeChildren(target);
}
User parent = this.userOutVOToEntity(parentVO);
target.setParent(parent);
parent.addChildren(target);
} else if (copyIfNull) {
User parent = target.getParent();
target.setParent(null);
if (parent != null) {
parent.removeChildren(target);
}
}
}
/**
* {@inheritDoc}
*/
public void toUserSettingsInVO(
User source,
UserSettingsInVO target) {
super.toUserSettingsInVO(source, target);
}
/**
* {@inheritDoc}
*/
public UserSettingsInVO toUserSettingsInVO(final User entity) {
return super.toUserSettingsInVO(entity);
}
/**
* {@inheritDoc}
*/
public User userSettingsInVOToEntity(UserSettingsInVO userSettingsInVO) {
User entity = this.loadUserFromUserSettingsInVO(userSettingsInVO);
this.userSettingsInVOToEntity(userSettingsInVO, entity, true);
return entity;
}
/**
* {@inheritDoc}
*/
@Override
public void userSettingsInVOToEntity(
UserSettingsInVO source,
User target,
boolean copyIfNull) {
super.userSettingsInVOToEntity(source, target, copyIfNull);
if (source.getInheritedProperties().size() > 0 || copyIfNull) {
Collection inheritedProperties = UserReflexionGraph.getInheritedProperties(target.getInheritedPropertyList());
inheritedProperties.removeAll(CommonUtil.USER_SETTINGS_INHERITABLE_PROPERTIES);
inheritedProperties.addAll(source.getInheritedProperties());
target.setInheritedPropertyList(UserReflexionGraph.toInheritedPropertyList(inheritedProperties));
}
}
/**
* Retrieves the entity object that is associated with the specified value object
* from the object store. If no such entity object exists in the object store,
* a new, blank entity is created
*/
private User loadUserFromUserSettingsInVO(UserSettingsInVO userSettingsInVO) {
User user = null;
Long id = userSettingsInVO.getId();
if (id != null) {
user = this.load(id);
}
if (user == null) {
user = User.Factory.newInstance();
}
return user;
}
private User loadUserFromUserInheritedVO(UserInheritedVO userInheritedVO) {
throw new UnsupportedOperationException("org.phoenixctms.ctsms.domain.loadUserFromUserInheritedVO(UserInheritedVO) not yet implemented.");
}
@Override
public User userInheritedVOToEntity(UserInheritedVO userInheritedVO) {
User entity = this.loadUserFromUserInheritedVO(userInheritedVO);
this.userInheritedVOToEntity(userInheritedVO, entity, true);
return entity;
}
@Override
public void userInheritedVOToEntity(
UserInheritedVO source,
User target,
boolean copyIfNull) {
super.userInheritedVOToEntity(source, target, copyIfNull);
}
@Override
public UserInheritedVO toUserInheritedVO(final User entity) {
return super.toUserInheritedVO(entity);
}
@Override
public void toUserInheritedVO(
User source,
UserInheritedVO target) {
super.toUserInheritedVO(source, target);
HashMap<Long, HashSet<String>> inheritPropertyMap = new HashMap<Long, HashSet<String>>();
setInheritedProperty(source, target, "enableInventoryModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableStaffModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableCourseModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableTrialModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableInputFieldModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableProbandModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableMassMailModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "enableUserModule", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "visibleInventoryTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleStaffTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleCourseTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleTrialTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleProbandTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleInputFieldTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleUserTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "visibleMassMailTabList", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "decrypt", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "decryptUntrusted", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "locked", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "timeZone", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "locale", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "showTooltips", Boolean.TYPE, inheritPropertyMap);
setInheritedProperty(source, target, "theme", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "decimalSeparator", String.class, inheritPropertyMap);
setInheritedProperty(source, target, "dateFormat", String.class, inheritPropertyMap);
}
private static boolean isInherited(User user, String propertyName, HashMap<Long, HashSet<String>> inheritPropertyMap) {
HashSet<String> inheritedPropertyList;
if (inheritPropertyMap.containsKey(user.getId())) {
inheritedPropertyList = inheritPropertyMap.get(user.getId());
} else {
inheritedPropertyList = UserReflexionGraph.getInheritedProperties(user.getInheritedPropertyList());
inheritPropertyMap.put(user.getId(), inheritedPropertyList);
}
return inheritedPropertyList.contains(propertyName);
}
private static void setInheritedProperty(User source, UserInheritedVO target, String propertyName, Class type, HashMap<Long, HashSet<String>> inheritPropertyMap) {
try {
if (isInherited(source, propertyName, inheritPropertyMap)) {
User parent = source.getParent();
if (parent != null) {
CommonUtil.getPropertySetter(UserInheritedVO.class, propertyName, type).invoke(target,
getInheritedProperty(parent, propertyName, inheritPropertyMap));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Object getInheritedProperty(User user, String propertyName, HashMap<Long, HashSet<String>> inheritPropertyMap) {
try {
if (isInherited(user, propertyName, inheritPropertyMap)) {
User parent = user.getParent();
if (parent != null) {
return getInheritedProperty(parent, propertyName, inheritPropertyMap);
}
}
return CommonUtil.getPropertyGetter(User.class, propertyName).invoke(user);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package org.tribbloid.spookystuff.http;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class HttpUtils {
private static URL dummyURL() {
try {
return new URL("http:
} catch (MalformedURLException e) {
throw new RuntimeException("WTF?");
}
}
private static URL dummyURL = dummyURL();
public static URI uri(String s) throws URISyntaxException {
//this solution is abandoned as it cannot handle question mark
// URI uri;
// try {
// uri = new URI(s);
// catch (URISyntaxException e) {
// uri = new URI(URIUtil.encodePath(s));
// return uri.normalize();
try {
URL url = new URL(s);
return new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
} catch (MalformedURLException e) {
URL url = null;
try {
url = new URL(dummyURL, s);
} catch (MalformedURLException e1) {
throw new RuntimeException(e1);
}
return new URI(null, null, url.getPath(), url.getQuery(), null);
}
}
}
|
package org.egordorichev.lasttry.language;
import com.badlogic.gdx.Gdx;
import org.egordorichev.lasttry.core.Crash;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public final class LocalizationUtil {
public static void localize(Class clazz, Class ... targetClazz){
List<Field> localizableFields = new ArrayList<>();
for (int i = 0; i < clazz.getFields().length; i++){
Field field = clazz.getFields()[i];
for (int j = 0; j < targetClazz.length; j++){
if(Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && field.getType() == targetClazz[j]){
localizableFields.add(field);
break;
}
}
}
StringBuilder text = new StringBuilder();
text.append("\n
.append(clazz.getPackage().toString().substring(8))
.append("\n")
.append("
.append(clazz.getSimpleName())
.append(".java")
.append("\n");
for (int i = 0; i < localizableFields.size(); i++){
Field field = localizableFields.get(i);
text.append("\t").append(field.getName()).append(" = ").append(capitalize(field.getName()).replaceAll("(\\p{Ll})(\\p{Lu})","$1 $2")).append("\n");
}
try {
Files.write(Paths.get(Gdx.files.internal("languages/language_en_US.properties").path()), text.toString().getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
Crash.report(Thread.currentThread(), e);
}
}
private static String capitalize(String string){
return Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
}
|
package com.meowster.mcquad;
import com.meowster.rec.Record;
import com.meowster.test.AbstractTest;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Unit tests for {@link com.meowster.mcquad.BlockColorsStore}.
*
* @author Simon Hunt
*/
public class BlockColorsStoreTest extends AbstractTest {
private static final int EXP_NUM_BLOCK_RECORDS = 482;
private BlockColorsStore store;
@Before
public void setUp() {
store = new BlockColorsStore();
}
@Test
public void basic() {
title("basic");
print(store);
assertEquals(AM_UXS, EXP_NUM_BLOCK_RECORDS, store.size());
}
@Test
public void firstFewRecordsCheckInts() {
title("firstFewRecordsCheckInts");
Iterator<Record> iter = store.getRecords().iterator();
checkIdDv(iter.next(), -1);
checkIdDv(iter.next(), 0);
checkIdDv(iter.next(), 1, 0);
checkIdDv(iter.next(), 1, 1);
checkIdDv(iter.next(), 1, 2);
checkIdDv(iter.next(), 1, 3);
checkIdDv(iter.next(), 1, 4);
checkIdDv(iter.next(), 1, 5);
checkIdDv(iter.next(), 1, 6);
checkIdDv(iter.next(), 2);
checkIdDv(iter.next(), 3, 0);
checkIdDv(iter.next(), 3, 1);
checkIdDv(iter.next(), 3, 2);
checkIdDv(iter.next(), 4);
checkIdDv(iter.next(), 5, 0);
checkIdDv(iter.next(), 5, 1);
checkIdDv(iter.next(), 5, 2);
checkIdDv(iter.next(), 5, 3);
checkIdDv(iter.next(), 5, 4);
checkIdDv(iter.next(), 5, 5);
}
private void checkIdDv(Record rec, int id) {
checkIdDv(rec, id, BlockId.DV_NA);
}
private void checkIdDv(Record rec, int id, int dv) {
BlockColorsStore.BlockRecord brec = (BlockColorsStore.BlockRecord) rec;
print(brec);
if (id == -1)
assertNull(AM_HUH, brec.blockId());
else {
BlockId blockId = brec.blockId();
assertEquals(AM_NEQ, id, blockId.id());
assertEquals(AM_NEQ, dv, blockId.dv());
}
}
}
|
package org.usfirst.frc.team340.robot.commands;
import java.util.logging.Logger;
import org.usfirst.frc.team340.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
public class MoveArm extends Command {
Logger logger = Robot.getLogger(MoveArm.class);
private double speed = 0.0;
public MoveArm(double speed) {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
this.speed = speed;
requires(Robot.harvester);
}
// Called just before this Command runs the first time
protected void initialize() {
logger.info("[Initializing]");
}
private double leftSpeed = speed;
private double rightSpeed = speed;
// Called repeatedly when this Command is scheduled to run
protected void execute() {
/*if(Math.abs(leftPot-rightPot) < 5) {
Robot.harvester.setLeftTilt(speed);
Robot.harvester.setRightTilt(speed);
} else*/
double leftPot = Robot.harvester.getLeftAimPot();
double rightPot = Robot.harvester.getRightAimPot();
/*if((leftPot < rightPot && speed > 0)
|| (leftPot > rightPot && speed < 0)) {
Robot.harvester.setLeftTilt(speed);
leftSpeed = speed;
rightSpeed = speed/2.5;
Robot.harvester.setRightTilt(speed/2.5);
} else if ((rightPot < leftPot && speed > 0)
|| (rightPot > leftPot && speed < 0)){
Robot.harvester.setLeftTilt(speed/2.5);
leftSpeed = speed/2.5;
rightSpeed = speed;
Robot.harvester.setRightTilt(speed);
}*/
leftSpeed = speed;
rightSpeed = speed;
if(Robot.harvester.getLeftLimit() /*|| leftPot > 50*/) {
leftSpeed = 0;
rightSpeed /= 2;
}
if(Robot.harvester.getRightLimit() /*|| rightPot > 50*/) {
rightSpeed = 0;
leftSpeed /= 2;
}
Robot.harvester.setLeftTilt(leftSpeed);
Robot.harvester.setRightTilt(rightSpeed);
// logger.info("Execute: leftSpeed: " + leftSpeed + " rightSpeed: " + rightSpeed);
logger.info(" ");
logger.info("left pot: " + leftPot + " right pot: " + rightPot);
logger.info("left Pot: " + Robot.harvester.getLeftLimit() + " right pot: " + Robot.harvester.getRightLimit());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return leftSpeed == 0 && rightSpeed == 0;
}
// Called once after isFinished returns true
protected void end() {
// logger.info("[Ending]");
Robot.harvester.setLeftTilt(0);
Robot.harvester.setRightTilt(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
// logger.info("[Interrupted]");
end();
}
}
|
package net.coobird.thumbnailator.filters;
import static org.junit.Assert.assertTrue;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.test.BufferedImageAssert;
import net.coobird.thumbnailator.test.BufferedImageComparer;
import net.coobird.thumbnailator.util.BufferedImages;
import org.junit.Test;
public class FlipTest {
@Test
public void flipHorizontal() throws Exception {
// given
BufferedImage img = ImageIO.read(new File("test-resources/Exif/original.png"));
// when
BufferedImage result = Flip.HORIZONTAL.apply(img);
// then
BufferedImageAssert.assertMatches(
result,
new float[] {
1, 1, 1,
1, 1, 1,
0, 0, 1,
}
);
}
@Test
public void flipVertical() throws Exception {
// given
BufferedImage img = ImageIO.read(new File("test-resources/Exif/original.png"));
// when
BufferedImage result = Flip.VERTICAL.apply(img);
// then
BufferedImageAssert.assertMatches(
result,
new float[] {
1, 0, 0,
1, 1, 1,
1, 1, 1,
}
);
}
/**
* Checks that the input image contents are not altered, when using the
* {@link Flip#HORIZONTAL}.
*/
@Test
public void inputContentsAreNotAltered_UsingFlipHorizontal()
{
// given
BufferedImage originalImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
BufferedImage copyImage = BufferedImages.copy(originalImage);
ImageFilter filter = Flip.HORIZONTAL;
// when
filter.apply(originalImage);
// then
assertTrue(BufferedImageComparer.isSame(originalImage, copyImage));
}
/**
* Checks that the input image contents are not altered, when using the
* {@link Flip#VERTICAL}.
*/
@Test
public void inputContentsAreNotAltered_UsingFlipVertical()
{
// given
BufferedImage originalImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
BufferedImage copyImage = BufferedImages.copy(originalImage);
ImageFilter filter = Flip.VERTICAL;
// when
filter.apply(originalImage);
// then
assertTrue(BufferedImageComparer.isSame(originalImage, copyImage));
}
}
|
package org.bouncycastle.crypto.test;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.agreement.ECDHBasicAgreement;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.engines.IESEngine;
import org.bouncycastle.crypto.engines.TwofishEngine;
import org.bouncycastle.crypto.generators.KDF2BytesGenerator;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.IESParameters;
import org.bouncycastle.crypto.params.IESWithCipherParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* test for ECIES - Elliptic Curve Integrated Encryption Scheme
*/
public class ECIESTest
extends SimpleTest
{
ECIESTest()
{
}
public String getName()
{
return "ECIES";
}
private void staticTest()
throws Exception
{
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16));
ECDomainParameters params = new ECDomainParameters(
curve,
curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")),
new BigInteger("6277101735386680763835789423176059013767194773182842284081"));
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("651056770906015076056810763456358567190100156695615665659"),
params);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
curve.decodePoint(Hex.decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")),
params);
AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);
// stream test
IESEngine i1 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()));
IESEngine i2 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IESParameters p = new IESParameters(d, e, 64);
i1.init(true, p1.getPrivate(), p2.getPublic(), p);
i2.init(false, p2.getPrivate(), p1.getPublic(), p);
byte[] message = Hex.decode("1234567890abcdef");
byte[] out1 = i1.processBlock(message, 0, message.length);
if (!areEqual(out1, Hex.decode("2442ae1fbf90dd9c06b0dcc3b27e69bd11c9aee4ad4cfc9e50eceb44")))
{
fail("stream cipher test failed on enc");
}
byte[] out2 = i2.processBlock(out1, 0, out1.length);
if (!areEqual(out2, message))
{
fail("stream cipher test failed");
}
// twofish with CBC
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new TwofishEngine()));
i1 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
c1);
i2 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IESWithCipherParameters(d, e, 64, 128);
i1.init(true, p1.getPrivate(), p2.getPublic(), p);
i2.init(false, p2.getPrivate(), p1.getPublic(), p);
message = Hex.decode("1234567890abcdef");
out1 = i1.processBlock(message, 0, message.length);
if (!areEqual(out1, Hex.decode("2ea288651e21576215f2424bbb3f68816e282e3931b44bd1c429ebdb5f1b290cf1b13309")))
{
fail("twofish cipher test failed on enc");
}
out2 = i2.processBlock(out1, 0, out1.length);
if (!areEqual(out2, message))
{
fail("twofish cipher test failed");
}
}
private void doTest(AsymmetricCipherKeyPair p1, AsymmetricCipherKeyPair p2)
throws Exception
{
// stream test
IESEngine i1 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()));
IESEngine i2 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IESParameters p = new IESParameters(d, e, 64);
i1.init(true, p1.getPrivate(), p2.getPublic(), p);
i2.init(false, p2.getPrivate(), p1.getPublic(), p);
byte[] message = Hex.decode("1234567890abcdef");
byte[] out1 = i1.processBlock(message, 0, message.length);
byte[] out2 = i2.processBlock(out1, 0, out1.length);
if (!areEqual(out2, message))
{
fail("stream cipher test failed");
}
// twofish with CBC
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new TwofishEngine()));
i1 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
c1);
i2 = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA1Digest()),
new HMac(new SHA1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IESWithCipherParameters(d, e, 64, 128);
i1.init(true, p1.getPrivate(), p2.getPublic(), p);
i2.init(false, p2.getPrivate(), p1.getPublic(), p);
message = Hex.decode("1234567890abcdef");
out1 = i1.processBlock(message, 0, message.length);
out2 = i2.processBlock(out1, 0, out1.length);
if (!areEqual(out2, message))
{
fail("twofish cipher test failed");
}
}
public void performTest()
throws Exception
{
staticTest();
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16));
ECDomainParameters params = new ECDomainParameters(
curve,
curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")),
new BigInteger("6277101735386680763835789423176059013767194773182842284081"));
ECKeyPairGenerator eGen = new ECKeyPairGenerator();
KeyGenerationParameters gParam = new ECKeyGenerationParameters(params, new SecureRandom());
eGen.init(gParam);
AsymmetricCipherKeyPair p1 = eGen.generateKeyPair();
AsymmetricCipherKeyPair p2 = eGen.generateKeyPair();
doTest(p1, p2);
}
public static void main(
String[] args)
{
runTest(new ECIESTest());
}
}
|
// $Id: ConnectStressTest.java,v 1.18 2007/07/02 15:57:17 belaban Exp $
package org.jgroups.tests;
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jgroups.*;
import org.jgroups.util.Util;
import java.util.Vector;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
/**
* Creates 1 channel, then creates NUM channels, all try to join the same channel concurrently.
* @author Bela Ban Nov 20 2003
* @version $Id: ConnectStressTest.java,v 1.18 2007/07/02 15:57:17 belaban Exp $
*/
public class ConnectStressTest extends TestCase {
static CyclicBarrier start_connecting=null;
static CyclicBarrier connected=null;
static CyclicBarrier received_all_views=null;
static CyclicBarrier start_disconnecting=null;
static CyclicBarrier disconnected=null;
static final int NUM=30;
static final MyThread[] threads=new MyThread[NUM];
static JChannel channel=null;
static String groupname="ConcurrentTestDemo";
static String props="udp.xml";
public ConnectStressTest(String name) {
super(name);
}
static void log(String msg) {
System.out.println("-- [" + Thread.currentThread().getName() + "] " + msg);
}
public void testConcurrentJoins() throws Exception {
start_connecting=new CyclicBarrier(NUM +1);
connected=new CyclicBarrier(NUM +1);
received_all_views=new CyclicBarrier(NUM +1);
start_disconnecting=new CyclicBarrier(NUM +1);
disconnected=new CyclicBarrier(NUM +1);
long start, stop;
// create main channel - will be coordinator for JOIN requests
channel=new JChannel(props);
channel.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE);
start=System.currentTimeMillis();
channel.connect(groupname);
stop=System.currentTimeMillis();
log(channel.getLocalAddress() + " connected in " + (stop-start) + " msecs (" +
channel.getView().getMembers().size() + " members). VID=" + channel.getView().getVid());
assertEquals(1, channel.getView().getMembers().size());
for(int i=0; i < threads.length; i++) {
threads[i]=new MyThread(i);
threads[i].start();
}
// signal the threads to start connecting to their channels
start_connecting.await();
start=System.currentTimeMillis();
try {
connected.await();
stop=System.currentTimeMillis();
System.out.println("-- took " + (stop-start) + " msecs for all " + NUM + " threads to connect");
received_all_views.await();
stop=System.currentTimeMillis();
System.out.println("-- took " + (stop-start) + " msecs for all " + NUM + " threads to see all views");
int num_members=-1;
for(int i=0; i < 10; i++) {
View v=channel.getView();
num_members=v.getMembers().size();
System.out.println("*--* number of members connected: " + num_members + ", (expected: " +(NUM+1) +
"), v=" + v);
if(num_members == NUM+1)
break;
Util.sleep(500);
}
assertEquals((NUM+1), num_members);
}
catch(Exception ex) {
fail(ex.toString());
}
}
public void testConcurrentLeaves() throws Exception {
start_disconnecting.await();
long start, stop;
start=System.currentTimeMillis();
disconnected.await();
stop=System.currentTimeMillis();
System.out.println("-- took " + (stop-start) + " msecs for " + NUM + " threads to disconnect");
int num_members=0;
for(int i=0; i < 10; i++) {
View v=channel.getView();
Vector mbrs=v != null? v.getMembers() : null;
if(mbrs != null) {
num_members=mbrs.size();
System.out.println("*--* number of members connected: " + num_members + ", (expected: 1), view=" + v);
if(num_members <= 1)
break;
}
Util.sleep(3000);
}
assertEquals(1, num_members);
log("closing all channels");
for(int i=0; i < threads.length; i++) {
MyThread t=threads[i];
t.closeChannel();
}
channel.close();
}
public static class MyThread extends Thread {
int index=-1;
long total_connect_time=0, total_disconnect_time=0;
private JChannel ch=null;
private Address my_addr=null;
public MyThread(int i) {
super("thread
index=i;
}
public void closeChannel() {
if(ch != null) {
ch.close();
}
}
public void run() {
View view;
try {
ch=new JChannel(props);
start_connecting.await();
long start=System.currentTimeMillis(), stop;
ch.connect(groupname);
stop=System.currentTimeMillis();
total_connect_time=stop-start;
view=ch.getView();
my_addr=ch.getLocalAddress();
log(my_addr + " connected in " + total_connect_time + " msecs (" +
view.getMembers().size() + " members). VID=" + view.getVid());
connected.await();
int num_members=0;
while(true) {
View v=ch.getView();
Vector mbrs=v != null? v.getMembers() : null;
if(mbrs == null) {
System.err.println("mbrs is null, v=" + v);
}
else {
num_members=mbrs.size();
log("num_members=" + num_members);
if(num_members == NUM+1) // all threads (NUM) plus the first channel (1)
break;
}
Util.sleep(2000);
}
log("reached " + num_members + " members");
received_all_views.await();
start_disconnecting.await();
start=System.currentTimeMillis();
ch.disconnect();
stop=System.currentTimeMillis();
log(my_addr + " disconnected in " + (stop-start) + " msecs");
disconnected.await();
}
catch(BrokenBarrierException e) {
e.printStackTrace();
}
catch(ChannelException e) {
e.printStackTrace();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static Test suite() {
TestSuite s=new TestSuite();
// we're adding the tests manually, because they need to be run in *this exact order*
s.addTest(new ConnectStressTest("testConcurrentJoins"));
s.addTest(new ConnectStressTest("testConcurrentLeaves"));
return s;
}
public static void main(String[] args) {
String[] testCaseName={ConnectStressTest.class.getName()};
junit.textui.TestRunner.main(testCaseName);
}
}
|
// $Id: TimeSchedulerTest.java,v 1.8 2006/09/04 07:14:09 belaban Exp $
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.stack.Interval;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import org.jgroups.util.Promise;
import org.jgroups.TimeoutException;
import java.util.HashMap;
/**
* Test cases for TimeScheduler
*
* @author Bela Ban
*/
public class TimeSchedulerTest extends TestCase {
TimeScheduler timer=null;
final int NUM_MSGS=1000;
long[] xmit_timeouts={1000, 2000, 4000, 8000};
double PERCENTAGE_OFF=0.3; // how much can expected xmit_timeout and real timeout differ to still be okay ?
HashMap msgs=new HashMap(); // keys=seqnos (Long), values=Entries
public TimeSchedulerTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
timer=new TimeScheduler();
}
public void tearDown() throws Exception {
super.tearDown();
try {
timer.stop();
}
catch(InterruptedException e) {
}
}
static class ImmediateTask implements TimeScheduler.Task {
Promise p;
boolean executed=false;
public ImmediateTask(Promise p) {
this.p=p;
}
public boolean cancelled() {
return executed;
}
public long nextInterval() {
return 0;
}
public void run() {
p.setResult(Boolean.TRUE);
executed=true;
}
}
public void testImmediateExecution() {
Promise p=new Promise();
ImmediateTask task=new ImmediateTask(p);
timer.add(task);
try {
long start=System.currentTimeMillis(), stop;
p.getResultWithTimeout(5);
stop=System.currentTimeMillis();
System.out.println("task took " + (stop-start) + "ms");
}
catch(TimeoutException e) {
fail("ran into timeout - task should have executed immediately");
}
}
// class MyTask implements TimeScheduler.Task {
// String name;
// long timeout=0;
// boolean cancelled=false;
// public MyTask(String name, long timeout) {
// this.name=name;
// this.timeout=timeout;
// public boolean cancelled() {
// return cancelled;
// public long nextInterval() {
// return timeout;
// public void run() {
// System.out.println("task " + name + " is run at " + System.currentTimeMillis());
// cancelled=true;
// public void testSimpleSchedule() {
// TimeScheduler.Task t=new MyTask("one", 5000);
// System.out.println("adding new task at " + System.currentTimeMillis());
// timer.add(t, false);
// Util.sleep(12000);
static class MyTask implements TimeScheduler.Task {
boolean done=false;
private long timeout=0;
MyTask(long timeout) {
this.timeout=timeout;
}
public boolean cancelled() {
return done;
}
public long nextInterval() {
return timeout;
}
public void run() {
System.out.println(System.currentTimeMillis() + ": this is MyTask running - done");
done=true;
}
}
static class StressTask implements TimeScheduler.Task {
boolean cancelled=false;
public void cancel() {
cancelled=true;
}
public boolean cancelled() {
return cancelled;
}
public long nextInterval() {
return 50;
}
public void run() {
System.out.println("executed");
}
}
// public void testStress() {
// StressTask t;
// for(int i=0; i < 1000; i++) {
// for(int j=0; j < 1000; j++) {
// t=new StressTask();
// timer.add(t);
// t.cancel();
// System.out.println(i + ": " + timer.size());
// // Util.sleep(300);
// for(int i=0; i < 10; i++) {
// System.out.println(timer.size());
// Util.sleep(500);
public void test2Tasks() {
int size;
System.out.println(System.currentTimeMillis() + ": adding task");
timer.add(new MyTask(500));
size=timer.size();
System.out.println("queue size=" + size);
assertEquals(1, size);
Util.sleep(1000);
size=timer.size();
System.out.println("queue size=" + size);
assertEquals(0, size);
Util.sleep(1500);
System.out.println(System.currentTimeMillis() + ": adding task");
timer.add(new MyTask(500));
System.out.println(System.currentTimeMillis() + ": adding task");
timer.add(new MyTask(500));
System.out.println(System.currentTimeMillis() + ": adding task");
timer.add(new MyTask(500));
size=timer.size();
System.out.println("queue size=" + size);
assertEquals(3, size);
Util.sleep(1000);
size=timer.size();
System.out.println("queue size=" + size);
assertEquals(0, size);
}
// public void testMultipleTasks() {
// timer.setSuspendInterval(5000);
// for(int i=0; i < 10; i++) {
// timer.add(new MyTask(1));
// Util.sleep(1000);
// Util.sleep(100);
// assertEquals(timer.size(), 0);
// Util.sleep(60000);
/**
* Tests whether retransmits are called at correct times for 1000 messages. A retransmit should not be
* more than 30% earlier or later than the scheduled retransmission time
*/
public void testRetransmits() {
Entry entry;
int num_non_correct_entries=0;
// 1. Add NUM_MSGS messages:
System.out.println("-- adding " + NUM_MSGS + " messages:");
for(long i=0; i < NUM_MSGS; i++) {
entry=new Entry(i);
msgs.put(new Long(i), entry);
timer.add(entry);
}
System.out.println("-- done");
// 2. Wait for at least 4 xmits/msg: total of 1000 + 2000 + 4000 + 8000ms = 15000ms; wait for 20000ms
System.out.println("-- waiting for 20 secs for all retransmits");
Util.sleep(20000);
// 3. Check whether all Entries have correct retransmission times
for(long i=0; i < NUM_MSGS; i++) {
entry=(Entry)msgs.get(new Long(i));
if(!entry.isCorrect()) {
num_non_correct_entries++;
}
}
if(num_non_correct_entries > 0)
System.err.println("Number of incorrect retransmission timeouts: " + num_non_correct_entries);
else {
for(long i=0; i < NUM_MSGS; i++) {
entry=(Entry)msgs.get(new Long(i));
if(entry != null)
System.out.println(i + ": " + entry);
}
}
assertEquals(0, num_non_correct_entries);
}
public static Test suite() {
TestSuite suite;
suite=new TestSuite(TimeSchedulerTest.class);
return (suite);
}
public static void main(String[] args) {
String[] name={TimeSchedulerTest.class.getName()};
junit.textui.TestRunner.main(name);
}
class Entry implements TimeScheduler.Task {
long start_time=0; // time message was added
long first_xmit=0; // time between start_time and first_xmit should be ca. 1000ms
long second_xmit=0; // time between first_xmit and second_xmit should be ca. 2000ms
long third_xmit=0; // time between third_xmit and second_xmit should be ca. 4000ms
long fourth_xmit=0; // time between third_xmit and second_xmit should be ca. 8000ms
boolean cancelled=false;
Interval interval=new Interval(xmit_timeouts);
long seqno=0;
Entry(long seqno) {
this.seqno=seqno;
start_time=System.currentTimeMillis();
}
public void cancel() {
cancelled=true;
}
public boolean cancelled() {
return cancelled;
}
public long nextInterval() {
return interval.next();
}
public void run() {
if(first_xmit == 0)
first_xmit=System.currentTimeMillis();
else
if(second_xmit == 0)
second_xmit=System.currentTimeMillis();
else
if(third_xmit == 0)
third_xmit=System.currentTimeMillis();
else
if(fourth_xmit == 0)
fourth_xmit=System.currentTimeMillis();
}
/**
* Entry is correct if xmit timeouts are not more than 30% off the mark
*/
boolean isCorrect() {
long t;
long expected;
long diff, delta;
boolean off=false;
t=first_xmit - start_time;
expected=xmit_timeouts[0];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=second_xmit - first_xmit;
expected=xmit_timeouts[1];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=third_xmit - second_xmit;
expected=xmit_timeouts[2];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=fourth_xmit - third_xmit;
expected=xmit_timeouts[3];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
if(off) {
System.err.println("#" + seqno + ": " + this + ": (" + "entry is more than " +
PERCENTAGE_OFF + " percentage off ");
return false;
}
return true;
}
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append(first_xmit - start_time).append(", ").append(second_xmit - first_xmit).append(", ");
sb.append(third_xmit - second_xmit).append(", ").append(fourth_xmit - third_xmit);
return sb.toString();
}
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.samskivert.util.StringUtil;
import com.samskivert.util.Tuple;
import com.threerings.io.Intern;
import com.threerings.util.StreamableTuple;
/**
* Tests the {@link Streamable} class.
*/
public class StreamableTest
{
public static class Widget extends SimpleStreamableObject
implements Cloneable
{
public boolean bool1 = true;
public byte byte1 = Byte.MAX_VALUE;
public char char1 = 'a';
public short short1 = Short.MAX_VALUE;
public int int1 = Integer.MAX_VALUE;
public long long1 = Long.MAX_VALUE;
public float float1 = Float.MAX_VALUE;
public double double1 = Double.MAX_VALUE;
public Boolean boxedBool = true;
public Byte boxedByte = Byte.MAX_VALUE;
public Character boxedChar = 'a';
public Short boxedShort = Short.MAX_VALUE;
public Integer boxedInt = Integer.MAX_VALUE;
public Long boxedLong = Long.MAX_VALUE;
public Float boxedFloat = Float.MAX_VALUE;
public Double boxedDouble = Double.MAX_VALUE;
public Boolean nullBoxedBool;
public Byte nullBoxedByte;
public Character nullBoxedChar;
public Short nullBoxedShort;
public Integer nullBoxedInt;
public Long nullBoxedLong;
public Float nullBoxedFloat;
public Double nullBoxedDouble;
public String string1 = "one";
public String nullString1;
@Intern public String internedString1 = "monkey butter";
@Intern public String nullInternedString1;
public Date date1 = new Date(42L);
// public Date nullDate1; // null Date is apparently not supported, interesting!
// note: must be a Streamable class
public Class<?> class1 = Widget.class;
public Class<?> nullClass1;
public boolean[] bools = new boolean[] { true, false, true };
public byte[] bytes = new byte[] { Byte.MAX_VALUE, 2, 3 };
public short[] shorts = new short[] { Short.MAX_VALUE, 2, 3 };
public char[] chars = new char[] { 'a', 'b', 'c' };
public int[] ints = new int[] { Integer.MAX_VALUE, 2, 3 };
public long[] longs = new long[] { Long.MAX_VALUE, 2, 3 };
public float[] floats = new float[] { Float.MAX_VALUE, 2, 3 };
public double[] doubles = new double[] { Double.MAX_VALUE, 2, 3 };
public boolean[] nullBools;
public byte[] nullBytes;
public short[] nullShorts;
public char[] nullChars;
public int[] nullInts;
public long[] nullLongs;
public float[] nullFloats;
public double[] nullDoubles;
public Wocket wocket1 = new Wocket();
public Wocket[] wockets = new Wocket[] { new Wocket(), new Wocket() };
public Wicket[] wickets = new Wicket[] { new Wicket(), new Wicket(), new Wicket() };
public Wocket nullWocket1;
public Wocket[] nullWockets;
public Wicket[] nullWickets;
public Object object1 = new Wocket();
public Object nullObject1 = new Wocket();
// this will come back as "new Object[] { new Wocket(), new Wocket() }", so it's not kosher
// to rely on the type of your array being preserved, only the type of its contents
public Object[] objects = new Wocket[] { new Wocket(), new Wocket() };
public Object[] nullObjects;
public List<Integer> list = Lists.newArrayList(1, 2, 3);
public List<Integer> nullList = null;
public ArrayList<Integer> arrayList = Lists.newArrayList(3, 2, 1);
public ArrayList<Integer> nullArrayList = null;
@Override
public boolean equals (Object other) {
if (!(other instanceof Widget)) {
return false;
}
Widget ow = (Widget)other;
return bool1 == ow.bool1 &&
byte1 == ow.byte1 &&
char1 == ow.char1 &&
short1 == ow.short1 &&
int1 == ow.int1 &&
long1 == ow.long1 &&
float1 == ow.float1 &&
double1 == ow.double1 &&
Objects.equal(boxedBool, ow.boxedBool) &&
Objects.equal(boxedByte, ow.boxedByte) &&
Objects.equal(boxedShort, ow.boxedShort) &&
Objects.equal(boxedChar, ow.boxedChar) &&
Objects.equal(boxedInt, ow.boxedInt) &&
Objects.equal(boxedLong, ow.boxedLong) &&
Objects.equal(boxedFloat, ow.boxedFloat) &&
Objects.equal(boxedDouble, ow.boxedDouble) &&
Objects.equal(nullBoxedBool, ow.nullBoxedBool) &&
Objects.equal(nullBoxedByte, ow.nullBoxedByte) &&
Objects.equal(nullBoxedShort, ow.nullBoxedShort) &&
Objects.equal(nullBoxedChar, ow.nullBoxedChar) &&
Objects.equal(nullBoxedInt, ow.nullBoxedInt) &&
Objects.equal(nullBoxedLong, ow.nullBoxedLong) &&
Objects.equal(nullBoxedFloat, ow.nullBoxedFloat) &&
Objects.equal(nullBoxedDouble, ow.nullBoxedDouble) &&
Objects.equal(string1, ow.string1) &&
Objects.equal(nullString1, ow.nullString1) &&
internedString1 == ow.internedString1 &&
nullInternedString1 == ow.nullInternedString1 &&
Objects.equal(date1, ow.date1) &&
// Objects.equal(nullDate1, ow.nullDate1) &&
class1 == ow.class1 &&
nullClass1 == ow.nullClass1 &&
Arrays.equals(bools, ow.bools) &&
Arrays.equals(bytes, ow.bytes) &&
Arrays.equals(shorts, ow.shorts) &&
Arrays.equals(chars, ow.chars) &&
Arrays.equals(ints, ow.ints) &&
Arrays.equals(longs, ow.longs) &&
Arrays.equals(floats, ow.floats) &&
Arrays.equals(doubles, ow.doubles) &&
Arrays.equals(nullBools, ow.nullBools) &&
Arrays.equals(nullBytes, ow.nullBytes) &&
Arrays.equals(nullShorts, ow.nullShorts) &&
Arrays.equals(nullChars, ow.nullChars) &&
Arrays.equals(nullInts, ow.nullInts) &&
Arrays.equals(nullLongs, ow.nullLongs) &&
Arrays.equals(nullFloats, ow.nullFloats) &&
Arrays.equals(nullDoubles, ow.nullDoubles) &&
Objects.equal(wocket1, ow.wocket1) &&
Arrays.equals(wockets, ow.wockets) &&
Arrays.equals(wickets, ow.wickets) &&
Objects.equal(nullWocket1, ow.nullWocket1) &&
Arrays.equals(nullWockets, ow.nullWockets) &&
Arrays.equals(nullWickets, ow.nullWickets) &&
Objects.equal(object1, ow.object1) &&
Objects.equal(nullObject1, ow.nullObject1) &&
Arrays.equals(objects, ow.objects) &&
Arrays.equals(nullObjects, ow.nullObjects) &&
Objects.equal(list, ow.list) &&
Objects.equal(nullList, ow.nullList) &&
Objects.equal(arrayList, ow.arrayList) &&
Objects.equal(nullArrayList, ow.nullArrayList);
}
@Override
public Widget clone ()
{
try {
return (Widget)super.clone();
} catch (CloneNotSupportedException cnse) {
throw new AssertionError(cnse);
}
}
}
public static class Wocket extends SimpleStreamableObject
{
public byte bizyte = 15;
public short shizort = Short.MAX_VALUE;
public double dizouble = Math.PI;
@Override
public boolean equals (Object other) {
if (!(other instanceof Wocket)) {
return false;
}
Wocket ow = (Wocket)other;
return bizyte == ow.bizyte &&
shizort == ow.shizort &&
dizouble == ow.dizouble;
}
}
public static final class Wicket extends SimpleStreamableObject
{
public byte bizyte = 15;
public short shizort = Short.MAX_VALUE;
public double dizouble = Math.PI;
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
out.writeInt(_fizzle);
}
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_fizzle = in.readInt();
}
@Override
public boolean equals (Object other) {
if (!(other instanceof Wicket)) {
return false;
}
Wicket ow = (Wicket)other;
return bizyte == ow.bizyte &&
shizort == ow.shizort &&
dizouble == ow.dizouble &&
_fizzle == ow._fizzle;
}
@Override
protected void toString (StringBuilder buf)
{
super.toString(buf);
buf.append(", fizzle=").append(_fizzle);
}
protected int _fizzle = 19;
}
@Test
public void testFields ()
throws IOException, ClassNotFoundException
{
Widget w = new Widget();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(w);
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(bout.toByteArray()));
assertEquals(w, oin.readObject());
}
@Test
public void testWireFormat ()
throws IOException, ClassNotFoundException
{
Widget w = new Widget();
// make sure that we serialize to the expected stream of bytes
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(w);
byte[] data = bout.toByteArray();
// uncomment this and rerun the tests to generate an updated WIRE_DATA blob:
// String dstr = StringUtil.wordWrap(StringUtil.hexlate(data), 80);
// dstr = StringUtil.join(dstr.split("\n"), "\" +\n \"");
// System.out.println(" protected static final byte[] WIRE_DATA = " +
// "StringUtil.unhexlate(\n \"" + dstr + "\");");
// oddly, JUnit doesn't like comparing byte arrays directly (this fails:
// assertEquals(WIRE_DATA, WIRE_DATA.clone())), but comparing strings is fine
assertEquals(StringUtil.hexlate(data), StringUtil.hexlate(WIRE_DATA));
// make sure that we unserialize a known stream of bytes to the expected object
ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(WIRE_DATA));
assertEquals(w, oin.readObject());
}
@Test
public void testPostStreamingMutation ()
throws IOException, ClassNotFoundException
{
// create an object graph to be streamed
Widget w = new Widget();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
Widget w1 = w.clone();
oout.writeObject(w);
w.string1 = "two";
Widget w2 = w.clone();
oout.writeObject(w);
w.string1 = "three";
Widget w3 = w.clone();
oout.writeObject(w);
Tuple<String,String> tup = StreamableTuple.newTuple("left", "right");
oout.writeObject(tup);
byte[] data = bout.toByteArray();
// System.out.println(data.length + " bytes were written.");
ByteArrayInputStream bin = new ByteArrayInputStream(data);
ObjectInputStream oin = new ObjectInputStream(bin);
Object ow1 = oin.readObject(); // widget
Object ow2 = oin.readObject(); // modified widget
Object ow3 = oin.readObject(); // again modified widget
Object otup = oin.readObject(); // streamable tuple
assertEquals(w1, ow1);
assertEquals(w2, ow2);
assertEquals(w3, ow3);
assertEquals(tup, otup);
}
protected static final byte[] WIRE_DATA = StringUtil.unhexlate(
"ffff0027636f6d2e746872656572696e67732e696f2e53747265616d61626c655465737424576964" +
"676574017f00617fff7fffffff7fffffffffffffff7f7fffff7fefffffffffffff0101017f010061" +
"017fff017fffffff017fffffffffffffff017f7fffff017fefffffffffffff000000000000000001" +
"00036f6e6500ffff000d6d6f6e6b6579206275747465720000000000000000002a01000100010000" +
"000301000101000000037f020301000000037fff0002000301000000030061006200630100000003" +
"7fffffff000000020000000301000000037fffffffffffffff000000000000000200000000000000" +
"0301000000037f7fffff400000004040000001000000037fefffffffffffff400000000000000040" +
"080000000000000000000000000000fffe0027636f6d2e746872656572696e67732e696f2e537472" +
"65616d61626c655465737424576f636b65740f7fff400921fb54442d18fffd002a5b4c636f6d2e74" +
"6872656572696e67732e696f2e53747265616d61626c655465737424576f636b65743b0000000200" +
"020f7fff400921fb54442d1800020f7fff400921fb54442d18fffc002a5b4c636f6d2e7468726565" +
"72696e67732e696f2e53747265616d61626c6554657374245769636b65743b000000030001070f7f" +
"ff400921fb54442d1800000013000000130f7fff400921fb54442d1800000013000000130f7fff40" +
"0921fb54442d18000000130000001300000000000000020f7fff400921fb54442d1800020f7fff40" +
"0921fb54442d18010000000200020f7fff400921fb54442d1800020f7fff400921fb54442d1800ff" +
"fb00136a6176612e7574696c2e41727261794c69737400000003fffa00116a6176612e6c616e672e" +
"496e7465676572000000010006000000020006000000030000010000000300060000000300060000" +
"000200060000000100");
}
|
package org.bouncycastle.tls;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers;
import org.bouncycastle.asn1.eac.EACObjectIdentifiers;
import org.bouncycastle.asn1.edec.EdECObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RSASSAPSSparams;
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.tls.crypto.TlsAgreement;
import org.bouncycastle.tls.crypto.TlsCertificate;
import org.bouncycastle.tls.crypto.TlsCipher;
import org.bouncycastle.tls.crypto.TlsCrypto;
import org.bouncycastle.tls.crypto.TlsCryptoParameters;
import org.bouncycastle.tls.crypto.TlsCryptoUtils;
import org.bouncycastle.tls.crypto.TlsDHConfig;
import org.bouncycastle.tls.crypto.TlsECConfig;
import org.bouncycastle.tls.crypto.TlsHMAC;
import org.bouncycastle.tls.crypto.TlsHash;
import org.bouncycastle.tls.crypto.TlsSecret;
import org.bouncycastle.tls.crypto.TlsStreamSigner;
import org.bouncycastle.tls.crypto.TlsStreamVerifier;
import org.bouncycastle.tls.crypto.TlsVerifier;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
import org.bouncycastle.util.Shorts;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.io.Streams;
/**
* Some helper functions for the TLS API.
*/
public class TlsUtils
{
private static byte[] DOWNGRADE_TLS11 = Hex.decodeStrict("444F574E47524400");
private static byte[] DOWNGRADE_TLS12 = Hex.decodeStrict("444F574E47524401");
// Map OID strings to HashAlgorithm values
private static final Hashtable CERT_SIG_ALG_OIDS = createCertSigAlgOIDs();
private static final Vector DEFAULT_SUPPORTED_SIG_ALGS = createDefaultSupportedSigAlgs();
private static void addCertSigAlgOID(Hashtable h, ASN1ObjectIdentifier oid, short hashAlgorithm, short signatureAlgorithm)
{
h.put(oid.getId(), SignatureAndHashAlgorithm.getInstance(hashAlgorithm, signatureAlgorithm));
}
private static Hashtable createCertSigAlgOIDs()
{
Hashtable h = new Hashtable();
addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha224, HashAlgorithm.sha224, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha256, HashAlgorithm.sha256, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha384, HashAlgorithm.sha384, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha512, HashAlgorithm.sha512, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, OIWObjectIdentifiers.dsaWithSHA1, HashAlgorithm.sha1, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, OIWObjectIdentifiers.sha1WithRSA, HashAlgorithm.sha1, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, PKCSObjectIdentifiers.sha1WithRSAEncryption, HashAlgorithm.sha1, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, PKCSObjectIdentifiers.sha224WithRSAEncryption, HashAlgorithm.sha224, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, PKCSObjectIdentifiers.sha256WithRSAEncryption, HashAlgorithm.sha256, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, PKCSObjectIdentifiers.sha384WithRSAEncryption, HashAlgorithm.sha384, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, PKCSObjectIdentifiers.sha512WithRSAEncryption, HashAlgorithm.sha512, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, X9ObjectIdentifiers.id_dsa_with_sha1, HashAlgorithm.sha1, SignatureAlgorithm.dsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, HashAlgorithm.sha1, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, HashAlgorithm.sha256, SignatureAlgorithm.rsa);
addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa);
addCertSigAlgOID(h, EdECObjectIdentifiers.id_Ed25519, HashAlgorithm.Intrinsic, SignatureAlgorithm.ed25519);
addCertSigAlgOID(h, EdECObjectIdentifiers.id_Ed448, HashAlgorithm.Intrinsic, SignatureAlgorithm.ed448);
return h;
}
private static Vector createDefaultSupportedSigAlgs()
{
Vector result = new Vector();
result.addElement(SignatureAndHashAlgorithm.ed25519);
result.addElement(SignatureAndHashAlgorithm.ed448);
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha384, SignatureAlgorithm.ecdsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha512, SignatureAlgorithm.ecdsa));
result.addElement(SignatureAndHashAlgorithm.rsa_pss_rsae_sha256);
result.addElement(SignatureAndHashAlgorithm.rsa_pss_rsae_sha384);
result.addElement(SignatureAndHashAlgorithm.rsa_pss_rsae_sha512);
result.addElement(SignatureAndHashAlgorithm.rsa_pss_pss_sha256);
result.addElement(SignatureAndHashAlgorithm.rsa_pss_pss_sha384);
result.addElement(SignatureAndHashAlgorithm.rsa_pss_pss_sha512);
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha256, SignatureAlgorithm.rsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha384, SignatureAlgorithm.rsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha512, SignatureAlgorithm.rsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha256, SignatureAlgorithm.dsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha384, SignatureAlgorithm.dsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha512, SignatureAlgorithm.dsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha224, SignatureAlgorithm.ecdsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha224, SignatureAlgorithm.rsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha224, SignatureAlgorithm.dsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.rsa));
result.addElement(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.dsa));
return result;
}
public static final byte[] EMPTY_BYTES = new byte[0];
public static final short[] EMPTY_SHORTS = new short[0];
public static final int[] EMPTY_INTS = new int[0];
public static final long[] EMPTY_LONGS = new long[0];
protected static short MINIMUM_HASH_STRICT = HashAlgorithm.sha1;
protected static short MINIMUM_HASH_PREFERRED = HashAlgorithm.sha256;
public static void checkUint8(short i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint8(int i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint8(long i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint16(int i) throws IOException
{
if (!isValidUint16(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint16(long i) throws IOException
{
if (!isValidUint16(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint24(int i) throws IOException
{
if (!isValidUint24(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint24(long i) throws IOException
{
if (!isValidUint24(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint32(long i) throws IOException
{
if (!isValidUint32(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint48(long i) throws IOException
{
if (!isValidUint48(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint64(long i) throws IOException
{
if (!isValidUint64(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static boolean isValidUint8(short i)
{
return (i & 0xFF) == i;
}
public static boolean isValidUint8(int i)
{
return (i & 0xFF) == i;
}
public static boolean isValidUint8(long i)
{
return (i & 0xFFL) == i;
}
public static boolean isValidUint16(int i)
{
return (i & 0xFFFF) == i;
}
public static boolean isValidUint16(long i)
{
return (i & 0xFFFFL) == i;
}
public static boolean isValidUint24(int i)
{
return (i & 0xFFFFFF) == i;
}
public static boolean isValidUint24(long i)
{
return (i & 0xFFFFFFL) == i;
}
public static boolean isValidUint32(long i)
{
return (i & 0xFFFFFFFFL) == i;
}
public static boolean isValidUint48(long i)
{
return (i & 0xFFFFFFFFFFFFL) == i;
}
public static boolean isValidUint64(long i)
{
return true;
}
public static boolean isSSL(TlsContext context)
{
return context.getServerVersion().isSSL();
}
public static boolean isTLSv10(ProtocolVersion version)
{
return ProtocolVersion.TLSv10.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv10(TlsContext context)
{
return isTLSv10(context.getServerVersion());
}
public static boolean isTLSv11(ProtocolVersion version)
{
return ProtocolVersion.TLSv11.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv11(TlsContext context)
{
return isTLSv11(context.getServerVersion());
}
public static boolean isTLSv12(ProtocolVersion version)
{
return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv12(TlsContext context)
{
return isTLSv12(context.getServerVersion());
}
public static boolean isTLSv13(ProtocolVersion version)
{
return ProtocolVersion.TLSv13.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv13(TlsContext context)
{
return isTLSv13(context.getServerVersion());
}
public static void writeUint8(short i, OutputStream output)
throws IOException
{
output.write(i);
}
public static void writeUint8(int i, OutputStream output)
throws IOException
{
output.write(i);
}
public static void writeUint8(short i, byte[] buf, int offset)
{
buf[offset] = (byte)i;
}
public static void writeUint8(int i, byte[] buf, int offset)
{
buf[offset] = (byte)i;
}
public static void writeUint16(int i, OutputStream output)
throws IOException
{
output.write(i >>> 8);
output.write(i);
}
public static void writeUint16(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 8);
buf[offset + 1] = (byte)i;
}
public static void writeUint24(int i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint24(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 16);
buf[offset + 1] = (byte)(i >>> 8);
buf[offset + 2] = (byte)i;
}
public static void writeUint32(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint32(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 24);
buf[offset + 1] = (byte)(i >>> 16);
buf[offset + 2] = (byte)(i >>> 8);
buf[offset + 3] = (byte)i;
}
public static void writeUint48(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 40));
output.write((byte)(i >>> 32));
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint48(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 40);
buf[offset + 1] = (byte)(i >>> 32);
buf[offset + 2] = (byte)(i >>> 24);
buf[offset + 3] = (byte)(i >>> 16);
buf[offset + 4] = (byte)(i >>> 8);
buf[offset + 5] = (byte)i;
}
public static void writeUint64(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 56));
output.write((byte)(i >>> 48));
output.write((byte)(i >>> 40));
output.write((byte)(i >>> 32));
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint64(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 56);
buf[offset + 1] = (byte)(i >>> 48);
buf[offset + 2] = (byte)(i >>> 40);
buf[offset + 3] = (byte)(i >>> 32);
buf[offset + 4] = (byte)(i >>> 24);
buf[offset + 5] = (byte)(i >>> 16);
buf[offset + 6] = (byte)(i >>> 8);
buf[offset + 7] = (byte)i;
}
public static void writeOpaque8(byte[] buf, OutputStream output)
throws IOException
{
checkUint8(buf.length);
writeUint8(buf.length, output);
output.write(buf);
}
public static void writeOpaque8(byte[] data, byte[] buf, int off)
throws IOException
{
checkUint8(data.length);
writeUint8(data.length, buf, off);
System.arraycopy(data, 0, buf, off + 1, data.length);
}
public static void writeOpaque16(byte[] buf, OutputStream output)
throws IOException
{
checkUint16(buf.length);
writeUint16(buf.length, output);
output.write(buf);
}
public static void writeOpaque24(byte[] buf, OutputStream output)
throws IOException
{
checkUint24(buf.length);
writeUint24(buf.length, output);
output.write(buf);
}
public static void writeUint8Array(short[] uints, OutputStream output)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint8(uints[i], output);
}
}
public static void writeUint8Array(short[] uints, byte[] buf, int offset)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint8(uints[i], buf, offset);
++offset;
}
}
public static void writeUint8ArrayWithUint8Length(short[] uints, OutputStream output)
throws IOException
{
checkUint8(uints.length);
writeUint8(uints.length, output);
writeUint8Array(uints, output);
}
public static void writeUint8ArrayWithUint8Length(short[] uints, byte[] buf, int offset)
throws IOException
{
checkUint8(uints.length);
writeUint8(uints.length, buf, offset);
writeUint8Array(uints, buf, offset + 1);
}
public static void writeUint16Array(int[] uints, OutputStream output)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint16(uints[i], output);
}
}
public static void writeUint16Array(int[] uints, byte[] buf, int offset)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint16(uints[i], buf, offset);
offset += 2;
}
}
public static void writeUint16ArrayWithUint16Length(int[] uints, OutputStream output)
throws IOException
{
int length = 2 * uints.length;
checkUint16(length);
writeUint16(length, output);
writeUint16Array(uints, output);
}
public static void writeUint16ArrayWithUint16Length(int[] uints, byte[] buf, int offset)
throws IOException
{
int length = 2 * uints.length;
checkUint16(length);
writeUint16(length, buf, offset);
writeUint16Array(uints, buf, offset + 2);
}
public static byte[] decodeOpaque8(byte[] buf)
throws IOException
{
return decodeOpaque8(buf, 0);
}
public static byte[] decodeOpaque8(byte[] buf, int minLength)
throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
if (buf.length < 1)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
short length = readUint8(buf, 0);
if (buf.length != (length + 1) || length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return copyOfRangeExact(buf, 1, buf.length);
}
public static byte[] decodeOpaque16(byte[] buf)
throws IOException
{
return decodeOpaque16(buf, 0);
}
public static byte[] decodeOpaque16(byte[] buf, int minLength)
throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
if (buf.length < 2)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
int length = readUint16(buf, 0);
if (buf.length != (length + 2) || length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return copyOfRangeExact(buf, 2, buf.length);
}
public static short decodeUint8(byte[] buf) throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
if (buf.length != 1)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readUint8(buf, 0);
}
public static short[] decodeUint8ArrayWithUint8Length(byte[] buf) throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
int count = readUint8(buf, 0);
if (buf.length != (count + 1))
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
short[] uints = new short[count];
for (int i = 0; i < count; ++i)
{
uints[i] = readUint8(buf, i + 1);
}
return uints;
}
public static int decodeUint16(byte[] buf) throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
if (buf.length != 2)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readUint16(buf, 0);
}
public static long decodeUint32(byte[] buf) throws IOException
{
if (buf == null)
{
throw new IllegalArgumentException("'buf' cannot be null");
}
if (buf.length != 4)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readUint32(buf, 0);
}
public static byte[] encodeOpaque8(byte[] buf)
throws IOException
{
checkUint8(buf.length);
return Arrays.prepend(buf, (byte)buf.length);
}
public static byte[] encodeOpaque16(byte[] buf)
throws IOException
{
return Arrays.concatenate(encodeUint16(buf.length), buf);
}
public static byte[] encodeUint8(short uint) throws IOException
{
checkUint8(uint);
byte[] encoding = new byte[1];
writeUint8(uint, encoding, 0);
return encoding;
}
public static byte[] encodeUint8ArrayWithUint8Length(short[] uints) throws IOException
{
byte[] result = new byte[1 + uints.length];
writeUint8ArrayWithUint8Length(uints, result, 0);
return result;
}
public static byte[] encodeUint16(int uint) throws IOException
{
checkUint16(uint);
byte[] encoding = new byte[2];
writeUint16(uint, encoding, 0);
return encoding;
}
public static byte[] encodeUint16ArrayWithUint16Length(int[] uints) throws IOException
{
int length = 2 * uints.length;
byte[] result = new byte[2 + length];
writeUint16ArrayWithUint16Length(uints, result, 0);
return result;
}
public static byte[] encodeUint32(long uint) throws IOException
{
checkUint32(uint);
byte[] encoding = new byte[4];
writeUint32(uint, encoding, 0);
return encoding;
}
public static byte[] encodeVersion(ProtocolVersion version) throws IOException
{
return new byte[]{
(byte)version.getMajorVersion(),
(byte)version.getMinorVersion()
};
}
public static int readInt32(byte[] buf, int offset)
{
int n = buf[offset] << 24;
n |= (buf[++offset] & 0xff) << 16;
n |= (buf[++offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n;
}
public static short readUint8(InputStream input)
throws IOException
{
int i = input.read();
if (i < 0)
{
throw new EOFException();
}
return (short)i;
}
public static short readUint8(byte[] buf, int offset)
{
return (short)(buf[offset] & 0xff);
}
public static int readUint16(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
if (i2 < 0)
{
throw new EOFException();
}
return (i1 << 8) | i2;
}
public static int readUint16(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n;
}
public static int readUint24(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
int i3 = input.read();
if (i3 < 0)
{
throw new EOFException();
}
return (i1 << 16) | (i2 << 8) | i3;
}
public static int readUint24(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 16;
n |= (buf[++offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n;
}
public static long readUint32(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
int i3 = input.read();
int i4 = input.read();
if (i4 < 0)
{
throw new EOFException();
}
return ((i1 << 24) | (i2 << 16) | (i3 << 8) | i4) & 0xFFFFFFFFL;
}
public static long readUint32(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 24;
n |= (buf[++offset] & 0xff) << 16;
n |= (buf[++offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n & 0xFFFFFFFFL;
}
public static long readUint48(InputStream input)
throws IOException
{
int hi = readUint24(input);
int lo = readUint24(input);
return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL);
}
public static long readUint48(byte[] buf, int offset)
{
int hi = readUint24(buf, offset);
int lo = readUint24(buf, offset + 3);
return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL);
}
public static byte[] readAllOrNothing(int length, InputStream input)
throws IOException
{
if (length < 1)
{
return EMPTY_BYTES;
}
byte[] buf = new byte[length];
int read = Streams.readFully(input, buf);
if (read == 0)
{
return null;
}
if (read != length)
{
throw new EOFException();
}
return buf;
}
public static byte[] readFully(int length, InputStream input)
throws IOException
{
if (length < 1)
{
return EMPTY_BYTES;
}
byte[] buf = new byte[length];
if (length != Streams.readFully(input, buf))
{
throw new EOFException();
}
return buf;
}
public static void readFully(byte[] buf, InputStream input)
throws IOException
{
int length = buf.length;
if (length > 0 && length != Streams.readFully(input, buf))
{
throw new EOFException();
}
}
public static byte[] readOpaque8(InputStream input)
throws IOException
{
short length = readUint8(input);
return readFully(length, input);
}
public static byte[] readOpaque8(InputStream input, int minLength)
throws IOException
{
short length = readUint8(input);
if (length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readFully(length, input);
}
public static byte[] readOpaque8(InputStream input, int minLength, int maxLength)
throws IOException
{
short length = readUint8(input);
if (length < minLength || maxLength < length)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readFully(length, input);
}
public static byte[] readOpaque16(InputStream input)
throws IOException
{
int length = readUint16(input);
return readFully(length, input);
}
public static byte[] readOpaque16(InputStream input, int minLength)
throws IOException
{
int length = readUint16(input);
if (length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readFully(length, input);
}
public static byte[] readOpaque24(InputStream input)
throws IOException
{
int length = readUint24(input);
return readFully(length, input);
}
public static byte[] readOpaque24(InputStream input, int minLength)
throws IOException
{
int length = readUint24(input);
if (length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readFully(length, input);
}
public static short[] readUint8Array(int count, InputStream input)
throws IOException
{
short[] uints = new short[count];
for (int i = 0; i < count; ++i)
{
uints[i] = readUint8(input);
}
return uints;
}
public static short[] readUint8ArrayWithUint8Length(InputStream input, int minLength)
throws IOException
{
int length = TlsUtils.readUint8(input);
if (length < minLength)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return readUint8Array(length, input);
}
public static int[] readUint16Array(int count, InputStream input)
throws IOException
{
int[] uints = new int[count];
for (int i = 0; i < count; ++i)
{
uints[i] = readUint16(input);
}
return uints;
}
public static ProtocolVersion readVersion(byte[] buf, int offset)
{
return ProtocolVersion.get(buf[offset] & 0xFF, buf[offset + 1] & 0xFF);
}
public static ProtocolVersion readVersion(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
if (i2 < 0)
{
throw new EOFException();
}
return ProtocolVersion.get(i1, i2);
}
public static ASN1Primitive readASN1Object(byte[] encoding) throws IOException
{
ASN1InputStream asn1 = new ASN1InputStream(encoding);
ASN1Primitive result = asn1.readObject();
if (null == result)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
if (null != asn1.readObject())
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return result;
}
public static ASN1Primitive readDERObject(byte[] encoding) throws IOException
{
/*
* NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is
* canonical, we can check it by re-encoding the result and comparing to the original.
*/
ASN1Primitive result = readASN1Object(encoding);
byte[] check = result.getEncoded(ASN1Encoding.DER);
if (!Arrays.areEqual(check, encoding))
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return result;
}
public static void writeGMTUnixTime(byte[] buf, int offset)
{
int t = (int)(System.currentTimeMillis() / 1000L);
buf[offset] = (byte)(t >>> 24);
buf[offset + 1] = (byte)(t >>> 16);
buf[offset + 2] = (byte)(t >>> 8);
buf[offset + 3] = (byte)t;
}
public static void writeVersion(ProtocolVersion version, OutputStream output)
throws IOException
{
output.write(version.getMajorVersion());
output.write(version.getMinorVersion());
}
public static void writeVersion(ProtocolVersion version, byte[] buf, int offset)
{
buf[offset] = (byte)version.getMajorVersion();
buf[offset + 1] = (byte)version.getMinorVersion();
}
public static void addIfSupported(Vector supportedAlgs, TlsCrypto crypto, SignatureAndHashAlgorithm alg)
{
if (crypto.hasSignatureAndHashAlgorithm(alg))
{
supportedAlgs.addElement(alg);
}
}
public static void addIfSupported(Vector supportedGroups, TlsCrypto crypto, int namedGroup)
{
if (crypto.hasNamedGroup(namedGroup))
{
supportedGroups.addElement(Integers.valueOf(namedGroup));
}
}
public static void addIfSupported(Vector supportedGroups, TlsCrypto crypto, int[] namedGroups)
{
for (int i = 0; i < namedGroups.length; ++i)
{
addIfSupported(supportedGroups, crypto, namedGroups[i]);
}
}
public static boolean addToSet(Vector s, int i)
{
boolean result = !s.contains(Integers.valueOf(i));
if (result)
{
s.add(Integers.valueOf(i));
}
return result;
}
public static Vector getDefaultDSSSignatureAlgorithms()
{
return getDefaultSignatureAlgorithms(SignatureAlgorithm.dsa);
}
public static Vector getDefaultECDSASignatureAlgorithms()
{
return getDefaultSignatureAlgorithms(SignatureAlgorithm.ecdsa);
}
public static Vector getDefaultRSASignatureAlgorithms()
{
return getDefaultSignatureAlgorithms(SignatureAlgorithm.rsa);
}
public static SignatureAndHashAlgorithm getDefaultSignatureAlgorithm(short signatureAlgorithm)
{
/*
* RFC 5246 7.4.1.4.1. If the client does not send the signature_algorithms extension,
* the server MUST do the following:
*
* - If the negotiated key exchange algorithm is one of (RSA, DHE_RSA, DH_RSA, RSA_PSK,
* ECDH_RSA, ECDHE_RSA), behave as if client had sent the value {sha1,rsa}.
*
* - If the negotiated key exchange algorithm is one of (DHE_DSS, DH_DSS), behave as if
* the client had sent the value {sha1,dsa}.
*
* - If the negotiated key exchange algorithm is one of (ECDH_ECDSA, ECDHE_ECDSA),
* behave as if the client had sent value {sha1,ecdsa}.
*/
switch (signatureAlgorithm)
{
case SignatureAlgorithm.dsa:
case SignatureAlgorithm.ecdsa:
case SignatureAlgorithm.rsa:
return SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, signatureAlgorithm);
default:
return null;
}
}
public static Vector getDefaultSignatureAlgorithms(short signatureAlgorithm)
{
SignatureAndHashAlgorithm sigAndHashAlg = getDefaultSignatureAlgorithm(signatureAlgorithm);
return null == sigAndHashAlg ? new Vector() : vectorOfOne(sigAndHashAlg);
}
public static Vector getDefaultSupportedSignatureAlgorithms(TlsContext context)
{
TlsCrypto crypto = context.getCrypto();
int count = DEFAULT_SUPPORTED_SIG_ALGS.size();
Vector result = new Vector(count);
for (int i = 0; i < count; ++i)
{
addIfSupported(result, crypto, (SignatureAndHashAlgorithm)DEFAULT_SUPPORTED_SIG_ALGS.elementAt(i));
}
return result;
}
public static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(TlsContext context,
TlsCredentialedSigner signerCredentials)
throws IOException
{
return getSignatureAndHashAlgorithm(context.getServerVersion(), signerCredentials);
}
static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(ProtocolVersion negotiatedVersion,
TlsCredentialedSigner signerCredentials) throws IOException
{
SignatureAndHashAlgorithm signatureAndHashAlgorithm = null;
if (isTLSv12(negotiatedVersion))
{
signatureAndHashAlgorithm = signerCredentials.getSignatureAndHashAlgorithm();
if (signatureAndHashAlgorithm == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
return signatureAndHashAlgorithm;
}
public static byte[] getExtensionData(Hashtable extensions, Integer extensionType)
{
return extensions == null ? null : (byte[])extensions.get(extensionType);
}
public static boolean hasExpectedEmptyExtensionData(Hashtable extensions, Integer extensionType,
short alertDescription) throws IOException
{
byte[] extension_data = getExtensionData(extensions, extensionType);
if (extension_data == null)
{
return false;
}
if (extension_data.length != 0)
{
throw new TlsFatalAlert(alertDescription);
}
return true;
}
public static TlsSession importSession(byte[] sessionID, SessionParameters sessionParameters)
{
return new TlsSessionImpl(sessionID, sessionParameters);
}
static boolean isExtendedMasterSecretOptionalDTLS(ProtocolVersion[] activeProtocolVersions)
{
return ProtocolVersion.contains(activeProtocolVersions, ProtocolVersion.DTLSv12)
|| ProtocolVersion.contains(activeProtocolVersions, ProtocolVersion.DTLSv10);
}
static boolean isExtendedMasterSecretOptionalTLS(ProtocolVersion[] activeProtocolVersions)
{
return ProtocolVersion.contains(activeProtocolVersions, ProtocolVersion.TLSv12)
|| ProtocolVersion.contains(activeProtocolVersions, ProtocolVersion.TLSv11)
|| ProtocolVersion.contains(activeProtocolVersions, ProtocolVersion.TLSv10);
}
public static boolean isNullOrContainsNull(Object[] array)
{
if (null == array)
{
return true;
}
int count = array.length;
for (int i = 0; i < count; ++i)
{
if (null == array[i])
{
return true;
}
}
return false;
}
public static boolean isNullOrEmpty(byte[] array)
{
return null == array || array.length < 1;
}
public static boolean isNullOrEmpty(Object[] array)
{
return null == array || array.length < 1;
}
public static boolean isSignatureAlgorithmsExtensionAllowed(ProtocolVersion version)
{
return null != version
&& ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static short getLegacyClientCertType(short signatureAlgorithm)
{
switch (signatureAlgorithm)
{
case SignatureAlgorithm.rsa:
return ClientCertificateType.rsa_sign;
case SignatureAlgorithm.dsa:
return ClientCertificateType.dss_sign;
case SignatureAlgorithm.ecdsa:
return ClientCertificateType.ecdsa_sign;
default:
return -1;
}
}
public static short getLegacySignatureAlgorithmClient(short clientCertificateType)
{
switch (clientCertificateType)
{
case ClientCertificateType.dss_sign:
return SignatureAlgorithm.dsa;
case ClientCertificateType.ecdsa_sign:
return SignatureAlgorithm.ecdsa;
case ClientCertificateType.rsa_sign:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
public static short getLegacySignatureAlgorithmClientCert(short clientCertificateType)
{
switch (clientCertificateType)
{
case ClientCertificateType.dss_sign:
case ClientCertificateType.dss_fixed_dh:
return SignatureAlgorithm.dsa;
case ClientCertificateType.ecdsa_sign:
case ClientCertificateType.ecdsa_fixed_ecdh:
return SignatureAlgorithm.ecdsa;
case ClientCertificateType.rsa_sign:
case ClientCertificateType.rsa_fixed_dh:
case ClientCertificateType.rsa_fixed_ecdh:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
public static short getLegacySignatureAlgorithmServer(int keyExchangeAlgorithm)
{
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.SRP_DSS:
return SignatureAlgorithm.dsa;
case KeyExchangeAlgorithm.ECDHE_ECDSA:
return SignatureAlgorithm.ecdsa;
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.SRP_RSA:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
public static short getLegacySignatureAlgorithmServerCert(int keyExchangeAlgorithm)
{
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.SRP_DSS:
return SignatureAlgorithm.dsa;
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
return SignatureAlgorithm.ecdsa;
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDH_RSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.RSA:
case KeyExchangeAlgorithm.RSA_PSK:
case KeyExchangeAlgorithm.SRP_RSA:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
public static Vector getLegacySupportedSignatureAlgorithms()
{
Vector result = new Vector(3);
result.add(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.dsa));
result.add(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa));
result.add(SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, SignatureAlgorithm.rsa));
return result;
}
public static void encodeSupportedSignatureAlgorithms(Vector supportedSignatureAlgorithms, OutputStream output)
throws IOException
{
if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1
|| supportedSignatureAlgorithms.size() >= (1 << 15))
{
throw new IllegalArgumentException(
"'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)");
}
// supported_signature_algorithms
int length = 2 * supportedSignatureAlgorithms.size();
checkUint16(length);
writeUint16(length, output);
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i);
if (entry.getSignature() == SignatureAlgorithm.anonymous)
{
/*
* RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used
* in Section 7.4.3. It MUST NOT appear in this extension.
*/
throw new IllegalArgumentException(
"SignatureAlgorithm.anonymous MUST NOT appear in the signature_algorithms extension");
}
entry.encode(output);
}
}
public static Vector parseSupportedSignatureAlgorithms(InputStream input)
throws IOException
{
// supported_signature_algorithms
int length = readUint16(input);
if (length < 2 || (length & 1) != 0)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
int count = length / 2;
Vector supportedSignatureAlgorithms = new Vector(count);
for (int i = 0; i < count; ++i)
{
SignatureAndHashAlgorithm sigAndHashAlg = SignatureAndHashAlgorithm.parse(input);
if (SignatureAlgorithm.anonymous != sigAndHashAlg.getSignature())
{
supportedSignatureAlgorithms.addElement(sigAndHashAlg);
}
}
return supportedSignatureAlgorithms;
}
public static void verifySupportedSignatureAlgorithm(Vector supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm)
throws IOException
{
if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1
|| supportedSignatureAlgorithms.size() >= (1 << 15))
{
throw new IllegalArgumentException(
"'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)");
}
if (signatureAlgorithm == null)
{
throw new IllegalArgumentException("'signatureAlgorithm' cannot be null");
}
if (signatureAlgorithm.getSignature() == SignatureAlgorithm.anonymous
|| !containsSignatureAlgorithm(supportedSignatureAlgorithms, signatureAlgorithm))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
public static boolean containsSignatureAlgorithm(Vector supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm)
throws IOException
{
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i);
if (entry.getHash() == signatureAlgorithm.getHash() && entry.getSignature() == signatureAlgorithm.getSignature())
{
return true;
}
}
return false;
}
public static boolean containsAnySignatureAlgorithm(Vector supportedSignatureAlgorithms, short signatureAlgorithm)
{
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i);
if (entry.getSignature() == signatureAlgorithm)
{
return true;
}
}
return false;
}
public static TlsSecret PRF(SecurityParameters securityParameters, TlsSecret secret, String asciiLabel, byte[] seed,
int length)
{
return secret.deriveUsingPRF(securityParameters.getPRFAlgorithm(), asciiLabel, seed, length);
}
/**
* @deprecated Use {@link #PRF(SecurityParameters, TlsSecret, String, byte[], int)} instead.
*/
public static TlsSecret PRF(TlsContext context, TlsSecret secret, String asciiLabel, byte[] seed, int length)
{
return PRF(context.getSecurityParametersHandshake(), secret, asciiLabel, seed, length);
}
public static byte[] clone(byte[] data)
{
return null == data ? (byte[])null : data.length == 0 ? EMPTY_BYTES : (byte[])data.clone();
}
public static boolean constantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, int bOff)
{
int d = 0;
for (int i = 0; i < len; ++i)
{
d |= (a[aOff + i] ^ b[bOff + i]);
}
return 0 == d;
}
public static byte[] copyOfRangeExact(byte[] original, int from, int to)
{
int newLength = to - from;
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0, newLength);
return copy;
}
static byte[] concat(byte[] a, byte[] b)
{
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static byte[] calculateEndPointHash(TlsContext context, TlsCertificate certificate, byte[] enc) throws IOException
{
return calculateEndPointHash(context, certificate, enc, 0, enc.length);
}
/*
* TODO[tls13] Check relevance of endpoint hash in TLS 1.3; if still exists, what about
* signature schemes using Intrinsic hash?
*/
static byte[] calculateEndPointHash(TlsContext context, TlsCertificate certificate, byte[] enc, int encOff,
int encLen) throws IOException
{
short hashAlgorithm = HashAlgorithm.none;
String sigAlgOID = certificate.getSigAlgOID();
if (sigAlgOID != null)
{
if (PKCSObjectIdentifiers.id_RSASSA_PSS.getId().equals(sigAlgOID))
{
RSASSAPSSparams pssParams = RSASSAPSSparams.getInstance(certificate.getSigAlgParams());
if (null != pssParams)
{
ASN1ObjectIdentifier hashOID = pssParams.getHashAlgorithm().getAlgorithm();
if (NISTObjectIdentifiers.id_sha256.equals(hashOID))
{
hashAlgorithm = HashAlgorithm.sha256;
}
else if (NISTObjectIdentifiers.id_sha384.equals(hashOID))
{
hashAlgorithm = HashAlgorithm.sha384;
}
else if (NISTObjectIdentifiers.id_sha512.equals(hashOID))
{
hashAlgorithm = HashAlgorithm.sha512;
}
}
}
else
{
SignatureAndHashAlgorithm sigAndHashAlg = (SignatureAndHashAlgorithm)CERT_SIG_ALG_OIDS.get(sigAlgOID);
if (sigAndHashAlg != null)
{
hashAlgorithm = sigAndHashAlg.getHash();
}
}
}
switch (hashAlgorithm)
{
case HashAlgorithm.Intrinsic:
hashAlgorithm = HashAlgorithm.none;
break;
case HashAlgorithm.md5:
case HashAlgorithm.sha1:
hashAlgorithm = HashAlgorithm.sha256;
break;
}
if (HashAlgorithm.none != hashAlgorithm)
{
TlsHash hash = context.getCrypto().createHash(hashAlgorithm);
if (hash != null)
{
hash.update(enc, encOff, encLen);
return hash.calculateHash();
}
}
return EMPTY_BYTES;
}
public static byte[] calculateExporterSeed(SecurityParameters securityParameters, byte[] context)
{
byte[] cr = securityParameters.getClientRandom(), sr = securityParameters.getServerRandom();
if (null == context)
{
return Arrays.concatenate(cr, sr);
}
if (!isValidUint16(context.length))
{
throw new IllegalArgumentException("'context' must have length less than 2^16 (or be null)");
}
byte[] contextLength = new byte[2];
writeUint16(context.length, contextLength, 0);
return Arrays.concatenate(cr, sr, contextLength, context);
}
static TlsSecret calculateMasterSecret(TlsContext context, TlsSecret preMasterSecret)
{
SecurityParameters sp = context.getSecurityParametersHandshake();
String asciiLabel;
byte[] seed;
if (sp.isExtendedMasterSecret())
{
asciiLabel = ExporterLabel.extended_master_secret;
seed = sp.getSessionHash();
}
else
{
asciiLabel = ExporterLabel.master_secret;
seed = concat(sp.getClientRandom(), sp.getServerRandom());
}
return PRF(sp, preMasterSecret, asciiLabel, seed, 48);
}
static byte[] calculateVerifyData(TlsContext context, TlsHandshakeHash handshakeHash, boolean isServer)
throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (isTLSv13(negotiatedVersion))
{
TlsSecret baseKey = isServer
? securityParameters.getTrafficSecretServer()
: securityParameters.getTrafficSecretClient();
TlsSecret finishedKey = deriveSecret(securityParameters, baseKey, "finished", TlsUtils.EMPTY_BYTES);
byte[] transcriptHash = getCurrentPRFHash(handshakeHash);
TlsCrypto crypto = context.getCrypto();
byte[] hmacKey = crypto.adoptSecret(finishedKey).extract();
TlsHMAC hmac = crypto.createHMAC(securityParameters.getPRFHashAlgorithm());
hmac.setKey(hmacKey, 0, hmacKey.length);
hmac.update(transcriptHash, 0, transcriptHash.length);
return hmac.calculateMAC();
}
if (negotiatedVersion.isSSL())
{
return SSL3Utils.calculateVerifyData(handshakeHash, isServer);
}
String asciiLabel = isServer ? ExporterLabel.server_finished : ExporterLabel.client_finished;
byte[] prfHash = getCurrentPRFHash(handshakeHash);
TlsSecret master_secret = securityParameters.getMasterSecret();
int verify_data_length = securityParameters.getVerifyDataLength();
return PRF(securityParameters, master_secret, asciiLabel, prfHash, verify_data_length).extract();
}
static void establish13PhaseSecrets(TlsContext context) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
short hash = securityParameters.getPRFHashAlgorithm();
int hashLen = securityParameters.getPRFHashLength();
byte[] zeroes = new byte[hashLen];
byte[] psk = securityParameters.getPSK();
if (null == psk)
{
psk = zeroes;
}
else
{
securityParameters.psk = null;
}
byte[] ecdhe = zeroes;
TlsSecret sharedSecret = securityParameters.getSharedSecret();
if (null != sharedSecret)
{
securityParameters.sharedSecret = null;
ecdhe = sharedSecret.extract();
}
TlsCrypto crypto = context.getCrypto();
byte[] emptyTranscriptHash = crypto.createHash(hash).calculateHash();
TlsSecret earlySecret = crypto.hkdfInit(hash)
.hkdfExtract(hash, psk);
TlsSecret handshakeSecret = deriveSecret(securityParameters, earlySecret, "derived", emptyTranscriptHash)
.hkdfExtract(hash, ecdhe);
TlsSecret masterSecret = deriveSecret(securityParameters, handshakeSecret, "derived", emptyTranscriptHash)
.hkdfExtract(hash, zeroes);
securityParameters.earlySecret = earlySecret;
securityParameters.handshakeSecret = handshakeSecret;
securityParameters.masterSecret = masterSecret;
}
private static void establish13TrafficSecrets(TlsContext context, byte[] transcriptHash, TlsSecret phaseSecret,
String clientLabel, String serverLabel, RecordStream recordStream) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
securityParameters.trafficSecretClient = deriveSecret(securityParameters, phaseSecret, clientLabel,
transcriptHash);
if (null != serverLabel)
{
securityParameters.trafficSecretServer = deriveSecret(securityParameters, phaseSecret, serverLabel,
transcriptHash);
}
// TODO[tls13] Early data (client->server only)
recordStream.setPendingConnectionState(initCipher(context));
recordStream.receivedReadCipherSpec();
recordStream.sentWriteCipherSpec();
}
static void establish13PhaseApplication(TlsContext context, byte[] serverFinishedTranscriptHash,
RecordStream recordStream) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
TlsSecret phaseSecret = securityParameters.getMasterSecret();
establish13TrafficSecrets(context, serverFinishedTranscriptHash, phaseSecret, "c ap traffic", "s ap traffic",
recordStream);
securityParameters.exporterMasterSecret = deriveSecret(securityParameters, phaseSecret, "exp master",
serverFinishedTranscriptHash);
}
static void establish13PhaseEarly(TlsContext context, byte[] clientHelloTranscriptHash, RecordStream recordStream)
throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
TlsSecret phaseSecret = securityParameters.getEarlySecret();
// TODO[tls13] binder_key
// TODO[tls13] Early data (client->server only)
if (null != recordStream)
{
establish13TrafficSecrets(context, clientHelloTranscriptHash, phaseSecret, "c e traffic", null,
recordStream);
}
securityParameters.earlyExporterMasterSecret = deriveSecret(securityParameters, phaseSecret, "e exp master",
clientHelloTranscriptHash);
}
static void establish13PhaseHandshake(TlsContext context, byte[] serverHelloTranscriptHash,
RecordStream recordStream) throws IOException
{
TlsSecret phaseSecret = context.getSecurityParametersHandshake().getHandshakeSecret();
establish13TrafficSecrets(context, serverHelloTranscriptHash, phaseSecret, "c hs traffic", "s hs traffic",
recordStream);
}
public static short getHashAlgorithmForHMACAlgorithm(int macAlgorithm)
{
switch (macAlgorithm)
{
case MACAlgorithm.hmac_md5:
return HashAlgorithm.md5;
case MACAlgorithm.hmac_sha1:
return HashAlgorithm.sha1;
case MACAlgorithm.hmac_sha256:
return HashAlgorithm.sha256;
case MACAlgorithm.hmac_sha384:
return HashAlgorithm.sha384;
case MACAlgorithm.hmac_sha512:
return HashAlgorithm.sha512;
default:
throw new IllegalArgumentException("specified MACAlgorithm not an HMAC: " + MACAlgorithm.getText(macAlgorithm));
}
}
public static short getHashAlgorithmForPRFAlgorithm(int prfAlgorithm)
{
switch (prfAlgorithm)
{
case PRFAlgorithm.ssl_prf_legacy:
case PRFAlgorithm.tls_prf_legacy:
throw new IllegalArgumentException("legacy PRF not a valid algorithm");
case PRFAlgorithm.tls_prf_sha256:
case PRFAlgorithm.tls13_hkdf_sha256:
return HashAlgorithm.sha256;
case PRFAlgorithm.tls_prf_sha384:
case PRFAlgorithm.tls13_hkdf_sha384:
return HashAlgorithm.sha384;
default:
throw new IllegalArgumentException("unknown PRFAlgorithm: " + PRFAlgorithm.getText(prfAlgorithm));
}
}
public static ASN1ObjectIdentifier getOIDForHashAlgorithm(short hashAlgorithm)
{
switch (hashAlgorithm)
{
case HashAlgorithm.md5:
return PKCSObjectIdentifiers.md5;
case HashAlgorithm.sha1:
return X509ObjectIdentifiers.id_SHA1;
case HashAlgorithm.sha224:
return NISTObjectIdentifiers.id_sha224;
case HashAlgorithm.sha256:
return NISTObjectIdentifiers.id_sha256;
case HashAlgorithm.sha384:
return NISTObjectIdentifiers.id_sha384;
case HashAlgorithm.sha512:
return NISTObjectIdentifiers.id_sha512;
default:
throw new IllegalArgumentException("invalid HashAlgorithm: " + HashAlgorithm.getText(hashAlgorithm));
}
}
static int getPRFAlgorithm(SecurityParameters securityParameters, int cipherSuite) throws IOException
{
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
final boolean isTLSv13 = TlsUtils.isTLSv13(negotiatedVersion);
final boolean isTLSv12Exactly = !isTLSv13 && TlsUtils.isTLSv12(negotiatedVersion);
final boolean isSSL = negotiatedVersion.isSSL();
switch (cipherSuite)
{
case CipherSuite.TLS_AES_128_CCM_SHA256:
case CipherSuite.TLS_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_AES_128_GCM_SHA256:
case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:
{
if (isTLSv13)
{
return PRFAlgorithm.tls13_hkdf_sha256;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_AES_256_GCM_SHA384:
{
if (isTLSv13)
{
return PRFAlgorithm.tls13_hkdf_sha384;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
{
if (isTLSv12Exactly)
{
return PRFAlgorithm.tls_prf_sha256;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
{
if (isTLSv12Exactly)
{
return PRFAlgorithm.tls_prf_sha384;
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
{
if (isTLSv13)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
if (isTLSv12Exactly)
{
return PRFAlgorithm.tls_prf_sha384;
}
if (isSSL)
{
return PRFAlgorithm.ssl_prf_legacy;
}
return PRFAlgorithm.tls_prf_legacy;
}
default:
{
if (isTLSv13)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
if (isTLSv12Exactly)
{
return PRFAlgorithm.tls_prf_sha256;
}
if (isSSL)
{
return PRFAlgorithm.ssl_prf_legacy;
}
return PRFAlgorithm.tls_prf_legacy;
}
}
}
static byte[] calculateSignatureHash(TlsContext context, SignatureAndHashAlgorithm algorithm, DigestInputBuffer buf)
{
TlsCrypto crypto = context.getCrypto();
TlsHash h = algorithm == null
? new CombinedHash(crypto)
: crypto.createHash(algorithm.getHash());
SecurityParameters sp = context.getSecurityParametersHandshake();
byte[] cr = sp.getClientRandom(), sr = sp.getServerRandom();
h.update(cr, 0, cr.length);
h.update(sr, 0, sr.length);
buf.updateDigest(h);
return h.calculateHash();
}
static void sendSignatureInput(TlsContext context, DigestInputBuffer buf, OutputStream output)
throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
// NOTE: The implicit copy here is intended (and important)
output.write(Arrays.concatenate(securityParameters.getClientRandom(), securityParameters.getServerRandom()));
buf.copyTo(output);
output.close();
}
static DigitallySigned generateCertificateVerifyClient(TlsClientContext clientContext,
TlsCredentialedSigner credentialedSigner, TlsStreamSigner streamSigner, TlsHandshakeHash handshakeHash)
throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (isTLSv13(negotiatedVersion))
{
// Should be using generateCertificateVerify13 instead
throw new TlsFatalAlert(AlertDescription.internal_error);
}
/*
* RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
*/
SignatureAndHashAlgorithm signatureAndHashAlgorithm = getSignatureAndHashAlgorithm(negotiatedVersion,
credentialedSigner);
byte[] signature;
if (streamSigner != null)
{
handshakeHash.copyBufferTo(streamSigner.getOutputStream());
signature = streamSigner.getSignature();
}
else
{
byte[] hash;
if (signatureAndHashAlgorithm == null)
{
hash = securityParameters.getSessionHash();
}
else
{
hash = handshakeHash.getFinalHash(signatureAndHashAlgorithm.getHash());
}
signature = credentialedSigner.generateRawSignature(hash);
}
return new DigitallySigned(signatureAndHashAlgorithm, signature);
}
static DigitallySigned generate13CertificateVerify(TlsContext context, TlsCredentialedSigner credentialedSigner,
TlsHandshakeHash handshakeHash) throws IOException
{
SignatureAndHashAlgorithm signatureAndHashAlgorithm = credentialedSigner.getSignatureAndHashAlgorithm();
if (null == signatureAndHashAlgorithm)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
String contextString = context.isServer()
? "TLS 1.3, server CertificateVerify"
: "TLS 1.3, client CertificateVerify";
byte[] signature = generate13CertificateVerify(context.getCrypto(), credentialedSigner, contextString,
handshakeHash, signatureAndHashAlgorithm.getHash());
return new DigitallySigned(signatureAndHashAlgorithm, signature);
}
private static byte[] generate13CertificateVerify(TlsCrypto crypto, TlsCredentialedSigner credentialedSigner,
String contextString, TlsHandshakeHash handshakeHash, short hashAlgorithm) throws IOException
{
TlsStreamSigner streamSigner = credentialedSigner.getStreamSigner();
byte[] header = getCertificateVerifyHeader(contextString);
byte[] prfHash = getCurrentPRFHash(handshakeHash);
if (null != streamSigner)
{
OutputStream output = streamSigner.getOutputStream();
output.write(header, 0, header.length);
output.write(prfHash, 0, prfHash.length);
return streamSigner.getSignature();
}
TlsHash tlsHash = crypto.createHash(hashAlgorithm);
tlsHash.update(header, 0, header.length);
tlsHash.update(prfHash, 0, prfHash.length);
byte[] hash = tlsHash.calculateHash();
return credentialedSigner.generateRawSignature(hash);
}
static void verifyCertificateVerifyClient(TlsServerContext serverContext, CertificateRequest certificateRequest,
DigitallySigned certificateVerify, TlsHandshakeHash handshakeHash) throws IOException
{
SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake();
Certificate clientCertificate = securityParameters.getPeerCertificate();
TlsCertificate verifyingCert = clientCertificate.getCertificateAt(0);
SignatureAndHashAlgorithm sigAndHashAlg = certificateVerify.getAlgorithm();
short signatureAlgorithm;
if (null == sigAndHashAlg)
{
signatureAlgorithm = verifyingCert.getLegacySignatureAlgorithm();
short clientCertType = getLegacyClientCertType(signatureAlgorithm);
if (clientCertType < 0 || !Arrays.contains(certificateRequest.getCertificateTypes(), clientCertType))
{
throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
}
}
else
{
signatureAlgorithm = sigAndHashAlg.getSignature();
// TODO Is it possible (maybe only pre-1.2 to check this immediately when the Certificate arrives?
if (!isValidSignatureAlgorithmForCertificateVerify(signatureAlgorithm, certificateRequest.getCertificateTypes()))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
verifySupportedSignatureAlgorithm(securityParameters.getServerSigAlgs(), sigAndHashAlg);
}
// Verify the CertificateVerify message contains a correct signature.
boolean verified;
try
{
TlsVerifier verifier = verifyingCert.createVerifier(signatureAlgorithm);
if (isTLSv13(securityParameters.getNegotiatedVersion()))
{
verified = verify13CertificateVerify(serverContext.getCrypto(), certificateVerify, verifier,
"TLS 1.3, client CertificateVerify", handshakeHash);
}
else
{
TlsStreamVerifier streamVerifier = verifier.getStreamVerifier(certificateVerify);
if (streamVerifier != null)
{
handshakeHash.copyBufferTo(streamVerifier.getOutputStream());
verified = streamVerifier.isVerified();
}
else
{
byte[] hash;
if (isTLSv12(serverContext))
{
hash = handshakeHash.getFinalHash(sigAndHashAlg.getHash());
}
else
{
hash = securityParameters.getSessionHash();
}
verified = verifier.verifyRawSignature(certificateVerify, hash);
}
}
}
catch (TlsFatalAlert e)
{
throw e;
}
catch (Exception e)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error, e);
}
if (!verified)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error);
}
}
static void verifyCertificateVerifyServer(TlsClientContext clientContext, DigitallySigned certificateVerify,
TlsHandshakeHash handshakeHash) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
Certificate serverCertificate = securityParameters.getPeerCertificate();
TlsCertificate verifyingCert = serverCertificate.getCertificateAt(0);
SignatureAndHashAlgorithm sigAndHashAlg = certificateVerify.getAlgorithm();
verifySupportedSignatureAlgorithm(securityParameters.getClientSigAlgs(), sigAndHashAlg);
short signatureAlgorithm = sigAndHashAlg.getSignature();
// Verify the CertificateVerify message contains a correct signature.
boolean verified;
try
{
TlsVerifier verifier = verifyingCert.createVerifier(signatureAlgorithm);
if (isTLSv13(securityParameters.getNegotiatedVersion()))
{
verified = verify13CertificateVerify(clientContext.getCrypto(), certificateVerify, verifier,
"TLS 1.3, server CertificateVerify", handshakeHash);
}
else
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
catch (TlsFatalAlert e)
{
throw e;
}
catch (Exception e)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error, e);
}
if (!verified)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error);
}
}
private static boolean verify13CertificateVerify(TlsCrypto crypto, DigitallySigned certificateVerify,
TlsVerifier verifier, String contextString, TlsHandshakeHash handshakeHash) throws IOException
{
TlsStreamVerifier streamVerifier = verifier.getStreamVerifier(certificateVerify);
byte[] header = getCertificateVerifyHeader(contextString);
byte[] prfHash = getCurrentPRFHash(handshakeHash);
if (null != streamVerifier)
{
OutputStream output = streamVerifier.getOutputStream();
output.write(header, 0, header.length);
output.write(prfHash, 0, prfHash.length);
return streamVerifier.isVerified();
}
TlsHash tlsHash = crypto.createHash(certificateVerify.getAlgorithm().getHash());
tlsHash.update(header, 0, header.length);
tlsHash.update(prfHash, 0, prfHash.length);
byte[] hash = tlsHash.calculateHash();
return verifier.verifyRawSignature(certificateVerify, hash);
}
private static byte[] getCertificateVerifyHeader(String contextString)
{
int count = contextString.length();
byte[] header = new byte[64 + count + 1];
for (int i = 0; i < 64; ++i)
{
header[i] = 0x20;
}
for (int i = 0; i < count; ++i)
{
char c = contextString.charAt(i);
header[64 + i] = (byte)c;
}
header[64 + count] = 0x00;
return header;
}
static void generateServerKeyExchangeSignature(TlsContext context, TlsCredentialedSigner credentials,
DigestInputBuffer digestBuffer) throws IOException
{
/*
* RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
*/
SignatureAndHashAlgorithm algorithm = getSignatureAndHashAlgorithm(context, credentials);
TlsStreamSigner streamSigner = credentials.getStreamSigner();
byte[] signature;
if (streamSigner != null)
{
sendSignatureInput(context, digestBuffer, streamSigner.getOutputStream());
signature = streamSigner.getSignature();
}
else
{
byte[] hash = calculateSignatureHash(context, algorithm, digestBuffer);
signature = credentials.generateRawSignature(hash);
}
DigitallySigned digitallySigned = new DigitallySigned(algorithm, signature);
digitallySigned.encode(digestBuffer);
}
static void verifyServerKeyExchangeSignature(TlsContext context, InputStream signatureInput,
TlsCertificate serverCertificate, DigestInputBuffer digestBuffer) throws IOException
{
DigitallySigned digitallySigned = DigitallySigned.parse(context, signatureInput);
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
int keyExchangeAlgorithm = securityParameters.getKeyExchangeAlgorithm();
SignatureAndHashAlgorithm sigAndHashAlg = digitallySigned.getAlgorithm();
short signatureAlgorithm;
if (sigAndHashAlg == null)
{
signatureAlgorithm = getLegacySignatureAlgorithmServer(keyExchangeAlgorithm);
}
else
{
signatureAlgorithm = sigAndHashAlg.getSignature();
if (!isValidSignatureAlgorithmForServerKeyExchange(signatureAlgorithm, keyExchangeAlgorithm))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
verifySupportedSignatureAlgorithm(securityParameters.getClientSigAlgs(), sigAndHashAlg);
}
TlsVerifier verifier = serverCertificate.createVerifier(signatureAlgorithm);
TlsStreamVerifier streamVerifier = verifier.getStreamVerifier(digitallySigned);
boolean verified;
if (streamVerifier != null)
{
sendSignatureInput(context, digestBuffer, streamVerifier.getOutputStream());
verified = streamVerifier.isVerified();
}
else
{
byte[] hash = calculateSignatureHash(context, sigAndHashAlg, digestBuffer);
verified = verifier.verifyRawSignature(digitallySigned, hash);
}
if (!verified)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error);
}
}
static void trackHashAlgorithms(TlsHandshakeHash handshakeHash, Vector supportedSignatureAlgorithms)
{
if (supportedSignatureAlgorithms != null)
{
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm signatureAndHashAlgorithm = (SignatureAndHashAlgorithm)
supportedSignatureAlgorithms.elementAt(i);
short hashAlgorithm = signatureAndHashAlgorithm.getHash();
if (HashAlgorithm.Intrinsic == hashAlgorithm)
{
// TODO[RFC 8422]
handshakeHash.forceBuffering();
}
else if (HashAlgorithm.isRecognized(hashAlgorithm))
{
handshakeHash.trackHashAlgorithm(hashAlgorithm);
}
else //if (HashAlgorithm.isPrivate(hashAlgorithm))
{
// TODO Support values in the "Reserved for Private Use" range
}
}
}
}
public static boolean hasSigningCapability(short clientCertificateType)
{
switch (clientCertificateType)
{
case ClientCertificateType.dss_sign:
case ClientCertificateType.ecdsa_sign:
case ClientCertificateType.rsa_sign:
return true;
default:
return false;
}
}
public static Vector vectorOfOne(Object obj)
{
Vector v = new Vector(1);
v.addElement(obj);
return v;
}
public static int getCipherType(int cipherSuite)
{
int encryptionAlgorithm = getEncryptionAlgorithm(cipherSuite);
return getEncryptionAlgorithmType(encryptionAlgorithm);
}
public static int getEncryptionAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
return EncryptionAlgorithm._3DES_EDE_CBC;
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
return EncryptionAlgorithm.AES_128_CBC;
case CipherSuite.TLS_AES_128_CCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
return EncryptionAlgorithm.AES_128_CCM;
case CipherSuite.TLS_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
return EncryptionAlgorithm.AES_128_CCM_8;
case CipherSuite.TLS_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
return EncryptionAlgorithm.AES_128_GCM;
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return EncryptionAlgorithm.AES_256_CBC;
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
return EncryptionAlgorithm.AES_256_CCM;
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
return EncryptionAlgorithm.AES_256_CCM_8;
case CipherSuite.TLS_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
return EncryptionAlgorithm.AES_256_GCM;
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
return EncryptionAlgorithm.ARIA_128_CBC;
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
return EncryptionAlgorithm.ARIA_128_GCM;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
return EncryptionAlgorithm.ARIA_256_CBC;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
return EncryptionAlgorithm.ARIA_256_GCM;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
return EncryptionAlgorithm.CAMELLIA_128_CBC;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
return EncryptionAlgorithm.CAMELLIA_128_GCM;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
return EncryptionAlgorithm.CAMELLIA_256_CBC;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
return EncryptionAlgorithm.CAMELLIA_256_GCM;
case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
return EncryptionAlgorithm.CHACHA20_POLY1305;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
return EncryptionAlgorithm.SEED_CBC;
default:
return -1;
}
}
public static int getEncryptionAlgorithmType(int encryptionAlgorithm)
{
switch (encryptionAlgorithm)
{
case EncryptionAlgorithm.AES_128_CCM:
case EncryptionAlgorithm.AES_128_CCM_8:
case EncryptionAlgorithm.AES_128_GCM:
case EncryptionAlgorithm.AES_256_CCM:
case EncryptionAlgorithm.AES_256_CCM_8:
case EncryptionAlgorithm.AES_256_GCM:
case EncryptionAlgorithm.ARIA_128_GCM:
case EncryptionAlgorithm.ARIA_256_GCM:
case EncryptionAlgorithm.CAMELLIA_128_GCM:
case EncryptionAlgorithm.CAMELLIA_256_GCM:
case EncryptionAlgorithm.CHACHA20_POLY1305:
return CipherType.aead;
case EncryptionAlgorithm.RC2_CBC_40:
case EncryptionAlgorithm.IDEA_CBC:
case EncryptionAlgorithm.DES40_CBC:
case EncryptionAlgorithm.DES_CBC:
case EncryptionAlgorithm._3DES_EDE_CBC:
case EncryptionAlgorithm.AES_128_CBC:
case EncryptionAlgorithm.AES_256_CBC:
case EncryptionAlgorithm.ARIA_128_CBC:
case EncryptionAlgorithm.ARIA_256_CBC:
case EncryptionAlgorithm.CAMELLIA_128_CBC:
case EncryptionAlgorithm.CAMELLIA_256_CBC:
case EncryptionAlgorithm.SEED_CBC:
return CipherType.block;
case EncryptionAlgorithm.NULL:
case EncryptionAlgorithm.RC4_40:
case EncryptionAlgorithm.RC4_128:
return CipherType.stream;
default:
return -1;
}
}
public static int getKeyExchangeAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_anon;
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_DSS;
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_RSA;
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DHE_DSS;
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
return KeyExchangeAlgorithm.DHE_PSK;
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DHE_RSA;
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
return KeyExchangeAlgorithm.ECDH_anon;
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
return KeyExchangeAlgorithm.ECDH_ECDSA;
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
return KeyExchangeAlgorithm.ECDH_RSA;
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
return KeyExchangeAlgorithm.ECDHE_ECDSA;
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
return KeyExchangeAlgorithm.ECDHE_PSK;
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
return KeyExchangeAlgorithm.ECDHE_RSA;
case CipherSuite.TLS_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_AES_128_CCM_SHA256:
case CipherSuite.TLS_AES_128_GCM_SHA256:
case CipherSuite.TLS_AES_256_GCM_SHA384:
case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:
return KeyExchangeAlgorithm.NULL;
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
return KeyExchangeAlgorithm.PSK;
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.RSA;
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
return KeyExchangeAlgorithm.RSA_PSK;
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP;
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP_DSS;
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP_RSA;
default:
return -1;
}
}
public static Vector getKeyExchangeAlgorithms(int[] cipherSuites)
{
Vector result = new Vector();
if (null != cipherSuites)
{
for (int i = 0; i < cipherSuites.length; ++i)
{
addToSet(result, getKeyExchangeAlgorithm(cipherSuites[i]));
}
result.removeElement(Integers.valueOf(-1));
}
return result;
}
public static int getMACAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_AES_128_CCM_SHA256:
case CipherSuite.TLS_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_AES_128_GCM_SHA256:
case CipherSuite.TLS_AES_256_GCM_SHA384:
case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
return MACAlgorithm._null;
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return MACAlgorithm.hmac_sha1;
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return MACAlgorithm.hmac_sha256;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
return MACAlgorithm.hmac_sha384;
default:
return -1;
}
}
public static ProtocolVersion getMinimumVersion(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_AES_128_CCM_SHA256:
case CipherSuite.TLS_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_AES_128_GCM_SHA256:
case CipherSuite.TLS_AES_256_GCM_SHA384:
case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:
return ProtocolVersion.TLSv13;
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return ProtocolVersion.TLSv12;
default:
return ProtocolVersion.SSLv3;
}
}
public static Vector getNamedGroupRoles(int[] cipherSuites)
{
return getNamedGroupRoles(getKeyExchangeAlgorithms(cipherSuites));
}
public static Vector getNamedGroupRoles(Vector keyExchangeAlgorithms)
{
Vector result = new Vector();
for (int i = 0; i < keyExchangeAlgorithms.size(); ++i)
{
int keyExchangeAlgorithm = ((Integer)keyExchangeAlgorithms.elementAt(i)).intValue();
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_anon:
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_PSK:
case KeyExchangeAlgorithm.DHE_RSA:
{
addToSet(result, NamedGroupRole.dh);
break;
}
case KeyExchangeAlgorithm.ECDH_anon:
case KeyExchangeAlgorithm.ECDH_RSA:
case KeyExchangeAlgorithm.ECDHE_PSK:
case KeyExchangeAlgorithm.ECDHE_RSA:
{
addToSet(result, NamedGroupRole.ecdh);
break;
}
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
{
addToSet(result, NamedGroupRole.ecdh);
addToSet(result, NamedGroupRole.ecdsa);
break;
}
case KeyExchangeAlgorithm.NULL:
{
// TODO[tls13] We're conservatively adding both here, though maybe only one is needed
addToSet(result, NamedGroupRole.dh);
addToSet(result, NamedGroupRole.ecdh);
break;
}
}
}
return result;
}
public static boolean isAEADCipherSuite(int cipherSuite) throws IOException
{
return CipherType.aead == getCipherType(cipherSuite);
}
public static boolean isBlockCipherSuite(int cipherSuite) throws IOException
{
return CipherType.block == getCipherType(cipherSuite);
}
public static boolean isStreamCipherSuite(int cipherSuite) throws IOException
{
return CipherType.stream == getCipherType(cipherSuite);
}
/**
* @return Whether a server can select the specified cipher suite given the available signature
* algorithms for ServerKeyExchange.
*/
public static boolean isValidCipherSuiteForSignatureAlgorithms(int cipherSuite, Vector sigAlgs)
{
final int keyExchangeAlgorithm = getKeyExchangeAlgorithm(cipherSuite);
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.NULL:
case KeyExchangeAlgorithm.SRP_RSA:
case KeyExchangeAlgorithm.SRP_DSS:
break;
default:
return true;
}
int count = sigAlgs.size();
for (int i = 0; i < count; ++i)
{
Short sigAlg = (Short)sigAlgs.elementAt(i);
if (null != sigAlg)
{
short signatureAlgorithm = sigAlg.shortValue();
if (isValidSignatureAlgorithmForServerKeyExchange(signatureAlgorithm, keyExchangeAlgorithm))
{
return true;
}
}
}
return false;
}
/**
* @deprecated Use {@link #isValidVersionForCipherSuite(int, ProtocolVersion)} instead.
*/
public static boolean isValidCipherSuiteForVersion(int cipherSuite, ProtocolVersion version)
{
return isValidVersionForCipherSuite(cipherSuite, version);
}
static boolean isValidCipherSuiteSelection(int[] offeredCipherSuites, int cipherSuite)
{
return null != offeredCipherSuites
&& Arrays.contains(offeredCipherSuites, cipherSuite)
&& CipherSuite.TLS_NULL_WITH_NULL_NULL != cipherSuite
&& !CipherSuite.isSCSV(cipherSuite);
}
static boolean isValidKeyShareSelection(ProtocolVersion negotiatedVersion, int[] clientSupportedGroups,
Hashtable clientAgreements, int keyShareGroup)
{
return null != clientSupportedGroups
&& Arrays.contains(clientSupportedGroups, keyShareGroup)
&& !clientAgreements.containsKey(Integers.valueOf(keyShareGroup))
&& NamedGroup.canBeNegotiated(keyShareGroup, negotiatedVersion);
}
static boolean isValidSignatureAlgorithmForCertificateVerify(short signatureAlgorithm, short[] clientCertificateTypes)
{
short clientCertificateType = SignatureAlgorithm.getClientCertificateType(signatureAlgorithm);
return clientCertificateType >= 0 && Arrays.contains(clientCertificateTypes, clientCertificateType);
}
static boolean isValidSignatureAlgorithmForServerKeyExchange(short signatureAlgorithm, int keyExchangeAlgorithm)
{
// TODO [tls13]
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.SRP_RSA:
switch (signatureAlgorithm)
{
case SignatureAlgorithm.rsa:
case SignatureAlgorithm.rsa_pss_rsae_sha256:
case SignatureAlgorithm.rsa_pss_rsae_sha384:
case SignatureAlgorithm.rsa_pss_rsae_sha512:
case SignatureAlgorithm.rsa_pss_pss_sha256:
case SignatureAlgorithm.rsa_pss_pss_sha384:
case SignatureAlgorithm.rsa_pss_pss_sha512:
return true;
default:
return false;
}
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.SRP_DSS:
return SignatureAlgorithm.dsa == signatureAlgorithm;
case KeyExchangeAlgorithm.ECDHE_ECDSA:
switch (signatureAlgorithm)
{
case SignatureAlgorithm.ecdsa:
case SignatureAlgorithm.ed25519:
case SignatureAlgorithm.ed448:
return true;
default:
return false;
}
case KeyExchangeAlgorithm.NULL:
return SignatureAlgorithm.anonymous != signatureAlgorithm;
default:
return false;
}
}
public static boolean isValidSignatureSchemeForServerKeyExchange(int signatureScheme, int keyExchangeAlgorithm)
{
short signatureAlgorithm = SignatureScheme.getSignatureAlgorithm(signatureScheme);
return isValidSignatureAlgorithmForServerKeyExchange(signatureAlgorithm, keyExchangeAlgorithm);
}
public static boolean isValidVersionForCipherSuite(int cipherSuite, ProtocolVersion version)
{
version = version.getEquivalentTLSVersion();
ProtocolVersion minimumVersion = getMinimumVersion(cipherSuite);
if (minimumVersion == version)
{
return true;
}
if (!minimumVersion.isEarlierVersionOf(version))
{
return false;
}
return ProtocolVersion.TLSv13.isEqualOrEarlierVersionOf(minimumVersion)
|| ProtocolVersion.TLSv13.isLaterVersionOf(version);
}
public static SignatureAndHashAlgorithm chooseSignatureAndHashAlgorithm(TlsContext context, Vector sigHashAlgs, short signatureAlgorithm)
throws IOException
{
if (!isTLSv12(context))
{
return null;
}
if (sigHashAlgs == null)
{
/*
* TODO[tls13] RFC 8446 4.2.3 Clients which desire the server to authenticate itself via
* a certificate MUST send the "signature_algorithms" extension.
*/
sigHashAlgs = getDefaultSignatureAlgorithms(signatureAlgorithm);
}
SignatureAndHashAlgorithm result = null;
for (int i = 0; i < sigHashAlgs.size(); ++i)
{
SignatureAndHashAlgorithm sigHashAlg = (SignatureAndHashAlgorithm)sigHashAlgs.elementAt(i);
if (sigHashAlg.getSignature() == signatureAlgorithm)
{
short hash = sigHashAlg.getHash();
if (hash < MINIMUM_HASH_STRICT)
{
continue;
}
if (result == null)
{
result = sigHashAlg;
continue;
}
short current = result.getHash();
if (current < MINIMUM_HASH_PREFERRED)
{
if (hash > current)
{
result = sigHashAlg;
}
}
else if (hash >= MINIMUM_HASH_PREFERRED)
{
if (hash < current)
{
result = sigHashAlg;
}
}
}
}
if (result == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return result;
}
public static Vector getUsableSignatureAlgorithms(Vector sigHashAlgs)
{
if (sigHashAlgs == null)
{
Vector v = new Vector(3);
v.addElement(Shorts.valueOf(SignatureAlgorithm.rsa));
v.addElement(Shorts.valueOf(SignatureAlgorithm.dsa));
v.addElement(Shorts.valueOf(SignatureAlgorithm.ecdsa));
return v;
}
Vector v = new Vector();
for (int i = 0; i < sigHashAlgs.size(); ++i)
{
SignatureAndHashAlgorithm sigHashAlg = (SignatureAndHashAlgorithm)sigHashAlgs.elementAt(i);
if (sigHashAlg.getHash() >= MINIMUM_HASH_STRICT)
{
Short sigAlg = Shorts.valueOf(sigHashAlg.getSignature());
if (!v.contains(sigAlg))
{
// TODO Check for crypto support before choosing (or pass in cached list?)
v.addElement(sigAlg);
}
}
}
return v;
}
public static int[] getCommonCipherSuites(int[] peerCipherSuites, int[] localCipherSuites, boolean useLocalOrder)
{
int[] ordered = peerCipherSuites, unordered = localCipherSuites;
if (useLocalOrder)
{
ordered = localCipherSuites;
unordered = peerCipherSuites;
}
int count = 0, limit = Math.min(ordered.length, unordered.length);
int[] candidates = new int[limit];
for (int i = 0; i < ordered.length; ++i)
{
int candidate = ordered[i];
if (!contains(candidates, 0, count, candidate)
&& Arrays.contains(unordered, candidate))
{
candidates[count++] = candidate;
}
}
if (count < limit)
{
candidates = Arrays.copyOf(candidates, count);
}
return candidates;
}
public static int[] getSupportedCipherSuites(TlsCrypto crypto, int[] suites)
{
return getSupportedCipherSuites(crypto, suites, suites.length);
}
public static int[] getSupportedCipherSuites(TlsCrypto crypto, int[] suites, int suitesCount)
{
int[] supported = new int[suitesCount];
int count = 0;
for (int i = 0; i < suitesCount; ++i)
{
int suite = suites[i];
if (isSupportedCipherSuite(crypto, suite))
{
supported[count++] = suite;
}
}
if (count < suitesCount)
{
supported = Arrays.copyOf(supported, count);
}
return supported;
}
public static boolean isSupportedCipherSuite(TlsCrypto crypto, int cipherSuite)
{
return isSupportedKeyExchange(crypto, getKeyExchangeAlgorithm(cipherSuite))
&& crypto.hasEncryptionAlgorithm(getEncryptionAlgorithm(cipherSuite))
&& crypto.hasMacAlgorithm(getMACAlgorithm(cipherSuite));
}
public static boolean isSupportedKeyExchange(TlsCrypto crypto, int keyExchangeAlgorithm)
{
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_anon:
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DHE_PSK:
return crypto.hasDHAgreement();
case KeyExchangeAlgorithm.DHE_DSS:
return crypto.hasDHAgreement()
&& crypto.hasSignatureAlgorithm(SignatureAlgorithm.dsa);
case KeyExchangeAlgorithm.DHE_RSA:
return crypto.hasDHAgreement()
&& hasAnyRSASigAlgs(crypto);
case KeyExchangeAlgorithm.ECDH_anon:
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDH_RSA:
case KeyExchangeAlgorithm.ECDHE_PSK:
return crypto.hasECDHAgreement();
case KeyExchangeAlgorithm.ECDHE_ECDSA:
return crypto.hasECDHAgreement()
&& (crypto.hasSignatureAlgorithm(SignatureAlgorithm.ecdsa)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.ed25519)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.ed448));
case KeyExchangeAlgorithm.ECDHE_RSA:
return crypto.hasECDHAgreement()
&& hasAnyRSASigAlgs(crypto);
case KeyExchangeAlgorithm.NULL:
case KeyExchangeAlgorithm.PSK:
return true;
case KeyExchangeAlgorithm.RSA:
case KeyExchangeAlgorithm.RSA_PSK:
return crypto.hasRSAEncryption();
case KeyExchangeAlgorithm.SRP:
return crypto.hasSRPAuthentication();
case KeyExchangeAlgorithm.SRP_DSS:
return crypto.hasSRPAuthentication()
&& crypto.hasSignatureAlgorithm(SignatureAlgorithm.dsa);
case KeyExchangeAlgorithm.SRP_RSA:
return crypto.hasSRPAuthentication()
&& hasAnyRSASigAlgs(crypto);
default:
return false;
}
}
static boolean hasAnyRSASigAlgs(TlsCrypto crypto)
{
return crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha256)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha384)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha512)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha256)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha384)
|| crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha512);
}
static byte[] getCurrentPRFHash(TlsHandshakeHash handshakeHash)
{
return handshakeHash.forkPRFHash().calculateHash();
}
static void sealHandshakeHash(TlsContext context, TlsHandshakeHash handshakeHash, boolean forceBuffering)
{
if (forceBuffering || !context.getCrypto().hasAllRawSignatureAlgorithms())
{
handshakeHash.forceBuffering();
}
handshakeHash.sealHashAlgorithms();
}
private static TlsKeyExchange createKeyExchangeClient(TlsClient client, int keyExchange) throws IOException
{
TlsKeyExchangeFactory factory = client.getKeyExchangeFactory();
switch (keyExchange)
{
case KeyExchangeAlgorithm.DH_anon:
return factory.createDHanonKeyExchangeClient(keyExchange, client.getDHGroupVerifier());
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
return factory.createDHKeyExchange(keyExchange);
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_RSA:
return factory.createDHEKeyExchangeClient(keyExchange, client.getDHGroupVerifier());
case KeyExchangeAlgorithm.ECDH_anon:
return factory.createECDHanonKeyExchangeClient(keyExchange);
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDH_RSA:
return factory.createECDHKeyExchange(keyExchange);
case KeyExchangeAlgorithm.ECDHE_ECDSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
return factory.createECDHEKeyExchangeClient(keyExchange);
case KeyExchangeAlgorithm.RSA:
return factory.createRSAKeyExchange(keyExchange);
case KeyExchangeAlgorithm.DHE_PSK:
return factory.createPSKKeyExchangeClient(keyExchange, client.getPSKIdentity(),
client.getDHGroupVerifier());
case KeyExchangeAlgorithm.ECDHE_PSK:
case KeyExchangeAlgorithm.PSK:
case KeyExchangeAlgorithm.RSA_PSK:
return factory.createPSKKeyExchangeClient(keyExchange, client.getPSKIdentity(), null);
case KeyExchangeAlgorithm.SRP:
case KeyExchangeAlgorithm.SRP_DSS:
case KeyExchangeAlgorithm.SRP_RSA:
return factory.createSRPKeyExchangeClient(keyExchange, client.getSRPIdentity(),
client.getSRPConfigVerifier());
default:
/*
* Note: internal error here; the TlsProtocol implementation verifies that the
* server-selected cipher suite was in the list of client-offered cipher suites, so if
* we now can't produce an implementation, we shouldn't have offered it!
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
private static TlsKeyExchange createKeyExchangeServer(TlsServer server, int keyExchange) throws IOException
{
TlsKeyExchangeFactory factory = server.getKeyExchangeFactory();
switch (keyExchange)
{
case KeyExchangeAlgorithm.DH_anon:
return factory.createDHanonKeyExchangeServer(keyExchange, server.getDHConfig());
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_RSA:
return factory.createDHKeyExchange(keyExchange);
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_RSA:
return factory.createDHEKeyExchangeServer(keyExchange, server.getDHConfig());
case KeyExchangeAlgorithm.ECDH_anon:
return factory.createECDHanonKeyExchangeServer(keyExchange, server.getECDHConfig());
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDH_RSA:
return factory.createECDHKeyExchange(keyExchange);
case KeyExchangeAlgorithm.ECDHE_ECDSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
return factory.createECDHEKeyExchangeServer(keyExchange, server.getECDHConfig());
case KeyExchangeAlgorithm.RSA:
return factory.createRSAKeyExchange(keyExchange);
case KeyExchangeAlgorithm.DHE_PSK:
return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), server.getDHConfig(),
null);
case KeyExchangeAlgorithm.ECDHE_PSK:
return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), null, server.getECDHConfig());
case KeyExchangeAlgorithm.PSK:
case KeyExchangeAlgorithm.RSA_PSK:
return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), null, null);
case KeyExchangeAlgorithm.SRP:
case KeyExchangeAlgorithm.SRP_DSS:
case KeyExchangeAlgorithm.SRP_RSA:
return factory.createSRPKeyExchangeServer(keyExchange, server.getSRPLoginParameters());
default:
/*
* Note: internal error here; the TlsProtocol implementation verifies that the
* server-selected cipher suite was in the list of client-offered cipher suites, so if
* we now can't produce an implementation, we shouldn't have offered it!
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
static TlsKeyExchange initKeyExchangeClient(TlsClientContext clientContext, TlsClient client) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
TlsKeyExchange keyExchange = createKeyExchangeClient(client, securityParameters.getKeyExchangeAlgorithm());
keyExchange.init(clientContext);
return keyExchange;
}
static TlsKeyExchange initKeyExchangeServer(TlsServerContext serverContext, TlsServer server) throws IOException
{
SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake();
TlsKeyExchange keyExchange = createKeyExchangeServer(server, securityParameters.getKeyExchangeAlgorithm());
keyExchange.init(serverContext);
return keyExchange;
}
static TlsCipher initCipher(TlsContext context) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
int cipherSuite = securityParameters.getCipherSuite();
int encryptionAlgorithm = getEncryptionAlgorithm(cipherSuite);
int macAlgorithm = getMACAlgorithm(cipherSuite);
if (encryptionAlgorithm < 0 || macAlgorithm < 0)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return context.getCrypto().createCipher(new TlsCryptoParameters(context), encryptionAlgorithm, macAlgorithm);
}
/**
* Check the signature algorithm for certificates in the peer's CertPath as specified in RFC
* 5246 7.4.2, 7.4.4, 7.4.6 and similar rules for earlier TLS versions. The supplied CertPath
* should include the trust anchor (its signature algorithm isn't checked, but in the general
* case checking a certificate requires the issuer certificate).
*
* @throws IOException
* if any certificate in the CertPath (excepting the trust anchor) has a signature
* algorithm that is not one of the locally supported signature algorithms.
*/
public static void checkPeerSigAlgs(TlsContext context, TlsCertificate[] peerCertPath) throws IOException
{
if (context.isServer())
{
checkSigAlgOfClientCerts(context, peerCertPath);
}
else
{
checkSigAlgOfServerCerts(context, peerCertPath);
}
}
private static void checkSigAlgOfClientCerts(TlsContext context, TlsCertificate[] clientCertPath) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
short[] clientCertTypes = securityParameters.getClientCertTypes();
Vector serverSigAlgsCert = securityParameters.getServerSigAlgsCert();
int trustAnchorPos = clientCertPath.length - 1;
for (int i = 0; i < trustAnchorPos; ++i)
{
TlsCertificate subjectCert = clientCertPath[i];
TlsCertificate issuerCert = clientCertPath[i + 1];
SignatureAndHashAlgorithm sigAndHashAlg = getCertSigAndHashAlg(subjectCert, issuerCert);
boolean valid = false;
if (null == sigAndHashAlg)
{
// We don't recognize the 'signatureAlgorithm' of the certificate
}
else if (null == serverSigAlgsCert)
{
// TODO Review this (legacy) logic with RFC 4346 (7.4?.2?)
if (null != clientCertTypes)
{
for (int j = 0; j < clientCertTypes.length; ++j)
{
short signatureAlgorithm = getLegacySignatureAlgorithmClientCert(clientCertTypes[j]);
if (sigAndHashAlg.getSignature() == signatureAlgorithm)
{
valid = true;
break;
}
}
}
}
else
{
/*
* RFC 5246 7.4.4 Any certificates provided by the client MUST be signed using a
* hash/signature algorithm pair found in supported_signature_algorithms.
*/
valid = containsSignatureAlgorithm(serverSigAlgsCert, sigAndHashAlg);
}
if (!valid)
{
throw new TlsFatalAlert(AlertDescription.bad_certificate);
}
}
}
private static void checkSigAlgOfServerCerts(TlsContext context, TlsCertificate[] serverCertPath) throws IOException
{
SecurityParameters securityParameters = context.getSecurityParametersHandshake();
Vector clientSigAlgsCert = securityParameters.getClientSigAlgsCert();
Vector clientSigAlgs = securityParameters.getClientSigAlgs();
/*
* NOTE: For TLS 1.2, we'll check 'signature_algorithms' too (if it's distinct), since
* there's no way of knowing whether the server understood 'signature_algorithms_cert'.
*/
if (clientSigAlgs == clientSigAlgsCert || isTLSv13(securityParameters.getNegotiatedVersion()))
{
clientSigAlgs = null;
}
int trustAnchorPos = serverCertPath.length - 1;
for (int i = 0; i < trustAnchorPos; ++i)
{
TlsCertificate subjectCert = serverCertPath[i];
TlsCertificate issuerCert = serverCertPath[i + 1];
SignatureAndHashAlgorithm sigAndHashAlg = getCertSigAndHashAlg(subjectCert, issuerCert);
boolean valid = false;
if (null == sigAndHashAlg)
{
// We don't recognize the 'signatureAlgorithm' of the certificate
}
else if (null == clientSigAlgsCert)
{
/*
* RFC 4346 7.4.2. Unless otherwise specified, the signing algorithm for the
* certificate MUST be the same as the algorithm for the certificate key.
*/
short signatureAlgorithm = getLegacySignatureAlgorithmServerCert(
securityParameters.getKeyExchangeAlgorithm());
valid = (signatureAlgorithm == sigAndHashAlg.getSignature());
}
else
{
/*
* RFC 5246 7.4.2. If the client provided a "signature_algorithms" extension, then
* all certificates provided by the server MUST be signed by a hash/signature algorithm
* pair that appears in that extension.
*/
valid = containsSignatureAlgorithm(clientSigAlgsCert, sigAndHashAlg)
|| (null != clientSigAlgs && containsSignatureAlgorithm(clientSigAlgs, sigAndHashAlg));
}
if (!valid)
{
throw new TlsFatalAlert(AlertDescription.bad_certificate);
}
}
}
static void checkTlsFeatures(Certificate serverCertificate, Hashtable clientExtensions, Hashtable serverExtensions) throws IOException
{
/*
* RFC 7633 4.3.3. A client MUST treat a certificate with a TLS feature extension as an
* invalid certificate if the features offered by the server do not contain all features
* present in both the client's ClientHello message and the TLS feature extension.
*/
byte[] tlsFeatures = serverCertificate.getCertificateAt(0).getExtension(TlsObjectIdentifiers.id_pe_tlsfeature);
if (tlsFeatures != null)
{
Enumeration tlsExtensions = ((ASN1Sequence)readDERObject(tlsFeatures)).getObjects();
while (tlsExtensions.hasMoreElements())
{
BigInteger tlsExtension = ((ASN1Integer)tlsExtensions.nextElement()).getPositiveValue();
if (tlsExtension.bitLength() <= 16)
{
Integer extensionType = Integers.valueOf(tlsExtension.intValue());
if (clientExtensions.containsKey(extensionType) && !serverExtensions.containsKey(extensionType))
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
}
}
}
}
static void processClientCertificate(TlsServerContext serverContext, Certificate clientCertificate,
TlsKeyExchange keyExchange, TlsServer server) throws IOException
{
SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake();
if (null != securityParameters.getPeerCertificate())
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
if (clientCertificate.isEmpty())
{
/*
* NOTE: We tolerate SSLv3 clients sending an empty chain, although "If no suitable
* certificate is available, the client should send a no_certificate alert instead".
*/
keyExchange.skipClientCredentials();
}
else
{
keyExchange.processClientCertificate(clientCertificate);
}
securityParameters.peerCertificate = clientCertificate;
/*
* RFC 5246 7.4.6. If the client does not send any certificates, the server MAY at its
* discretion either continue the handshake without client authentication, or respond with a
* fatal handshake_failure alert. Also, if some aspect of the certificate chain was
* unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its
* discretion either continue the handshake (considering the client unauthenticated) or send
* a fatal alert.
*/
server.notifyClientCertificate(clientCertificate);
}
static void processServerCertificate(TlsClientContext clientContext,
CertificateStatus serverCertificateStatus, TlsKeyExchange keyExchange, TlsAuthentication clientAuthentication,
Hashtable clientExtensions, Hashtable serverExtensions) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
boolean isTLSv13 = TlsUtils.isTLSv13(securityParameters.getNegotiatedVersion());
if (null == clientAuthentication)
{
if (isTLSv13)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
// There was no server certificate message; check it's OK
keyExchange.skipServerCredentials();
securityParameters.tlsServerEndPoint = EMPTY_BYTES;
return;
}
Certificate serverCertificate = securityParameters.getPeerCertificate();
checkTlsFeatures(serverCertificate, clientExtensions, serverExtensions);
if (!isTLSv13)
{
keyExchange.processServerCertificate(serverCertificate);
}
clientAuthentication.notifyServerCertificate(new TlsServerCertificateImpl(serverCertificate, serverCertificateStatus));
}
static SignatureAndHashAlgorithm getCertSigAndHashAlg(TlsCertificate subjectCert, TlsCertificate issuerCert)
throws IOException
{
String sigAlgOID = subjectCert.getSigAlgOID();
if (null != sigAlgOID)
{
if (!PKCSObjectIdentifiers.id_RSASSA_PSS.getId().equals(sigAlgOID))
{
return (SignatureAndHashAlgorithm)CERT_SIG_ALG_OIDS.get(sigAlgOID);
}
RSASSAPSSparams pssParams = RSASSAPSSparams.getInstance(subjectCert.getSigAlgParams());
if (null != pssParams)
{
ASN1ObjectIdentifier hashOID = pssParams.getHashAlgorithm().getAlgorithm();
if (NISTObjectIdentifiers.id_sha256.equals(hashOID))
{
if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_pss_sha256))
{
return SignatureAndHashAlgorithm.rsa_pss_pss_sha256;
}
else if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_rsae_sha256))
{
return SignatureAndHashAlgorithm.rsa_pss_rsae_sha256;
}
}
else if (NISTObjectIdentifiers.id_sha384.equals(hashOID))
{
if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_pss_sha384))
{
return SignatureAndHashAlgorithm.rsa_pss_pss_sha384;
}
else if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_rsae_sha384))
{
return SignatureAndHashAlgorithm.rsa_pss_rsae_sha384;
}
}
else if (NISTObjectIdentifiers.id_sha512.equals(hashOID))
{
if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_pss_sha512))
{
return SignatureAndHashAlgorithm.rsa_pss_pss_sha512;
}
else if (issuerCert.supportsSignatureAlgorithmCA(SignatureAlgorithm.rsa_pss_rsae_sha512))
{
return SignatureAndHashAlgorithm.rsa_pss_rsae_sha512;
}
}
}
}
return null;
}
static CertificateRequest validateCertificateRequest(CertificateRequest certificateRequest, TlsKeyExchange keyExchange)
throws IOException
{
short[] validClientCertificateTypes = keyExchange.getClientCertificateTypes();
if (validClientCertificateTypes == null || validClientCertificateTypes.length < 1)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
certificateRequest = normalizeCertificateRequest(certificateRequest, validClientCertificateTypes);
if (certificateRequest == null)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
return certificateRequest;
}
static CertificateRequest normalizeCertificateRequest(CertificateRequest certificateRequest, short[] validClientCertificateTypes)
{
if (containsAll(validClientCertificateTypes, certificateRequest.getCertificateTypes()))
{
return certificateRequest;
}
short[] retained = retainAll(certificateRequest.getCertificateTypes(), validClientCertificateTypes);
if (retained.length < 1)
{
return null;
}
// TODO Filter for unique sigAlgs/CAs only
return new CertificateRequest(retained, certificateRequest.getSupportedSignatureAlgorithms(),
certificateRequest.getCertificateAuthorities());
}
static boolean contains(int[] buf, int off, int len, int value)
{
for (int i = 0; i < len; ++i)
{
if (value == buf[off + i])
{
return true;
}
}
return false;
}
static boolean containsAll(short[] container, short[] elements)
{
for (int i = 0; i < elements.length; ++i)
{
if (!Arrays.contains(container, elements[i]))
{
return false;
}
}
return true;
}
static short[] retainAll(short[] retainer, short[] elements)
{
short[] retained = new short[Math.min(retainer.length, elements.length)];
int count = 0;
for (int i = 0; i < elements.length; ++i)
{
if (Arrays.contains(retainer, elements[i]))
{
retained[count++] = elements[i];
}
}
return truncate(retained, count);
}
static short[] truncate(short[] a, int n)
{
if (n < a.length)
{
return a;
}
short[] t = new short[n];
System.arraycopy(a, 0, t, 0, n);
return t;
}
static TlsCredentialedAgreement requireAgreementCredentials(TlsCredentials credentials)
throws IOException
{
if (!(credentials instanceof TlsCredentialedAgreement))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return (TlsCredentialedAgreement)credentials;
}
static TlsCredentialedDecryptor requireDecryptorCredentials(TlsCredentials credentials)
throws IOException
{
if (!(credentials instanceof TlsCredentialedDecryptor))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return (TlsCredentialedDecryptor)credentials;
}
static TlsCredentialedSigner requireSignerCredentials(TlsCredentials credentials)
throws IOException
{
if (!(credentials instanceof TlsCredentialedSigner))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return (TlsCredentialedSigner)credentials;
}
private static void checkDowngradeMarker(byte[] randomBlock, byte[] downgradeMarker) throws IOException
{
int len = downgradeMarker.length;
if (constantTimeAreEqual(len, downgradeMarker, 0, randomBlock, randomBlock.length - len))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
static void checkDowngradeMarker(ProtocolVersion version, byte[] randomBlock) throws IOException
{
version = version.getEquivalentTLSVersion();
if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv11))
{
checkDowngradeMarker(randomBlock, DOWNGRADE_TLS11);
}
if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv12))
{
checkDowngradeMarker(randomBlock, DOWNGRADE_TLS12);
}
}
static void writeDowngradeMarker(ProtocolVersion version, byte[] randomBlock) throws IOException
{
version = version.getEquivalentTLSVersion();
byte[] marker;
if (ProtocolVersion.TLSv12 == version)
{
marker = DOWNGRADE_TLS12;
}
else if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv11))
{
marker = DOWNGRADE_TLS11;
}
else
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
System.arraycopy(marker, 0, randomBlock, randomBlock.length - marker.length, marker.length);
}
static TlsAuthentication receiveServerCertificate(TlsClientContext clientContext, TlsClient client,
ByteArrayInputStream buf) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
if (null != securityParameters.getPeerCertificate())
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
ByteArrayOutputStream endPointHash = new ByteArrayOutputStream();
Certificate serverCertificate = Certificate.parse(clientContext, buf, endPointHash);
TlsProtocol.assertEmpty(buf);
if (TlsUtils.isTLSv13(securityParameters.getNegotiatedVersion()))
{
if (serverCertificate.getCertificateRequestContext().length > 0)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
if (serverCertificate.isEmpty())
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
securityParameters.peerCertificate = serverCertificate;
securityParameters.tlsServerEndPoint = endPointHash.toByteArray();
TlsAuthentication authentication = client.getAuthentication();
if (null == authentication)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return authentication;
}
public static boolean containsNonAscii(byte[] bs)
{
for (int i = 0; i < bs.length; ++i)
{
int c = bs[i] & 0xFF;;
if (c >= 0x80)
{
return true;
}
}
return false;
}
public static boolean containsNonAscii(String s)
{
for (int i = 0; i < s.length(); ++i)
{
int c = s.charAt(i);
if (c >= 0x80)
{
return true;
}
}
return false;
}
static Hashtable addEarlyKeySharesToClientHello(TlsClientContext clientContext, TlsClient client,
Hashtable clientExtensions) throws IOException
{
/*
* RFC 8446 9.2. If containing a "supported_groups" extension, it MUST also contain a
* "key_share" extension, and vice versa. An empty KeyShare.client_shares vector is
* permitted.
*/
if (!isTLSv13(clientContext.getClientVersion())
|| !clientExtensions.containsKey(TlsExtensionsUtils.EXT_supported_groups))
{
return null;
}
int[] supportedGroups = TlsExtensionsUtils.getSupportedGroupsExtension(clientExtensions);
Vector keyShareGroups = client.getEarlyKeyShareGroups();
Hashtable clientAgreements = new Hashtable(3);
Vector clientShares = new Vector(2);
collectKeyShares(clientContext.getCrypto(), supportedGroups, keyShareGroups, clientAgreements, clientShares);
TlsExtensionsUtils.addKeyShareClientHello(clientExtensions, clientShares);
return clientAgreements;
}
static Hashtable addKeyShareToClientHelloRetry(TlsClientContext clientContext, Hashtable clientExtensions,
int keyShareGroup) throws IOException
{
int[] supportedGroups = new int[]{ keyShareGroup };
Vector keyShareGroups = vectorOfOne(Integers.valueOf(keyShareGroup));
Hashtable clientAgreements = new Hashtable(1, 1.0f);
Vector clientShares = new Vector(1);
collectKeyShares(clientContext.getCrypto(), supportedGroups, keyShareGroups, clientAgreements, clientShares);
TlsExtensionsUtils.addKeyShareClientHello(clientExtensions, clientShares);
if (clientAgreements.isEmpty() || clientShares.isEmpty())
{
// NOTE: Probable cause is declaring an unsupported NamedGroup in supported_groups extension
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return clientAgreements;
}
private static void collectKeyShares(TlsCrypto crypto, int[] supportedGroups, Vector keyShareGroups,
Hashtable clientAgreements, Vector clientShares) throws IOException
{
if (null == supportedGroups || supportedGroups.length < 1)
{
return;
}
if (null == keyShareGroups || keyShareGroups.isEmpty())
{
return;
}
for (int i = 0; i < supportedGroups.length; ++i)
{
int supportedGroup = supportedGroups[i];
Integer supportedGroupElement = Integers.valueOf(supportedGroup);
if (!keyShareGroups.contains(supportedGroupElement)
|| clientAgreements.containsKey(supportedGroupElement)
|| !crypto.hasNamedGroup(supportedGroup))
{
continue;
}
TlsAgreement agreement = null;
if (NamedGroup.refersToASpecificCurve(supportedGroup))
{
if (crypto.hasECDHAgreement())
{
agreement = crypto.createECDomain(new TlsECConfig(supportedGroup)).createECDH();
}
}
else if (NamedGroup.refersToASpecificFiniteField(supportedGroup))
{
if (crypto.hasDHAgreement())
{
agreement = crypto.createDHDomain(new TlsDHConfig(supportedGroup, true)).createDH();
}
}
if (null != agreement)
{
byte[] key_exchange = agreement.generateEphemeral();
KeyShareEntry clientShare = new KeyShareEntry(supportedGroup, key_exchange);
clientShares.addElement(clientShare);
clientAgreements.put(supportedGroupElement, agreement);
}
}
}
static byte[] readEncryptedPMS(TlsContext context, InputStream input) throws IOException
{
if (isSSL(context))
{
return SSL3Utils.readEncryptedPMS(input);
}
return readOpaque16(input);
}
static void writeEncryptedPMS(TlsContext context, byte[] encryptedPMS, OutputStream output) throws IOException
{
if (isSSL(context))
{
SSL3Utils.writeEncryptedPMS(encryptedPMS, output);
}
else
{
writeOpaque16(encryptedPMS, output);
}
}
static byte[] getSessionID(TlsSession tlsSession)
{
if (null != tlsSession)
{
byte[] sessionID = tlsSession.getSessionID();
if (null != sessionID
&& sessionID.length > 0
&& sessionID.length <= 32)
{
return sessionID;
}
}
return EMPTY_BYTES;
}
static void adjustTranscriptForRetry(TlsHandshakeHash handshakeHash)
throws IOException
{
byte[] clientHelloHash = getCurrentPRFHash(handshakeHash);
handshakeHash.reset();
int length = clientHelloHash.length;
checkUint8(length);
byte[] synthetic = new byte[4 + length];
writeUint8(HandshakeType.message_hash, synthetic, 0);
writeUint24(length, synthetic, 1);
System.arraycopy(clientHelloHash, 0, synthetic, 4, length);
handshakeHash.update(synthetic, 0, synthetic.length);
}
static TlsCredentials establishClientCredentials(TlsAuthentication clientAuthentication,
CertificateRequest certificateRequest) throws IOException
{
return validateCredentials(clientAuthentication.getClientCredentials(certificateRequest));
}
static TlsCredentialedSigner establish13ClientCredentials(TlsAuthentication clientAuthentication,
CertificateRequest certificateRequest) throws IOException
{
return validate13Credentials(clientAuthentication.getClientCredentials(certificateRequest));
}
static void establishClientSigAlgs(SecurityParameters securityParameters, Hashtable clientExtensions)
throws IOException
{
securityParameters.clientSigAlgs = TlsExtensionsUtils.getSignatureAlgorithmsExtension(clientExtensions);
securityParameters.clientSigAlgsCert = TlsExtensionsUtils.getSignatureAlgorithmsCertExtension(clientExtensions);
/*
* TODO[tls13] RFC 8446 4.2.3 Clients which desire the server to authenticate itself via a
* certificate MUST send the "signature_algorithms" extension.
*/
}
static TlsCredentials establishServerCredentials(TlsServer server) throws IOException
{
return validateCredentials(server.getCredentials());
}
static TlsCredentialedSigner establish13ServerCredentials(TlsServer server) throws IOException
{
return validate13Credentials(server.getCredentials());
}
static void establishServerSigAlgs(SecurityParameters securityParameters, CertificateRequest certificateRequest)
throws IOException
{
securityParameters.clientCertTypes = certificateRequest.getCertificateTypes();
securityParameters.serverSigAlgs = certificateRequest.getSupportedSignatureAlgorithms();
securityParameters.serverSigAlgsCert = certificateRequest.getSupportedSignatureAlgorithmsCert();
if (null == securityParameters.getServerSigAlgsCert())
{
securityParameters.serverSigAlgsCert = securityParameters.getServerSigAlgs();
}
}
static TlsCredentials validateCredentials(TlsCredentials credentials) throws IOException
{
if (null != credentials)
{
int count = 0;
count += (credentials instanceof TlsCredentialedAgreement) ? 1 : 0;
count += (credentials instanceof TlsCredentialedDecryptor) ? 1 : 0;
count += (credentials instanceof TlsCredentialedSigner) ? 1 : 0;
if (count != 1)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
return credentials;
}
static TlsCredentialedSigner validate13Credentials(TlsCredentials credentials) throws IOException
{
if (null == credentials)
{
return null;
}
if (!(credentials instanceof TlsCredentialedSigner))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return (TlsCredentialedSigner)credentials;
}
static void negotiatedCipherSuite(SecurityParameters securityParameters, int cipherSuite) throws IOException
{
securityParameters.cipherSuite = cipherSuite;
securityParameters.keyExchangeAlgorithm = getKeyExchangeAlgorithm(cipherSuite);
int prfAlgorithm = getPRFAlgorithm(securityParameters, cipherSuite);
securityParameters.prfAlgorithm = prfAlgorithm;
switch (prfAlgorithm)
{
case PRFAlgorithm.ssl_prf_legacy:
case PRFAlgorithm.tls_prf_legacy:
{
securityParameters.prfHashAlgorithm = -1;
securityParameters.prfHashLength = -1;
break;
}
default:
{
short prfHashAlgorithm = getHashAlgorithmForPRFAlgorithm(prfAlgorithm);
securityParameters.prfHashAlgorithm = prfHashAlgorithm;
securityParameters.prfHashLength = HashAlgorithm.getOutputSize(prfHashAlgorithm);
break;
}
}
/*
* TODO[tls13] We're slowly moving towards negotiating cipherSuite THEN version. We could
* move this to "after parameter negotiation" i.e. after ServerHello/EncryptedExtensions.
*/
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (isTLSv13(negotiatedVersion))
{
securityParameters.verifyDataLength = securityParameters.getPRFHashLength();
}
else
{
securityParameters.verifyDataLength = negotiatedVersion.isSSL() ? 36 : 12;
}
}
static void negotiatedVersion(SecurityParameters securityParameters) throws IOException
{
if (!isSignatureAlgorithmsExtensionAllowed(securityParameters.getNegotiatedVersion()))
{
securityParameters.clientSigAlgs = null;
securityParameters.clientSigAlgsCert = null;
return;
}
if (null == securityParameters.getClientSigAlgs())
{
securityParameters.clientSigAlgs = getLegacySupportedSignatureAlgorithms();
}
if (null == securityParameters.getClientSigAlgsCert())
{
securityParameters.clientSigAlgsCert = securityParameters.getClientSigAlgs();
}
}
static void negotiatedVersionDTLSClient(TlsClientContext clientContext, TlsClient client) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (!ProtocolVersion.isSupportedDTLSVersionClient(negotiatedVersion))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
negotiatedVersion(securityParameters);
client.notifyServerVersion(negotiatedVersion);
}
static void negotiatedVersionDTLSServer(TlsServerContext serverContext) throws IOException
{
SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (!ProtocolVersion.isSupportedDTLSVersionServer(negotiatedVersion))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
negotiatedVersion(securityParameters);
}
static void negotiatedVersionTLSClient(TlsClientContext clientContext, TlsClient client) throws IOException
{
SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (!ProtocolVersion.isSupportedTLSVersionClient(negotiatedVersion))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
negotiatedVersion(securityParameters);
client.notifyServerVersion(negotiatedVersion);
}
static void negotiatedVersionTLSServer(TlsServerContext serverContext) throws IOException
{
SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake();
ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion();
if (!ProtocolVersion.isSupportedTLSVersionServer(negotiatedVersion))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
negotiatedVersion(securityParameters);
}
static TlsSecret deriveSecret(SecurityParameters securityParameters, TlsSecret secret, String label,
byte[] transcriptHash) throws IOException
{
return TlsCryptoUtils.hkdfExpandLabel(secret, securityParameters.getPRFHashAlgorithm(), label, transcriptHash,
securityParameters.getPRFHashLength());
}
}
|
package com.dmdirc.addons.ui_swing.framemanager.tree;
import com.dmdirc.addons.ui_swing.UIUtilities;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.addons.ui_swing.actions.CloseFrameContainerAction;
import com.dmdirc.addons.ui_swing.components.TextFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyVetoException;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import net.miginfocom.layout.PlatformDefaults;
/**
* Specialised JTree for the frame manager.
*/
public class Tree extends JTree implements TreeSelectionListener,
MouseMotionListener, ConfigChangeListener, MouseListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** Drag selection enabled? */
private boolean dragSelect;
/** Tree frame manager. */
private TreeFrameManager manager;
/** Current selection path. */
private TreePath path;
/**
* Specialised JTree for frame manager.
*
* @param manager Frame manager
* @param model tree model.
*/
public Tree(final TreeFrameManager manager, final TreeModel model) {
super(model);
this.manager = manager;
putClientProperty("JTree.lineStyle", "Angled");
getInputMap().setParent(null);
getInputMap(JComponent.WHEN_FOCUSED).clear();
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).clear();
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).clear();
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
setRootVisible(false);
setRowHeight(0);
setShowsRootHandles(false);
setOpaque(true);
setBorder(BorderFactory.createEmptyBorder(
(int) PlatformDefaults.getUnitValueX("related").getValue(),
(int) PlatformDefaults.getUnitValueX("related").getValue(),
(int) PlatformDefaults.getUnitValueX("related").getValue(),
(int) PlatformDefaults.getUnitValueX("related").getValue()));
new TreeTreeScroller(this);
setFocusable(false);
dragSelect = IdentityManager.getGlobalConfig().getOptionBool("treeview",
"dragSelection");
IdentityManager.getGlobalConfig().addChangeListener("treeview",
"dragSelection", this);
addMouseListener(this);
addMouseMotionListener(this);
addTreeSelectionListener(this);
}
/**
* Set path.
*
* @param path Path
*/
public void setTreePath(final TreePath path) {
this.path = path;
}
/** {@inheritDoc} */
@Override
public void valueChanged(final TreeSelectionEvent e) {
if (!this.path.equals(path)) {
setSelection(e.getPath());
}
}
/**
* Sets the tree selection path.
*
* @param path Tree path
*/
public void setSelection(final TreePath path) {
if (this.path != null) {
setSelectionPath(path);
if (!this.path.equals(path)) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
setTreePath(path);
((TreeViewNode) path.getLastPathComponent()).getFrameContainer().activateFrame();
}
});
}
}
}
/**
* Returns the node for the specified location, returning null if rollover
* is disabled or there is no node at the specified location.
*
* @param x x coordiantes
* @param y y coordiantes
*
* @return node or null
*/
public TreeViewNode getNodeForLocation(final int x,
final int y) {
TreeViewNode node = null;
final TreePath selectedPath = getPathForLocation(x, y);
if (selectedPath != null) {
node = (TreeViewNode) selectedPath.getLastPathComponent();
}
return node;
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
dragSelect = IdentityManager.getGlobalConfig().getOptionBool("treeview",
"dragSelection");
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseDragged(final MouseEvent e) {
if (dragSelect) {
final TreeViewNode node = getNodeForLocation(e.getX(), e.getY());
if (node != null) {
setSelection(new TreePath(node.getPath()));
}
}
manager.checkRollover(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseMoved(final MouseEvent e) {
manager.checkRollover(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseClicked(MouseEvent e) {
processMouseEvents(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
final TreePath selectedPath = getPathForLocation(e.getX(), e.getY());
if (selectedPath != null) {
setSelection(selectedPath);
}
}
processMouseEvents(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseReleased(MouseEvent e) {
processMouseEvents(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseEntered(MouseEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseExited(MouseEvent e) {
manager.checkRollover(null);
}
/**
* Processes every mouse button event to check for a popup trigger.
* @param e mouse event
*/
public void processMouseEvents(final MouseEvent e) {
final TreePath localPath = getPathForLocation(e.getX(), e.getY());
if (localPath != null) {
if (e.isPopupTrigger()) {
final TextFrame frame = (TextFrame) ((TreeViewNode) localPath.getLastPathComponent()).getFrameContainer().
getFrame();
final JPopupMenu popupMenu = frame.getPopupMenu(null, "");
frame.addCustomPopupItems(popupMenu);
if (popupMenu.getComponentCount() > 0) {
popupMenu.addSeparator();
}
popupMenu.add(new JMenuItem(new CloseFrameContainerAction(frame.getContainer())));
popupMenu.show(this, e.getX(), e.getY());
}
if (((TextFrame) ((TreeViewNode) localPath.getLastPathComponent()).getFrameContainer().
getFrame()).isIcon()) {
try {
((TextFrame) ((TreeViewNode) localPath.getLastPathComponent()).getFrameContainer().
getFrame()).setIcon(false);
((TreeViewNode) localPath.getLastPathComponent()).getFrameContainer().
activateFrame();
} catch (PropertyVetoException ex) {
//Ignore
}
}
}
}
}
|
package com.esotericsoftware.reflectasm;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import java.util.ArrayList;
class AccessClassLoader extends ClassLoader {
static private final ArrayList<AccessClassLoader> accessClassLoaders = new ArrayList();
static AccessClassLoader get (Class type) {
ClassLoader parent = type.getClassLoader();
synchronized (accessClassLoaders) {
for (int i = 0, n = accessClassLoaders.size(); i < n; i++) {
AccessClassLoader accessClassLoader = accessClassLoaders.get(i);
if (accessClassLoader.getParent() == parent) return accessClassLoader;
}
AccessClassLoader accessClassLoader = new AccessClassLoader(parent);
accessClassLoaders.add(accessClassLoader);
return accessClassLoader;
}
}
static void remove (ClassLoader parent) {
synchronized (accessClassLoaders) {
for (int i = accessClassLoaders.size() - 1; i >= 0; i
AccessClassLoader accessClassLoader = accessClassLoaders.get(i);
if (accessClassLoader.getParent() == parent) accessClassLoaders.remove(i);
}
}
}
private AccessClassLoader (ClassLoader parent) {
super(parent);
}
protected synchronized java.lang.Class<?> loadClass (String name, boolean resolve) throws ClassNotFoundException {
// These classes come from the classloader that loaded AccessClassLoader.
if (name.equals(FieldAccess.class.getName())) return FieldAccess.class;
if (name.equals(MethodAccess.class.getName())) return MethodAccess.class;
if (name.equals(ConstructorAccess.class.getName())) return ConstructorAccess.class;
// All other classes come from the classloader that loaded the type we are accessing.
return super.loadClass(name, resolve);
}
Class<?> defineClass (String name, byte[] bytes) throws ClassFormatError {
try {
// Attempt to load the access class in the same loader, which makes protected and default access members accessible.
Method method = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] {String.class, byte[].class, int.class,
int.class, ProtectionDomain.class});
method.setAccessible(true);
return (Class)method.invoke(getParent(), new Object[] {name, bytes, Integer.valueOf(0), Integer.valueOf(bytes.length),
getClass().getProtectionDomain()});
} catch (Exception ignored) {
}
return defineClass(name, bytes, 0, bytes.length);
}
}
|
package com.github.andlyticsproject.console.v2;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.JsonReader;
import android.util.Log;
import com.github.andlyticsproject.console.DevConsoleException;
import com.github.andlyticsproject.model.AppDetails;
import com.github.andlyticsproject.model.AppInfo;
import com.github.andlyticsproject.model.AppStats;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.model.Revenue;
import com.github.andlyticsproject.model.RevenueSummary;
import com.github.andlyticsproject.util.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class JsonParser {
private static final String TAG = JsonParser.class.getSimpleName();
private static final boolean DEBUG = false;
private JsonParser() {
}
/**
* Parses the supplied JSON string and adds the extracted ratings to the supplied
* {@link AppStats} object
*
* @param json
* @param stats
* @throws JSONException
*/
static void parseRatings(String json, AppStats stats) throws JSONException {
// Extract just the array with the values
JSONObject values = new JSONObject(json).getJSONObject("result").getJSONArray("1")
.getJSONObject(0);
// Ratings are at index 2 - 6
stats.setRating(values.getInt("2"), values.getInt("3"), values.getInt("4"),
values.getInt("5"), values.getInt("6"));
}
/**
* Parses the supplied JSON string and adds the extracted statistics to the supplied
* {@link AppStats} object
* based on the supplied statsType
* Not used at the moment
*
* @param json
* @param stats
* @param statsType
* @throws JSONException
*/
static void parseStatistics(String json, AppStats stats, int statsType) throws JSONException {
// Extract the top level values array
JSONObject values = new JSONObject(json).getJSONObject("result").getJSONObject("1");
/*
* null
* Nested array [null, [null, Array containing historical data]]
* null
* null
* null
* Nested arrays containing summary and historical data broken down by dimension e.g.
* Android version
* null
* null
* App name
*/
// For now we just care about todays value, later we may delve into the historical and
// dimensioned data
JSONArray historicalData = values.getJSONObject("1").getJSONArray("1");
JSONObject latestData = historicalData.getJSONObject(historicalData.length() - 1);
/*
* null
* Date
* [null, value]
*/
int latestValue = latestData.getJSONObject("2").getInt("1");
switch (statsType) {
case DevConsoleV2Protocol.STATS_TYPE_TOTAL_USER_INSTALLS:
stats.setTotalDownloads(latestValue);
break;
case DevConsoleV2Protocol.STATS_TYPE_ACTIVE_DEVICE_INSTALLS:
stats.setActiveInstalls(latestValue);
break;
default:
break;
}
}
/**
* Parses the supplied JSON string and builds a list of apps from it
*
* @param json
* @param accountName
* @param skipIncomplete
* @return List of apps
* @throws JSONException
*/
static List<AppInfo> parseAppInfos(String json, String accountName, boolean skipIncomplete)
throws JSONException {
Date now = new Date();
List<AppInfo> apps = new ArrayList<AppInfo>();
// Extract the base array containing apps
JSONObject result = new JSONObject(json).getJSONObject("result");
if (DEBUG) {
pp("result", result);
}
JSONArray jsonApps = result.optJSONArray("1");
if (DEBUG) {
pp("jsonApps", jsonApps);
}
if (jsonApps == null) {
// no apps yet?
return apps;
}
int numberOfApps = jsonApps.length();
Log.d(TAG, String.format("Found %d apps in JSON", numberOfApps));
for (int i = 0; i < numberOfApps; i++) {
AppInfo app = new AppInfo();
app.setAccount(accountName);
app.setLastUpdate(now);
// Per app:
// 1 : { 1: package name,
// 2 : { 1: [{1 : lang, 2: name, 3: description, 4: ??, 5: what's new}], 2 : ?? },
// 4 : update history,
// 5 : price,
// 6 : update date,
// 7 : state?
// 3 : { 1: active dnd, 2: # ratings, 3: avg rating, 4: ???, 5: total dnd }
// arrays have changed to objects, with the index as the key
/*
* Per app:
* null
* [ APP_INFO_ARRAY
* * null
* * packageName
* * Nested array with details
* * null
* * Nested array with version details
* * Nested array with price details
* * Last update Date
* * Number [1=published, 5 = draft?]
* ]
* null
* [ APP_STATS_ARRAY
* * null,
* * Active installs
* * Total ratings
* * Average rating
* * Errors
* * Total installs
* ]
*/
JSONObject jsonApp = jsonApps.getJSONObject(i);
JSONObject jsonAppInfo = jsonApp.getJSONObject("1");
if (DEBUG) {
pp("jsonAppInfo", jsonAppInfo);
}
String packageName = jsonAppInfo.getString("1");
// Look for "tmp.7238057230750432756094760456.235728507238057230542"
if (packageName == null
|| (packageName.startsWith("tmp.") && Character.isDigit(packageName.charAt(4)))) {
Log.d(TAG, String.format("Skipping draft app %d, package name=%s", i, packageName));
continue;
// Draft app
}
// Check number code and last updated date
// Published: 1
// Unpublished: 2
// Draft: 5
// Draft w/ in-app items?: 6
// TODO figure out the rest and add don't just skip, filter, etc. Cf. #223
int publishState = jsonAppInfo.optInt("7");
Log.d(TAG, String.format("%s: publishState=%d", packageName, publishState));
if (publishState != 1) {
// Not a published app, skipping
Log.d(TAG, String.format(
"Skipping app %d with state != 1: package name=%s: state=%d", i,
packageName, publishState));
continue;
}
app.setPublishState(publishState);
app.setPackageName(packageName);
/*
* Per app details:
* 1: Country code
* 2: App Name
* 3: Description
* 4: Promo text
* 5: Last what's new
*/
// skip if we can't get all the data
// XXX should we just let this crash so we know there is a problem?
if (!jsonAppInfo.has("2")) {
if (skipIncomplete) {
Log.d(TAG, String.format(
"Skipping app %d because no app details found: package name=%s", i,
packageName));
} else {
Log.d(TAG, "Adding incomplete app: " + packageName);
apps.add(app);
}
continue;
}
if (!jsonAppInfo.has("4")) {
if (skipIncomplete) {
Log.d(TAG, String.format(
"Skipping app %d because no versions info found: package name=%s", i,
packageName));
} else {
Log.d(TAG, "Adding incomplete app: " + packageName);
apps.add(app);
}
continue;
}
JSONObject appDetails = jsonAppInfo.getJSONObject("2").getJSONArray("1")
.getJSONObject(0);
if (DEBUG) {
pp("appDetails", appDetails);
}
app.setName(appDetails.getString("2"));
String description = appDetails.getString("3");
String changelog = appDetails.optString("5");
Long lastPlayStoreUpdate = jsonAppInfo.optLong("6");
AppDetails details = new AppDetails(description, changelog, lastPlayStoreUpdate);
app.setDetails(details);
/*
* Per app version details:
* null
* null
* packageName
* versionNumber
* versionName
* null
* Array with app icon [null,null,null,icon]
*/
// XXX
JSONArray appVersions = jsonAppInfo.getJSONObject("4").getJSONObject("1")
.optJSONArray("1");
if (DEBUG) {
pp("appVersions", appVersions);
}
if (appVersions == null) {
if (skipIncomplete) {
Log.d(TAG, String.format(
"Skipping app %d because no versions info found: package name=%s", i,
packageName));
} else {
Log.d(TAG, "Adding incomplete app: " + packageName);
apps.add(app);
}
continue;
}
JSONObject lastAppVersionDetails = appVersions.getJSONObject(appVersions.length() - 1)
.getJSONObject("2");
if (DEBUG) {
pp("lastAppVersionDetails", lastAppVersionDetails);
}
app.setVersionName(lastAppVersionDetails.getString("4"));
app.setIconUrl(lastAppVersionDetails.getJSONObject("6").getString("3"));
// App stats
/*
* null,
* Active installs
* Total ratings
* Average rating
* Errors
* Total installs
*/
// XXX this index might not be correct for all apps?
// 3 : { 1: active dnd, 2: # ratings, 3: avg rating, 4: #errors?, 5: total dnd }
JSONObject jsonAppStats = jsonApp.optJSONObject("3");
if (DEBUG) {
pp("jsonAppStats", jsonAppStats);
}
if (jsonAppStats == null) {
if (skipIncomplete) {
Log.d(TAG, String.format(
"Skipping app %d because no stats found: package name=%s", i,
packageName));
} else {
Log.d(TAG, "Adding incomplete app: " + packageName);
apps.add(app);
}
continue;
}
AppStats stats = new AppStats();
stats.setDate(now);
if (jsonAppStats.length() < 4) {
// no statistics (yet?) or weird format
// TODO do we need differentiate?
stats.setActiveInstalls(0);
stats.setTotalDownloads(0);
stats.setNumberOfErrors(0);
} else {
stats.setActiveInstalls(jsonAppStats.getInt("1"));
stats.setTotalDownloads(jsonAppStats.getInt("5"));
stats.setNumberOfErrors(jsonAppStats.optInt("4"));
}
app.setLatestStats(stats);
apps.add(app);
}
return apps;
}
private static void pp(String name, JSONArray jsonArr) {
try {
String pp = jsonArr == null ? "null" : jsonArr.toString(2);
Log.d(TAG, String.format("%s: %s", name, pp));
FileUtils.writeToDebugDir(name + "-pp.json", pp);
} catch (JSONException e) {
Log.w(TAG, "Error printing JSON: " + e.getMessage(), e);
}
}
private static void pp(String name, JSONObject jsonObj) {
try {
String pp = jsonObj == null ? "null" : jsonObj.toString(2);
Log.d(TAG, String.format("%s: %s", name, pp));
FileUtils.writeToDebugDir(name + "-pp.json", pp);
} catch (JSONException e) {
Log.w(TAG, "Error printing JSON: " + e.getMessage(), e);
}
}
/**
* Parses the supplied JSON string and returns the number of comments.
*
* @param json
* @return
* @throws JSONException
*/
static int parseCommentsCount(String json) throws JSONException {
// Just extract the number of comments
/*
* null
* Array containing arrays of comments
* numberOfComments
*/
return new JSONObject(json).getJSONObject("result").getInt("2");
}
/**
* Parses the supplied JSON string and returns a list of comments.
*
* @param json
* @return
* @throws JSONException
*/
static List<Comment> parseComments(String json) throws JSONException {
List<Comment> comments = new ArrayList<Comment>();
/*
* null
* Array containing arrays of comments
* numberOfComments
*/
JSONArray jsonComments = new JSONObject(json).getJSONObject("result").getJSONArray("1");
int count = jsonComments.length();
for (int i = 0; i < count; i++) {
Comment comment = new Comment();
JSONObject jsonComment = jsonComments.getJSONObject(i);
// TODO These examples are out of date and need updating
/*
* null
* "gaia:17919762185957048423:1:vm:11887109942373535891", -- ID?
* "REVIEWERS_NAME",
* "1343652956570", -- DATE?
* RATING,
* null
* "COMMENT",
* null,
* "VERSION_NAME",
* [ null,
* "DEVICE_CODE_NAME",
* "DEVICE_MANFACTURER",
* "DEVICE_MODEL"
* ],
* "LOCALE",
* null,
* 0
*/
// Example with developer reply
/*
* [
* null,
* "gaia:12824185113034449316:1:vm:18363775304595766012",
* "Mickal",
* "1350333837326",
* 1,
* "",
* "Nul\tNul!! N'arrive pas a scanner le moindre code barre!",
* 73,
* "3.2.5",
* [
* null,
* "X10i",
* "SEMC",
* "Xperia X10"
* ],
* "fr_FR",
* [
* null,
* "Prixing fonctionne pourtant bien sur Xperia X10. Essayez de prendre un minimum de recul, au moins 20 30cm, vitez les ombres et les reflets. N'hsitez pas nous crire sur contact@prixing.fr pour une assistance personnalise."
* ,
* null,
* "1350393460968"
* ],
* 1
* ]
*/
String uniqueId = jsonComment.getString("1");
comment.setUniqueId(uniqueId);
String user = jsonComment.optString("2");
if (user != null && !"".equals(user) && !"null".equals(user)) {
comment.setUser(user);
}
comment.setDate(parseDate(jsonComment.getLong("3")));
comment.setRating(jsonComment.getInt("4"));
String version = jsonComment.optString("7");
if (version != null && !"".equals(version) && !version.equals("null")) {
comment.setAppVersion(version);
}
String commentLang = jsonComment.optJSONObject("5").getString("1");
String commentText = jsonComment.optJSONObject("5").getString("3");
comment.setLanguage(commentLang);
comment.setOriginalText(commentText);
// overwritten if translation is available
comment.setText(commentText);
JSONObject translation = jsonComment.optJSONObject("11");
if (translation != null) {
String displayLanguage = Locale.getDefault().getLanguage();
String translationLang = translation.getString("1");
String translationText = translation.getString("3");
if (translationLang.contains(displayLanguage)) {
comment.setText(translationText);
}
}
JSONObject jsonDevice = jsonComment.optJSONObject("8");
if (jsonDevice != null) {
String device = jsonDevice.optString("3");
JSONArray extraInfo = jsonDevice.optJSONArray("2");
if (extraInfo != null) {
device += " " + extraInfo.optString(0);
}
comment.setDevice(device.trim());
}
JSONObject jsonReply = jsonComment.optJSONObject("9");
if (jsonReply != null) {
Comment reply = new Comment(true);
reply.setText(jsonReply.getString("1"));
reply.setDate(parseDate(jsonReply.getLong("3")));
reply.setOriginalCommentDate(comment.getDate());
comment.setReply(reply);
}
comments.add(comment);
}
return comments;
}
static Comment parseCommentReplyResponse(String json) throws JSONException {
// {"result":{"1":{"1":"REPLY","3":"TIME_STAMP"},"2":true},"xsrf":"XSRF_TOKEN"}
// {"error":{"data":{"1":ERROR_CODE},"code":ERROR_CODE}}
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("error")) {
throw parseError(jsonObj, "replying to comments");
}
JSONObject replyObj = jsonObj.getJSONObject("result").getJSONObject("1");
Comment result = new Comment(true);
result.setText(replyObj.getString("1"));
result.setDate(parseDate(Long.parseLong(replyObj.getString("3"))));
return result;
}
private static DevConsoleException parseError(JSONObject jsonObj, String message)
throws JSONException {
JSONObject errorObj = jsonObj.getJSONObject("error");
String data = errorObj.getJSONObject("data").optString("1");
String errorCode = errorObj.optString("code");
return new DevConsoleException(String.format("Error %s: %s, errorCode=%s", message, data,
errorCode));
}
static RevenueSummary parseRevenueResponse(String json) throws JSONException {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("error")) {
throw parseError(jsonObj, "fetch revenue summary");
}
JSONObject resultObj = jsonObj.getJSONObject("result");
String currency = resultObj.optString("1");
// XXX does this really mean that the app has no revenue
if (currency == null || "".equals(currency)) {
return null;
}
// "6": "1376352000000"
long timestamp = resultObj.getLong("6");
// no time info, 00:00:00 GMT(?)
Date date = new Date(timestamp / 1000);
// 2 -total, 3 -sales, 4- in-app products
// we only use total (for now)
JSONObject revenueObj = resultObj.getJSONObject("2");
// even keys are for previous period
double lastDay = revenueObj.getDouble("1");
double last7Days = revenueObj.getDouble("3");
double last30Days = revenueObj.getDouble("5");
// NaN is treated like NULL -> DB error
double overall = revenueObj.optDouble("7", 0.0);
return RevenueSummary.createTotal(currency, date, lastDay, last7Days, last30Days, overall);
}
/**
* Parses the given date
*
* @param unixDateCode
* @return
*/
private static Date parseDate(long unixDateCode) {
return new Date(unixDateCode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static Revenue parseLatestTotalRevenue(String json) throws IOException {
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
String currency = null;
Date reportDate = null;
Date revenueDate = null;
String revenueType1 = null;
String revenueType2 = null;
double value = 0;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if ("result".equals(name)) {
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
// 1: sales, 2: in-app, 3: subscriptions?
// XXX this doesn't handle the case where there is more
// than one, e.g. app sales + subscriptions
if ("1".equals(name) || "2".equals(name) || "3".equals(name)) {
// revenue list: date->amount
// [{"1":"1304103600000","2":{"2":234.0}},..{"1":"1304449200000","2":{"2":123.0}},...]
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
if ("1".equals(name)) {
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
double dailyRevenue = 0;
Date date = null;
while (reader.hasNext()) {
name = reader.nextName();
if ("1".equals(name)) {
date = new Date(reader.nextLong());
if (revenueDate == null) {
revenueDate = (Date) date.clone();
}
} else if ("2".equals(name)) {
reader.beginObject();
while (reader.hasNext()) {
name = reader.nextName();
if ("2".equals(name)) {
dailyRevenue = reader.nextDouble();
if (date != null
&& date.getTime() > revenueDate
.getTime()) {
revenueDate = date;
value = dailyRevenue;
}
}
}
reader.endObject();
}
}
reader.endObject();
}
reader.endArray();
} else if ("2".equals(name)) {
// "APP", "IN_APP",
revenueType1 = reader.nextString();
} else if ("3".equals(name)) {
revenueType2 = reader.nextString();
}
}
reader.endObject();
} else if ("4".equals(name)) {
reportDate = new Date(reader.nextLong());
} else if ("5".equals(name)) {
currency = reader.nextString();
}
}
reader.endObject();
} else if ("xsrf".equals(name)) {
// consume XSRF
reader.nextString();
}
}
reader.endObject();
// XXX what happens when there is more than one type?
Revenue.Type type = Revenue.Type.TOTAL;
if ("APP".equals(revenueType1)) {
type = Revenue.Type.APP_SALES;
} else if ("IN_APP".equals(revenueType1)) {
type = Revenue.Type.IN_APP;
} else {
type = Revenue.Type.SUBSCRIPTIONS;
}
// XXX do we need the date?
// return new Revenue(type, revenueDate, currency, value);
return new Revenue(type, value, currency);
}
}
|
package arez.processor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import static arez.processor.ProcessorUtil.*;
/**
* Declaration of an inverse.
*/
final class InverseDescriptor
{
@Nonnull
private final ComponentDescriptor _componentDescriptor;
@Nonnull
private final ObservableDescriptor _observable;
@Nonnull
private final String _referenceName;
@Nonnull
private final Multiplicity _multiplicity;
@Nonnull
private final TypeElement _targetType;
@Nonnull
private final String _otherName;
InverseDescriptor( @Nonnull final ComponentDescriptor componentDescriptor,
@Nonnull final ObservableDescriptor observable,
@Nonnull final String referenceName,
@Nonnull final Multiplicity multiplicity,
@Nonnull final TypeElement targetType )
{
_componentDescriptor = Objects.requireNonNull( componentDescriptor );
_observable = Objects.requireNonNull( observable );
_referenceName = Objects.requireNonNull( referenceName );
_multiplicity = Objects.requireNonNull( multiplicity );
_targetType = Objects.requireNonNull( targetType );
_observable.setInverseDescriptor( this );
final String targetName = _targetType.getSimpleName().toString();
_otherName = ProcessorUtil.firstCharacterToLowerCase( targetName );
}
@Nonnull
ObservableDescriptor getObservable()
{
return _observable;
}
@Nonnull
String getReferenceName()
{
return _referenceName;
}
@Nonnull
Multiplicity getMultiplicity()
{
return _multiplicity;
}
@Nonnull
TypeElement getTargetType()
{
return _targetType;
}
void validate()
{
if ( _observable.requireInitializer() )
{
throw new ArezProcessorException( "@Inverse target also specifies @Observable(initializer=ENABLE) but " +
"it is not valid to define an initializer for an inverse.",
_observable.getGetter() );
}
}
void buildInitializer( @Nonnull final MethodSpec.Builder builder )
{
if ( Multiplicity.MANY == _multiplicity )
{
final ParameterizedTypeName typeName =
(ParameterizedTypeName) TypeName.get( _observable.getGetter().getReturnType() );
final boolean isList = List.class.getName().equals( typeName.rawType.toString() );
builder.addStatement( "this.$N = new $T<>()",
_observable.getDataFieldName(),
isList ? ArrayList.class : HashSet.class );
builder.addStatement( "this.$N = null", _observable.getCollectionCacheDataFieldName() );
}
}
void buildMethods( @Nonnull final TypeSpec.Builder builder )
throws ArezProcessorException
{
if ( Multiplicity.MANY == _multiplicity )
{
builder.addMethod( buildAddMethod() );
builder.addMethod( buildRemoveMethod() );
}
else
{
builder.addMethod( buildSetMethod() );
builder.addMethod( buildUnsetMethod() );
}
}
@Nonnull
private MethodSpec buildAddMethod()
throws ArezProcessorException
{
final String methodName = GeneratorUtil.getInverseAddMethodName( _observable.getName() );
final MethodSpec.Builder builder = MethodSpec.methodBuilder( methodName );
if ( isReferenceInDifferentPackage() )
{
builder.addModifiers( Modifier.PUBLIC );
}
final ParameterSpec parameter =
ParameterSpec.builder( TypeName.get( _targetType.asType() ), _otherName, Modifier.FINAL )
.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME )
.build();
builder.addParameter( parameter );
GeneratorUtil.generateNotDisposedInvariant( builder, methodName );
builder.addStatement( "this.$N.preReportChanged()", _observable.getFieldName() );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", GeneratorUtil.AREZ_CLASSNAME );
block.addStatement( "$T.invariant( () -> !this.$N.contains( $N ), " +
"() -> \"Attempted to add reference '$N' to inverse '$N' " +
"but inverse already contained element. Inverse = \" + $N )",
GeneratorUtil.GUARDS_CLASSNAME,
_observable.getDataFieldName(),
_otherName,
_otherName,
_observable.getName(),
_observable.getFieldName() );
block.endControlFlow();
builder.addCode( block.build() );
builder.addStatement( "this.$N.add( $N )", _observable.getDataFieldName(), _otherName );
final CodeBlock.Builder clearCacheBlock = CodeBlock.builder();
clearCacheBlock.beginControlFlow( "if ( $T.areCollectionsPropertiesUnmodifiable() )",
GeneratorUtil.AREZ_CLASSNAME );
clearCacheBlock.addStatement( "this.$N = null", _observable.getCollectionCacheDataFieldName() );
clearCacheBlock.endControlFlow();
builder.addCode( clearCacheBlock.build() );
builder.addStatement( "this.$N.reportChanged()", _observable.getFieldName() );
return builder.build();
}
@Nonnull
private MethodSpec buildRemoveMethod()
throws ArezProcessorException
{
final String methodName = GeneratorUtil.getInverseRemoveMethodName( _observable.getName() );
final MethodSpec.Builder builder = MethodSpec.methodBuilder( methodName );
if ( isReferenceInDifferentPackage() )
{
builder.addModifiers( Modifier.PUBLIC );
}
final ParameterSpec parameter =
ParameterSpec.builder( TypeName.get( _targetType.asType() ), _otherName, Modifier.FINAL )
.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME )
.build();
builder.addParameter( parameter );
GeneratorUtil.generateNotDisposedInvariant( builder, methodName );
builder.addStatement( "this.$N.preReportChanged()", _observable.getFieldName() );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", GeneratorUtil.AREZ_CLASSNAME );
block.addStatement( "$T.invariant( () -> this.$N.contains( $N ), " +
"() -> \"Attempted to remove reference '$N' from inverse '$N' " +
"but inverse does not contain element. Inverse = \" + $N )",
GeneratorUtil.GUARDS_CLASSNAME,
_observable.getDataFieldName(),
_otherName,
_otherName,
_observable.getName(),
_observable.getFieldName() );
block.endControlFlow();
builder.addCode( block.build() );
builder.addStatement( "this.$N.remove( $N )", _observable.getDataFieldName(), _otherName );
final CodeBlock.Builder clearCacheBlock = CodeBlock.builder();
clearCacheBlock.beginControlFlow( "if ( $T.areCollectionsPropertiesUnmodifiable() )",
GeneratorUtil.AREZ_CLASSNAME );
clearCacheBlock.addStatement( "this.$N = null", _observable.getCollectionCacheDataFieldName() );
clearCacheBlock.endControlFlow();
builder.addCode( clearCacheBlock.build() );
builder.addStatement( "this.$N.reportChanged()", _observable.getFieldName() );
return builder.build();
}
@Nonnull
private MethodSpec buildSetMethod()
throws ArezProcessorException
{
final String methodName =
Multiplicity.ONE == _multiplicity ?
GeneratorUtil.getInverseSetMethodName( _observable.getName() ) :
GeneratorUtil.getInverseZSetMethodName( _observable.getName() );
final MethodSpec.Builder builder = MethodSpec.methodBuilder( methodName );
if ( isReferenceInDifferentPackage() )
{
builder.addModifiers( Modifier.PUBLIC );
}
final ParameterSpec.Builder parameter =
ParameterSpec.builder( TypeName.get( _targetType.asType() ), _otherName, Modifier.FINAL );
if ( Multiplicity.ONE == _multiplicity )
{
parameter.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
}
else
{
parameter.addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME );
}
builder.addParameter( parameter.build() );
GeneratorUtil.generateNotDisposedInvariant( builder, methodName );
builder.addStatement( "this.$N.preReportChanged()", _observable.getFieldName() );
builder.addStatement( "this.$N = $N", _observable.getDataFieldName(), _otherName );
builder.addStatement( "this.$N.reportChanged()", _observable.getFieldName() );
return builder.build();
}
@Nonnull
private MethodSpec buildUnsetMethod()
throws ArezProcessorException
{
final String methodName =
Multiplicity.ONE == _multiplicity ?
GeneratorUtil.getInverseUnsetMethodName( _observable.getName() ) :
GeneratorUtil.getInverseZUnsetMethodName( _observable.getName() );
final MethodSpec.Builder builder = MethodSpec.methodBuilder( methodName );
if ( isReferenceInDifferentPackage() )
{
builder.addModifiers( Modifier.PUBLIC );
}
final ParameterSpec parameter =
ParameterSpec.builder( TypeName.get( _targetType.asType() ), _otherName, Modifier.FINAL )
.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME )
.build();
builder.addParameter( parameter );
GeneratorUtil.generateNotDisposedInvariant( builder, methodName );
builder.addStatement( "this.$N.preReportChanged()", _observable.getFieldName() );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( this.$N == $N )", _observable.getDataFieldName(), _otherName );
block.addStatement( "this.$N = null", _observable.getDataFieldName() );
block.addStatement( "this.$N.reportChanged()", _observable.getFieldName() );
block.endControlFlow();
builder.addCode( block.build() );
return builder.build();
}
private boolean isReferenceInDifferentPackage()
{
final PackageElement targetPackageElement = ProcessorUtil.getPackageElement( _targetType );
final PackageElement selfPackageElement = getPackageElement( _componentDescriptor.getElement() );
return !Objects.equals( targetPackageElement.getQualifiedName(), selfPackageElement.getQualifiedName() );
}
void buildVerify( @Nonnull final CodeBlock.Builder code )
{
if ( Multiplicity.MANY == _multiplicity )
{
buildManyVerify( code );
}
else
{
buildSingularVerify( code );
}
}
private void buildSingularVerify( @Nonnull final CodeBlock.Builder code )
{
final CodeBlock.Builder builder = CodeBlock.builder();
builder.beginControlFlow( "if ( $T.shouldCheckApiInvariants() )", GeneratorUtil.AREZ_CLASSNAME );
builder.addStatement( "$T.apiInvariant( () -> $T.isNotDisposed( this.$N ), () -> \"Inverse relationship " +
"named '$N' on component named '\" + this.$N.getName() + \"' contains disposed element " +
"'\" + this.$N + \"'\" )",
GeneratorUtil.GUARDS_CLASSNAME,
GeneratorUtil.DISPOSABLE_CLASSNAME,
_observable.getDataFieldName(),
_observable.getName(),
GeneratorUtil.KERNEL_FIELD_NAME,
_observable.getDataFieldName() );
builder.endControlFlow();
code.add( builder.build() );
}
private void buildManyVerify( @Nonnull final CodeBlock.Builder code )
{
final CodeBlock.Builder builder = CodeBlock.builder();
builder.beginControlFlow( "for( final $T element : this.$N )", _targetType, _observable.getDataFieldName() );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() )", GeneratorUtil.AREZ_CLASSNAME );
block.addStatement( "$T.apiInvariant( () -> $T.isNotDisposed( element ), () -> \"Inverse relationship " +
"named '$N' on component named '\" + this.$N.getName() + \"' contains disposed element " +
"'\" + element + \"'\" )",
GeneratorUtil.GUARDS_CLASSNAME,
GeneratorUtil.DISPOSABLE_CLASSNAME,
_observable.getName(),
GeneratorUtil.KERNEL_FIELD_NAME );
block.endControlFlow();
builder.add( block.build() );
builder.endControlFlow();
code.add( builder.build() );
}
void buildDisposer( @Nonnull final MethodSpec.Builder builder )
{
if ( _multiplicity == Multiplicity.MANY )
{
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "for ( final $T other : new $T<>( $N ) )",
_targetType,
TypeName.get( ArrayList.class ),
_observable.getDataFieldName() );
block.addStatement( "( ($T) other ).$N()", getArezClassName(), getDelinkMethodName() );
block.endControlFlow();
builder.addCode( block.build() );
}
else
{
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( null != $N )", _observable.getDataFieldName() );
block.addStatement( "( ($T) $N ).$N()",
getArezClassName(),
_observable.getDataFieldName(),
getDelinkMethodName() );
block.endControlFlow();
builder.addCode( block.build() );
}
}
@Nonnull
private ClassName getArezClassName()
{
final TypeName typeName = TypeName.get( _observable.getGetter().getReturnType() );
final ClassName other = typeName instanceof ClassName ?
(ClassName) typeName :
(ClassName) ( (ParameterizedTypeName) typeName ).typeArguments.get( 0 );
final StringBuilder sb = new StringBuilder();
final String packageName = other.packageName();
if ( null != packageName )
{
sb.append( packageName );
sb.append( "." );
}
final List<String> simpleNames = other.simpleNames();
final int end = simpleNames.size() - 1;
for ( int i = 0; i < end; i++ )
{
sb.append( simpleNames.get( i ) );
sb.append( "_" );
}
sb.append( "Arez_" );
sb.append( simpleNames.get( end ) );
return ClassName.bestGuess( sb.toString() );
}
@Nonnull
private String getDelinkMethodName()
{
return GeneratorUtil.getDelinkMethodName( _referenceName );
}
}
|
package com.github.takuji31.appbase.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.ListView;
public class PagingListView extends ListView implements
AbsListView.OnScrollListener {
private static final int POST_DELAY_TIME = 50;
public static interface OnPagingListener {
public void onScrollStart(int page);
public void onScrollFinish(int page);
public void onNextListLoad(int page);
}
private int mPage;
private int mScrollDuration = 400;
private boolean mFlinged;
private OnPagingListener mListener;
private OnGlobalLayoutListener mLayoutListener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mViewHeight == 0) {
postDelayed(new Runnable() {
@Override
public void run() {
mViewHeight = getHeight();
invalidateViews();
}
}, POST_DELAY_TIME);
}
}
};
private Handler mHandler = new Handler();
private Runnable mIdleTask = new Runnable() {
public void run() {
int page = getPage();
setPage(page);
if (mListener != null) {
mListener.onScrollFinish(mPage);
}
}
};
private Runnable mFlingTask = new Runnable() {
public void run() {
int currentY = getCurrentTop();
int page = getFirstVisiblePosition();
Adapter adapter = getAdapter();
int count = adapter != null ? adapter.getCount() : 0;
if (currentY > startY && page + 1 < count) {
setPage(page + 1);
} else if (currentY < startY && page > 0) {
setPage(page - 1);
} else {
setPage(page);
}
if (mListener != null) {
mListener.onScrollStart(mPage);
}
}
};
int mViewHeight;
public PagingListView(Context context) {
super(context);
init();
}
public PagingListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagingListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setOnPagingListener(OnPagingListener listener) {
mListener = listener;
}
public void setPage(int page) {
int distance = getPositionByPage(page) - getCurrentTop();
smoothScrollBy(distance, mScrollDuration * (Math.abs(page - getFirstVisiblePosition()) + 1));
}
private int getPositionByPage(int page) {
return getHeight() * page;
}
int getPage() {
return Math.round((getCurrentTop() * 1.0f) / (getHeight() * 1.0f));
}
private void init() {
setOnScrollListener(this);
ViewTreeObserver observer = getViewTreeObserver();
observer.addOnGlobalLayoutListener(mLayoutListener);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) {
ViewTreeObserver observer = getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
observer.removeOnGlobalLayoutListener(mLayoutListener);
} else {
observer.removeGlobalOnLayoutListener(mLayoutListener);
}
observer.addOnGlobalLayoutListener(listener);
observer.addOnGlobalLayoutListener(mLayoutListener);
}
int startY;
int getCurrentTop() {
int pos = getFirstVisiblePosition();
int top = 0;
View firstView = getChildAt(0);
if (firstView != null) {
top = firstView.getTop();
}
return getHeight() * pos - top;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
if (mFlinged) {
mFlinged = false;
if (mListener != null) {
mListener.onScrollFinish(mPage);
}
} else {
mHandler.postDelayed(mIdleTask, POST_DELAY_TIME);
}
break;
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
startY = getCurrentTop();
break;
case OnScrollListener.SCROLL_STATE_FLING:
mFlinged = true;
mHandler.postDelayed(mFlingTask, POST_DELAY_TIME);
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
View v = getChildAt(0);
if (v != null) {
Log.d(VIEW_LOG_TAG, String.valueOf(v.getTop()));
}
if (mListener != null) {
mListener.onNextListLoad(mPage);
}
}
}
|
package com.kchmielewski.algorithm.dijkstra.core;
import com.kchmielewski.algorithm.dijkstra.structure.Edge;
import com.kchmielewski.algorithm.dijkstra.structure.Graph;
import com.kchmielewski.algorithm.dijkstra.structure.Vertex;
import java.util.*;
public class Dijkstra {
public <T> Optional<Float> calculate(Graph<T> graph, Vertex<T> from, Vertex<T> to) {
Set<Vertex<T>> vertices = new HashSet<>(graph.vertices());
vertices.stream().filter(v -> v != from).forEach(v -> v.value(Float.MAX_VALUE));
from.value(0);
Queue<Vertex<T>> queue = new PriorityQueue<>(vertices);
while (!queue.isEmpty()) {
Vertex<T> current = queue.remove();
for (Edge<T> edge : current.edges()) {
Vertex<T> neighbour = edge.other(current);
float newValue = current.value() + edge.value();
if (newValue < neighbour.value()) {
neighbour.value(newValue);
queue.remove(neighbour);
queue.add(neighbour);
}
}
}
if (to.value() == Float.MAX_VALUE) {
return Optional.empty();
}
return Optional.of(to.value());
}
}
|
package com.svs.util;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class TimeUtils {
public static Date getFullDateFromDay(String partDate) {
int[] todayMonthYear = TimeUtils.getTodaysMonthAndYear();
String fullString = null;
String[] subStr = partDate.split(",");
int realLength = 0;
if (subStr[subStr.length-1].trim().length() > 0){
realLength = subStr.length;
} else {
realLength = subStr.length -1;
}
if (realLength == 3) {
fullString = subStr[0] + "/" + subStr[1] + "/" + subStr[2];
}
if (realLength == 2) {
fullString = subStr[0] + "/" + subStr[1] + "/" + todayMonthYear[1];
}
if (realLength == 1) {
fullString = subStr[0] + "/" + todayMonthYear[0] + "/" + todayMonthYear[1];
}
Date d = null;
try {
d = DateUtils.parseDateStrictly(fullString, "dd/MM/yyyy");
} catch (ParseException e) {
System.out.println("Error in arguments parsing!");
} catch (IllegalArgumentException e1) {
System.out.println("Error in arguments length!");
}
return d;
}
public static int[] getTodaysMonthAndYear(){
int[] monthYear = new int[2];
Date d = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
monthYear[0] = month+1; //months start from 0 ffs
monthYear[1] = year;
return monthYear;
}
}
|
package com.protocolanalyzer.andres;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.util.ByteArrayBuffer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.WindowManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.bluetoothutils.andres.BluetoothHelper;
import com.bluetoothutils.andres.OnNewBluetoothDataReceived;
import com.multiwork.andres.MainMenu;
import com.multiwork.andres.R;
import com.protocolanalyzer.api.andres.LogicData;
import com.protocolanalyzer.api.andres.LogicDataSet;
import com.protocolanalyzer.api.andres.LogicHelper;
import com.protocolanalyzer.api.andres.LogicData.Protocol;
public class LogicAnalizerActivity extends SherlockFragmentActivity implements OnActionBarClickListener, OnNewBluetoothDataReceived{
private static final boolean DEBUG = true;
private static final byte startByte = 'S';
private static final byte logicAnalyzerMode = 'L';
private static final int initialBufferSize = 1000;
private static final int PREFERENCES_CODE = 1;
private static final int F40MHz = 'A';
private static final int F20MHz = 'S';
private static final int F10MHz = 'D';
private static final int F4MHz = 'F';
private static final int F400KHz = 'G';
private static final int F2KHz = 'H';
private static final int F10Hz = 'J';
private static final int updateDialogTitle = 0;
private static final int dispatchInterfaces = 1;
private static final int dismissDialog = 2;
/** Interface donde paso los datos decodificados a los Fragments, los mismo deben implementar el Listener */
private static OnDataDecodedListener mChartDataDecodedListener;
private static OnDataDecodedListener mListDataDecodedListener;
/** Fragment que contiene al grafico */
private static Fragment mFragmentChart;
/** Fragment que con la lista de datos en formato raw */
private static Fragment mFragmentList;
/** Numero de canales de entrada */
public static final int channelsNumber = 4;
/** Indica si recibo datos del Service o no (Play o Pause) */
private static boolean isPlaying = false;
/** Tiempo del grafico */
private static double time = 0;
private static BluetoothHelper mBluetoothHelper;
/** Buffers de recepcion donde se guarda los bytes recibidos */
private static byte[] ReceptionBuffer;
private static ByteArrayBuffer mByteArrayBuffer = new ByteArrayBuffer(initialBufferSize);
/** Dato decodificado desde LogicHelper para ser mostrado en el grafico, contiene las posiciones para mostar
* el tipo de protocolo, etc
* @see LogicData.java */
private static LogicData[] mData = new LogicData[channelsNumber];
private static LogicDataSet mDataSet = new LogicDataSet();
private static boolean isStarting = true;
private static ProgressDialog mDialog;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
if(DEBUG) Log.i("mFragmentActivity","onCreate() LogicAnalizerActivity");
ReceptionBuffer = new byte[1];
setContentView(R.layout.logic_fragments);
mFragmentList = getSupportFragmentManager().findFragmentById(R.id.logicFragment);
// Obtengo el OnDataDecodedListener de los Fragments
try { mListDataDecodedListener = (OnDataDecodedListener) mFragmentList; }
catch (ClassCastException e) { throw new ClassCastException(mFragmentList.toString() + " must implement OnDataDecodedListener"); }
// Creo los LogicData y los agrego al DataSet
for(int n=0; n < channelsNumber; ++n){
mData[n] = new LogicData();
mDataSet.addLogicData(mData[n]);
}
}
// Si estoy tomando datos y salgo de la Activity elimino el CallBack para no recibir mas datos desde el Service.
@Override
protected void onPause() {
if(DEBUG) Log.i("mFragmentActivity","onPause()");
mBluetoothHelper.write(0);
super.onPause();
}
/**
* En onResume() se llama a supportInvalidateOptionsMenu(); para dibujar el boton Play/Pause en el modo correcto y no
* en el que aparece en el layout XML del ActionBar por defecto.
*/
@Override
protected void onResume() {
if(DEBUG) Log.i("mFragmentActivity","onResume()");
isStarting = true;
isPlaying = false;
// Solo si estoy en modo online procedo a obtener la conexion
mBluetoothHelper = MainMenu.mBluetoothHelper;
mBluetoothHelper.setOnNewBluetoothDataReceived(this);
mBluetoothHelper.write(logicAnalyzerMode);
setPreferences();
this.supportInvalidateOptionsMenu(); // Actualizo el ActionBar
super.onResume();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
// Si la aplicacion ya esta abierta ir a ella no abrir otra nueva
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
// Boton Play/Pause
case R.id.PlayPauseLogic:
// Digo al PIC que comienze el muestreo
mBluetoothHelper.write(1);
if(LogicData.getSampleRate() == 40000000) mBluetoothHelper.write(F40MHz);
else if(LogicData.getSampleRate() == 20000000) mBluetoothHelper.write(F20MHz);
else if(LogicData.getSampleRate() == 10000000) mBluetoothHelper.write(F10MHz);
else if(LogicData.getSampleRate() == 4000000) mBluetoothHelper.write(F4MHz);
else if(LogicData.getSampleRate() == 400000) mBluetoothHelper.write(F400KHz);
else if(LogicData.getSampleRate() == 2000) mBluetoothHelper.write(F2KHz);
else if(LogicData.getSampleRate() == 10) mBluetoothHelper.write(F10Hz);
isPlaying = true;
supportInvalidateOptionsMenu();
mDialog = ProgressDialog.show(this, getString(R.string.AnalyzerDialogReceiving),
getString(R.string.PleaseWait), true);
mDialog.setCancelable(false);
break;
case R.id.listLogic:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// de atras se vuelva a este Fragment y no se destruya el mismo
if(getSupportFragmentManager().findFragmentByTag("ChartLogic") == null
|| !getSupportFragmentManager().findFragmentByTag("ChartLogic").isVisible()){
if(DEBUG) Log.i("mFragmentActivity", "Chart Fragment Launched");
transaction.replace(R.id.logicFragment, new LogicAnalizerChartFragment(mData), "ChartLogic");
transaction.addToBackStack(null);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
// Agrego el OnDataDecodedListener cuando se agrega el nuevo Fragment
mFragmentChart = getSupportFragmentManager().findFragmentByTag("ChartLogic");
try { mChartDataDecodedListener = (OnDataDecodedListener) mFragmentChart; }
catch (ClassCastException e) { throw new ClassCastException(mFragmentChart.toString() + " must implement OnDataDecodedListener"); }
}
else{
if(DEBUG) Log.i("mFragmentActivity","Chart Fragment Removed");
getSupportFragmentManager().popBackStackImmediate();
}
break;
case R.id.settingsLogic:
startActivityForResult(new Intent(this, LogicAnalizerPrefs.class), PREFERENCES_CODE);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Detecta si el Fragment identificado con el fragmentTag esta activo o no
* @param fragmentTag nombre del Fragment
* @return true si esta activo, false de otro modo
*/
private boolean isFragmentActive (String fragmentTag){
if(getSupportFragmentManager().findFragmentByTag(fragmentTag) == null ||
!getSupportFragmentManager().findFragmentByTag(fragmentTag).isVisible()){
return false;
}
else return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Cambio en las preferencias
if(requestCode == PREFERENCES_CODE){
if(resultCode == RESULT_OK) {
if(DEBUG) Log.i("mFragmentActivity", "Preferences Setted");
// Aviso a la Activity que cambiaron las preferencias
mListDataDecodedListener.onDataDecodedListener(mData, ReceptionBuffer.length, true);
if(isFragmentActive("ChartFragment")) mChartDataDecodedListener.onDataDecodedListener(mData, ReceptionBuffer.length, true);
setPreferences();
}
}
}
/**
* Listener cuando se presiona los botones del ActionBar de alguno de los Fragment. La Activity implementa
* la interface creada por mi onActionBarClickListener(); y los Fragments utilizan la misma para que la Activity
* realiza las operaciones necesarias.
*/
@Override
public void onActionBarClickListener(int buttonID) {
if(DEBUG) Log.i("mFragmentActivity","onActionBarClickListener() - " + this.toString());
switch(buttonID){
case R.id.restartLogic:
for(int n=0; n < channelsNumber; ++n){
mData[n].freeDataMemory();
mData[n].clearDecodedData();
}
break;
case R.id.settingsLogic:
setPreferences();
break;
}
}
/**
* Actualiza los iconos del ActionBar cuando se llama a supportInvalidateOptionsMenu(); porque si no se llama a esta
* opcion en cada onResume() cuando la Activity vuelve el ActionBar se crea con el layout del XML y el boton
* Play/Pause debe mostrarse de acuerdo al estado actual.
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(isPlaying) menu.findItem(R.id.PlayPauseLogic).setIcon(R.drawable.pause);
else menu.findItem(R.id.PlayPauseLogic).setIcon(R.drawable.play);
return true;
}
/**
* Define los parametros de los canales de acuerdo como tipo de protocolo, velocidad de muestreo,
* velocidad en Baudios para el UART y si la pantalla debe permanecer o no encendida.
*/
private void setPreferences() {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(this);
for(int n=0; n < channelsNumber; ++n){
// Seteo el protocolo para cada canal
switch(Byte.decode(getPrefs.getString("protocol" + (n+1), "0"))){
case 0: // I2C
mData[n].setProtocol(Protocol.I2C);
break;
case 1: // UART
mData[n].setProtocol(Protocol.UART);
break;
case 2: // CLOCK
mData[n].setProtocol(Protocol.CLOCK);
break;
case 3: // NONE
mData[n].setProtocol(Protocol.NONE);
break;
}
// Seteo el canal que hace de fuente de clock
mData[n].setClockSource(Byte.decode(getPrefs.getString("SCL" + (n+1), "0")));
// Defino la velocidad en baudios de cada canal en caso de usarse UART
mData[n].setBaudRate(Long.decode(getPrefs.getString("BaudRate" + (n+1), "9600")));
}
// Defino la velocidad de muestreo que es comun a todos los canales (por defecto 4MHz)
LogicData.setSampleRate(Long.decode(getPrefs.getString("sampleRate", "4000000")));
if(getPrefs.getBoolean("keepScreenAwake", false)) {
if(DEBUG) Log.i("LogicAnalizerActivity","Screen Awake");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
// Handler para actualizar el UI Thread
final Handler updateUIThread = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case updateDialogTitle:
mDialog.setTitle(getString(R.string.AnalyzerDialogLoading));
break;
case dispatchInterfaces:
time = mListDataDecodedListener.onDataDecodedListener(mData, ReceptionBuffer.length, false);
if(isFragmentActive("ChartFragment")) mChartDataDecodedListener.onDataDecodedListener(mData, ReceptionBuffer.length, false);
break;
case dismissDialog:
mDialog.dismiss();
supportInvalidateOptionsMenu();
break;
}
}
};
@Override
public boolean onNewBluetoothDataReceivedListener(InputStream mBTIn, OutputStream mBTOut) {
if(DEBUG) Log.i("LogicAnalizerBT", "onNewBluetoothDataReceivedListener()");
// La primera vez veo que lo que halla recibido coincida con el modo en el que estoy
if(isStarting){
if(DEBUG) Log.i("LogicAnalizerBT", "Starting");
try {
while(mBTIn.available() > 0){
if(mBTIn.read() == logicAnalyzerMode){
isStarting = false;
break;
}
}
// Si no tengo el modo que corresponde notifico con un Toast
if(isStarting){
if(DEBUG) Log.i("LogicAnalizerBT", "Nothing detected");
}
} catch (IOException e) { e.printStackTrace(); }
}
else if(isPlaying){
if(DEBUG) Log.i("LogicAnalizerBT", "Data receive");
try {
int[] data = new int[3];
while(mBTIn.available() > 0){
if(mBTIn.read() == startByte && mBTIn.read() == logicAnalyzerMode){
if(DEBUG) Log.i("LogicAnalizerBT", "Receiving data...");
boolean keepGoing = true;
while(mBTIn.available() > 0 && keepGoing){
for(int n = 0; n < data.length; ++n){
data[n] = mBTIn.read();
if(DEBUG) Log.i("LogicAnalizerBT", "Data [HEX] " + n + ": " + Integer.toHexString(data[n]));
if(n == 1 && data[0] == 0xFF && data[1] == 0xFF){
keepGoing = false;
break;
}
}
if(keepGoing){
mByteArrayBuffer.append(data[0]);
mByteArrayBuffer.append(data[1]);
mByteArrayBuffer.append(data[2]);
}
}
if(DEBUG) Log.i("LogicAnalizerBT", "Byte buffer lenght: " + mByteArrayBuffer.length());
updateUIThread.sendEmptyMessage(updateDialogTitle);
// Paso el array de bytes decodificados con el algoritmo Run Lenght
mDataSet.BufferToChannel(LogicHelper.runLenghtDecode(mByteArrayBuffer));
// Decodifico cada canal con su correspondiente fuente de clock
for(int n = 0; n < channelsNumber; ++n) {
mDataSet.decode(n, time);
}
// Paso los datos decodificados a los Fragment en el Thread de la UI
updateUIThread.sendEmptyMessage(dispatchInterfaces);
}
}
} catch (IOException e) { e.printStackTrace(); }
isPlaying = false;
updateUIThread.sendEmptyMessage(dismissDialog);
}
return true;
}
}
|
package com.google.step.snippet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import com.google.step.snippet.data.Card;
import com.google.step.snippet.external.W3SchoolClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class W3SchoolClientTest {
private final W3SchoolClient client = new W3SchoolClient();
@Test
public void htmlImage() {
Card actual = client.search("https:
Card expected =
new Card(
"HTML <img> Tag",
"<img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">",
"https:
"How to insert an image:");
assertEquals(actual, expected);
}
@Test
public void jsJson() {
Card actual = client.search("https:
Card expected =
new Card(
"JSON - Introduction",
"var myObj = {name: \"John\", age: 31, city: \"New York\"}; var myJSON ="
+ " JSON.stringify(myObj); window.location = \"demo_json.php?x=\" + myJSON;",
"https:
"JSON: JavaScript Object Notation.");
assertEquals(actual, expected);
}
@Test
public void incompleteCard() {
Card actual = client.search("https:
assertNull(actual);
}
@Test
public void invalidLink() {
Card actual = client.search("https:
assertNull(actual);
}
@Test
public void blankPage() {
Card actual = client.search("https:
assertNull(actual);
}
}
|
package com.relteq.sirius.simulator;
import java.util.ArrayList;
import java.util.List;
public final class InitialDensityProfile extends com.relteq.sirius.jaxb.InitialDensityProfile {
protected Scenario myScenario;
protected Double [][] initial_density; // [veh/mile] indexed by link and type
protected Link [] link; // ordered array of references
protected Integer [] vehicletypeindex; // index of vehicle types into global list
protected double timestamp;
// populate / reset / validate / update
protected void populate(Scenario myScenario){
int i;
this.myScenario = myScenario;
// allocate
int numLinks = getDensity().size();
initial_density = new Double [numLinks][];
link = new Link [numLinks];
vehicletypeindex = myScenario.getVehicleTypeIndices(getVehicleTypeOrder());
// copy profile information to arrays in extended object
for(i=0;i<numLinks;i++){
com.relteq.sirius.jaxb.Density density = getDensity().get(i);
link[i] = myScenario.getLinkWithCompositeId(density.getNetworkId(),density.getLinkId());
Double1DVector D = new Double1DVector(density.getContent(),":");
initial_density[i] = D.getData();
}
// round to the nearest decisecond
if(getTstamp()!=null)
timestamp = SiriusMath.round(getTstamp().doubleValue()*10.0)/10.0;
else
timestamp = 0.0;
}
protected boolean validate() {
int i;
// check that all vehicle types are accounted for
if(vehicletypeindex.length!=myScenario.getNumVehicleTypes()){
SiriusErrorLog.addErrorMessage("Demand profile list of vehicle types does not match that of settings.");
return false;
}
// check that vehicle types are valid
for(i=0;i<vehicletypeindex.length;i++){
if(vehicletypeindex[i]<0){
SiriusErrorLog.addErrorMessage("Bad vehicle type name.");
return false;
}
}
// check that links are valid
for(i=0;i<link.length;i++){
if(link[i]==null){
SiriusErrorLog.addErrorMessage("Bad link id");
return false;
}
}
// check size of data
for(i=0;i<link.length;i++){
if(initial_density[i].length!=vehicletypeindex.length){
SiriusErrorLog.addErrorMessage("Wrong number of data points.");
return false;
}
}
// check that values are between 0 and jam density
int j;
Double sum;
Double x;
for(i=0;i<initial_density.length;i++){
if(link[i].issource) // does not apply to source links
continue;
sum = 0.0;
for(j=0;j<vehicletypeindex.length;j++){
x = initial_density[i][j];
if(x<0 || x.isNaN()){
SiriusErrorLog.addErrorMessage("Invalid initial density.");
return false;
}
sum += x;
}
// NOTE: REMOVED THIS CHECK TEMPORARILY. NEED TO DECIDE HOW TO DO IT
// WITH ENSEMBLE FUNDAMENTAL DIAGRAMS
// if(sum>link[i].getDensityJamInVPMPL()){
// SiriusErrorLog.addErrorMessage("Initial density exceeds jam density.");
// return false;
}
return true;
}
protected void reset() {
}
protected void update() {
}
// public API
public Double [] getDensityForLinkIdInVeh(String network_id,String linkid){
Double [] d = SiriusMath.zeros(myScenario.getNumVehicleTypes());
for(int i=0;i<link.length;i++){
if(link[i].getId().equals(linkid) && link[i].myNetwork.getId().equals(network_id)){
for(int j=0;j<vehicletypeindex.length;j++)
d[vehicletypeindex[j]] = initial_density[i][j]*link[i].getLengthInMiles();
return d;
}
}
return d;
}
public class Tuple {
private String link_id;
private String network_id;
private int vehicle_type_index;
private double density;
public Tuple(String link_id, String network_id, int vehicle_type_index,
double density) {
this.link_id = link_id;
this.network_id = network_id;
this.vehicle_type_index = vehicle_type_index;
this.density = density;
}
/**
* @return the link id
*/
public String getLinkId() {
return link_id;
}
/**
* @return the network id
*/
public String getNetworkId() {
return network_id;
}
/**
* @return the vehicle type index
*/
public int getVehicleTypeIndex() {
return vehicle_type_index;
}
/**
* @return the density, in vehicles
*/
public double getDensity() {
return density;
}
}
/**
* Constructs a list of initial densities,
* along with the corresponding link identifiers and vehicle types
* @return a list of <code/><link id, network id, vehicle type index, density></code> tuples
*/
public List<Tuple> getData() {
List<Tuple> data = new ArrayList<Tuple>(link.length * vehicletypeindex.length);
for (int iii = 0; iii < link.length; ++iii)
for (int jjj = 0; jjj < vehicletypeindex.length; ++jjj)
data.add(new Tuple(link[iii].getId(), link[iii].myNetwork.getId(),
vehicletypeindex[iii].intValue(),
initial_density[iii][jjj] * link[iii].getLengthInMiles()));
return data;
}
}
|
package com.tinkerpop.pipes.pgm;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerGraph;
import com.tinkerpop.blueprints.pgm.Edge;
import com.tinkerpop.blueprints.pgm.Graph;
import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerGraphFactory;
import com.tinkerpop.pipes.Pipe;
import com.tinkerpop.pipes.SingleIterator;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class VertexEdgePipeTest extends TestCase {
public void testOutGoingEdges() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex marko = graph.getVertex("1");
VertexEdgePipe vsf = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
vsf.setStarts(Arrays.asList(marko).iterator());
assertTrue(vsf.hasNext());
int counter = 0;
while (vsf.hasNext()) {
Edge e = vsf.next();
assertEquals(e.getOutVertex(), marko);
assertTrue(e.getInVertex().getId().equals("2") || e.getInVertex().getId().equals("3") || e.getInVertex().getId().equals("4"));
counter++;
}
assertEquals(counter, 3);
try {
vsf.next();
assertTrue(false);
} catch (NoSuchElementException e) {
assertFalse(false);
}
Vertex josh = graph.getVertex("4");
vsf = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
vsf.setStarts(Arrays.asList(josh).iterator());
assertTrue(vsf.hasNext());
counter = 0;
while (vsf.hasNext()) {
Edge e = vsf.next();
assertEquals(e.getOutVertex(), josh);
assertTrue(e.getInVertex().getId().equals("5") || e.getInVertex().getId().equals("3"));
counter++;
}
assertEquals(counter, 2);
try {
vsf.next();
assertTrue(false);
} catch (NoSuchElementException e) {
assertFalse(false);
}
Vertex lop = graph.getVertex("3");
vsf = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
vsf.setStarts(Arrays.asList(lop).iterator());
assertFalse(vsf.hasNext());
counter = 0;
while (vsf.hasNext()) {
counter++;
}
assertEquals(counter, 0);
try {
vsf.next();
assertTrue(false);
} catch (NoSuchElementException e) {
assertFalse(false);
}
}
public void testInEdges() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex josh = graph.getVertex("4");
VertexEdgePipe pipe = new VertexEdgePipe(VertexEdgePipe.Step.IN_EDGES);
pipe.setStarts(new SingleIterator<Vertex>(josh));
int counter = 0;
while (pipe.hasNext()) {
counter++;
Edge edge = pipe.next();
assertEquals(edge.getId(), "8");
}
assertEquals(counter, 1);
}
public void testBothEdges() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex josh = graph.getVertex("4");
VertexEdgePipe pipe = new VertexEdgePipe(VertexEdgePipe.Step.BOTH_EDGES);
pipe.setStarts(new SingleIterator<Vertex>(josh));
int counter = 0;
while (pipe.hasNext()) {
counter++;
Edge edge = pipe.next();
assertTrue(edge.getId().equals("8") || edge.getId().equals("10") || edge.getId().equals("11"));
}
assertEquals(counter, 3);
}
public void testBigGraphWithNoEdges() {
// This used to cause a stack overflow. Not crashing makes this a success.
TinkerGraph graph = new TinkerGraph();
for (int i = 0; i < 100000; i++) {
graph.addVertex(null);
}
Pipe<Graph, Vertex> vertices = new GraphElementPipe<Vertex>(GraphElementPipe.ElementType.VERTEX);
vertices.setStarts(new SingleIterator<Graph>(graph));
VertexEdgePipe outEdges = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
outEdges.setStarts(vertices);
int counter = 0;
while (outEdges.hasNext()) {
outEdges.next();
counter++;
}
assertEquals(counter, 0);
}
}
|
package com.wavefront.agent;
import com.wavefront.common.Clock;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.MetricName;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import wavefront.report.ReportPoint;
import static com.wavefront.agent.Validation.validatePoint;
/**
* Adds all graphite strings to a working list, and batches them up on a set schedule (100ms) to be sent (through the
* daemon's logic) up to the collector on the server side.
*/
public class PointHandlerImpl implements PointHandler {
private static final Logger logger = Logger.getLogger(PointHandlerImpl.class.getCanonicalName());
private static final Logger blockedPointsLogger = Logger.getLogger("RawBlockedPoints");
private static final Logger validPointsLogger = Logger.getLogger("RawValidPoints");
private final Histogram receivedPointLag;
private final String validationLevel;
private final String handle;
private boolean logPoints = false;
private volatile long logPointsUpdatedMillis = 0L;
/**
* Value of system property wavefront.proxy.logging (for backwards compatibility)
*/
private final boolean logPointsFlag;
@Nullable
private final String prefix;
protected final int blockedPointsPerBatch;
protected final PostPushDataTimedTask[] sendDataTasks;
public PointHandlerImpl(final String handle,
final String validationLevel,
final int blockedPointsPerBatch,
final PostPushDataTimedTask[] sendDataTasks) {
this(handle, validationLevel, blockedPointsPerBatch, null, sendDataTasks);
}
public PointHandlerImpl(final String handle,
final String validationLevel,
final int blockedPointsPerBatch,
@Nullable final String prefix,
final PostPushDataTimedTask[] sendDataTasks) {
this.validationLevel = validationLevel;
this.handle = handle;
this.blockedPointsPerBatch = blockedPointsPerBatch;
this.prefix = prefix;
String logPointsProperty = System.getProperty("wavefront.proxy.logpoints");
this.logPointsFlag = logPointsProperty != null && logPointsProperty.equalsIgnoreCase("true");
this.receivedPointLag = Metrics.newHistogram(new MetricName("points." + handle + ".received", "", "lag"));
this.sendDataTasks = sendDataTasks;
}
@Override
public void reportPoint(ReportPoint point, @Nullable String debugLine) {
final PostPushDataTimedTask randomPostTask = getRandomPostTask();
try {
if (prefix != null) {
point.setMetric(prefix + "." + point.getMetric());
}
validatePoint(
point,
"" + handle,
debugLine,
validationLevel == null ? null : Validation.Level.valueOf(validationLevel));
String strPoint = pointToString(point);
if (logPointsUpdatedMillis + TimeUnit.SECONDS.toMillis(1) < System.currentTimeMillis()) {
// refresh validPointsLogger level once a second
logPoints = validPointsLogger.isLoggable(Level.FINEST);
logPointsUpdatedMillis = System.currentTimeMillis();
}
if (logPoints || logPointsFlag) {
// we log valid points only if system property wavefront.proxy.logpoints is true or RawValidPoints log level is
// set to "ALL". this is done to prevent introducing overhead and accidentally logging points to the main log
validPointsLogger.info(strPoint);
}
randomPostTask.addPoint(strPoint);
randomPostTask.enforceBufferLimits();
receivedPointLag.update(Clock.now() - point.getTimestamp());
} catch (IllegalArgumentException e) {
blockedPointsLogger.warning(pointToString(point));
this.handleBlockedPoint(e.getMessage());
} catch (Exception ex) {
logger.log(Level.SEVERE, "WF-500 Uncaught exception when handling point (" +
(debugLine == null ? pointToString(point) : debugLine) + ")", ex);
}
}
@Override
public void reportPoints(List<ReportPoint> points) {
for (final ReportPoint point : points) {
reportPoint(point, null);
}
}
public PostPushDataTimedTask getRandomPostTask() {
// return the task with the lowest number of pending points and, if possible, not currently flushing to retry queue
long min = Long.MAX_VALUE;
PostPushDataTimedTask randomPostTask = null;
PostPushDataTimedTask firstChoicePostTask = null;
for (int i = 0; i < this.sendDataTasks.length; i++) {
long pointsToSend = this.sendDataTasks[i].getNumPointsToSend();
if (pointsToSend < min) {
min = pointsToSend;
randomPostTask = this.sendDataTasks[i];
if (!this.sendDataTasks[i].getFlushingToQueueFlag()) {
firstChoicePostTask = this.sendDataTasks[i];
}
}
}
return firstChoicePostTask == null ? randomPostTask : firstChoicePostTask;
}
@Override
public void handleBlockedPoint(@Nullable String pointLine) {
final PostPushDataTimedTask randomPostTask = getRandomPostTask();
if (pointLine != null && randomPostTask.getBlockedSampleSize() < this.blockedPointsPerBatch) {
randomPostTask.addBlockedSample(pointLine);
}
randomPostTask.incrementBlockedPoints();
}
private static String quote = "\"";
private static String escapedQuote = "\\\"";
private static String escapeQuotes(String raw) {
return StringUtils.replace(raw, quote, escapedQuote);
}
private static void appendTagMap(StringBuilder sb, @Nullable Map<String, String> tags) {
if (tags == null) {
return;
}
for (Map.Entry<String, String> entry : tags.entrySet()) {
sb.append(' ').append(quote).append(escapeQuotes(entry.getKey())).append(quote)
.append("=")
.append(quote).append(escapeQuotes(entry.getValue())).append(quote);
}
}
private static String pointToStringSB(ReportPoint point) {
if (point.getValue() instanceof Double || point.getValue() instanceof Long || point.getValue() instanceof String) {
StringBuilder sb = new StringBuilder(quote)
.append(escapeQuotes(point.getMetric())).append(quote).append(" ")
.append(point.getValue()).append(" ")
.append(point.getTimestamp() / 1000).append(" ")
.append("source=").append(quote).append(escapeQuotes(point.getHost())).append(quote);
appendTagMap(sb, point.getAnnotations());
return sb.toString();
} else if (point.getValue() instanceof wavefront.report.Histogram){
wavefront.report.Histogram h = (wavefront.report.Histogram) point.getValue();
StringBuilder sb = new StringBuilder();
// BinType
switch (h.getDuration()) {
case (int) DateUtils.MILLIS_PER_MINUTE:
sb.append("!M ");
break;
case (int) DateUtils.MILLIS_PER_HOUR:
sb.append("!H ");
break;
case (int) DateUtils.MILLIS_PER_DAY:
sb.append("!D ");
break;
default:
throw new RuntimeException("Unexpected histogram duration " + h.getDuration());
}
// Timestamp
sb.append(point.getTimestamp() / 1000).append(' ');
// Centroids
int numCentroids = Math.min(CollectionUtils.size(h.getBins()), CollectionUtils.size(h.getCounts()));
for (int i=0; i<numCentroids; ++i) {
// Count
sb.append('#').append(h.getCounts().get(i)).append(' ');
// Mean
sb.append(h.getBins().get(i)).append(' ');
}
// Metric
sb.append(quote).append(escapeQuotes(point.getMetric())).append(quote).append(" ");
// Source
sb.append("source=").append(quote).append(escapeQuotes(point.getHost())).append(quote);
appendTagMap(sb, point.getAnnotations());
return sb.toString();
}
throw new RuntimeException("Unsupported value class: " + point.getValue().getClass().getCanonicalName());
}
public static String pointToString(ReportPoint point) {
return pointToStringSB(point);
}
}
|
package org.commcare.util;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceInitializationException;
import org.commcare.resources.model.ResourceLocation;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.resources.model.installers.LocaleFileInstaller;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.Profile;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Suite;
import org.commcare.util.mocks.LivePrototypeFactory;
import org.commcare.util.reference.JavaResourceRoot;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageFactory;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.util.DummyIndexedStorageUtility;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.javarosa.xpath.XPathMissingInstanceException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
import java.util.zip.ZipFile;
/**
* @author ctsims
*
*/
public class CommCareConfigEngine {
private OutputStream output;
private ResourceTable table;
private ResourceTable updateTable;
private ResourceTable recoveryTable;
private PrintStream print;
private final CommCarePlatform platform;
private int fileuricount = 0;
private PrototypeFactory mLiveFactory;
private ArchiveFileRoot mArchiveRoot;
public CommCareConfigEngine() {
this(new LivePrototypeFactory());
}
public CommCareConfigEngine(PrototypeFactory prototypeFactory) {
this(System.out, prototypeFactory);
}
public CommCareConfigEngine(OutputStream output, PrototypeFactory prototypeFactory) {
this.output = output;
this.print = new PrintStream(output);
this.platform = new CommCarePlatform(2, 23);
this.mLiveFactory = prototypeFactory;
setRoots();
table = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility(Resource.class, mLiveFactory));
updateTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility(Resource.class, mLiveFactory));
recoveryTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility(Resource.class, mLiveFactory));
//All of the below is on account of the fact that the installers
//aren't going through a factory method to handle them differently
//per device.
StorageManager.forceClear();
StorageManager.setStorageFactory(new IStorageFactory() {
public IStorageUtility newStorage(String name, Class type) {
return new DummyIndexedStorageUtility(type, mLiveFactory);
}
});
StorageManager.registerStorage(Profile.STORAGE_KEY, Profile.class);
StorageManager.registerStorage(Suite.STORAGE_KEY, Suite.class);
StorageManager.registerStorage(FormDef.STORAGE_KEY, FormDef.class);
StorageManager.registerStorage("fixture", FormInstance.class);
//StorageManager.registerStorage(Suite.STORAGE_KEY, Suite.class);
}
private void setRoots() {
ReferenceManager._().addReferenceFactory(new JavaHttpRoot());
this.mArchiveRoot = new ArchiveFileRoot();
ReferenceManager._().addReferenceFactory(mArchiveRoot);
ReferenceManager._().addReferenceFactory(new JavaResourceRoot(this.getClass()));
}
public void initFromArchive(String archiveURL) {
String fileName;
if(archiveURL.startsWith("http")) {
fileName = downloadToTemp(archiveURL);
} else {
fileName = archiveURL;
}
ZipFile zip;
try {
zip = new ZipFile(fileName);
} catch (IOException e) {
print.println("File at " + archiveURL + ": is not a valid CommCare Package. Downloaded to: " + fileName);
e.printStackTrace(print);
System.exit(-1);
return;
}
String archiveGUID = this.mArchiveRoot.addArchiveFile(zip);
init("jr://archive/" + archiveGUID + "/profile.ccpr");
}
private String downloadToTemp(String resource) {
try{
URL url = new URL(resource);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully.
HttpURLConnection.setFollowRedirects(true);
File file = File.createTempFile("commcare_", ".ccz");
FileOutputStream fos = new FileOutputStream(file);
StreamsUtil.writeFromInputToOutput(new BufferedInputStream(conn.getInputStream()), fos);
return file.getAbsolutePath();
} catch(IOException e) {
print.println("Issue downloading or create stream for " +resource);
e.printStackTrace(print);
System.exit(-1);
return null;
}
}
public void initFromLocalFileResource(String resource) {
//Get the location of the file. In the future, we'll treat this as the resource root
String root = resource.substring(0,resource.lastIndexOf(File.separator));
//cut off the end
resource = resource.substring(resource.lastIndexOf(File.separator) + 1);
//(That root now reads as jr://file/)
ReferenceManager._().addReferenceFactory(new JavaFileRoot(root));
//(Now jr://resource/ points there too)
ReferenceManager._().addRootTranslator(new RootTranslator("jr://resource","jr://file"));
//(Now jr://resource/ points there too)
ReferenceManager._().addRootTranslator(new RootTranslator("jr://media","jr://file"));
//Now build the testing reference we'll use
String reference = "jr://file/" + resource;
init(reference);
}
/**
* super, super hacky for now, gets a jar directory and loads language resources
* from it.
* @param pathToResources
*/
public void addJarResources(String pathToResources) {
File resources = new File(pathToResources);
if(!resources.exists() && resources.isDirectory()) {
throw new RuntimeException("Couldn't find jar resources at " + resources.getAbsolutePath() + " . Please correct the path, or use the -nojarresources flag to skip loading jar resources.");
}
fileuricount++;
String jrroot = "extfile" + fileuricount;
ReferenceManager._().addReferenceFactory(new JavaFileRoot(new String[]{jrroot}, resources.getAbsolutePath()));
for(File file : resources.listFiles()) {
String name = file.getName();
if(name.endsWith("txt")) {
ResourceLocation location = new ResourceLocation(Resource.RESOURCE_AUTHORITY_LOCAL, "jr://" + jrroot + "/" + name);
Vector<ResourceLocation> locations = new Vector<ResourceLocation>();
locations.add(location);
if(!(name.lastIndexOf("_") < name.lastIndexOf("."))) {
//skip it
} else {
String locale = name.substring(name.lastIndexOf("_") + 1, name.lastIndexOf("."));
Resource test = new Resource(-2, name, locations, "Internal Strings: " + locale);
try {
table.addResource(test, new LocaleFileInstaller(locale),null);
} catch (StorageFullException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
//we don't support other file types yet
}
}
}
public void addResource(String reference) {
}
private void init(String profileRef) {
try {
installAppFromReference(profileRef);
print.println("Table resources intialized and fully resolved.");
print.println(table);
} catch (UnresolvedResourceException e) {
print.println("While attempting to resolve the necessary resources, one couldn't be found: " + e.getResource().getResourceId());
e.printStackTrace(print);
System.exit(-1);
} catch (UnfullfilledRequirementsException e) {
print.println("While attempting to resolve the necessary resources, a requirement wasn't met");
e.printStackTrace(print);
System.exit(-1);
}
}
public void installAppFromReference(String profileReference) throws UnresolvedResourceException,
UnfullfilledRequirementsException {
platform.init(profileReference, this.table, true);
}
public void initEnvironment() {
try {
Localization.init(true);
table.initializeResources(platform);
//Make sure there's a default locale, since the app doesn't necessarily use the
//localization engine
Localization.getGlobalLocalizerAdvanced().addAvailableLocale("default");
Localization.setDefaultLocale("default");
print.println("Locales defined: ");
String newLocale = null;
for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
if (newLocale == null) {
newLocale = locale;
}
System.out.println("* " + locale);
}
print.println("Setting locale to: " + newLocale);
Localization.setLocale(newLocale);
} catch (ResourceInitializationException e) {
print.println("Error while initializing one of the resolved resources");
e.printStackTrace(print);
System.exit(-1);
}
}
public void describeApplication() {
print.println("Locales defined: ");
for(String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
System.out.println("* " + locale);
}
Localization.setDefaultLocale("default");
Vector<Menu> root = new Vector<Menu>();
Hashtable<String, Vector<Menu>> mapping = new Hashtable<String, Vector<Menu>>();
mapping.put("root",new Vector<Menu>());
for(Suite s : platform.getInstalledSuites()) {
for(Menu m : s.getMenus()) {
if(m.getId().equals("root")) {
root.add(m);
} else {
Vector<Menu> menus = mapping.get(m.getRoot());
if(menus == null) {
menus = new Vector<Menu>();
}
menus.add(m);
mapping.put(m.getRoot(), menus);
}
}
}
for(String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
Localization.setLocale(locale);
print.println("Application details for locale: " + locale);
print.println("CommCare");
for(Menu m : mapping.get("root")) {
print.println("|- " + m.getName().evaluate());
for(String command : m.getCommandIds()) {
for(Suite s : platform.getInstalledSuites()) {
if(s.getEntries().containsKey(command)) {
print(s,s.getEntries().get(command),2);
}
}
}
}
for(Menu m : root) {
for(String command : m.getCommandIds()) {
for(Suite s : platform.getInstalledSuites()) {
if(s.getEntries().containsKey(command)) {
print(s,s.getEntries().get(command),1);
}
}
}
}
}
}
public CommCarePlatform getPlatform() {
return platform;
}
public FormDef loadFormByXmlns(String xmlns) {
IStorageUtilityIndexed<FormDef> formStorage =
(IStorageUtilityIndexed)StorageManager.getStorage(FormDef.STORAGE_KEY);
return formStorage.getRecordForValue("XMLNS", xmlns);
}
private void print(Suite s, Entry e, int level) {
String head = "";
String emptyhead = "";
for(int i = 0; i < level; ++i ){
head += "|- ";
emptyhead += " ";
}
print.println(head + "Entry: " + e.getText().evaluate());
for(SessionDatum datum : e.getSessionDataReqs()) {
if(datum.getType() == SessionDatum.DATUM_TYPE_FORM) {
print.println(emptyhead + "Form: " + datum.getValue());
} else {
if(datum.getShortDetail() != null) {
Detail d = s.getDetail(datum.getShortDetail());
try {
print.println(emptyhead + "|Select: " + d.getTitle().getText().evaluate(new EvaluationContext(null)));
} catch(XPathMissingInstanceException ex) {
print.println(emptyhead + "|Select: " + "(dynamic title)");
}
print.print(emptyhead + "| ");
for(DetailField f : d.getFields()) {
print.print(f.getHeader().evaluate() + " | ");
}
print.print("\n");
}
}
}
}
final static private class QuickStateListener implements TableStateListener{
int lastComplete = 0;
@Override
public void resourceStateUpdated(ResourceTable table) {
}
@Override
public void incrementProgress(int complete, int total) {
int diff = complete - lastComplete;
lastComplete = complete;
for(int i = 0 ; i < diff ; ++i) {
System.out.print(".");
}
}
};
public void attemptAppUpdate(boolean forceNew) {
ResourceTable global = table;
// Ok, should figure out what the state of this bad boy is.
Resource profileRef = global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
Profile profileObj = this.getPlatform().getCurrentProfile();
global.setStateListener(new QuickStateListener());
updateTable.setStateListener(new QuickStateListener());
// When profileRef points is http, add appropriate dev flags
String authRef = profileObj.getAuthReference();
try {
URL authUrl = new URL(authRef);
// profileRef couldn't be parsed as a URL, so don't worry
// about adding dev flags to the url's query
// If we want to be using/updating to the latest build of the
// app (instead of latest release), add it to the query tags of
// the profile reference
if (forceNew &&
("https".equals(authUrl.getProtocol()) ||
"http".equals(authUrl.getProtocol()))) {
if (authUrl.getQuery() != null) {
// If the profileRef url already have query strings
// just add a new one to the end
authRef = authRef + "&target=build";
} else {
// otherwise, start off the query string with a ?
authRef = authRef + "?target=build";
}
}
} catch (MalformedURLException e) {
System.out.print("Warning: Unrecognized URL format: " + authRef);
}
try {
// This populates the upgrade table with resources based on
// binary files, starting with the profile file. If the new
// profile is not a newer version, statgeUpgradeTable doesn't
// actually pull in all the new references
System.out.println("Checking for updates....");
platform.stageUpgradeTable(global, updateTable, recoveryTable, authRef, true);
Resource newProfile = updateTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if (!newProfile.isNewer(profileRef)) {
System.out.println("Your app is up to date!");
return;
}
System.out.println("Update found. New Version: " + newProfile.getVersion());
System.out.print("Installing update");
// Replaces global table with temporary, or w/ recovery if
// something goes wrong
platform.upgrade(global, updateTable, recoveryTable);
} catch(UnresolvedResourceException e) {
System.out.println("Update Failed! Couldn't find or install one of the remote resources");
e.printStackTrace();
return;
} catch(UnfullfilledRequirementsException e) {
System.out.println("Update Failed! This CLI host is incompatible with the app");
e.printStackTrace();
return;
} catch(Exception e) {
System.out.println("Update Failed! There is a problem with one of the resources");
e.printStackTrace();
return;
}
// Initializes app resources and the app itself, including doing a check to see if this
// app record was converted by the db upgrader
initEnvironment();
}
}
|
package eu.freme.common.persistence;
import eu.freme.common.FREMECommonConfig;
import eu.freme.common.persistence.dao.DatasetDAO;
import eu.freme.common.persistence.dao.UserDAO;
import eu.freme.common.persistence.model.Dataset;
import eu.freme.common.persistence.model.OwnedResource;
import eu.freme.common.persistence.model.User;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = FREMECommonConfig.class)
public class DatasetDAOTest {
@Autowired
UserDAO userDAO;
@Autowired
DatasetDAO datasetDAO;
private Logger logger = Logger.getLogger(DatasetDAOTest.class);
@Test
public void test() throws Exception {
long countBefore = datasetDAO.count();
logger.info("create user and save it");
User user = new User("hallo", "welt", User.roleUser);
userDAO.save(user);
logger.info("create dataset");
Dataset dataset = new Dataset(user, OwnedResource.Visibility.PUBLIC, "name", "description");
//// does not work: the current session has to be authenticated for accessibility checks!
// datasetDAO.save(dataset);
//// use this instead (but the id will not be set correctly, so we have to do it manually):
dataset.setId(1);
datasetDAO.getRepository().save(dataset);
long id = dataset.getId();
logger.info("id of saved dataset: "+id);
assertEquals(countBefore + 1, datasetDAO.count());
logger.info("fetch and check saved dataset");
Dataset fetchedDataset = datasetDAO.getRepository().findOneById(id);
assertEquals("name", fetchedDataset.getName());
assertEquals("description", fetchedDataset.getDescription());
assertEquals(0, fetchedDataset.getTotalEntities());
datasetDAO.getRepository().delete(fetchedDataset);
logger.info("delete dataset");
assertEquals(countBefore, datasetDAO.count());
userDAO.delete(user);
}
}
|
package net.md_5.bungee;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import net.md_5.bungee.api.ServerPing;
import java.lang.reflect.Type;
import java.util.UUID;
public class PlayerInfoSerializer implements JsonSerializer<ServerPing.PlayerInfo>, JsonDeserializer<ServerPing.PlayerInfo>
{
private final int protocol;
public PlayerInfoSerializer(int protocol)
{
this.protocol = protocol;
}
@Override
public ServerPing.PlayerInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject js = json.getAsJsonObject();
ServerPing.PlayerInfo info = new ServerPing.PlayerInfo( js.get( "name" ).getAsString(), (UUID) null );
String id = js.get( "id" ).getAsString();
if ( protocol == 4 || !id.contains( "-" ))
{
info.setId( id );
} else
{
info.setUniqueId( UUID.fromString( id ) );
}
return info;
}
@Override
public JsonElement serialize(ServerPing.PlayerInfo src, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject out = new JsonObject();
out.addProperty( "name", src.getName() );
if ( protocol == 4 )
{
out.addProperty( "id", src.getId() );
} else
{
out.addProperty( "id", src.getUniqueId().toString() );
}
return out;
}
}
|
package org.commcare.util;
import org.commcare.modern.reference.ArchiveFileRoot;
import org.commcare.modern.reference.JavaFileRoot;
import org.commcare.modern.reference.JavaHttpRoot;
import org.commcare.resources.ResourceManager;
import org.commcare.resources.model.InstallCancelledException;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.FormIdDatum;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.OfflineUserRestore;
import org.commcare.suite.model.Profile;
import org.commcare.suite.model.PropertySetter;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Suite;
import org.javarosa.core.io.BufferedInputStream;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.ResourceReferenceFactory;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageFactory;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.util.DummyIndexedStorageUtility;
import org.javarosa.core.util.externalizable.LivePrototypeFactory;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.javarosa.xpath.XPathMissingInstanceException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
import java.util.zip.ZipFile;
/**
* @author ctsims
*/
public class CommCareConfigEngine {
private final ResourceTable table;
private final ResourceTable updateTable;
private final ResourceTable recoveryTable;
private final PrintStream print;
private final CommCarePlatform platform;
private final PrototypeFactory mLiveFactory;
private ArchiveFileRoot mArchiveRoot;
public CommCareConfigEngine() {
this(new LivePrototypeFactory());
}
public CommCareConfigEngine(PrototypeFactory prototypeFactory) {
this(System.out, prototypeFactory);
}
public CommCareConfigEngine(OutputStream output, PrototypeFactory prototypeFactory) {
this.print = new PrintStream(output);
this.platform = new CommCarePlatform(2, 32);
this.mLiveFactory = prototypeFactory;
setRoots();
table = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
updateTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
recoveryTable = ResourceTable.RetrieveTable(new DummyIndexedStorageUtility<>(Resource.class, mLiveFactory));
//All of the below is on account of the fact that the installers
//aren't going through a factory method to handle them differently
//per device.
StorageManager.forceClear();
StorageManager.setStorageFactory(new IStorageFactory() {
@Override
public IStorageUtility newStorage(String name, Class type) {
return new DummyIndexedStorageUtility(type, mLiveFactory);
}
});
StorageManager.registerStorage(Profile.STORAGE_KEY, Profile.class);
StorageManager.registerStorage(Suite.STORAGE_KEY, Suite.class);
StorageManager.registerStorage(FormDef.STORAGE_KEY, FormDef.class);
StorageManager.registerStorage(FormInstance.STORAGE_KEY, FormInstance.class);
StorageManager.registerStorage(OfflineUserRestore.STORAGE_KEY, OfflineUserRestore.class);
}
private void setRoots() {
ReferenceManager._().addReferenceFactory(new JavaHttpRoot());
this.mArchiveRoot = new ArchiveFileRoot();
ReferenceManager._().addReferenceFactory(mArchiveRoot);
ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory());
}
public void initFromArchive(String archiveURL) {
String fileName;
if (archiveURL.startsWith("http")) {
fileName = downloadToTemp(archiveURL);
} else {
fileName = archiveURL;
}
ZipFile zip;
try {
zip = new ZipFile(fileName);
} catch (IOException e) {
print.println("File at " + archiveURL + ": is not a valid CommCare Package. Downloaded to: " + fileName);
e.printStackTrace(print);
System.exit(-1);
return;
}
String archiveGUID = this.mArchiveRoot.addArchiveFile(zip);
init("jr://archive/" + archiveGUID + "/profile.ccpr");
}
private String downloadToTemp(String resource) {
try {
URL url = new URL(resource);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully.
HttpURLConnection.setFollowRedirects(true);
File file = File.createTempFile("commcare_", ".ccz");
FileOutputStream fos = new FileOutputStream(file);
StreamsUtil.writeFromInputToOutput(new BufferedInputStream(conn.getInputStream()), fos);
return file.getAbsolutePath();
} catch (IOException e) {
print.println("Issue downloading or create stream for " + resource);
e.printStackTrace(print);
System.exit(-1);
return null;
}
}
public void initFromLocalFileResource(String resource) {
String reference = setFileSystemRootFromResourceAndReturnRelativeRef(resource);
init(reference);
}
private String setFileSystemRootFromResourceAndReturnRelativeRef(String resource) {
int lastSeparator = resource.lastIndexOf(File.separator);
String rootPath;
String filePart;
if (lastSeparator == -1) {
rootPath = new File("").getAbsolutePath();
filePart = resource;
} else {
//Get the location of the file. In the future, we'll treat this as the resource root
rootPath = resource.substring(0, resource.lastIndexOf(File.separator));
//cut off the end
filePart = resource.substring(resource.lastIndexOf(File.separator) + 1);
}
//(That root now reads as jr://file/)
ReferenceManager._().addReferenceFactory(new JavaFileRoot(rootPath));
//Now build the testing reference we'll use
return "jr://file/" + filePart;
}
private void init(String profileRef) {
try {
installAppFromReference(profileRef);
print.println("Table resources intialized and fully resolved.");
print.println(table);
} catch (InstallCancelledException e) {
print.println("Install was cancelled by the user or system");
e.printStackTrace(print);
System.exit(-1);
} catch (UnresolvedResourceException e) {
print.println("While attempting to resolve the necessary resources, one couldn't be found: " + e.getResource().getResourceId());
e.printStackTrace(print);
System.exit(-1);
} catch (UnfullfilledRequirementsException e) {
print.println("While attempting to resolve the necessary resources, a requirement wasn't met");
e.printStackTrace(print);
System.exit(-1);
}
}
public void installAppFromReference(String profileReference) throws UnresolvedResourceException,
UnfullfilledRequirementsException, InstallCancelledException {
ResourceManager.installAppResources(platform, profileReference, this.table, true);
}
public void initEnvironment() {
Localization.init(true);
try {
table.initializeResources(platform, false);
} catch (RuntimeException e) {
print.println("Error while initializing one of the resolved resources");
e.printStackTrace(print);
System.exit(-1);
}
//Make sure there's a default locale, since the app doesn't necessarily use the
//localization engine
Localization.getGlobalLocalizerAdvanced().addAvailableLocale("default");
Localization.setDefaultLocale("default");
print.println("Locales defined: ");
for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
System.out.println("* " + locale);
}
setDefaultLocale();
}
private void setDefaultLocale() {
String defaultLocale = "default";
for (PropertySetter prop : platform.getCurrentProfile().getPropertySetters()) {
if ("cur_locale".equals(prop.getKey())) {
defaultLocale = prop.getValue();
break;
}
}
print.println("Setting locale to: " + defaultLocale);
Localization.setLocale(defaultLocale);
}
public void describeApplication() {
print.println("Locales defined: ");
for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
System.out.println("* " + locale);
}
Localization.setDefaultLocale("default");
Vector<Menu> root = new Vector<>();
Hashtable<String, Vector<Menu>> mapping = new Hashtable<>();
mapping.put("root", new Vector<Menu>());
for (Suite s : platform.getInstalledSuites()) {
for (Menu m : s.getMenus()) {
if (m.getId().equals("root")) {
root.add(m);
} else {
Vector<Menu> menus = mapping.get(m.getRoot());
if (menus == null) {
menus = new Vector<>();
}
menus.add(m);
mapping.put(m.getRoot(), menus);
}
}
}
for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) {
Localization.setLocale(locale);
print.println("Application details for locale: " + locale);
print.println("CommCare");
for (Menu m : mapping.get("root")) {
print.println("|- " + m.getName().evaluate());
for (String command : m.getCommandIds()) {
for (Suite s : platform.getInstalledSuites()) {
if (s.getEntries().containsKey(command)) {
print(s, s.getEntries().get(command), 2);
}
}
}
}
for (Menu m : root) {
for (String command : m.getCommandIds()) {
for (Suite s : platform.getInstalledSuites()) {
if (s.getEntries().containsKey(command)) {
print(s, s.getEntries().get(command), 1);
}
}
}
}
}
}
public CommCarePlatform getPlatform() {
return platform;
}
public FormDef loadFormByXmlns(String xmlns) {
IStorageUtilityIndexed<FormDef> formStorage =
(IStorageUtilityIndexed)StorageManager.getStorage(FormDef.STORAGE_KEY);
return formStorage.getRecordForValue("XMLNS", xmlns);
}
private void print(Suite s, Entry e, int level) {
String head = "";
String emptyhead = "";
for (int i = 0; i < level; ++i) {
head += "|- ";
emptyhead += " ";
}
if (e.isView()) {
print.println(head + "View: " + e.getText().evaluate());
} else {
print.println(head + "Entry: " + e.getText().evaluate());
}
for (SessionDatum datum : e.getSessionDataReqs()) {
if (datum instanceof FormIdDatum) {
print.println(emptyhead + "Form: " + datum.getValue());
} else if (datum instanceof EntityDatum) {
String shortDetailId = ((EntityDatum)datum).getShortDetail();
if (shortDetailId != null) {
Detail d = s.getDetail(shortDetailId);
try {
print.println(emptyhead + "|Select: " + d.getTitle().getText().evaluate(new EvaluationContext(null)));
} catch (XPathMissingInstanceException ex) {
print.println(emptyhead + "|Select: " + "(dynamic title)");
}
print.print(emptyhead + "| ");
for (DetailField f : d.getFields()) {
print.print(f.getHeader().evaluate() + " | ");
}
print.print("\n");
}
}
}
}
final static private class QuickStateListener implements TableStateListener {
int lastComplete = 0;
@Override
public void simpleResourceAdded() {
}
@Override
public void compoundResourceAdded(ResourceTable table) {
}
@Override
public void incrementProgress(int complete, int total) {
int diff = complete - lastComplete;
lastComplete = complete;
for (int i = 0; i < diff; ++i) {
System.out.print(".");
}
}
}
public void attemptAppUpdate(String updateTarget) {
ResourceTable global = table;
// Ok, should figure out what the state of this bad boy is.
Resource profileRef = global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
Profile profileObj = this.getPlatform().getCurrentProfile();
global.setStateListener(new QuickStateListener());
updateTable.setStateListener(new QuickStateListener());
// When profileRef points is http, add appropriate dev flags
String authRef = profileObj.getAuthReference();
try {
URL authUrl = new URL(authRef);
// profileRef couldn't be parsed as a URL, so don't worry
// about adding dev flags to the url's query
// If we want to be using/updating to the latest build of the
// app (instead of latest release), add it to the query tags of
// the profile reference
if (updateTarget != null &&
("https".equals(authUrl.getProtocol()) ||
"http".equals(authUrl.getProtocol()))) {
if (authUrl.getQuery() != null) {
// If the profileRef url already have query strings
// just add a new one to the end
authRef = authRef + "&target=" + updateTarget;
} else {
// otherwise, start off the query string with a ?
authRef = authRef + "?target" + updateTarget;
}
}
} catch (MalformedURLException e) {
System.out.print("Warning: Unrecognized URL format: " + authRef);
}
try {
// This populates the upgrade table with resources based on
// binary files, starting with the profile file. If the new
// profile is not a newer version, statgeUpgradeTable doesn't
// actually pull in all the new references
System.out.println("Checking for updates....");
ResourceManager resourceManager = new ResourceManager(platform, global, updateTable, recoveryTable);
resourceManager.stageUpgradeTable(authRef, true);
Resource newProfile = updateTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if (!newProfile.isNewer(profileRef)) {
System.out.println("Your app is up to date!");
return;
}
System.out.println("Update found. New Version: " + newProfile.getVersion());
System.out.println("Downloading / Preparing Update");
resourceManager.prepareUpgradeResources();
System.out.print("Installing update");
// Replaces global table with temporary, or w/ recovery if
// something goes wrong
resourceManager.upgrade();
} catch (UnresolvedResourceException e) {
System.out.println("Update Failed! Couldn't find or install one of the remote resources");
e.printStackTrace();
return;
} catch (UnfullfilledRequirementsException e) {
System.out.println("Update Failed! This CLI host is incompatible with the app");
e.printStackTrace();
return;
} catch (Exception e) {
System.out.println("Update Failed! There is a problem with one of the resources");
e.printStackTrace();
return;
}
// Initializes app resources and the app itself, including doing a check to see if this
// app record was converted by the db upgrader
initEnvironment();
}
}
|
package mil.nga.geopackage.test.db;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import junit.framework.TestCase;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.db.CoreSQLUtils;
import mil.nga.geopackage.db.GeoPackageConnection;
import mil.nga.geopackage.db.GeoPackageDataType;
import mil.nga.geopackage.db.master.SQLiteMaster;
import mil.nga.geopackage.db.master.SQLiteMasterQuery;
import mil.nga.geopackage.db.master.SQLiteMasterType;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.features.columns.GeometryColumnsDao;
import mil.nga.geopackage.features.index.FeatureIndexManager;
import mil.nga.geopackage.features.index.FeatureIndexType;
import mil.nga.geopackage.features.user.FeatureColumn;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureTable;
import mil.nga.geopackage.test.features.user.FeatureUtils;
/**
* Alter Table test utils
*
* @author osbornb
*/
public class AlterTableUtils {
/**
* Test column table alterations
*
* @param geoPackage
* GeoPackage
* @throws SQLException
* upon error
*/
public static void testColumns(GeoPackage geoPackage) throws SQLException {
GeometryColumnsDao geometryColumnsDao = geoPackage
.getGeometryColumnsDao();
if (geometryColumnsDao.isTableExists()) {
List<GeometryColumns> results = geometryColumnsDao.queryForAll();
for (GeometryColumns geometryColumns : results) {
GeoPackageConnection db = geoPackage.getConnection();
FeatureDao dao = geoPackage.getFeatureDao(geometryColumns);
FeatureIndexManager indexManager = new FeatureIndexManager(
geoPackage, dao);
int indexGeoPackageCount;
if (indexManager.isIndexed(FeatureIndexType.GEOPACKAGE)) {
indexManager
.prioritizeQueryLocation(FeatureIndexType.GEOPACKAGE);
indexGeoPackageCount = (int) indexManager.count();
} else {
indexGeoPackageCount = indexManager
.index(FeatureIndexType.GEOPACKAGE);
}
TestCase.assertTrue(indexManager
.isIndexed(FeatureIndexType.GEOPACKAGE));
int indexRTreeCount;
if (indexManager.isIndexed(FeatureIndexType.RTREE)) {
indexManager
.prioritizeQueryLocation(FeatureIndexType.RTREE);
indexRTreeCount = (int) indexManager.count();
} else {
indexRTreeCount = indexManager
.index(FeatureIndexType.RTREE);
}
TestCase.assertTrue(indexManager
.isIndexed(FeatureIndexType.RTREE));
FeatureTable featureTable = dao.getTable();
String tableName = featureTable.getTableName();
for (FeatureColumn column : featureTable.getColumns()) {
indexColumn(db, tableName, column);
}
createView(db, featureTable, "v_", true);
createView(db, featureTable, "v2_", false);
int rowCount = dao.count();
int tableCount = SQLiteMaster.count(geoPackage.getDatabase(),
SQLiteMasterType.TABLE, tableName);
int indexCount = SQLiteMaster.count(geoPackage.getDatabase(),
SQLiteMasterType.INDEX, tableName);
int triggerCount = SQLiteMaster.count(geoPackage.getDatabase(),
SQLiteMasterType.TRIGGER, tableName);
int viewCount = SQLiteMaster.count(geoPackage.getDatabase(),
SQLiteMasterType.VIEW,
SQLiteMasterQuery.createTableViewQuery(tableName));
TestCase.assertEquals(1, tableCount);
TestCase.assertTrue(indexCount >= featureTable.columnCount() - 2);
TestCase.assertTrue(triggerCount >= 6);
TestCase.assertTrue(viewCount >= 2);
FeatureTable table = dao.getTable();
int existingColumns = table.getColumns().size();
FeatureColumn pk = table.getPkColumn();
FeatureColumn geometry = table.getGeometryColumn();
int newColumns = 0;
String newColumnName = "new_column";
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.TEXT, false, ""));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.REAL));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.BOOLEAN));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.BLOB));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.INTEGER));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length()));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.BLOB, (long) UUID
.randomUUID().toString().getBytes().length));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.DATE));
dao.addColumn(FeatureColumn.createColumn(newColumnName
+ ++newColumns, GeoPackageDataType.DATETIME));
TestCase.assertEquals(existingColumns + newColumns, table
.getColumns().size());
TestCase.assertEquals(rowCount, dao.count());
testTableCounts(db, tableName, tableCount, indexCount,
triggerCount, viewCount);
for (int index = existingColumns; index < table.getColumns()
.size(); index++) {
indexColumn(db, tableName, table.getColumn(index));
String name = newColumnName + (index - existingColumns + 1);
TestCase.assertEquals(name, table.getColumnName(index));
TestCase.assertEquals(index, table.getColumnIndex(name));
TestCase.assertEquals(name, table.getColumn(index)
.getName());
TestCase.assertEquals(index, table.getColumn(index)
.getIndex());
TestCase.assertEquals(name, table.getColumnNames()[index]);
TestCase.assertEquals(name, table.getColumns().get(index)
.getName());
try {
table.getColumn(index).setIndex(index - 1);
TestCase.fail("Changed index on a created table column");
} catch (Exception e) {
}
table.getColumn(index).setIndex(index);
}
testTableCounts(db, tableName, tableCount, indexCount
+ newColumns, triggerCount, viewCount);
TestCase.assertEquals(geometryColumns.getTableName(),
table.getTableName());
TestCase.assertEquals(pk, table.getPkColumn());
TestCase.assertEquals(geometry, table.getGeometryColumn());
testIndex(indexManager, indexGeoPackageCount, indexRTreeCount);
FeatureUtils.testUpdate(dao);
String newerColumnName = "newer_column";
for (int newColumn = 2; newColumn <= newColumns; newColumn++) {
dao.renameColumn(newColumnName + newColumn, newerColumnName
+ newColumn);
}
dao.alterColumn(FeatureColumn.createColumn(newerColumnName + 3,
GeoPackageDataType.BOOLEAN, true, false));
dao.alterColumn(FeatureColumn.createColumn(newerColumnName + 5,
GeoPackageDataType.FLOAT, true, 1.5f));
dao.alterColumn(FeatureColumn.createColumn(newerColumnName + 6,
GeoPackageDataType.DATETIME, true,
"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"));
dao.alterColumn(FeatureColumn.createColumn(newerColumnName + 8,
GeoPackageDataType.TEXT, true, "date_to_text"));
for (int index = existingColumns + 1; index < table
.getColumns().size(); index++) {
String name = newerColumnName
+ (index - existingColumns + 1);
TestCase.assertEquals(name, table.getColumnName(index));
TestCase.assertEquals(index, table.getColumnIndex(name));
TestCase.assertEquals(name, table.getColumn(index)
.getName());
TestCase.assertEquals(index, table.getColumn(index)
.getIndex());
TestCase.assertEquals(name, table.getColumnNames()[index]);
TestCase.assertEquals(name, table.getColumns().get(index)
.getName());
}
TestCase.assertEquals(existingColumns + newColumns, table
.getColumns().size());
TestCase.assertEquals(rowCount, dao.count());
testTableCounts(db, tableName, tableCount, indexCount
+ newColumns, triggerCount, viewCount);
TestCase.assertEquals(geometryColumns.getTableName(),
table.getTableName());
TestCase.assertEquals(pk, table.getPkColumn());
TestCase.assertEquals(geometry, table.getGeometryColumn());
testIndex(indexManager, indexGeoPackageCount, indexRTreeCount);
FeatureUtils.testUpdate(dao);
dao.dropColumn(newColumnName + 1);
testTableCounts(db, tableName, tableCount, indexCount
+ newColumns - 1, triggerCount, viewCount);
for (int newColumn = 2; newColumn <= newColumns; newColumn++) {
dao.dropColumn(newerColumnName + newColumn);
}
TestCase.assertEquals(existingColumns, table.getColumns()
.size());
TestCase.assertEquals(rowCount, dao.count());
// Renamed columns double quote wrap columns and allow indexes
// than indexCount indexes
testTableCounts(db, tableName, tableCount, indexCount
+ newColumns - 1, triggerCount, viewCount);
for (int index = 0; index < existingColumns; index++) {
TestCase.assertEquals(index, table.getColumn(index)
.getIndex());
}
TestCase.assertEquals(geometryColumns.getTableName(),
table.getTableName());
TestCase.assertEquals(pk, table.getPkColumn());
TestCase.assertEquals(geometry, table.getGeometryColumn());
testIndex(indexManager, indexGeoPackageCount, indexRTreeCount);
FeatureUtils.testUpdate(dao);
}
}
}
/**
* Index the column
*
* @param db
* connection
* @param tableName
* table name
* @param column
* feature column
*/
private static void indexColumn(GeoPackageConnection db, String tableName,
FeatureColumn column) {
if (!column.isPrimaryKey() && !column.isGeometry()) {
StringBuilder index = new StringBuilder(
"CREATE INDEX IF NOT EXISTS ");
index.append(CoreSQLUtils.quoteWrap("ids_" + tableName + "_"
+ column.getName()));
index.append(" ON ");
index.append(CoreSQLUtils.quoteWrap(tableName));
index.append(" ( ");
String columnName = column.getName();
if (columnName.contains(" ")) {
columnName = CoreSQLUtils.quoteWrap(columnName);
}
index.append(columnName);
index.append(" )");
db.execSQL(index.toString());
}
}
/**
* Create a table view
*
* @param db
* connection
* @param featureTable
* feature column
* @param namePrefix
* view name prefix
* @param quoteWrap
*/
private static void createView(GeoPackageConnection db,
FeatureTable featureTable, String namePrefix, boolean quoteWrap) {
StringBuilder view = new StringBuilder("CREATE VIEW ");
String viewName = namePrefix + featureTable.getTableName();
if (quoteWrap) {
viewName = CoreSQLUtils.quoteWrap(viewName);
}
view.append(viewName);
view.append(" AS SELECT ");
for (int i = 0; i < featureTable.columnCount(); i++) {
if (i > 0) {
view.append(", ");
}
view.append(CoreSQLUtils.quoteWrap(featureTable.getColumnName(i)));
view.append(" AS ");
String columnName = "column" + (i + 1);
if (quoteWrap) {
columnName = CoreSQLUtils.quoteWrap(columnName);
}
view.append(columnName);
}
view.append(" FROM ");
String tableName = featureTable.getTableName();
if (quoteWrap) {
tableName = CoreSQLUtils.quoteWrap(tableName);
}
view.append(tableName);
db.execSQL(view.toString());
}
/**
* Test the table schema counts
*
* @param db
* connection
* @param tableName
* table name
* @param tableCount
* table count
* @param indexCount
* index count
* @param triggerCount
* trigger count
* @param viewCount
* view count
*/
private static void testTableCounts(GeoPackageConnection db,
String tableName, int tableCount, int indexCount, int triggerCount,
int viewCount) {
TestCase.assertEquals(tableCount,
SQLiteMaster.count(db, SQLiteMasterType.TABLE, tableName));
TestCase.assertEquals(indexCount,
SQLiteMaster.count(db, SQLiteMasterType.INDEX, tableName));
TestCase.assertEquals(triggerCount,
SQLiteMaster.count(db, SQLiteMasterType.TRIGGER, tableName));
TestCase.assertEquals(
viewCount,
SQLiteMaster.count(db, SQLiteMasterType.VIEW,
SQLiteMasterQuery.createTableViewQuery(tableName)));
}
/**
* Test the feature indexes
*
* @param indexManager
* index manager
* @param geoPackageCount
* GeoPackage index count
* @param rTreeCount
* RTree index count
*/
private static void testIndex(FeatureIndexManager indexManager,
int geoPackageCount, int rTreeCount) {
TestCase.assertTrue(indexManager.isIndexed(FeatureIndexType.GEOPACKAGE));
indexManager.prioritizeQueryLocation(FeatureIndexType.GEOPACKAGE);
TestCase.assertEquals(geoPackageCount, indexManager.count());
TestCase.assertTrue(indexManager.isIndexed(FeatureIndexType.RTREE));
indexManager.prioritizeQueryLocation(FeatureIndexType.RTREE);
TestCase.assertEquals(rTreeCount, indexManager.count());
}
}
|
package com.twosquaredstudios.PortalLink;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PortalLinkConfig {
private final PortalLink plugin;
private Map<String,PortalLinkLinkValue> definedLinks = new HashMap<String,PortalLinkLinkValue>();
//private LinkedList<String> overriddenLines = new LinkedList<String>();
public PortalLinkConfig(PortalLink instance) {
plugin = instance;
}
public Map<String,PortalLinkLinkValue> getUserDefinedLinks() {
return definedLinks;
}
public void loadUserDefinedLinks() {
definedLinks.clear();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(plugin.getDataFolder() + "/links.properties"), "UTF-8"));
String s = "";
Integer line = 0;
while ((s = in.readLine()) != null) {
line++;
int length = 0;
s = s.trim();
if (s.isEmpty()) continue;
if (s.endsWith("=")) length++;
if (s.startsWith("#")) continue;
String tempArgs[] = s.split("=");
length += tempArgs.length;
String args[] = new String[length];
System.arraycopy(tempArgs, 0, args, 0, tempArgs.length);
if (length > tempArgs.length) {
args[length-1] = "";
}
args[0] = args[0].trim();
args[1] = args[1].trim();
if (args.length > 2) args[2] = args[2].trim();
boolean twoway = false;
if (args[1].equals("") && args.length > 2) {
args[1] = args[2];
twoway = true;
}
if (args.length > (twoway ? 3 : 2)) {
plugin.logWarning("Only one link can be specified per line - ignoring all other links on the line.");
//overriddenLines.add(s);
}
int whichNether = 0;
if (args[0].startsWith("<") && args[0].endsWith(">")) {
whichNether += 1;
args[0] = args[0].substring(1, args[0].length() - 1);
}
if (args[1].startsWith("<") && args[1].endsWith(">")) {
whichNether += 2;
args[1] = args[1].substring(1, args[1].length() - 1);
}
if (!args[0].equals("")) {
if (definedLinks.containsKey(args[0])) {
plugin.logWarning("Overriding previous link for \"" + args[0] + "\".");
}
definedLinks.put(args[0], new PortalLinkLinkValue(args[1],whichNether));
}
Environment environmentForWorld1 = Environment.NORMAL;
Environment environmentForWorld2 = Environment.NORMAL;
switch (whichNether) {
case 0:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NORMAL;
break;
case 1:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NORMAL;
break;
case 2:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NETHER;
break;
case 3:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NETHER;
break;
default:
break;
}
if (!args[0].equals("")) plugin.getServer().createWorld(args[0], environmentForWorld1);
if (!args[1].equals("")) plugin.getServer().createWorld(args[1], environmentForWorld2);
if (twoway) {
if (whichNether == 2) {
whichNether
} else if (whichNether == 1) {
whichNether++;
}
if (!args[1].equals("")) {
if (definedLinks.containsKey(args[1])) {
plugin.logWarning("Overriding previous link for \"" + args[1] + "\".");
}
definedLinks.put(args[1], new PortalLinkLinkValue(args[0], whichNether));
}
}
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
File pluginFolder = plugin.getDataFolder();
try {
pluginFolder.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Writer out = new OutputStreamWriter(new FileOutputStream(plugin.getDataFolder() + "/links.properties"), "UTF-8");
out.write("# Place any custom links inside this file.\n");
out.write("# Any world will be automatically linked with its name followed by \"_nether\".\n");
out.write("# Links should be specified with the format World=<NetherWorld>.\n");
out.write("# All nether worlds MUST be surrounded by < and > as shown in the above example.\n");
out.write("# You can link two nethers or two normal worlds if desired.\n");
out.write("# By default all links are one way (left world to right world) - to link them both\n");
out.write("# ways, change the \"=\" to \"==\".\n");
out.write("# A blank link will stop a player from being able to use a portal in that world.\n");
out.write("# Only one link per line (extra links will be ignored).\n");
out.write("# Later links will override previous ones.\n");
out.write("# Lines beginning with a hash (\"#\") are treated as comments and so are ignored.\n");
out.write("\n");
out.close();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/*
public void saveUserDefinedLinks() {
String outStr = "";
for (String string : overriddenLines) {
outStr = outStr.concat(string + "\n");
}
Iterator<Map.Entry<String,String>> iterator = definedLinks.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> entry = iterator.next();
outStr = outStr.concat(entry.getKey() + "=" + entry.getValue() + "\n");
}
try {
Writer out = new OutputStreamWriter(new FileOutputStream(plugin.getDataFolder() + "/links.properties.tmp"), "UTF-8");
out.write(outStr);
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
plugin.logError("The save file could not be accessed!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File tempFile = new File(plugin.getDataFolder() + "/links.properties.tmp");
File targetFile = new File(plugin.getDataFolder() + "/links.properties");
if (!tempFile.renameTo(targetFile)) {
plugin.logError("Unable to rename the temporary file!");
}
}
*/
public void addLink(String str1, String str2, int whichNether) {
addLink(str1, str2, null, false, whichNether);
}
public void addLink(String str1, String str2, CommandSender sender, boolean twoway, int whichNether) {
String outStr = "";
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(plugin.getDataFolder() + "/links.properties"), "UTF-8"));
String s = "";
while ((s = in.readLine()) != null) {
outStr = outStr.concat(s + "\n");
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
String str1Mod = str1;
String str2Mod = str2;
switch (whichNether) {
case 0:
break;
case 1:
str1Mod = "<" + str1Mod + ">";
break;
case 2:
str2Mod = "<" + str2Mod + ">";
break;
case 3:
str1Mod = "<" + str1Mod + ">";
str2Mod = "<" + str2Mod + ">";
break;
default:
break;
}
if (twoway) {
outStr = outStr.concat(str1Mod + "==" + str2Mod + "\n");
if (definedLinks.containsKey(str1)) {
if (sender != null) {
sender.sendMessage("Overriding previous link for \"" + str1 + "\".");
}
plugin.logWarning("Overriding previous link for \"" + str1 + "\".");
}
definedLinks.put(str1, new PortalLinkLinkValue(str2, whichNether));
if (sender != null) {
sender.sendMessage("Creating link...");
}
plugin.logInfo("Creating link...");
Environment environmentForWorld1 = Environment.NORMAL;
Environment environmentForWorld2 = Environment.NORMAL;
switch (whichNether) {
case 0:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NORMAL;
break;
case 1:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NORMAL;
break;
case 2:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NETHER;
break;
case 3:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NETHER;
break;
default:
break;
}
if (!str1.equals("")) plugin.getServer().createWorld(str1, environmentForWorld1);
if (!str2.equals("")) plugin.getServer().createWorld(str2, environmentForWorld2);
if (whichNether == 2) {
whichNether
} else if (whichNether == 1) {
whichNether++;
}
if (definedLinks.containsKey(str2)) {
if (sender != null) {
sender.sendMessage("Overriding previous link for \"" + str2 + "\".");
}
plugin.logWarning("Overriding previous link for \"" + str2 + "\".");
}
definedLinks.put(str2, new PortalLinkLinkValue(str1, whichNether));
} else {
outStr = outStr.concat(str1Mod + "=" + str2Mod + "\n");
if (definedLinks.containsKey(str1)) {
if (sender != null) {
sender.sendMessage("Overriding previous link for \"" + str1 + "\".");
}
plugin.logWarning("Overriding previous link for \"" + str1 + "\".");
}
definedLinks.put(str1, new PortalLinkLinkValue(str2, whichNether));
if (sender != null) {
sender.sendMessage("Creating link...");
}
plugin.logInfo("Creating link...");
Environment environmentForWorld1 = Environment.NORMAL;
Environment environmentForWorld2 = Environment.NORMAL;
switch (whichNether) {
case 0:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NORMAL;
break;
case 1:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NORMAL;
break;
case 2:
environmentForWorld1 = Environment.NORMAL;
environmentForWorld2 = Environment.NETHER;
break;
case 3:
environmentForWorld1 = Environment.NETHER;
environmentForWorld2 = Environment.NETHER;
break;
default:
break;
}
if (!str1.equals("")) plugin.getServer().createWorld(str1, environmentForWorld1);
if (!str2.equals("")) plugin.getServer().createWorld(str2, environmentForWorld2);
}
try {
Writer out = new OutputStreamWriter(new FileOutputStream(plugin.getDataFolder() + "/links.properties.tmp"), "UTF-8");
out.write(outStr);
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
plugin.logError("The save file could not be accessed!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File tempFile = new File(plugin.getDataFolder() + "/links.properties.tmp");
File targetFile = new File(plugin.getDataFolder() + "/links.properties");
if (!tempFile.renameTo(targetFile)) {
if (!targetFile.delete()) {
}
if (!tempFile.renameTo(targetFile)) {
plugin.logError("Unable to rename the temporary file!");
} else {
if (sender != null) {
sender.sendMessage("Link successfully created!");
}
plugin.logInfo("Link successfully created!");
}
} else {
if (sender != null) {
sender.sendMessage("Link successfully created!");
}
plugin.logInfo("Link successfully created!");
}
}
}
|
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesStore;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.time.*;
import java.util.UUID;
import static net.openhft.chronicle.bytes.NativeBytes.nativeBytes;
import static org.junit.Assert.*;
public class BinaryWire2Test {
@NotNull
Bytes bytes = nativeBytes();
@NotNull
private BinaryWire createWire() {
bytes.clear();
return new BinaryWire(bytes, false, false, false, 32, "lzw");
}
@Test
public void testBool() {
Wire wire = createWire();
wire.write().bool(false)
.write().bool(true)
.write().bool(null);
wire.read().bool("error", Assert::assertFalse)
.read().bool("error", Assert::assertTrue)
.read().bool("error", Assert::assertNull);
}
@Test
public void testBytesStore() {
Wire wire = createWire();
wire.write().object(Bytes.from("Hello"));
Bytes b = Bytes.elasticByteBuffer();
wire.read().object(b, Object.class);
assertEquals("Hello", b.toString());
}
@Test
public void testFloat32() {
Wire wire = createWire();
wire.write().float32(0.0F)
.write().float32(Float.NaN)
.write().float32(Float.POSITIVE_INFINITY);
wire.read().float32(this, (o, t) -> assertEquals(0.0F, t, 0.0F))
.read().float32(this, (o, t) -> assertTrue(Float.isNaN(t)))
.read().float32(this, (o, t) -> assertEquals(Float.POSITIVE_INFINITY, t, 0.0F));
}
@Test
public void testTime() {
Wire wire = createWire();
LocalTime now = LocalTime.now();
wire.write().time(now)
.write().time(LocalTime.MAX)
.write().time(LocalTime.MIN);
wire.read().time(now, Assert::assertEquals)
.read().time(LocalTime.MAX, Assert::assertEquals)
.read().time(LocalTime.MIN, Assert::assertEquals);
}
@Test
public void testZonedDateTime() {
Wire wire = createWire();
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime max = ZonedDateTime.of(LocalDateTime.MAX, ZoneId.systemDefault());
ZonedDateTime min = ZonedDateTime.of(LocalDateTime.MIN, ZoneId.systemDefault());
wire.write().zonedDateTime(now)
.write().zonedDateTime(max)
.write().zonedDateTime(min);
wire.read().zonedDateTime(now, Assert::assertEquals)
.read().zonedDateTime(max, Assert::assertEquals)
.read().zonedDateTime(min, Assert::assertEquals);
}
@Test
public void testDate() {
Wire wire = createWire();
LocalDate now = LocalDate.now();
wire.write().date(now)
.write().date(LocalDate.MAX)
.write().date(LocalDate.MIN);
wire.read().date(now, Assert::assertEquals)
.read().date(LocalDate.MAX, Assert::assertEquals)
.read().date(LocalDate.MIN, Assert::assertEquals);
}
@Test
public void testUuid() {
Wire wire = createWire();
UUID uuid = UUID.randomUUID();
wire.write().uuid(uuid)
.write().uuid(new UUID(0, 0))
.write().uuid(new UUID(Long.MAX_VALUE, Long.MAX_VALUE));
wire.read().uuid(this, (o, t) -> assertEquals(uuid, t))
.read().uuid(this, (o, t) -> assertEquals(new UUID(0, 0), t))
.read().uuid(this, (o, t) -> assertEquals(new UUID(Long.MAX_VALUE, Long.MAX_VALUE), t));
}
@Test
public void testSequence() {
Wire wire = createWire();
writeMessage(wire);
System.out.println(wire.bytes().toHexString());
Wire twire = new TextWire(Bytes.elasticByteBuffer());
writeMessage(twire);
System.out.println(Wires.fromSizePrefixedBlobs(twire.bytes()));
}
private void writeMessage(@NotNull WireOut wire) {
wire.writeDocument(true, w -> w
.write(() -> "csp").text("//path/service")
.write(() -> "tid").int64(123456789));
wire.writeDocument(false, w -> w
.write(() -> "entrySet").sequence(s -> {
s.marshallable(m -> m
.write(() -> "key").text("key-1")
.write(() -> "value").text("value-1"));
s.marshallable(m -> m
.write(() -> "key").text("key-2")
.write(() -> "value").text("value-2"));
}));
}
@Test
public void testSequenceContext() {
Wire wire = createWire();
writeMessageContext(wire);
System.out.println(wire.bytes().toHexString());
Wire twire = new TextWire(Bytes.elasticByteBuffer());
writeMessageContext(twire);
System.out.println(Wires.fromSizePrefixedBlobs(twire.bytes()));
}
private void writeMessageContext(@NotNull WireOut wire) {
try (DocumentContext _ = wire.writingDocument(true)) {
wire.write(() -> "csp").text("//path/service")
.write(() -> "tid").int64(123456789);
}
try (DocumentContext _ = wire.writingDocument(false)) {
wire.write(() -> "entrySet").sequence(s -> {
s.marshallable(m -> m
.write(() -> "key").text("key-1")
.write(() -> "value").text("value-1"));
s.marshallable(m -> m
.write(() -> "key").text("key-2")
.write(() -> "value").text("value-2"));
});
}
}
@Test
public void testEnum() {
Wire wire = createWire();
wire.write().object(WireType.BINARY)
.write().object(WireType.TEXT)
.write().object(WireType.RAW);
assertEquals(WireType.BINARY, wire.read().object(Object.class));
assertEquals(WireType.TEXT, wire.read().object(Object.class));
assertEquals(WireType.RAW, wire.read().object(Object.class));
}
@Test
public void fieldAfterText() {
Wire wire = createWire();
wire.writeDocument(false, w -> w.write(() -> "data")
.typePrefix("!UpdateEvent").marshallable(
v -> v.write(() -> "assetName").text("/name")
.write(() -> "key").object("test")
.write(() -> "oldValue").object("world1")
.write(() -> "value").object("world2")));
assertEquals("--- !!data #binary\n" +
"data: !!UpdateEvent {\n" +
" assetName: /name,\n" +
" key: test,\n" +
" oldValue: world1,\n" +
" value: world2\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
wire.readDocument(null, w -> w.read(() -> "data").typePrefix(this, (o, t) -> assertEquals("!UpdateEvent", t.toString())).marshallable(
m -> m.read(() -> "assetName").object(String.class, "/name", Assert::assertEquals)
.read(() -> "key").object(String.class, "test", Assert::assertEquals)
.read(() -> "oldValue").object(String.class, "world1", Assert::assertEquals)
.read(() -> "value").object(String.class, "world2", Assert::assertEquals)));
}
@Test
public void fieldAfterNull() {
Wire wire = createWire();
wire.writeDocument(false, w -> w.write(() -> "data").typedMarshallable("!UpdateEvent",
v -> v.write(() -> "assetName").text("/name")
.write(() -> "key").object("test")
.write(() -> "oldValue").object(null)
.write(() -> "value").object("world2")));
assertEquals("--- !!data #binary\n" +
"data: !!UpdateEvent {\n" +
" assetName: /name,\n" +
" key: test,\n" +
" oldValue: !!null \"\",\n" +
" value: world2\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
wire.readDocument(null, w -> w.read(() -> "data").typePrefix(this, (o, t) -> assertEquals("!UpdateEvent", t.toString())).marshallable(
m -> m.read(() -> "assetName").object(String.class, "/name", Assert::assertEquals)
.read(() -> "key").object(String.class, "test", Assert::assertEquals)
.read(() -> "oldValue").object(String.class, "error", Assert::assertNull)
.read(() -> "value").object(String.class, "world2", Assert::assertEquals)));
}
@Test
public void fieldAfterNullContext() {
Wire wire = createWire();
try (DocumentContext _ = wire.writingDocument(true)) {
wire.write(() -> "tid").int64(1234567890L);
}
try (DocumentContext _ = wire.writingDocument(false)) {
wire.write(() -> "data").typedMarshallable("!UpdateEvent",
v -> v.write(() -> "assetName").text("/name")
.write(() -> "key").object("test")
.write(() -> "oldValue").object(null)
.write(() -> "value").object("world2"));
}
assertEquals("--- !!meta-data #binary\n" +
"tid: 1234567890\n" +
"--- !!data #binary\n" +
"data: !!UpdateEvent {\n" +
" assetName: /name,\n" +
" key: test,\n" +
" oldValue: !!null \"\",\n" +
" value: world2\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
try (DocumentContext context = wire.readingDocument()) {
assertTrue(context.isPresent());
assertTrue(context.isMetaData());
Assert.assertEquals(1234567890L, wire.read(() -> "tid").int64());
}
try (DocumentContext context = wire.readingDocument()) {
assertTrue(context.isPresent());
assertTrue(context.isData());
wire.read(() -> "data").typePrefix(this, (o, t) -> assertEquals("!UpdateEvent", t.toString())).marshallable(
m -> m.read(() -> "assetName").object(String.class, "/name", Assert::assertEquals)
.read(() -> "key").object(String.class, "test", Assert::assertEquals)
.read(() -> "oldValue").object(String.class, "error", Assert::assertNull)
.read(() -> "value").object(String.class, "world2", Assert::assertEquals));
}
try (DocumentContext context = wire.readingDocument()) {
assertFalse(context.isPresent());
}
}
@Test
public void readDemarshallable() {
Wire wire = createWire();
try (DocumentContext $ = wire.writingDocument(true)) {
wire.getValueOut().typedMarshallable(new DemarshallableObject("test", 12345));
}
assertEquals("--- !!meta-data #binary\n" +
"!net.openhft.chronicle.wire.DemarshallableObject {\n" +
" name: test,\n" +
" value: 12345\n" +
"}\n", Wires.fromSizePrefixedBlobs(wire.bytes()));
try (DocumentContext $ = wire.readingDocument()) {
DemarshallableObject dobj = wire.getValueIn().typedMarshallable();
assertEquals("test", dobj.name);
assertEquals(12345, dobj.value);
}
}
@Test
public void testSnappyCompressWithSnappy() throws IOException {
Wire wire = createWire();
String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
wire.write(() -> "message").compress("snappy", str);
wire.bytes().readPosition(0);
String str2 = wire.read(() -> "message").text();
assertEquals(str, str2);
wire.bytes().readPosition(0);
Bytes asText = Bytes.elasticByteBuffer();
wire.copyTo(new TextWire(asText));
assertEquals("message: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", asText.toString());
}
@Test
@Ignore("Todo fix")
public void testSnappyCompressWithSnappy2() throws IOException {
Wire wire = createWire();
Bytes str = Bytes.from("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
wire.write(() -> "message").compress("snappy", str);
wire.bytes().readPosition(0);
String str2 = wire.read(() -> "message").text();
assertEquals(str.toString(), str2);
wire.bytes().readPosition(0);
Bytes asText = Bytes.elasticByteBuffer();
wire.copyTo(new TextWire(asText));
assertEquals("message: # snappy\n" +
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", asText.toString());
}
@Test
public void testCompression() {
for (String comp : "binary,gzip,lzw".split(",")) {
bytes.clear();
Wire wire = new BinaryWire(bytes, false, false, false, 32, comp);
String str = "xxxxxxxxxxxxxxxx2xxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyy2yyyyyyyyyyyyyyyyy";
BytesStore bytes = BytesStore.from(str);
wire.write()
.bytes(bytes);
System.out.println(comp + ": str.length() = " + str.length() + ", wire.bytes().readRemaining() = " + wire.bytes().readRemaining());
if (!comp.equals("binary"))
assertTrue(wire.bytes().readRemaining() + " >= " + str.length(),
wire.bytes().readRemaining() < str.length());
wire.bytes().readPosition(0);
BytesStore bytesStore = wire.read()
.bytesStore();
assert bytesStore != null;
assertEquals(bytes.toDebugString(), bytesStore.toDebugString());
}
}
}
|
package com.valkryst.VTerminal.builder;
import com.valkryst.VJSON.VJSONParser;
import com.valkryst.VTerminal.component.RadioButton;
import com.valkryst.VTerminal.component.RadioButtonGroup;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.json.simple.JSONObject;
@Data
@NoArgsConstructor
public class RadioButtonBuilder extends ButtonBuilder implements VJSONParser {
/** The character to display when the radio button is not checked. */
private char emptyButtonChar;
/** The character to display when the radio button is checked. */
private char checkedButtonChar;
/** The radio button group that the radio button will belong to. */
@NonNull private RadioButtonGroup group;
@Override
public RadioButton build() {
checkState();
super.setDimensions(super.getText().length() + 2, 1);
super.setText(emptyButtonChar + " " + super.getText());
final RadioButton radioButton = new RadioButton(this);
group.addRadioButton(radioButton);
return radioButton;
}
/** Checks the current state of the builder. */
protected void checkState() throws NullPointerException {
super.checkState();
if (group == null) {
group = new RadioButtonGroup();
}
}
@Override
public void parse(final JSONObject jsonObject) {
if (jsonObject == null) {
return;
}
super.parse(jsonObject);
final Character emptyButtonChar = getChar(jsonObject, "emptyButtonChar");
final Character checkedButtonChar = getChar(jsonObject, "checkedButtonChar");
// todo Add isChecked
if (emptyButtonChar == null) {
throw new NullPointerException("The 'emptyButtonChar' value was not found.");
} else {
this.emptyButtonChar = emptyButtonChar;
}
if (checkedButtonChar == null) {
throw new NullPointerException("The 'checkedButtonChar' value was not found.");
} else {
this.checkedButtonChar = checkedButtonChar;
}
}
@Override
public void reset() {
super.reset();
emptyButtonChar = '';
checkedButtonChar = '';
group = null;
}
}
|
package org.neo4j.gis.spatial;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.neo4j.collections.rtree.Envelope;
import org.neo4j.gis.spatial.geotools.data.StyledImageExporter;
import org.neo4j.gis.spatial.pipes.GeoPipeFlow;
import org.neo4j.gis.spatial.pipes.GeoPipeline;
import org.neo4j.gis.spatial.query.SearchContain;
import org.neo4j.gis.spatial.query.SearchPointsWithinOrthodromicDistance;
import org.neo4j.gis.spatial.query.SearchWithin;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateList;
import com.vividsolutions.jts.geom.Point;
public class TestSimplePointLayer extends Neo4jTestCase {
@Test
public void testSimplePointLayer() {
SpatialDatabaseService db = new SpatialDatabaseService(graphDb());
EditableLayer layer = (EditableLayer) db.createSimplePointLayer("test", "Longitude", "Latitude");
assertNotNull(layer);
SpatialRecord record = layer.add(layer.getGeometryFactory().createPoint(new Coordinate(15.3, 56.2)));
assertNotNull(record);
// finds geometries that contain the given geometry
SearchContain searchQuery = new SearchContain(
layer.getGeometryFactory().toGeometry(new com.vividsolutions.jts.geom.Envelope(15.0, 16.0, 56.0, 57.0)));
layer.getIndex().executeSearch(searchQuery);
List<SpatialDatabaseRecord> results = searchQuery.getExtendedResults();
// should not be contained
assertEquals(0, results.size());
SearchWithin withinQuery = new SearchWithin(
layer.getGeometryFactory().toGeometry(new com.vividsolutions.jts.geom.Envelope(15.0, 16.0, 56.0, 57.0)));
layer.getIndex().executeSearch(withinQuery);
results = withinQuery.getExtendedResults();
assertEquals(1, results.size());
}
@Test
public void testNeoTextLayer() {
SpatialDatabaseService db = new SpatialDatabaseService(graphDb());
SimplePointLayer layer = db.createSimplePointLayer("neo-text");
assertNotNull(layer);
for (Coordinate coordinate : makeCoordinateDataFromTextFile("NEO4J-SPATIAL.txt")) {
SpatialRecord record = layer.add(coordinate);
assertNotNull(record);
}
saveLayerAsImage(layer, 700, 70);
Envelope bbox = layer.getIndex().getBoundingBox();
double[] centre = bbox.centre();
List<GeoPipeFlow> results = GeoPipeline.startNearestNeighborLatLonSearch(layer, new Coordinate(centre[0] + 0.1, centre[1]), 10.0)
.sort("OrthodromicDistance").toList();
saveResultsAsImage(results, "temporary-results-layer-" + layer.getName(), 130, 70);
assertEquals(71, results.size());
checkPointOrder(results);
results = GeoPipeline.startNearestNeighborLatLonSearch(layer, new Coordinate(centre[0] + 0.1, centre[1]), 5.0)
.sort("OrthodromicDistance").toList();
saveResultsAsImage(results, "temporary-results-layer2-" + layer.getName(), 130, 70);
assertEquals(30, results.size());
checkPointOrder(results);
}
private void checkPointOrder(List<GeoPipeFlow> results) {
for (int i = 0; i < results.size() - 1; i++) {
GeoPipeFlow first = results.get(i);
GeoPipeFlow second = results.get(i + 1);
double d1 = (Double) first.getProperties().get("OrthodromicDistance");
double d2 = (Double) second.getProperties().get("OrthodromicDistance");
assertTrue("Point at position " + i + " (d=" + d1 + ") must be closer than point at position " + (i + 1) + " (d=" + d2
+ ")", d1 <= d2);
}
}
@Test
public void testDensePointLayer() {
SpatialDatabaseService db = new SpatialDatabaseService(graphDb());
SimplePointLayer layer = db.createSimplePointLayer("neo-dense", "lon", "lat");
assertNotNull(layer);
for (Coordinate coordinate : makeDensePointData()) {
Point point = layer.getGeometryFactory().createPoint(coordinate);
SpatialRecord record = layer.add(point);
assertNotNull(record);
}
saveLayerAsImage(layer, 300, 300);
Envelope bbox = layer.getIndex().getBoundingBox();
double[] centre = bbox.centre();
SearchPointsWithinOrthodromicDistance distanceQuery = new SearchPointsWithinOrthodromicDistance(
new Coordinate(centre[0], centre[1]), 10.0);
layer.getIndex().executeSearch(distanceQuery);
List<SpatialDatabaseRecord> results = distanceQuery.getExtendedResults();
saveResultsAsImage(results, "temporary-results-layer-" + layer.getName(), 150, 150);
assertEquals(456, results.size());
}
private void saveLayerAsImage(Layer layer, int width, int height) {
ShapefileExporter shpExporter = new ShapefileExporter(graphDb());
shpExporter.setExportDir("target/export/SimplePointTests");
StyledImageExporter imageExporter = new StyledImageExporter(graphDb());
imageExporter.setExportDir("target/export/SimplePointTests");
imageExporter.setZoom(0.9);
imageExporter.setSize(width, height);
try {
imageExporter.saveLayerImage(layer.getName());
shpExporter.exportLayer(layer.getName());
} catch (Exception e) {
throw new AssertionFailedError("Failed to save layer '" + layer.getName() + "' as image: " + e.getMessage());
}
}
private void saveResultsAsImage(List<? extends SpatialRecord> results, String layerName, int width, int height) {
ShapefileExporter shpExporter = new ShapefileExporter(graphDb());
shpExporter.setExportDir("target/export/SimplePointTests");
StyledImageExporter imageExporter = new StyledImageExporter(graphDb());
imageExporter.setExportDir("target/export/SimplePointTests");
imageExporter.setZoom(0.9);
imageExporter.setSize(width, height);
SpatialDatabaseService db = new SpatialDatabaseService(graphDb());
EditableLayer tmpLayer = (EditableLayer) db.createSimplePointLayer(layerName, "lon", "lat");
for (SpatialRecord record : results) {
tmpLayer.add(record.getGeometry());
}
try {
imageExporter.saveLayerImage(layerName);
shpExporter.exportLayer(layerName);
} catch (Exception e) {
throw new AssertionFailedError("Failed to save results image: " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
private static Coordinate[] makeCoordinateDataFromTextFile(String textFile) {
CoordinateList data = new CoordinateList();
try {
BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/"+textFile));
Coordinate origin = new Coordinate(13.0, 55.6);
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
int col = 0;
for (String character : line.split("")) {
if (col > 0 && !character.matches("\\s")) {
Coordinate coordinate = new Coordinate(origin.x + (double) col / 100.0, origin.y - (double) row / 100.0);
data.add(coordinate);
}
col++;
}
row++;
}
} catch (IOException e) {
throw new AssertionFailedError("Input data for string test invalid: " + e.getMessage());
}
return data.toCoordinateArray();
}
@SuppressWarnings("unchecked")
private static Coordinate[] makeDensePointData() {
CoordinateList data = new CoordinateList();
Coordinate origin = new Coordinate(13.0, 55.6);
for (int row = 0; row < 40; row++) {
for (int col = 0; col < 40; col++) {
Coordinate coordinate = new Coordinate(origin.x + (double) col / 100.0, origin.y - (double) row / 100.0);
data.add(coordinate);
}
}
return data.toCoordinateArray();
}
}
|
package org.threeten.bp.zone;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.List;
import org.testng.annotations.Test;
import org.threeten.bp.DayOfWeek;
import org.threeten.bp.Duration;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.LocalTime;
import org.threeten.bp.Month;
import org.threeten.bp.Year;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.zone.ZoneOffsetTransitionRule.TimeDefinition;
/**
* Test ZoneRules.
*/
@Test
public class TestStandardZoneRules {
private static final ZoneOffset OFFSET_ZERO = ZoneOffset.ofHours(0);
private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1);
private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2);
public static final String LATEST_TZDB = "2009b";
private static final int OVERLAP = 2;
private static final int GAP = 0;
// Basics
public void test_serialization_loaded() throws Exception {
assertSerialization(europeLondon());
assertSerialization(europeParis());
assertSerialization(americaNewYork());
}
private void assertSerialization(ZoneRules test) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(test);
baos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
ZoneRules result = (ZoneRules) in.readObject();
assertEquals(result, test);
}
// Etc/GMT
private ZoneRules etcGmt() {
return ZoneId.of("Etc/GMT").getRules();
}
public void test_EtcGmt_nextTransition() {
assertNull(etcGmt().nextTransition(Instant.EPOCH));
}
public void test_EtcGmt_previousTransition() {
assertNull(etcGmt().previousTransition(Instant.EPOCH));
}
// Europe/London
private ZoneRules europeLondon() {
return ZoneId.of("Europe/London").getRules();
}
public void test_London() {
ZoneRules test = europeLondon();
assertEquals(test.isFixedOffset(), false);
}
public void test_London_preTimeZones() {
ZoneRules test = europeLondon();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15);
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
public void test_London_getOffset() {
ZoneRules test = europeLondon();
assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO);
}
public void test_London_getOffset_toDST() {
ZoneRules test = europeLondon();
assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE);
}
public void test_London_getOffset_fromDST() {
ZoneRules test = europeLondon();
assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO);
}
public void test_London_getOffsetInfo() {
ZoneRules test = europeLondon();
checkOffset(test, createLDT(2008, 1, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 2, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 4, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 5, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 6, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 7, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 8, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 9, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 11, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 12, 1), OFFSET_ZERO, 1);
}
public void test_London_getOffsetInfo_toDST() {
ZoneRules test = europeLondon();
checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1);
// cutover at 01:00Z
checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1);
checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1);
}
public void test_London_getOffsetInfo_fromDST() {
ZoneRules test = europeLondon();
checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1);
// cutover at 01:00Z
checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1);
checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1);
}
public void test_London_getOffsetInfo_gap() {
ZoneRules test = europeLondon();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), OFFSET_ZERO);
assertEquals(trans.getOffsetAfter(), OFFSET_PONE);
assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC));
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0));
assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
assertEquals(trans.isValidOffset(OFFSET_PONE), false);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_ZERO));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_London_getOffsetInfo_overlap() {
ZoneRules test = europeLondon();
final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP);
assertEquals(trans.isGap(), false);
assertEquals(trans.isOverlap(), true);
assertEquals(trans.getOffsetBefore(), OFFSET_PONE);
assertEquals(trans.getOffsetAfter(), OFFSET_ZERO);
assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC));
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0));
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
assertEquals(trans.isValidOffset(OFFSET_ZERO), true);
assertEquals(trans.isValidOffset(OFFSET_PONE), true);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_PONE));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_London_getStandardOffset() {
ZoneRules test = europeLondon();
ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
while (zdt.getYear() < 2010) {
Instant instant = zdt.toInstant();
if (zdt.getYear() < 1848) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15));
} else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
} else {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
}
zdt = zdt.plusMonths(6);
}
}
public void test_London_getTransitions() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition first = trans.get(0);
assertEquals(first.getDateTimeBefore(), LocalDateTime.of(1847, 12, 1, 0, 0));
assertEquals(first.getOffsetBefore(), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15));
assertEquals(first.getOffsetAfter(), OFFSET_ZERO);
ZoneOffsetTransition spring1916 = trans.get(1);
assertEquals(spring1916.getDateTimeBefore(), LocalDateTime.of(1916, 5, 21, 2, 0));
assertEquals(spring1916.getOffsetBefore(), OFFSET_ZERO);
assertEquals(spring1916.getOffsetAfter(), OFFSET_PONE);
ZoneOffsetTransition autumn1916 = trans.get(2);
assertEquals(autumn1916.getDateTimeBefore(), LocalDateTime.of(1916, 10, 1, 3, 0));
assertEquals(autumn1916.getOffsetBefore(), OFFSET_PONE);
assertEquals(autumn1916.getOffsetAfter(), OFFSET_ZERO);
ZoneOffsetTransition zot = null;
Iterator<ZoneOffsetTransition> it = trans.iterator();
while (it.hasNext()) {
zot = it.next();
if (zot.getDateTimeBefore().getYear() == 1990) {
break;
}
}
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 3, 25, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 10, 28, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 3, 31, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 10, 27, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 3, 29, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 10, 25, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 3, 28, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 10, 24, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 3, 27, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 10, 23, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 3, 26, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 10, 22, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 3, 31, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 10, 27, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 3, 30, 1, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_ZERO);
zot = it.next();
assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 10, 26, 2, 0));
assertEquals(zot.getOffsetBefore(), OFFSET_PONE);
assertEquals(it.hasNext(), false);
}
public void test_London_getTransitionRules() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransitionRule> rules = test.getTransitionRules();
assertEquals(rules.size(), 2);
ZoneOffsetTransitionRule in = rules.get(0);
assertEquals(in.getMonth(), Month.MARCH);
assertEquals(in.getDayOfMonthIndicator(), 25); // optimized from -1
assertEquals(in.getDayOfWeek(), DayOfWeek.SUNDAY);
assertEquals(in.getLocalTime(), LocalTime.of(1, 0));
assertEquals(in.getTimeDefinition(), TimeDefinition.UTC);
assertEquals(in.getStandardOffset(), OFFSET_ZERO);
assertEquals(in.getOffsetBefore(), OFFSET_ZERO);
assertEquals(in.getOffsetAfter(), OFFSET_PONE);
ZoneOffsetTransitionRule out = rules.get(1);
assertEquals(out.getMonth(), Month.OCTOBER);
assertEquals(out.getDayOfMonthIndicator(), 25); // optimized from -1
assertEquals(out.getDayOfWeek(), DayOfWeek.SUNDAY);
assertEquals(out.getLocalTime(), LocalTime.of(1, 0));
assertEquals(out.getTimeDefinition(), TimeDefinition.UTC);
assertEquals(out.getStandardOffset(), OFFSET_ZERO);
assertEquals(out.getOffsetBefore(), OFFSET_PONE);
assertEquals(out.getOffsetAfter(), OFFSET_ZERO);
}
public void test_London_nextTransition_historic() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition first = trans.get(0);
assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first);
for (int i = 0; i < trans.size() - 1; i++) {
ZoneOffsetTransition cur = trans.get(i);
ZoneOffsetTransition next = trans.get(i + 1);
assertEquals(test.nextTransition(cur.getInstant()), next);
assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next);
}
}
public void test_London_nextTransition_rulesBased() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransitionRule> rules = test.getTransitionRules();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition last = trans.get(trans.size() - 1);
assertEquals(test.nextTransition(last.getInstant()), rules.get(0).createTransition(1998));
for (int year = 1998; year < 2010; year++) {
ZoneOffsetTransition a = rules.get(0).createTransition(year);
ZoneOffsetTransition b = rules.get(1).createTransition(year);
ZoneOffsetTransition c = rules.get(0).createTransition(year + 1);
assertEquals(test.nextTransition(a.getInstant()), b);
assertEquals(test.nextTransition(b.getInstant().minusNanos(1)), b);
assertEquals(test.nextTransition(b.getInstant()), c);
assertEquals(test.nextTransition(c.getInstant().minusNanos(1)), c);
}
}
public void test_London_nextTransition_lastYear() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransitionRule> rules = test.getTransitionRules();
ZoneOffsetTransition zot = rules.get(1).createTransition(Year.MAX_VALUE);
assertEquals(test.nextTransition(zot.getInstant()), null);
}
public void test_London_previousTransition_historic() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition first = trans.get(0);
assertEquals(test.previousTransition(first.getInstant()), null);
assertEquals(test.previousTransition(first.getInstant().minusNanos(1)), null);
for (int i = 0; i < trans.size() - 1; i++) {
ZoneOffsetTransition prev = trans.get(i);
ZoneOffsetTransition cur = trans.get(i + 1);
assertEquals(test.previousTransition(cur.getInstant()), prev);
assertEquals(test.previousTransition(prev.getInstant().plusSeconds(1)), prev);
assertEquals(test.previousTransition(prev.getInstant().plusNanos(1)), prev);
}
}
public void test_London_previousTransition_rulesBased() {
ZoneRules test = europeLondon();
List<ZoneOffsetTransitionRule> rules = test.getTransitionRules();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition last = trans.get(trans.size() - 1);
assertEquals(test.previousTransition(last.getInstant().plusSeconds(1)), last);
assertEquals(test.previousTransition(last.getInstant().plusNanos(1)), last);
// Jan 1st of year between transitions and rules
ZonedDateTime odt = ZonedDateTime.ofInstant(last.getInstant(), last.getOffsetAfter());
odt = odt.withDayOfYear(1).plusYears(1).with(LocalTime.MIDNIGHT);
assertEquals(test.previousTransition(odt.toInstant()), last);
// later years
for (int year = 1998; year < 2010; year++) {
ZoneOffsetTransition a = rules.get(0).createTransition(year);
ZoneOffsetTransition b = rules.get(1).createTransition(year);
ZoneOffsetTransition c = rules.get(0).createTransition(year + 1);
assertEquals(test.previousTransition(c.getInstant()), b);
assertEquals(test.previousTransition(b.getInstant().plusSeconds(1)), b);
assertEquals(test.previousTransition(b.getInstant().plusNanos(1)), b);
assertEquals(test.previousTransition(b.getInstant()), a);
assertEquals(test.previousTransition(a.getInstant().plusSeconds(1)), a);
assertEquals(test.previousTransition(a.getInstant().plusNanos(1)), a);
}
}
// Europe/Dublin
private ZoneRules europeDublin() {
return ZoneId.of("Europe/Dublin").getRules();
}
public void test_Dublin() {
ZoneRules test = europeDublin();
assertEquals(test.isFixedOffset(), false);
}
public void test_Dublin_getOffset() {
ZoneRules test = europeDublin();
assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO);
}
public void test_Dublin_getOffset_toDST() {
ZoneRules test = europeDublin();
assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE);
}
public void test_Dublin_getOffset_fromDST() {
ZoneRules test = europeDublin();
assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO);
assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO);
}
public void test_Dublin_getOffsetInfo() {
ZoneRules test = europeDublin();
checkOffset(test, createLDT(2008, 1, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 2, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 4, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 5, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 6, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 7, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 8, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 9, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 11, 1), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 12, 1), OFFSET_ZERO, 1);
}
public void test_Dublin_getOffsetInfo_toDST() {
ZoneRules test = europeDublin();
checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1);
// cutover at 01:00Z
checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1);
checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1);
}
public void test_Dublin_getOffsetInfo_fromDST() {
ZoneRules test = europeDublin();
checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1);
checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1);
// cutover at 01:00Z
checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1);
checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1);
}
public void test_Dublin_getOffsetInfo_gap() {
ZoneRules test = europeDublin();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), OFFSET_ZERO);
assertEquals(trans.getOffsetAfter(), OFFSET_PONE);
assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC));
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0));
assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
assertEquals(trans.isValidOffset(OFFSET_PONE), false);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]");
}
public void test_Dublin_getOffsetInfo_overlap() {
ZoneRules test = europeDublin();
final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP);
assertEquals(trans.isGap(), false);
assertEquals(trans.isOverlap(), true);
assertEquals(trans.getOffsetBefore(), OFFSET_PONE);
assertEquals(trans.getOffsetAfter(), OFFSET_ZERO);
assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC));
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0));
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
assertEquals(trans.isValidOffset(OFFSET_ZERO), true);
assertEquals(trans.isValidOffset(OFFSET_PONE), true);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]");
}
public void test_Dublin_getStandardOffset() {
ZoneRules test = europeDublin();
ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
while (zdt.getYear() < 2010) {
Instant instant = zdt.toInstant();
if (zdt.getYear() < 1881) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutes(0, -25));
} else if (zdt.getYear() >= 1881 && zdt.getYear() < 1917) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -25, -21));
} else if (zdt.getYear() >= 1917 && zdt.getYear() < 1969) {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO, zdt.toString());
} else {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE); // negative DST
}
zdt = zdt.plusMonths(6);
}
}
public void test_Dublin_dst() {
ZoneRules test = europeDublin();
assertEquals(test.isDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), false);
assertEquals(test.getDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0));
assertEquals(test.isDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), true);
assertEquals(test.getDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(1));
// negative DST causes isDaylightSavings() to reverse
assertEquals(test.isDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), true);
assertEquals(test.getDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(-1));
assertEquals(test.isDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), false);
assertEquals(test.getDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0));
// TZDB data is messed up, comment out tests until better fix available
// DateTimeFormatter formatter1 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.FULL).toFormatter();
// assertEquals(formatter1.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "Greenwich Mean Time");
// assertEquals(formatter1.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))), "Irish Standard Time");
// DateTimeFormatter formatter2 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.SHORT).toFormatter();
// assertEquals(formatter2.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "GMT");
// assertEquals(formatter2.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))), "IST");
}
// Europe/Paris
private ZoneRules europeParis() {
return ZoneId.of("Europe/Paris").getRules();
}
public void test_Paris() {
ZoneRules test = europeParis();
assertEquals(test.isFixedOffset(), false);
}
public void test_Paris_preTimeZones() {
ZoneRules test = europeParis();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21);
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
public void test_Paris_getOffset() {
ZoneRules test = europeParis();
assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_PONE);
}
public void test_Paris_getOffset_toDST() {
ZoneRules test = europeParis();
assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PTWO);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PTWO);
}
public void test_Paris_getOffset_fromDST() {
ZoneRules test = europeParis();
assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_PONE);
assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_PONE);
// cutover at 01:00Z
assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PTWO);
assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE);
}
public void test_Paris_getOffsetInfo() {
ZoneRules test = europeParis();
checkOffset(test, createLDT(2008, 1, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 2, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 4, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 5, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 6, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 7, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 8, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 9, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 10, 1), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 11, 1), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 12, 1), OFFSET_PONE, 1);
}
public void test_Paris_getOffsetInfo_toDST() {
ZoneRules test = europeParis();
checkOffset(test, createLDT(2008, 3, 24), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 25), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 26), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 27), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 28), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 29), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 30), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 3, 31), OFFSET_PTWO, 1);
// cutover at 01:00Z which is 02:00+01:00(local Paris time)
checkOffset(test, LocalDateTime.of(2008, 3, 30, 1, 59, 59, 999999999), OFFSET_PONE, 1);
checkOffset(test, LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0), OFFSET_PTWO, 1);
}
public void test_Paris_getOffsetInfo_fromDST() {
ZoneRules test = europeParis();
checkOffset(test, createLDT(2008, 10, 24), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 10, 25), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 10, 26), OFFSET_PTWO, 1);
checkOffset(test, createLDT(2008, 10, 27), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 28), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 29), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 30), OFFSET_PONE, 1);
checkOffset(test, createLDT(2008, 10, 31), OFFSET_PONE, 1);
// cutover at 01:00Z which is 02:00+01:00(local Paris time)
checkOffset(test, LocalDateTime.of(2008, 10, 26, 1, 59, 59, 999999999), OFFSET_PTWO, 1);
checkOffset(test, LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0), OFFSET_PONE, 1);
}
public void test_Paris_getOffsetInfo_gap() {
ZoneRules test = europeParis();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), OFFSET_PONE);
assertEquals(trans.getOffsetAfter(), OFFSET_PTWO);
assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC));
assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
assertEquals(trans.isValidOffset(OFFSET_PONE), false);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_PONE));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_Paris_getOffsetInfo_overlap() {
ZoneRules test = europeParis();
final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PTWO, OVERLAP);
assertEquals(trans.isGap(), false);
assertEquals(trans.isOverlap(), true);
assertEquals(trans.getOffsetBefore(), OFFSET_PTWO);
assertEquals(trans.getOffsetAfter(), OFFSET_PONE);
assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC));
assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
assertEquals(trans.isValidOffset(OFFSET_PONE), true);
assertEquals(trans.isValidOffset(OFFSET_PTWO), true);
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false);
assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_PTWO));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_Paris_getStandardOffset() {
ZoneRules test = europeParis();
ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
while (zdt.getYear() < 2010) {
Instant instant = zdt.toInstant();
if (zdt.toLocalDate().isBefore(LocalDate.of(1911, 3, 11))) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, 9, 21));
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1940, 6, 14))) {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1944, 8, 25))) {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1945, 9, 16))) {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
} else {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
}
zdt = zdt.plusMonths(6);
}
}
// America/New_York
private ZoneRules americaNewYork() {
return ZoneId.of("America/New_York").getRules();
}
public void test_NewYork() {
ZoneRules test = americaNewYork();
assertEquals(test.isFixedOffset(), false);
}
public void test_NewYork_preTimeZones() {
ZoneRules test = americaNewYork();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.of("-04:56:02");
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
public void test_NewYork_getOffset() {
ZoneRules test = americaNewYork();
ZoneOffset offset = ZoneOffset.ofHours(-5);
assertEquals(test.getOffset(createInstant(2008, 1, 1, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 2, 1, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 3, 1, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 4, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 5, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 6, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 7, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 8, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 9, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 10, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 12, 1, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 1, 28, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 2, 28, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 3, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 4, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 5, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 6, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 7, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 8, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 9, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 10, 28, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 11, 28, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 12, 28, offset)), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffset_toDST() {
ZoneRules test = americaNewYork();
ZoneOffset offset = ZoneOffset.ofHours(-5);
assertEquals(test.getOffset(createInstant(2008, 3, 8, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 3, 9, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 3, 10, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 3, 11, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 3, 12, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 3, 13, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 3, 14, offset)), ZoneOffset.ofHours(-4));
// cutover at 02:00 local
assertEquals(test.getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-4));
}
public void test_NewYork_getOffset_fromDST() {
ZoneRules test = americaNewYork();
ZoneOffset offset = ZoneOffset.ofHours(-4);
assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 11, 2, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 11, 3, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 11, 4, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 11, 5, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 11, 6, offset)), ZoneOffset.ofHours(-5));
assertEquals(test.getOffset(createInstant(2008, 11, 7, offset)), ZoneOffset.ofHours(-5));
// cutover at 02:00 local
assertEquals(test.getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-4));
assertEquals(test.getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffsetInfo() {
ZoneRules test = americaNewYork();
checkOffset(test, createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 2, 1), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 3, 1), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 4, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 5, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 6, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 7, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 8, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 9, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 10, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 12, 1), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 1, 28), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 2, 28), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 3, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 4, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 5, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 6, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 7, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 8, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 9, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 10, 28), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 11, 28), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1);
}
public void test_NewYork_getOffsetInfo_toDST() {
ZoneRules test = americaNewYork();
checkOffset(test, createLDT(2008, 3, 8), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 3, 9), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 3, 10), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 3, 11), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 3, 12), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 3, 13), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 3, 14), ZoneOffset.ofHours(-4), 1);
// cutover at 02:00 local
checkOffset(test, LocalDateTime.of(2008, 3, 9, 1, 59, 59, 999999999), ZoneOffset.ofHours(-5), 1);
checkOffset(test, LocalDateTime.of(2008, 3, 9, 3, 0, 0, 0), ZoneOffset.ofHours(-4), 1);
}
public void test_NewYork_getOffsetInfo_fromDST() {
ZoneRules test = americaNewYork();
checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 11, 2), ZoneOffset.ofHours(-4), 1);
checkOffset(test, createLDT(2008, 11, 3), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 11, 4), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 11, 5), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 11, 6), ZoneOffset.ofHours(-5), 1);
checkOffset(test, createLDT(2008, 11, 7), ZoneOffset.ofHours(-5), 1);
// cutover at 02:00 local
checkOffset(test, LocalDateTime.of(2008, 11, 2, 0, 59, 59, 999999999), ZoneOffset.ofHours(-4), 1);
checkOffset(test, LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0), ZoneOffset.ofHours(-5), 1);
}
public void test_NewYork_getOffsetInfo_gap() {
ZoneRules test = americaNewYork();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-5), GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5));
assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4));
assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5)));
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false);
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false);
assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(ZoneOffset.ofHours(-5)));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_NewYork_getOffsetInfo_overlap() {
ZoneRules test = americaNewYork();
final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-4), OVERLAP);
assertEquals(trans.isGap(), false);
assertEquals(trans.isOverlap(), true);
assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4));
assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5));
assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4)));
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true);
assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(ZoneOffset.ofHours(-4)));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
public void test_NewYork_getStandardOffset() {
ZoneRules test = americaNewYork();
ZonedDateTime dateTime = createZDT(1860, 1, 1, ZoneOffset.UTC);
while (dateTime.getYear() < 2010) {
Instant instant = dateTime.toInstant();
if (dateTime.toLocalDate().isBefore(LocalDate.of(1883, 11, 18))) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.of("-04:56:02"));
} else {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHours(-5));
}
dateTime = dateTime.plusMonths(6);
}
}
// Kathmandu
private ZoneRules asiaKathmandu() {
return ZoneId.of("Asia/Kathmandu").getRules();
}
public void test_Kathmandu_nextTransition_historic() {
ZoneRules test = asiaKathmandu();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition first = trans.get(0);
assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first);
for (int i = 0; i < trans.size() - 1; i++) {
ZoneOffsetTransition cur = trans.get(i);
ZoneOffsetTransition next = trans.get(i + 1);
assertEquals(test.nextTransition(cur.getInstant()), next);
assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next);
}
}
public void test_Kathmandu_nextTransition_noRules() {
ZoneRules test = asiaKathmandu();
List<ZoneOffsetTransition> trans = test.getTransitions();
ZoneOffsetTransition last = trans.get(trans.size() - 1);
assertEquals(test.nextTransition(last.getInstant()), null);
}
@Test(expectedExceptions=UnsupportedOperationException.class)
public void test_getTransitions_immutable() {
ZoneRules test = europeParis();
test.getTransitions().clear();
}
@Test(expectedExceptions=UnsupportedOperationException.class)
public void test_getTransitionRules_immutable() {
ZoneRules test = europeParis();
test.getTransitionRules().clear();
}
// equals() / hashCode()
public void test_equals() {
ZoneRules test1 = europeLondon();
ZoneRules test2 = europeParis();
ZoneRules test2b = europeParis();
assertEquals(test1.equals(test2), false);
assertEquals(test2.equals(test1), false);
assertEquals(test1.equals(test1), true);
assertEquals(test2.equals(test2), true);
assertEquals(test2.equals(test2b), true);
assertEquals(test1.hashCode() == test1.hashCode(), true);
assertEquals(test2.hashCode() == test2.hashCode(), true);
assertEquals(test2.hashCode() == test2b.hashCode(), true);
}
public void test_equals_null() {
assertEquals(europeLondon().equals(null), false);
}
public void test_equals_notZoneRules() {
assertEquals(europeLondon().equals("Europe/London"), false);
}
public void test_toString() {
assertEquals(europeLondon().toString().contains("ZoneRules"), true);
}
private Instant createInstant(int year, int month, int day, ZoneOffset offset) {
return LocalDateTime.of(year, month, day, 0, 0).toInstant(offset);
}
private Instant createInstant(int year, int month, int day, int hour, int min, ZoneOffset offset) {
return LocalDateTime.of(year, month, day, hour, min).toInstant(offset);
}
private Instant createInstant(int year, int month, int day, int hour, int min, int sec, int nano, ZoneOffset offset) {
return LocalDateTime.of(year, month, day, hour, min, sec, nano).toInstant(offset);
}
private ZonedDateTime createZDT(int year, int month, int day, ZoneId zone) {
return LocalDateTime.of(year, month, day, 0, 0).atZone(zone);
}
private LocalDateTime createLDT(int year, int month, int day) {
return LocalDateTime.of(year, month, day, 0, 0);
}
private ZoneOffsetTransition checkOffset(ZoneRules rules, LocalDateTime dateTime, ZoneOffset offset, int type) {
List<ZoneOffset> validOffsets = rules.getValidOffsets(dateTime);
assertEquals(validOffsets.size(), type);
assertEquals(rules.getOffset(dateTime), offset);
if (type == 1) {
assertEquals(validOffsets.get(0), offset);
return null;
} else {
ZoneOffsetTransition zot = rules.getTransition(dateTime);
assertNotNull(zot);
assertEquals(zot.isOverlap(), type == 2);
assertEquals(zot.isGap(), type == 0);
assertEquals(zot.isValidOffset(offset), type == 2);
return zot;
}
}
}
|
package com.qulice.pmd;
import com.google.common.base.Joiner;
import com.jcabi.matchers.RegexMatchers;
import com.qulice.spi.Environment;
import com.qulice.spi.ValidationException;
import com.qulice.spi.Validator;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link PMDValidator} class.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class PMDValidatorTest {
/**
* Pattern for non-constructor field initialization.
* @checkstyle LineLength (2 lines)
*/
private static final String NO_CON_INIT = "%s\\[\\d+-\\d+\\]: Avoid doing field initialization outside constructor.";
/**
* Pattern multiple constructors field initialization.
* @checkstyle LineLength (2 lines)
*/
private static final String MULT_CON_INIT = "%s\\[\\d+-\\d+\\]: Avoid field initialization in several constructors.";
/**
* PMDValidator can find violations in Java file(s).
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void findsProblemsInJavaFiles() throws Exception {
final Environment env = new Environment.Mock()
.withFile("src/main/java/Main.java", "class Main { int x = 0; }");
final Validator validator = new PMDValidator();
validator.validate(env);
}
/**
* PMDValidator can understand method references.
* @throws Exception If something wrong happens inside.
*/
@Test
public void understandsMethodReferences() throws Exception {
// @checkstyle MultipleStringLiteralsCheck (10 lines)
final Environment env = new Environment.Mock().withFile(
"src/main/java/Other.java",
Joiner.on('\n').join(
"import java.util.ArrayList;",
"class Other {",
" public static void test() {",
" new ArrayList<String>().forEach(Other::other);",
" }",
" private static void other(String some) {}",
"}"
)
);
final StringWriter writer = new StringWriter();
Logger.getRootLogger().addAppender(
new WriterAppender(new SimpleLayout(), writer)
);
final Validator validator = new PMDValidator();
boolean thrown = false;
try {
validator.validate(env);
} catch (final ValidationException ex) {
thrown = true;
}
MatcherAssert.assertThat(thrown, Matchers.is(true));
MatcherAssert.assertThat(
writer.toString(),
Matchers.not(Matchers.containsString("(UnusedPrivateMethod)"))
);
}
/**
* PMDValidator does not think that constant is unused when it is used
* just from the inner class.
* @throws Exception If something wrong happens inside.
*/
@Test
public void doesNotComplainAboutConstantsInInnerClasses() throws Exception {
// @checkstyle MultipleStringLiteralsCheck (10 lines)
final Environment env = new Environment.Mock().withFile(
"src/main/java/foo/Foo.java",
Joiner.on('\n').join(
"package foo;",
"interface Foo {",
" final class Bar implements Foo {",
" private static final Pattern TEST =",
" Pattern.compile(\"hey\");",
" public String doSomething() {",
" return Foo.Bar.TEST.toString();",
" }",
" }",
"}"
)
);
final StringWriter writer = new StringWriter();
Logger.getRootLogger().addAppender(
new WriterAppender(new SimpleLayout(), writer)
);
new PMDValidator().validate(env);
MatcherAssert.assertThat(
writer.toString(),
Matchers.allOf(
Matchers.not(Matchers.containsString("UnusedPrivateField")),
Matchers.containsString("No PMD violations found in 1 files")
)
);
}
/**
* PMDValidator can allow field initialization when constructor is missing.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsFieldInitializationWhenConstructorIsMissing()
throws Exception {
final String file = "FieldInitNoConstructor.java";
this.validatePMD(
file, false,
Matchers.not(
RegexMatchers.containsPattern(
String.format(PMDValidatorTest.NO_CON_INIT, file)
)
)
);
}
/**
* PMDValidator can forbid field initialization when constructor exists.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFieldInitializationWhenConstructorExists()
throws Exception {
final String file = "FieldInitConstructor.java";
this.validatePMD(
file, false,
RegexMatchers.containsPattern(
String.format(PMDValidatorTest.NO_CON_INIT, file)
)
);
}
/**
* PMDValidator can allow static field initialization when constructor
* exists.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsStaticFieldInitializationWhenConstructorExists()
throws Exception {
final String file = "StaticFieldInitConstructor.java";
this.validatePMD(
file, true,
Matchers.not(
RegexMatchers.containsPattern(
String.format(PMDValidatorTest.NO_CON_INIT, file)
)
)
);
}
/**
* PMDValidator can forbid field initialization in several constructors.
* Only one constructor should do real work. Others - delegate to it.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFieldInitializationInSeveralConstructors()
throws Exception {
final String file = "FieldInitSeveralConstructors.java";
this.validatePMD(
file, false,
RegexMatchers.containsPattern(
String.format(PMDValidatorTest.MULT_CON_INIT, file)
)
);
}
/**
* PMDValidator can allow field initialization in one constructor.
* Only one constructor should do real work. Others - delegate to it.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsFieldInitializationInOneConstructor()
throws Exception {
final String file = "FieldInitOneConstructor.java";
this.validatePMD(
file, true,
Matchers.not(
RegexMatchers.containsPattern(
String.format(PMDValidatorTest.MULT_CON_INIT, file)
)
)
);
}
/**
* Validates that PMD reported given violation.
* @param file File to check.
* @param result Expected validation result (true if valid).
* @param matcher Matcher to call on checkstyle output.
* @throws Exception In case of error
*/
private void validatePMD(final String file, final boolean result,
final Matcher<String> matcher) throws Exception {
final Environment.Mock mock = new Environment.Mock();
final StringWriter writer = new StringWriter();
final WriterAppender appender =
new WriterAppender(new SimpleLayout(), writer);
try {
Logger.getRootLogger().addAppender(
appender
);
final Environment env = mock.withFile(
String.format("src/main/java/foo/%s", file),
IOUtils.toString(
this.getClass().getResourceAsStream(file)
)
);
boolean valid = true;
try {
new PMDValidator().validate(env);
} catch (final ValidationException ex) {
valid = false;
}
MatcherAssert.assertThat(valid, Matchers.is(result));
MatcherAssert.assertThat(writer.toString(), matcher);
} finally {
Logger.getRootLogger().removeAppender(appender);
}
}
}
|
package org.tools4j.fx.highway.sbe;
import io.aeron.Aeron;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.aeron.driver.MediaDriver;
import io.aeron.driver.ThreadingMode;
import io.aeron.logbuffer.FragmentHandler;
import org.HdrHistogram.Histogram;
import org.agrona.concurrent.NanoClock;
import org.agrona.concurrent.SystemNanoClock;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.tools4j.fx.highway.message.ImmutableMarketDataSnapshot;
import org.tools4j.fx.highway.message.MarketDataSnapshot;
import org.tools4j.fx.highway.message.MutableMarketDataSnapshot;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.tools4j.fx.highway.sbe.SerializerHelper.*;
public class AeronPubSubTest {
private MediaDriver mediaDriver;
private Aeron aeron;
private Subscription subscription;
private Publication publication;
@Before
public void setup() {
final MediaDriver.Context mctx = new MediaDriver.Context();
mctx.threadingMode(ThreadingMode.DEDICATED);
mediaDriver = MediaDriver.launchEmbedded();
final Aeron.Context actx = new Aeron.Context();
actx.aeronDirectoryName(mediaDriver.aeronDirectoryName());
aeron = Aeron.connect(actx);
subscription = aeron.addSubscription("udp://localhost:40123", 10);
publication = aeron.addPublication("udp://localhost:40123", 10);
int cnt = 0;
while (!publication.isConnected()) {
if (cnt > 20) {
throw new RuntimeException("publisher not connected");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
cnt++;
}
}
@After
public void tearDown() {
publication.close();
subscription.close();
aeron.close();
mediaDriver.close();
}
@Test
public void subscriptionShouldReceivePublishedSnapshot() throws Exception {
//given
final MarketDataSnapshot newSnapshot = givenMarketDataSnapshot(new ImmutableMarketDataSnapshot.Builder());
final BlockingQueue<MarketDataSnapshot> queue = new ArrayBlockingQueue<>(1);
final CountDownLatch subscriberStarted = new CountDownLatch(1);
final AtomicBoolean terminate = new AtomicBoolean(false);
final NanoClock clock = new SystemNanoClock();
//when
final Thread subscriberThread = new Thread(() -> {
subscriberStarted.countDown();
System.out.println(clock.nanoTime() + " subscriber started");
while (!terminate.get()) {
subscription.poll((buf, offset, len, header) -> {
try {
System.out.println(clock.nanoTime() + " poll called, len=" + len);
final UnsafeBuffer directBuffer = new UnsafeBuffer(buf, offset, len);
final MarketDataSnapshot decoded = decode(directBuffer, new ImmutableMarketDataSnapshot.Builder());
queue.add(decoded);
System.out.println(clock.nanoTime() + " decoded: " + decoded);
} catch (Exception e) {
e.printStackTrace();
}
}, 10);
}
System.out.println(clock.nanoTime() + " subscriber thread terminating");
});
subscriberThread.start();
if (!subscriberStarted.await(2, TimeUnit.SECONDS)) {
throw new RuntimeException("subscriber not started");
}
final Thread publisherThread = new Thread(() -> {
System.out.println(clock.nanoTime() + " publisher thread started");
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
final UnsafeBuffer directBuffer = new UnsafeBuffer(byteBuffer);
final int len = encode(directBuffer, newSnapshot);
// publication.offer(directBuffer);
final long pubres = publication.offer(directBuffer, 0, len);
System.out.println(clock.nanoTime() + " published, res=" + pubres + ", len=" + len);
System.out.println(clock.nanoTime() + " publisher thread terminating");
});
publisherThread.start();
//then
final MarketDataSnapshot decoded = queue.poll(2, TimeUnit.SECONDS);
terminate.set(true);
publisherThread.join();
subscriberThread.join();
assertThat(decoded).isEqualTo(newSnapshot);
}
@Test
public void histogramTest() throws Exception {
//given
final int w = 1000000;//warmup
final int c = 1000000;//counted
final int n = w+c;
final long maxTimeToRunSeconds = 10;
final AtomicBoolean terminate = new AtomicBoolean(false);
final NanoClock clock = new SystemNanoClock();
final Histogram histogram = new Histogram(1, 1000000000, 3);
final CountDownLatch subscriberLatch = new CountDownLatch(n);
//when
final Thread subscriberThread = new Thread(() -> {
final MutableMarketDataSnapshot marketDataSnapshot = new MutableMarketDataSnapshot();
final UnsafeBuffer unsafeBuffer = new UnsafeBuffer(0, 0);
final AtomicInteger count = new AtomicInteger();
final AtomicLong t0 = new AtomicLong();
final AtomicLong t1 = new AtomicLong();
final AtomicLong t2 = new AtomicLong();
final FragmentHandler fh = (buf, offset, len, header) -> {
if (count.get() == 0) t0.set(clock.nanoTime());
else if (count.get() == w-1) t1.set(clock.nanoTime());
else if (count.get() == n-1) t2.set(clock.nanoTime());
unsafeBuffer.wrap(buf, offset, len);
final MarketDataSnapshot decoded = decode(unsafeBuffer, marketDataSnapshot.builder());
final long time = clock.nanoTime();
if (count.incrementAndGet() >= w) {
histogram.recordValue(time - decoded.getEventTimestamp());
if (count.get() - 10 < w) {
//System.out.println("c " + System.nanoTime() + ": " + time + " - " + decoded.getEventTimestamp() + ":\t" + (time - decoded.getEventTimestamp())/1000.0 + " us");
}
}
subscriberLatch.countDown();
};
while (!terminate.get()) {
subscription.poll(fh, 256);
}
System.out.println((t2.get() - t0.get())/1000.0 + " us total receiving time (" + (t2.get() - t1.get())/(1000f*c) + " us/message, " + c/((t2.get()-t1.get())/1000000000f) + " messages/second)");
});
subscriberThread.start();
//publisher
{
final MutableMarketDataSnapshot marketDataSnapshot = new MutableMarketDataSnapshot();
final UnsafeBuffer unsafeBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(256));
long cntAdmin = 0;
long cntBackp = 0;
long cnt = 0;
final long t0 = clock.nanoTime();
final long minTime = 600;
final long yieldTime = 2400;
long timeLast = t0 - minTime;
for (int i = 0; i < n && !terminate.get(); i++) {
if (clock.nanoTime() - timeLast < minTime) {
do {
cnt++;
Thread.yield();
} while (clock.nanoTime() - timeLast < yieldTime);
}
final MarketDataSnapshot newSnapshot = givenMarketDataSnapshot(marketDataSnapshot.builder());
timeLast = newSnapshot.getEventTimestamp();
final int len = encode(unsafeBuffer, newSnapshot);
long pubres;
do {
pubres = publication.offer(unsafeBuffer, 0, len);
if (pubres < 0) {
if (pubres == Publication.BACK_PRESSURED) {
cntBackp++;
} else if (pubres == Publication.ADMIN_ACTION) {
cntAdmin++;
} else {
throw new RuntimeException("publication failed with pubres=" + pubres);
}
}
} while (pubres < 0);
}
final long t1 = clock.nanoTime();
System.out.println((t1 - t0) / 1000.0 + " us total publishing time (backp=" + cntBackp + ", admin=" + cntAdmin + ", cnt=" + cnt + ")");
}
//then
if (!subscriberLatch.await(maxTimeToRunSeconds, TimeUnit.SECONDS)) {
terminate.set(true);
throw new RuntimeException("simulation timed out");
}
terminate.set(true);
subscriberThread.join();
System.out.println();
System.out.println("99% : " + histogram.getValueAtPercentile(99)/1000f);
System.out.println("99.9% : " + histogram.getValueAtPercentile(99.9)/1000f);
System.out.println("99.99% : " + histogram.getValueAtPercentile(99.99)/1000f);
System.out.println("99.999%: " + histogram.getValueAtPercentile(99.999)/1000f);
System.out.println();
System.out.println("Histogram (micros):");
histogram.outputPercentileDistribution(System.out, 1000.0);
}
}
|
//@@author A0147984L
package seedu.address.model.task;
import static org.junit.Assert.assertTrue;
import java.util.Set;
//@@author A0143049J
import org.junit.Test;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.tag.UniqueTagList.DuplicateTagException;
import seedu.address.testutil.TypicalTestTasks;
public class UniqueTagListTest {
private UniqueTagList tester = new UniqueTagList();
private final TypicalTestTasks testUtil = new TypicalTestTasks();
@Test
public void sort() throws DuplicateTagException, IllegalValueException {
Tag tag1 = new Tag("abc");
Tag tag2 = new Tag("test");
tester.add(tag1);
tester.add(tag2);
tester.sort();
Set<Tag> tags = tester.toSet();
assertTrue(tags.contains(tag1));
assertTrue(tags.contains(tag2));
}
@Test
public void constructorTest() throws DuplicateTagException, IllegalValueException {
Tag tag1 = new Tag("abc");
Tag tag2 = new Tag("test");
tester = new UniqueTagList(tag1, tag2);
Set<Tag> tags1 = tester.toSet();
assertTrue(tags1.contains(tag1));
assertTrue(tags1.contains(tag2));
UniqueTagList newTester = new UniqueTagList(tester);
Set<Tag> tags2 = newTester.toSet();
assertTrue(tags2.contains(tag1));
assertTrue(tags2.contains(tag2));
UniqueTagList newNewTester = new UniqueTagList(tags2);
Set<Tag> tags3 = newNewTester.toSet();
assertTrue(tags3.contains(tag1));
assertTrue(tags3.contains(tag2));
}
@Test
public void equalTest() throws IllegalValueException {
Tag tag1 = new Tag("abc");
Tag tag2 = new Tag("test");
tester = new UniqueTagList(tag1, tag2);
Set<Tag> tags1 = tester.toSet();
assertTrue(tags1.contains(tag1));
assertTrue(tags1.contains(tag2));
UniqueTagList newTester = new UniqueTagList(tester);
assertTrue(newTester.equals(tester));
}
@Test
public void mergeTest() throws IllegalValueException {
Tag tag1 = new Tag("abc");
Tag tag2 = new Tag("test");
Tag tag3 = new Tag("lala");
Tag tag4 = new Tag("xx");
tester = new UniqueTagList(tag1, tag2);
UniqueTagList newTester = new UniqueTagList(tag3, tag4);
tester.mergeFrom(newTester);
Set<Tag> tags1 = tester.toSet();
assertTrue(tags1.contains(tag1));
assertTrue(tags1.contains(tag2));
assertTrue(tags1.contains(tag3));
assertTrue(tags1.contains(tag4));
}
}
|
package org.wings.plaf.css;
import org.wings.plaf.css.script.LayoutFillScript;
import org.wings.io.Device;
import org.wings.*;
import java.io.IOException;
public class CmsFormCG extends FormCG implements org.wings.plaf.CmsFormCG {
@Override
public void writeInternal(final Device device, final SComponent component) throws IOException {
final SForm form = (SForm) component;
SLayoutManager layout = form.getLayout();
// Prevent nesting of forms
boolean formTagRequired = !form.getResidesInForm();
if (formTagRequired) {
device.print("<form method=\"");
if (form.isPostMethod()) {
device.print("post");
} else {
device.print("get");
}
device.print("\"");
Utils.writeAllAttributes(device, form);
Utils.optAttribute(device, "name", form.getName());
Utils.optAttribute(device, "enctype", form.getEncodingType());
Utils.optAttribute(device, "action", form.getRequestURL());
Utils.writeEvents(device, form, null);
// Is there a default button?
String defaultButtonName = "undefined";
if (form.getDefaultButton() != null) {
defaultButtonName = Utils.event(form.getDefaultButton());
}
// The "onsubmit"-handler of the form gets triggered
// ONLY if the user submits it by pressing <enter> in
// any of its fields. In all other cases - i.e. if a
// button is clicked - the affected component fires its
// "onclick"-event which calls "sendEvent(...)" which in
// turn submits the form VIA JAVASCRIPT (either by means
// of Ajax or the traditional way). Whenever forms are
// submitted via JS (e.g. form.submit()) the "onsubmit"-
// handler is NOT triggered. So once again, the code below
// will only be executed when <enter> has been pressed.
// Therefore we can use this mechanism in order to handle
// the default button of the form. (see SessionServlet)
device.print(" onsubmit=\"wingS.request.sendEvent(");
device.print("event,");
device.print("true,");
device.print(!component.isReloadForced());
device.print(",'default_button','");
device.print(defaultButtonName);
device.print("'); return false;\">");
writeCapture(device, form);
// This code is needed to trigger form events
device.print("<input type=\"hidden\" name=\"");
Utils.write(device, Utils.event(form));
device.print("\" value=\"");
Utils.write(device, form.getName());
device.print(SConstants.UID_DIVIDER);
device.print("\" />");
}
SDimension preferredSize = form.getPreferredSize();
String height = preferredSize != null ? preferredSize.getHeight() : null;
boolean clientLayout = isMSIE(form) && height != null && !"auto".equals(height)
&& (layout instanceof SBorderLayout || layout instanceof SGridBagLayout);
String tableName = form.getName() + "_div";
device.print("<div id=\"");
device.print(tableName);
device.print("\"");
if (clientLayout) {
device.print(" style=\"width:100%\"");
Utils.optAttribute(device, "layoutHeight", height);
form.getSession().getScriptManager().addScriptListener(new LayoutFillScript(tableName));
}
else
Utils.printCSSInlineFullSize(device, form.getPreferredSize());
device.print(">");
// Render the container itself
Utils.renderContainer(device, form);
device.print("</div>");
if (formTagRequired) {
writeCapture(device, form);
device.print("</form>");
}
}
/*
* we render two icons into the page that captures pressing simple 'return'
* in the page. Why ? Depending on the Browser, the Browser sends the
* first or the last submit-button it finds in the page as 'default'-Submit
* when we simply press 'return' somewhere. *
* However, we don't want to have this arbitrary behaviour in wingS.
* So we add these two (invisible image-) submit-Buttons, either of it
* gets triggered on simple 'return'.
*
* Formerly this mechanism was also used for the default button handling of
* the form. This is now done further above by the "onsubmit"-handler. However,
* we still need theses two images in order to always get the latter invoked.
*
* Watchout: the style of these images once had been changed to display:none;
* to prevent taking some pixel renderspace. However, display:none; made
* the Internet Explorer not accept this as an input getting the default-focus,
* so it fell back to the old behaviour. So changed that style to no-padding,
* no-margin, no-whatever (HZ).
*/
private void writeCapture(Device device, SForm form) throws IOException {
// Whenever a form is submitted via JS (like done in this case - see above)
// a input field of type image (like the one below) won't be sent. This is
// because for some reason it doesn't belong to the "form.elements"-collection
// which is eventually used to assemble the post-parameters. That's why we
// don't even name it - would be useless anyway...
device.print("<input type=\"image\" border=\"0\" ");
Utils.optAttribute(device, "src", getBlindIcon().getURL());
device.print(" width=\"0\" height=\"0\" tabindex=\"-1\"" +
" style=\"border:none;padding:0px;margin:0px;position:absolute\"/>");
}
}
|
package de.lmu.ifi.dbs.utilities.optionhandling;
import de.lmu.ifi.dbs.utilities.optionhandling.constraints.ParameterConstraint;
import java.util.List;
import java.util.Vector;
/**
* Abstract class for specifying a parameter.
* <p/>
* A parameter is defined as an option having a specific value.
* </p>
*
* @author Steffi Wanka
* @param <T> the type of a possible value (i.e., the type of the option)
* @param <O>
*/
public abstract class Parameter<T, O> extends Option<T> {
/**
* The default value of the parameter (may be null).
*/
protected T defaultValue;
/**
* Specifies if the default value of this parameter was taken as parameter value.
*/
private boolean defaultValueTaken;
/**
* Specifies if this parameter is an optional parameter.
*/
protected boolean optionalParameter;
/**
* Holds parameter constraints for this parameter.
*/
protected List<ParameterConstraint<O>> constraints;
/**
* Constructs a parameter with the given name and description.
*
* @param name the parameter name
* @param description the parameter description
*/
public Parameter(String name, String description) {
super(name, description);
constraints = new Vector<ParameterConstraint<O>>();
optionalParameter = false;
defaultValueTaken = false;
}
/**
* Adds a parameter constraint to the list of parameter constraints.
*
* @param constraint the parameter constraint to be added
*/
protected void addConstraint(ParameterConstraint<O> constraint) {
constraints.add(constraint);
}
/**
* Adds a list of parameter constraints to the current list of parameter constraints.
*
* @param constraints list of parameter constraints to be added
*/
protected void addConstraintList(List<ParameterConstraint<O>> constraints) {
this.constraints.addAll(constraints);
}
/**
* Sets the default value of this parameter.
*
* @param defaultValue default value of this parameter
*/
public void setDefaultValue(T defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Checks if this parameter has a default value.
*
* @return true, if this parameter has a default value, false otherwise
*/
public boolean hasDefaultValue() {
return !(defaultValue == null);
}
/**
* Sets the default value of this parameter as the actual value of this parameter.
*/
public void setDefaultValueToValue() {
this.value = defaultValue;
defaultValueTaken = true;
}
/**
* Specifies if this parameter is an optional parameter.
*
* @param opt true if this parameter is optional,false otherwise
*/
public void setOptional(boolean opt) {
this.optionalParameter = opt;
}
/**
* Checks if this parameter is an optional parameter.
*
* @return true if this parameter is optional, false otherwise
*/
public boolean isOptional() {
return this.optionalParameter;
}
/**
* Checks if the default value of this parameter was taken as the actual parameter value.
*
* @return true, if the default value was taken as actual parameter value, false otherwise
*/
public boolean tookDefaultValue() {
return defaultValueTaken;
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Option#isSet()
*/
@Override
public boolean isSet() {
return (value != null);
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Option#getValue()
*/
@Override
public T getValue() throws UnusedParameterException {
if (value == null && !optionalParameter)
throw new UnusedParameterException("Value of parameter " + name + " has not been specified.");
return value;
}
/**
* Returns the default value of the parameter.
* <p/>
* If the parameter has no default value, the method returns <b>null</b>.
*
* @return the default value of the parameter, <b>null</b> if the parameter has no default value.
*/
public T getDefaultValue() {
return defaultValue;
}
/**
* Resets the value of the parameter to null.
*/
public void reset() {
this.value = null;
}
}
|
package de.mazdermind.MultiWiiOps.UI.Cockpit;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.logging.Logger;
public class CompassPanel extends AngularPanel {
private static final long serialVersionUID = -8263909346345873374L;
private static final Logger log = Logger.getLogger( CompassPanel.class.getName() );
private float heading = 180, northing = 180;
private boolean hasNorthing;
private Polygon arrow;
public CompassPanel() {
super();
int[] xPoly = { -2, 0, +2, 0 };
int[] yPoly = { -2, 10, -2, 0 };
arrow = new Polygon(xPoly, yPoly, xPoly.length);
// experimental mouse input routines to test pitch- & roll display
final CompassPanel compassPanel = this;
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int d = e.getButton() == MouseEvent.BUTTON1 ? 1 : -1;
if(e.isShiftDown())
{
compassPanel.setNorthing(compassPanel.getNorthing() + 5 * d);
log.info("northing="+compassPanel.getNorthing());
}
else
{
compassPanel.setHeading(compassPanel.getHeading() + 5 * d);
log.info("heading="+compassPanel.getHeading());
}
}
});
}
public void paintComponent(Graphics g) {
// g is actually a g2; it just doesn't know yet ;)
Graphics2D g2 = (Graphics2D)g;
// Device-Configuration used to generate the image Layer
GraphicsConfiguration dc = g2.getDeviceConfiguration();
// generate layers and merge them onto the canvas
g2.drawImage(generateHeadingLayer(dc), 0, 0, null);
//if(hasNorthing)
// g2.drawImage(generateNorthingLayer(dc), 0, 0, null);
}
private Image generateHeadingLayer(GraphicsConfiguration dc) {
int
strokeWidth = 1,
w = getWidth() - 1,
h = getHeight() - 1,
sz = Math.min(w, h) - strokeWidth - 1,
sz2 = sz/2,
x = (w - sz) / 2,
y = (h - sz) / 2,
cx = x + sz/2,
cy = y + sz/2;
BufferedImage img = dc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
Graphics2D gfx = img.createGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setColor(Color.BLACK);
gfx.setStroke(new BasicStroke(strokeWidth));
gfx.setColor(Color.WHITE);
gfx.fillOval(x, y, sz, sz);
gfx.setColor(Color.BLACK);
gfx.drawOval(x, y, sz, sz);
AffineTransform transform = gfx.getTransform();
gfx.rotate(Math.toRadians(heading), cx, cy);
gfx.translate(cx, cy);
gfx.scale(sz/22, sz/22);
gfx.fillPolygon(arrow);
gfx.setTransform(transform);
for(float r = 0; r < 360; r += 22.5)
{
gfx.rotate(Math.toRadians(r), cx, cy);
gfx.drawLine(cx, cy + sz2 - 15, cx, cy + sz2 - strokeWidth);
}
gfx.dispose();
return img;
}
public float getHeading() {
return heading;
}
public void setHeading(float heading) {
this.heading = normalize(heading);
this.repaint();
}
public float getNorthing() {
return northing;
}
public void setNorthing(float northing) {
this.northing = normalize(northing);
this.repaint();
}
public boolean hasNorthing() {
return hasNorthing;
}
public void setHasNorthing(boolean hasNorthing) {
this.hasNorthing = hasNorthing;
}
}
|
package de.tu_darmstadt.gdi1.gorillas.ui.states;
import de.matthiasmann.twl.Button;
import de.matthiasmann.twl.slick.BasicTWLGameState;
import de.matthiasmann.twl.slick.RootPane;
import de.tu_darmstadt.gdi1.gorillas.assets.Assets;
import de.tu_darmstadt.gdi1.gorillas.main.*;
import de.tu_darmstadt.gdi1.gorillas.main.Game;
import de.tu_darmstadt.gdi1.gorillas.utils.KeyMap;
import org.newdawn.slick.*;
import org.newdawn.slick.state.StateBasedGame;
public class HelpState extends BasicTWLGameState {
private Image background;
private Button btnNext;
private Button btnBack;
private Button btnMainMenu;
private int page;
private String[] pages;
private StateBasedGame game;
@Override
public int getID() {
return Game.HELPSTATE;
}
@Override
public void init(GameContainer gameContainer, StateBasedGame game) throws SlickException {
this.game = game;
if (!Game.getInstance().isTestMode()) {
background = Assets.loadImage(Assets.Images.MAINMENU_BACKGROUND);
if(Game.BACKGROUND_SCALE != 1) background = background.getScaledCopy(Game.BACKGROUND_SCALE);
}
String page0 = "How to play the game:\n" +
"\n" +
"Each Player takes control of one gorilla and\n" +
"throws bananas at the other gorilla.\n" +
"The Player who hits tree times first wins the game.\n" +
"You can change the starting \n" +
"angle and speed to control the flight.\n" +
"Moreover, you can influence the gravity and \n" +
"switch the wind on or off in the Option Menu.";
String page1 = "Main menu:\n" +
" Return/N -> New Game\n" +
" Escape -> Exit Game\n" +
" M -> Mute\n" +
" S -> Highscore\n" +
" H -> Help\n" +
" O -> Options\n" +
" \n" +
"Setup New Game:\n" +
" Return -> Start Game\n" +
" Escape -> Return to Main Menu\n" +
" Tap -> Switch between text fields\n" +
" \n" +
"Help:\n" +
" Enter/Escape/H -> Return to previous Screen\n" +
" RIGHT/D -> Next Page\n" +
" LEFT/A -> Last Page";
String page2 = "In Game:\n" +
" Up/W -> Increase Speed(Angle)\n" +
" Down/S -> Decrease Speed(Angle)\n" +
" Right/D -> Increase Angle(Speed)\n" +
" Left/A -> Decrease Angle(Speed)\n" +
" \n" +
" Return/Space -> Throw Banana\n" +
" Escape/P -> Pause\n" +
" M -> Mute\n" +
" H -> Help\n" +
" O -> Options\n";
if(Game.getInstance().isDeveloperMode()) {
page2 += "\n" +
"Only for Developer in Game:\n" +
" 1 -> Flatt World\n" +
" Q -> New Background\n" +
" V -> Instant win";
}
String page3 = "Pause:\n" +
" Escape/P/Return -> Return to Game\n" +
" N -> New Game\n" +
" E -> Exit Game\n" +
" S -> Return to Main Menu\n" +
" M -> Mute\n" +
" H -> Help\n" +
" O -> Options\n" +
" \n" +
"Victory:\n" +
" Escape -> Return to Main Menu\n" +
" Return -> New Game\n" +
" \n" +
"Highscore:\n" +
" Return/Escape/S -> Main Menu";
String page4 = "Options:\n" +
" Escape/O/Enter -> Except Options and return to previous Screen\n" +
" UP -> Increase Gravity\n" +
" DOWN -> Decrease Gravity\n" +
" C -> Change Control for Angle/Speed\n" +
" W -> Turn Wind on/off\n" +
" M -> Mute\n" +
" P -> Switch Random Player Names/Store Player Names";
pages = new String[]{page0, page1, page2, page3, page4};
page = 0;
}
@Override
protected RootPane createRootPane() {
RootPane rp = super.createRootPane();
btnNext = new Button("Next");
btnBack = new Button("Back");
btnMainMenu = new Button("MainMenu");
btnNext.addCallback(this::nextPage);
btnBack.addCallback(this::prevPage);
btnMainMenu.addCallback(game::enterLastState);
rp.add(btnNext);
rp.add(btnBack);
rp.add(btnMainMenu);
return rp;
}
@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
if (Game.getInstance().isTestMode()) { return; } // Don't draw anything in testmode
graphics.drawImage(background, 0, 0);
graphics.setColor(new Color(50,50,50,150));
graphics.fillRect(0, 0, Gorillas.FRAME_WIDTH, Gorillas.FRAME_HEIGHT);
graphics.setColor(Color.yellow);
graphics.drawString(pages[page],100,50);
}
@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int i) throws SlickException {
Input in_key = gameContainer.getInput();
KeyMap.globalKeyPressedActions(gameContainer.getInput(), game);
if (in_key.isKeyPressed(Input.KEY_RIGHT) || in_key.isKeyPressed(Input.KEY_D)) { nextPage(); }
if (in_key.isKeyPressed(Input.KEY_LEFT) || in_key.isKeyPressed(Input.KEY_A)) { prevPage(); }
}
@Override
protected void layoutRootPane() {
int paneWidth = this.getRootPane().getWidth();
/* Layout subject to change */
btnNext.setSize(128, 32);
btnBack.setSize(128, 32);
btnMainMenu.setSize(128, 32);
/* Center the Textfields on the screen. */
int x = (paneWidth - btnNext.getWidth()) / 2;
btnNext.setPosition(x, 500);
btnBack.setPosition(x - 140, 500);
btnMainMenu.setPosition(x + 140, 500);
}
void prevPage() { page = page > 0 ? page - 1 : 3; }
void nextPage() { page = page < pages.length - 1 ? page + 1 : 0; }
}
|
package dr.inference.model;
import dr.util.NumberFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* A likelihood function which is simply the product of a set of likelihood functions.
*
* @author Marc Suchard
* @author Andrew Rambaut
* @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
*/
public class TestThreadedCompoundLikelihood implements Likelihood {
public static final boolean DEBUG = false;
public TestThreadedCompoundLikelihood() {
}
public TestThreadedCompoundLikelihood(List<Likelihood> likelihoods) {
for (Likelihood likelihood : likelihoods) {
addLikelihood(likelihood);
}
}
public void addLikelihood(Likelihood likelihood) {
if (!likelihoods.contains(likelihood)) {
likelihoods.add(likelihood);
if (likelihood.getModel() != null) {
compoundModel.addModel(likelihood.getModel());
}
likelihoodCallers.add(new LikelihoodCaller(likelihood));
}
}
public int getLikelihoodCount() {
return likelihoods.size();
}
public final Likelihood getLikelihood(int i) {
return likelihoods.get(i);
}
// Likelihood IMPLEMENTATION
public Model getModel() {
return compoundModel;
}
public double getLogLikelihood() {
double logLikelihood = 0.0;
if (threads == null) {
// first call so setup a thread for each likelihood...
threads = new LikelihoodThread[likelihoodCallers.size()];
for (int i = 0; i < threads.length; i++) {
// and start them running...
threads[i] = new LikelihoodThread();
threads[i].start();
}
}
for (int i = 0; i < threads.length; i++) {
// set the caller which will be called in each thread
LikelihoodCaller caller = likelihoodCallers.get(i);
if (caller.isLikelihoodKnown()) {
threads[i].setReturnValue(caller.call());
} else {
threads[i].setCaller(caller);
}
}
for (LikelihoodThread thread : threads) {
// now wait for the results to be set...
Double result = thread.getResult();
while (result == null) {
result = thread.getResult();
}
logLikelihood += result;
}
return logLikelihood; // * weightFactor;
}
public boolean evaluateEarly() {
return false;
}
public void makeDirty() {
for (Likelihood likelihood : likelihoods) {
likelihood.makeDirty();
}
}
public String prettyName() {
return Abstract.getPrettyName(this);
}
public String getDiagnosis() {
String message = "";
boolean first = true;
for (Likelihood lik : likelihoods) {
if (!first) {
message += ", ";
} else {
first = false;
}
String id = lik.getId();
if (id == null || id.trim().length() == 0) {
String[] parts = lik.getClass().getName().split("\\.");
id = parts[parts.length - 1];
}
message += id + "=";
if (lik instanceof TestThreadedCompoundLikelihood) {
String d = ((TestThreadedCompoundLikelihood) lik).getDiagnosis();
if (d != null && d.length() > 0) {
message += "(" + d + ")";
}
} else {
if (lik.getLogLikelihood() == Double.NEGATIVE_INFINITY) {
message += "-Inf";
} else if (Double.isNaN(lik.getLogLikelihood())) {
message += "NaN";
} else {
NumberFormatter nf = new NumberFormatter(6);
message += nf.formatDecimal(lik.getLogLikelihood(), 4);
}
}
}
return message;
}
public String toString() {
return Double.toString(getLogLikelihood());
}
public void setWeightFactor(double w) {
weightFactor = w;
}
public double getWeightFactor() {
return weightFactor;
}
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public dr.inference.loggers.LogColumn[] getColumns() {
return new dr.inference.loggers.LogColumn[]{
new LikelihoodColumn(getId())
};
}
private class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
public LikelihoodColumn(String label) {
super(label);
}
public double getDoubleValue() {
return getLogLikelihood();
}
}
// Identifiable IMPLEMENTATION
private String id = null;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
private LikelihoodThread[] threads;
private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>();
private final CompoundModel compoundModel = new CompoundModel("compoundModel");
private final List<LikelihoodCaller> likelihoodCallers = new ArrayList<LikelihoodCaller>();
private double weightFactor = 1.0;
class LikelihoodCaller {
public LikelihoodCaller(Likelihood likelihood) {
this.likelihood = likelihood;
}
public double call() {
return likelihood.getLogLikelihood();
}
private final Likelihood likelihood;
public boolean isLikelihoodKnown() {
return ((likelihood instanceof ThreadAwareLikelihood) &&
((ThreadAwareLikelihood) likelihood).isLikelihoodKnown());
}
}
class LikelihoodThread extends Thread {
public LikelihoodThread() {
}
public void setCaller(LikelihoodCaller caller) {
lock.lock();
resultAvailable = false;
try {
this.caller = caller;
condition.signal();
} finally {
lock.unlock();
}
}
/**
* Main run loop
*/
public void run() {
while (true) {
lock.lock();
try {
while (caller == null)
condition.await();
result = caller.call(); // SLOW
resultAvailable = true;
caller = null;
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
}
public Double getResult() {
Double returnValue = null;
if (!lock.isLocked() && resultAvailable) { // thread is not busy and completed
resultAvailable = false; // TODO need to lock before changing resultAvailable?
returnValue = result;
}
return returnValue;
}
private LikelihoodCaller caller = null;
private Double result = Double.NaN;
private boolean resultAvailable = false;
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void setReturnValue(double logLikelihood) {
result = logLikelihood;
resultAvailable = true;
}
}
public boolean isUsed() {
return isUsed;
}
public void setUsed() {
isUsed = true;
for (Likelihood l : likelihoods) {
l.setUsed();
}
}
private boolean isUsed = false;
}
|
package dr.inference.operators;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.SingularValueDecomposition;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.math.matrixAlgebra.CholeskyDecomposition;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.Matrix;
import dr.math.matrixAlgebra.SymmetricMatrix;
import dr.xml.*;
/**
* @author Marc Suchard
*/
public class MultivariateNormalOperator extends AbstractCoercableOperator {
public static final String MVN_OPERATOR = "mvnOperator";
public static final String SCALE_FACTOR = "scaleFactor";
public static final String VARIANCE_MATRIX = "varMatrix";
public static final String FORM_XTX = "formXtXInverse";
private double scaleFactor;
private final Parameter parameter;
private final int dim;
private double[][] cholesky;
public MultivariateNormalOperator(Parameter parameter, double scaleFactor, double[][] inMatrix, double weight,
CoercionMode mode, boolean isVarianceMatrix) {
super(mode);
this.scaleFactor = scaleFactor;
this.parameter = parameter;
setWeight(weight);
dim = parameter.getDimension();
SingularValueDecomposition svd = new SingularValueDecomposition(new DenseDoubleMatrix2D(inMatrix));
if (inMatrix[0].length != svd.rank()) {
throw new RuntimeException("Variance matrix in mvnOperator is not of full rank");
}
final double[][] matrix;
if (isVarianceMatrix) {
matrix = inMatrix;
} else {
matrix = formXtXInverse(inMatrix);
}
// System.err.println("Matrix:");
// System.err.println(new Matrix(matrix));
try {
cholesky = (new CholeskyDecomposition(matrix)).getL();
} catch (IllegalDimension illegalDimension) {
throw new RuntimeException("Unable to decompose matrix in mvnOperator");
}
// System.err.println("Cholesky:");
// System.err.println(new Matrix(cholesky));
// System.exit(-1);
}
public MultivariateNormalOperator(Parameter parameter, double scaleFactor,
MatrixParameter varMatrix, double weight, CoercionMode mode, boolean isVariance) {
this(parameter, scaleFactor, varMatrix.getParameterAsMatrix(), weight, mode, isVariance);
}
private double[][] formXtXInverse(double[][] X) {
int N = X.length;
int P = X[0].length;
double[][] matrix = new double[P][P];
for (int i = 0; i < P; i++) {
for (int j = 0; j < P; j++) {
double total = 0.0;
for (int k = 0; k < N; k++) {
total += X[k][i] * X[k][j];
}
matrix[i][j] = total;
}
}
// System.err.println("XtX:");
// System.err.println(new Matrix(matrix));
// Take inverse
matrix = new SymmetricMatrix(matrix).inverse().toComponents();
return matrix;
}
public double doOperation() throws OperatorFailedException {
double[] x = parameter.getParameterValues();
double[] epsilon = new double[dim];
//double[] y = new double[dim];
for (int i = 0; i < dim; i++)
epsilon[i] = scaleFactor * MathUtils.nextGaussian();
for (int i = 0; i < dim; i++) {
for (int j = i; j < dim; j++) {
x[i] += cholesky[j][i] * epsilon[j];
// caution: decomposition returns lower triangular
}
parameter.setParameterValueQuietly(i, x[i]);
// System.out.println(i+" : "+x[i]);
}
parameter.fireParameterChangedEvent();
// System.exit(-1);
return 0;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return parameter.getParameterName();
}
public double getCoercableParameter() {
return Math.log(scaleFactor);
}
public void setCoercableParameter(double value) {
scaleFactor = Math.exp(value);
}
public double getRawParameter() {
return scaleFactor;
}
public double getScaleFactor() {
return scaleFactor;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
double sf = OperatorUtils.optimizeWindowSize(scaleFactor, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MVN_OPERATOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
CoercionMode mode = CoercionMode.parseMode(xo);
double weight = xo.getDoubleAttribute(WEIGHT);
double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
if (scaleFactor <= 0.0) {
throw new XMLParseException("scaleFactor must be greater than 0.0");
}
Parameter parameter = (Parameter) xo.getChild(Parameter.class);
boolean formXtXInverse = xo.getAttribute(FORM_XTX, false);
XMLObject cxo = xo.getChild(VARIANCE_MATRIX);
MatrixParameter varMatrix = (MatrixParameter) cxo.getChild(MatrixParameter.class);
// Make sure varMatrix is square and dim(varMatrix) = dim(parameter)
if (!formXtXInverse) {
if (varMatrix.getColumnDimension() != varMatrix.getRowDimension())
throw new XMLParseException("The variance matrix is not square");
}
if (varMatrix.getColumnDimension() != parameter.getDimension())
throw new XMLParseException("The parameter and variance matrix have differing dimensions");
return new MultivariateNormalOperator(parameter, scaleFactor, varMatrix, weight, mode, !formXtXInverse);
}
|
package thredds.server.wms;
import org.joda.time.DateTime;
import uk.ac.rdg.resc.edal.dataset.DataSource;
import uk.ac.rdg.resc.edal.dataset.Dataset;
import uk.ac.rdg.resc.edal.dataset.DiscreteLayeredDataset;
import uk.ac.rdg.resc.edal.domain.Extent;
import uk.ac.rdg.resc.edal.domain.MapDomain;
import uk.ac.rdg.resc.edal.exceptions.EdalException;
import uk.ac.rdg.resc.edal.feature.DiscreteFeature;
import uk.ac.rdg.resc.edal.graphics.exceptions.EdalLayerNotFoundException;
import uk.ac.rdg.resc.edal.graphics.utils.EnhancedVariableMetadata;
import uk.ac.rdg.resc.edal.graphics.utils.LayerNameMapper;
import uk.ac.rdg.resc.edal.graphics.utils.PlottingDomainParams;
import uk.ac.rdg.resc.edal.graphics.utils.PlottingStyleParameters;
import uk.ac.rdg.resc.edal.graphics.utils.SldTemplateStyleCatalogue;
import uk.ac.rdg.resc.edal.graphics.utils.StyleCatalogue;
import uk.ac.rdg.resc.edal.metadata.DiscreteLayeredVariableMetadata;
import uk.ac.rdg.resc.edal.metadata.VariableMetadata;
import uk.ac.rdg.resc.edal.util.CollectionUtils;
import uk.ac.rdg.resc.edal.wms.WmsCatalogue;
import uk.ac.rdg.resc.edal.wms.util.ContactInfo;
import uk.ac.rdg.resc.edal.wms.util.ServerInfo;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import ucar.nc2.Attribute;
import ucar.nc2.dataset.NetcdfDataset;
/**
* Example of an implementation of a {@link WmsCatalogue} to work with the TDS.
*
* This is a working example, but many of the specifics will need to be
* implemented differently based on how the THREDDS team decide to configure WMS
* layers.
*
* This {@link WmsCatalogue} provides access to a SINGLE dataset. As such, each
* different dataset requested will have a new instance of this class.
*
* NB - No caching is implemented in this {@link WmsCatalogue}. I would
* recommend a cache which is shared amongst all {@link WmsCatalogue}s, passed
* in on object construction, and which performs the caching/retrieval in the
* {@link WmsCatalogue#getFeaturesForLayer(String, PlottingDomainParams)}
* method. The cache keys will be a pair of the layerName and the
* {@link PlottingDomainParams}, and the cached values will be
* {@link Collection}s of {@link DiscreteFeature}s.
*
* @author Guy Griffiths
*/
public class ThreddsWmsCatalogue implements WmsCatalogue {
/*
* I have declared this as static to be shared between all instances of this
* class.
*
* However, it *may* be the case that non-gridded datasets need to be
* supported in TDS, in which case a different DatasetFactory may be needed
* per dataset type. Currently in EDAL we have:
*
* The CdmGridDatasetFactory which uses the Unidata CDM to load gridded
* NetCDF data into the EDAL data model
*
* The En3DatasetFactory which uses the Unidata CDM to load the EN3 and EN4
* NetCDF in-situ datasets into the EDAL data model
*
* If only gridded datasets will be used, then this is fine. However, for
* maximum flexibility and easy integration of possible future
* DatasetFactory types, it may be better off being passed into this
* catalogue.
*/
static TdsWmsDatasetFactory datasetFactory = new TdsWmsDatasetFactory();
/*
* The Dataset associated with this catalogue
*/
private DiscreteLayeredDataset<? extends DataSource, ? extends DiscreteLayeredVariableMetadata> dataset;
/*
* A StyleCatalogue allows us to support different styles for different
* layer types.
*
* Currently EDAL/ncWMS only have one supported type of StyleCatalogue
*/
private static final StyleCatalogue styleCatalogue = SldTemplateStyleCatalogue.getStyleCatalogue();
private String datasetTitle;
public ThreddsWmsCatalogue(NetcdfDataset ncd, String id) throws IOException, EdalException {
// in the TDS, we already have a NetcdfFile object, so let's use it to create
// the edal-java related dataset. To do so, we use our own TdsWmsDatasetFactory, which
// overrides the getNetcdfDatasetFromLocation method from CdmGridDatasetFactory to take
// the NetcdfDataset directly. However, createDataset's signature does not take a NetcdfDataset,
// so we need to make it available to TdsWmsDatasetFactory to use.
datasetFactory.setNetcdfDataset(ncd);
// set dataset title
Attribute datasetTitleAttr;
datasetTitle = ncd.getTitle();
if (datasetTitle == null) {
datasetTitleAttr = ncd.findGlobalAttributeIgnoreCase("title");
if (datasetTitleAttr != null) {
datasetTitle = datasetTitleAttr.getStringValue();
}
}
String location = ncd.getLocation();
dataset = datasetFactory.createDataset(id, location);
}
@Override
public FeaturesAndMemberName getFeaturesForLayer(String layerName, PlottingDomainParams params)
throws EdalException {
/*
* This uses the method on GriddedDataset to extract the appropriate
* features.
*
* Caching of individual features (i.e. 2d plottable map features) can
* go here if caching is desired for the TDS WMS.
*/
MapDomain mapDomain = new MapDomain(params.getBbox(), params.getWidth(), params.getHeight(),
params.getTargetZ(), params.getTargetT());
List<? extends DiscreteFeature<?, ?>> extractedFeatures = dataset.extractMapFeatures(
CollectionUtils.setOf(layerName), mapDomain);
return new FeaturesAndMemberName(extractedFeatures, layerName);
}
@Override
public Collection<Dataset> getAllDatasets() {
/*
* This should return all datasets for the global capabilities document.
* Whilst global GetCapabilities are not supported for TDS, this should
* return the single dataset anyway.
*
* See comment below for more details
*/
Collection<Dataset> ret = new ArrayList<>();
ret.add(dataset);
return ret;
}
public boolean allowsGlobalCapabilities() {
return true;
}
@Override
public Dataset getDatasetFromId(String layerName) {
/*
* This catalogue only has one dataset, so we can ignore the ID
*/
return dataset;
}
/**
*
* Get the title of the dataset. If the title is null (i.e. not found), return
* the string value "Untitled Dataset"
*
* The title is found by the getTitle() method in NetcdfDataset, or by a global
* attribute "title" (not case-sensitive)
*
* @param layerName name of the layer
* @return
*/
@Override
public String getDatasetTitle(String layerName) {
return (this.datasetTitle != null) ? this.datasetTitle : "Untitled Dataset";
}
@Override
public boolean isDisabled(String layerName) {
/*
* Whether this dataset is disabled. Not sure if this has any meaning
* within TDS?
*/
return false;
}
@Override
public boolean isDownloadable(String layerName) {
/*
* Whether to allow data to be downloaded using the
* GetVerticalProfile/GetTimeseries requests with the format as
* "text/csv"
*/
return false;
}
@Override
public boolean isQueryable(String layerName) {
/*
* Whether this layer accepts GetFeatureInfo requests
*/
return true;
}
@Override
public DateTime getLastUpdateTime() {
/*
* Dummy return method. This is used in GetCapabilities to handle the
* UPDATESEQUENCE parameter
*/
return new DateTime();
}
@Override
public ContactInfo getContactInfo() {
/*
* Returns the contact information associated with this server. This
* gets used to populate the appropriate fields in the capabilities
* document
*/
return new ContactInfo() {
@Override
public String getTelephone() {
return "x5217";
}
@Override
public String getOrganisation() {
return "ReSC";
}
@Override
public String getName() {
return "Guy";
}
@Override
public String getEmail() {
return "guy@reading";
}
};
}
public ServerInfo getServerInfo() {
/*
* Misc info associated with this WMS server
*/
return new ServerInfo() {
@Override
public String getName() {
return "THREDDS server";
}
@Override
public int getMaxSimultaneousLayers() {
/*
* Number of layers which may be requested in a single WMS
* GetMap request. This should return 1: multiple layers are not
* implemented.
*/
return 1;
}
@Override
public int getMaxImageWidth() {
return 1000;
}
@Override
public int getMaxImageHeight() {
return 1000;
}
@Override
public List<String> getKeywords() {
return new ArrayList<>();
}
@Override
public String getAbstract() {
return "This is a THREDDS data server";
}
@Override
public boolean allowsFeatureInfo() {
return true;
}
@Override
public boolean allowsGlobalCapabilities() {
return true;
}
};
}
@Override
public LayerNameMapper getLayerNameMapper() {
/*
* Defines the mapping of layer names to dataset ID / variable ID.
*
* In ncWMS we map WMS layer names to pairs of datasets/variables.
*
* In THREDDS, this is not the case. The dataset ID is essentially
* encoded in the URL and has already been used to create this
* ThreddsWmsCatalogue object. The layer name then maps directly to the
* variable ID within that dataset. This implementation reflects that
* usage
*/
return new LayerNameMapper() {
@Override
public String getVariableIdFromLayerName(String layerName)
throws EdalLayerNotFoundException {
/*
* Variable IDs map directly to layer names
*/
return layerName;
}
@Override
public String getLayerName(String datasetId, String varId) {
/*
* Variable IDs map directly to layer names
*/
return varId;
}
@Override
public String getDatasetIdFromLayerName(String layerName)
throws EdalLayerNotFoundException {
/*
* There is one dataset per catalogue, so we ignore the layer
* name and return its ID here
*/
return dataset.getId();
}
};
}
@Override
public StyleCatalogue getStyleCatalogue() {
return styleCatalogue;
}
@Override
public EnhancedVariableMetadata getLayerMetadata(final VariableMetadata metadata)
throws EdalLayerNotFoundException {
/*
* This is the method which will need the most modification before being
* included in a full THREDDS server.
*
* How this works will depend to a certain degree on the mechanism the
* TDS team choose to configure WMS specific information. It covers a
* lot of the stuff which currently lives in the LayerSettings class.
*
* Generally speaking it provides default values for plotting etc.
* (which can be overriden by URL parameters), as well as some metadata.
* Most methods can safely return null, in which case sensible defaults
* will be used.
*
* The supplied VariableMetadata can be used to find out more about the
* variable being plotted.
*/
return new EnhancedVariableMetadata() {
/**
* @return The ID of the variable this {@link EnhancedVariableMetadata} is
* associated with
*/
@Override
public String getId() {
return metadata.getId();
}
/**
* @return The title of this layer to be displayed in the menu and the
* Capabilities document
*/
@Override
public String getTitle() {
/*
* Should perhaps be more meaningful/configurable?
*/
return metadata.getId();
}
/**
* @return A brief description of this layer to be displayed in the
* Capabilities document
*/
@Override
public String getDescription() {
return null;
}
@Override
public String getCopyright() {
return null;
}
/**
* @return More information about this layer to be displayed be clients
*/
@Override
public String getMoreInfo() {
return null;
}
/**
* @return The default plot settings for this variable - this may not return
* <code>null</code>, but any of the defined methods within the
* returned {@link PlottingStyleParameters} object may do.
*/
@Override
public PlottingStyleParameters getDefaultPlottingParameters() {
List<Extent<Float>> scaleRanges = null;
String palette = null;
Color aboveMaxColour = null;
Color belowMinColour = null;
Color noDataColour = null;
Boolean logScaling = false;
Integer numColourBands = null;
Float opacity = 1.0f;
return new PlottingStyleParameters(scaleRanges, palette, aboveMaxColour,
belowMinColour, noDataColour, logScaling, numColourBands,
opacity);
}
/**
* @return Whether or not this layer can be queried with GetFeatureInfo requests
*/
@Override
public boolean isQueryable() {
return false;
};
/**
* @return Whether or not this layer can be downloaded in CSV/CoverageJSON format
*/
@Override
public boolean isDownloadable() {
return false;
};
/**
* @return Whether this layer is disabled
*/
@Override
public boolean isDisabled() {
return false;
};
};
}
}
|
package org.jivesoftware.smackx;
import java.util.Iterator;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems;
/**
* Tests the service discovery functionality.
*
* @author Gaston Dombiak
*/
public class ServiceDiscoveryManagerTest extends SmackTestCase {
/**
* Constructor for ServiceDiscoveryManagerTest.
* @param arg0
*/
public ServiceDiscoveryManagerTest(String arg0) {
super(arg0);
}
/**
* Tests info discovery of a Smack client.
*/
public void testSmackInfo() {
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
.getInstanceFor(getConnection(0));
try {
// Discover the information of another Smack client
DiscoverInfo info = discoManager.discoverInfo(getFullJID(1));
// Check the identity of the Smack client
Iterator identities = info.getIdentities();
assertTrue("No identities were found", identities.hasNext());
DiscoverInfo.Identity identity = (DiscoverInfo.Identity)identities.next();
assertEquals("Name in identity is wrong", SmackConfiguration.getIdentityName(),
identity.getName());
assertEquals("Category in identity is wrong", "client", identity.getCategory());
assertEquals("Type in identity is wrong", SmackConfiguration.getIdentityType(),
identity.getType());
assertFalse("More identities were found", identities.hasNext());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests service discovery of XHTML support.
*/
public void testXHTMLFeature() {
// Check for local XHTML service support
// By default the XHTML service support is enabled in all the connections
assertTrue(XHTMLManager.isServiceEnabled(getConnection(0)));
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
// Check for XHTML support in connection1 from connection2
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1), getBareJID(0)));
// Disable the XHTML Message support in connection1
XHTMLManager.setServiceEnabled(getConnection(0), false);
// Check for local XHTML service support
assertFalse(XHTMLManager.isServiceEnabled(getConnection(0)));
assertTrue(XHTMLManager.isServiceEnabled(getConnection(1)));
// Check for XHTML support in connection1 from connection2
assertFalse(XHTMLManager.isServiceEnabled(getConnection(1), getFullJID(0)));
}
/**
* Tests support for publishing items to another entity.
*/
public void testDiscoverPublishItemsSupport() {
try {
boolean canPublish = ServiceDiscoveryManager.getInstanceFor(getConnection(0))
.canPublishItems(getHost());
assertFalse("Messenger does not support publishing...so far!!", canPublish);
}
catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Tests publishing items to another entity.
*/
/*public void testPublishItems() {
DiscoverItems itemsToPublish = new DiscoverItems();
DiscoverItems.Item itemToPublish = new DiscoverItems.Item("pubsub.shakespeare.lit");
itemToPublish.setName("Avatar");
itemToPublish.setNode("romeo/avatar");
itemToPublish.setAction(DiscoverItems.Item.UPDATE_ACTION);
itemsToPublish.addItem(itemToPublish);
try {
ServiceDiscoveryManager.getInstanceFor(getConnection(0)).publishItems(getHost(),
itemsToPublish);
}
catch (Exception e) {
fail(e.getMessage());
}
}*/
protected int getMaxConnections() {
return 2;
}
}
|
package org.mockito.internal.util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@SuppressWarnings("unchecked")
@RunWith(MockitoJUnitRunner.class)
public class DefaultMockingDetailsTest {
@Mock private Foo foo;
@Mock private Bar bar;
@Spy private Gork gork;
@Test
public void should_check_that_a_mock_is_indeed_a_mock() throws Exception {
assertEquals(true, mockingDetails(foo).isMock());
assertEquals(true, mockingDetails(bar).isMock());
assertEquals(true, mockingDetails(gork).isMock());
assertEquals(false, mockingDetails("no a mock").isMock());
}
@Test
public void should_check_that_a_spy_is_indeed_a_spy() throws Exception {
assertEquals(true, mockingDetails(gork).isSpy());
assertEquals(false, mockingDetails(foo).isSpy());
assertEquals(false, mockingDetails(bar).isSpy());
assertEquals(false, mockingDetails("not a spy").isSpy());
}
@Test
public void should_check_that_a_spy_is_also_a_mock() throws Exception {
assertEquals(true, mockingDetails(gork).isMock());
}
@Test
public void should_get_mocked_type() throws Exception {
assertEquals(Bar.class, mockingDetails(bar).getMockedType());
}
@Test(expected = NotAMockException.class)
public void should_report_when_not_a_mockito_mock_on_getMockedType() throws Exception {
mockingDetails("not a mock").getMockedType();
}
@Test
public void should_get_extra_interfaces() throws Exception {
Bar loup = mock(Bar.class, withSettings().extraInterfaces(List.class, Observer.class));
assertEquals(setOf(Observer.class, List.class), mockingDetails(loup).getExtraInterfaces());
}
@Test(expected = NotAMockException.class)
public void should_report_when_not_a_mockito_mock_on_getExtraInterfaces() throws Exception {
mockingDetails("not a mock").getExtraInterfaces();
}
private <T> Set<T> setOf(T... items) {
return new HashSet<T>(Arrays.asList(items));
}
public class Foo { }
public interface Bar { }
public static class Gork { }
}
|
package edu.berkeley.guir.prefuse.render;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.awt.geom.RoundRectangle2D;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.util.FontLib;
import edu.berkeley.guir.prefuse.util.StringAbbreviator;
public class TextItemRenderer extends ShapeRenderer {
public static final int ALIGNMENT_LEFT = 0;
public static final int ALIGNMENT_RIGHT = 1;
public static final int ALIGNMENT_CENTER = 2;
public static final int ALIGNMENT_BOTTOM = 1;
public static final int ALIGNMENT_TOP = 0;
protected String m_labelName = "label";
protected int m_xAlign = ALIGNMENT_CENTER;
protected int m_yAlign = ALIGNMENT_CENTER;
protected int m_horizBorder = 3;
protected int m_vertBorder = 0;
protected int m_maxTextWidth = -1;
protected int m_abbrevType = StringAbbreviator.TRUNCATE;
protected StringAbbreviator m_abbrev = StringAbbreviator.getInstance();
protected RectangularShape m_textBox = new Rectangle2D.Float();
protected Font m_font = FontLib.getFont("SansSerif", Font.PLAIN, 10);
protected Point2D m_tmpPoint = new Point2D.Float();
public TextItemRenderer() {
}
/**
* Sets the default font used by this Renderer. If calling getFont() on
* a VisualItem returns a non-null value, the returned Font will be used
* instead of this default one.
* @param f the default font to use. Note that this will ONLY be used when
* if a VisualItem's getFont() method returns null.
*/
public void setFont(Font f) {
m_font = f;
}
/**
* Rounds the corners of the bounding rectangle in which the text
* string is rendered.
* @param arcWidth the width of the curved corner
* @param arcHeight the height of the curved corner
*/
public void setRoundedCorner(int arcWidth, int arcHeight) {
if ( (arcWidth == 0 || arcHeight == 0) &&
!(m_textBox instanceof Rectangle2D) ) {
m_textBox = new Rectangle2D.Float();
} else {
if ( !(m_textBox instanceof RoundRectangle2D) )
m_textBox = new RoundRectangle2D.Float();
((RoundRectangle2D)m_textBox)
.setRoundRect(0,0,10,10,arcWidth,arcHeight);
}
}
/**
* Get the attribute name of the text to draw.
* @return the text tattribute name
*/
public String getTextAttributeName() {
return m_labelName;
}
/**
* Set the attribute name for the text to draw.
* @param name the text attribute name
*/
public void setTextAttributeName(String name) {
m_labelName = name;
}
/**
* Sets the maximum width that should be allowed of the text label.
* A value of -1 specifies no limit (this is the default).
* @param maxWidth the maximum width of the text or -1 for no limit
*/
public void setMaxTextWidth(int maxWidth) {
m_maxTextWidth = maxWidth;
}
/**
* Sets the type of abbreviation to be used if a text label is longer
* than the maximum text width. The value should be one of the constants
* provided by the {@link edu.berkeley.guir.prefuse.util.StringAbbreviator
* StringAbbreviator} class. To enable abbreviation, you must first set
* the maximum text width using the {@link #setMaxTextWidth(int)
* setMaxTextWidth} method.
* @param abbrevType the abbreviation type to use. Should be one of the
* constants provided by the
* {@link edu.berkeley.guir.prefuse.util.StringAbbreviator
* StringAbbreviator} class (e.g. StringAbbreviator.TRUNCATE or
* StringAbbreviator.NAME).
*/
public void setAbbrevType(int abbrevType) {
m_abbrevType = abbrevType;
}
/**
* Returns the text to draw. Subclasses can override this class to
* perform custom text rendering.
* @param item the item to represent as a <code>String</code>
* @return a <code>String</code> to draw
*/
protected String getText(VisualItem item) {
String s = (String)item.getAttribute(m_labelName);
if ( m_maxTextWidth > -1 ) {
Font font = item.getFont();
if ( font == null ) { font = m_font; }
FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(font);
if ( fm.stringWidth(s) > m_maxTextWidth ) {
s = m_abbrev.abbreviate(s, m_abbrevType, fm, m_maxTextWidth);
}
}
return s;
}
protected boolean isHyperlink(VisualItem item) {
Boolean b = (Boolean)item.getVizAttribute(m_labelName + "_LINK");
return ( b != null && Boolean.TRUE.equals(b) );
}
/**
* @see edu.berkeley.guir.prefuse.render.ShapeRenderer#getRawShape(edu.berkeley.guir.prefuse.VisualItem)
*/
protected Shape getRawShape(VisualItem item) {
String s = getText(item);
if ( s == null ) { s = ""; }
m_font = item.getFont();
// make renderer size-aware
double size = item.getSize();
if ( size != 1 )
m_font = FontLib.getFont(m_font.getName(), m_font.getStyle(),
(int)Math.round(size*m_font.getSize()));
FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(m_font);
double h = fm.getHeight() + size*2*m_vertBorder;
double w = fm.stringWidth(s) + size*2*m_horizBorder;
getAlignedPoint(m_tmpPoint, item, w, h, m_xAlign, m_yAlign);
m_textBox.setFrame(m_tmpPoint.getX(),m_tmpPoint.getY(),w,h);
return m_textBox;
}
/**
* Helper method, which calculates the top-left co-ordinate of a node
* given the node's alignment.
*/
protected static void getAlignedPoint(Point2D p, VisualItem item,
double w, double h, int xAlign, int yAlign)
{
double x = item.getX(), y = item.getY();
if ( xAlign == ALIGNMENT_CENTER ) {
x = x-(w/2);
} else if ( xAlign == ALIGNMENT_RIGHT ) {
x = x-w;
}
if ( yAlign == ALIGNMENT_CENTER ) {
y = y-(h/2);
} else if ( yAlign == ALIGNMENT_BOTTOM ) {
y = y-h;
}
p.setLocation(x,y);
}
/**
* @see edu.berkeley.guir.prefuse.render.Renderer#render(java.awt.Graphics2D, edu.berkeley.guir.prefuse.VisualItem)
*/
public void render(Graphics2D g, VisualItem item) {
Shape shape = getShape(item);
if ( shape != null ) {
super.drawShape(g, item, shape);
// now render the text
String s = getText(item);
if ( s != null ) {
Rectangle2D r = shape.getBounds2D();
g.setPaint(item.getColor());
g.setFont(m_font);
FontMetrics fm = g.getFontMetrics();
double size = item.getSize();
double x = r.getX() + size*m_horizBorder;
double y = r.getY() + size*m_vertBorder;
g.drawString(s, (float)x, (float)y+fm.getAscent());
if ( isHyperlink(item) ) {
int lx = (int)Math.round(x), ly = (int)Math.round(y);
g.drawLine(lx,ly,lx+fm.stringWidth(s),ly+fm.getHeight()-1);
}
}
}
}
/**
* Get the horizontal alignment of this node with respect to it's
* location co-ordinate.
* @return the horizontal alignment
*/
public int getHorizontalAlignment() {
return m_xAlign;
}
/**
* Get the vertical alignment of this node with respect to it's
* location co-ordinate.
* @return the vertical alignment
*/
public int getVerticalAlignment() {
return m_yAlign;
}
/**
* Set the horizontal alignment of this node with respect to it's
* location co-ordinate.
* @param align the horizontal alignment
*/
public void setHorizontalAlignment(int align) {
m_xAlign = align;
}
/**
* Set the vertical alignment of this node with respect to it's
* location co-ordinate.
* @param align the vertical alignment
*/
public void setVerticalAlignment(int align) {
m_yAlign = align;
}
/**
* Returns the amount of padding in pixels between text
* and the border of this item along the horizontal dimension.
* @return the horizontal padding
*/
public int getHorizontalPadding() {
return m_horizBorder;
}
/**
* Sets the amount of padding in pixels between text
* and the border of this item along the horizontal dimension.
* @param xpad the horizontal padding to set
*/
public void setHorizontalPadding(int xpad) {
m_horizBorder = xpad;
}
/**
* Returns the amount of padding in pixels between text
* and the border of this item along the vertical dimension.
* @return the vertical padding
*/
public int getVerticalPadding() {
return m_vertBorder;
}
/**
* Sets the amount of padding in pixels between text
* and the border of this item along the vertical dimension.
* @param ypad the vertical padding
*/
public void setVerticalPadding(int ypad) {
m_vertBorder = ypad;
}
} // end of class TextItemRenderer
|
package org.ossnipes.snipes.lib.irc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Utility methods used a lot in the bot and not really tied to a certain class.
* This class also contains an important method that is at the core of the Snipes
* event-sending mechanism. All the methods in this class are static.
*
* @author Jack McCracken (Auv5)
* @since Snipes 0.6
*/
public class BotUtils
implements BotConstants
{
private BotUtils() {}
public static Map<String,Object> stringObjectArraysToStringObjectMap(String[] keys, Object[] values)
{
if (keys.length != values.length)
{
throw new IllegalArgumentException("Length of keys array must be the same as length of values array.");
}
// Create a map to hold the result.
Map<String,Object> result = new HashMap<String,Object>();
// It really doesn't matter which one we loop through :).
for (int i = 0; i < keys.length; i++)
{
// Put the key with the value.
result.put(keys[i], values[i]);
}
return result;
}
/** This method is the heart of the Snipes event-sending mechanism. It sends the event specified by ev with the
* parameters in args to all registered {@link IRCEventListener}s.<BR/>
* This method treats {@link IRCBase}s specially, casting them down to IRCBase and calling it's {@link IRCBase#handleInternalEvent(Event, EventArgs)}
* method.
* @param ev The enumerated identifier for the event to be sent.
* @param args The arguments object to be passed to the functions.
* @param bot The bot that this event originated from. This is used to get the event handlers registered to it.
*/
public static void sendEvent(Event ev, EventArgs args, IRCBase bot)
{
sendEvent(ev, args, bot.getEventHandlerColl());
}
/** This method is the heart of the Snipes event-sending mechanism. It sends the event specified by ev with the
* parameters in args to all registered {@link IRCEventListener}s.<BR/>
* This method treats {@link IRCBase}s specially, casting them down to IRCBase and calling it's {@link IRCBase#handleInternalEvent(Event, EventArgs)}
* method.
* @param ev The enumerated identifier for the event to be sent.
* @param args The arguments object to be passed to the functions.
* @param coll The collection containing the event listeners registered.
*/
public static void sendEvent(Event ev, EventArgs args, EventHandlerCollection coll)
{
// Is it a internal event?
boolean isInternal = arrayContains(INTERNAL_EVENTS, ev);
List<EventHandlerManager> mans;
if (InternalConstants.USE_EVLIST_COPY)
{
mans = copyList(coll.getListeners());
}
else
{
mans = coll.getListeners();
}
int i = 0;
// Loop through the listeners
while (i < mans.size())
{
EventHandlerManager ehm = mans.get(i);
boolean isBase = ehm.isIRCBase();
if (!isBase)
{
if (ehm.isSubscribed(ev))
{
ehm.sendEvent(ev, args);
}
}
else
{
if (isInternal)
{
((IRCBase)ehm.getManaged()).handleInternalEvent(ev,args);
}
ehm.sendEvent(ev,args);
}
i++;
}
}
public static <T> Set<T> copySet(
Set<T> set) {
return new HashSet<T>(set);
}
public static <T> List<T> copyList(List<T> list)
{
return new ArrayList<T>(list);
}
/** Determines if a array of any type contains the given item. Comparison is done with
* the {@link Object}'s equals(Object) method. This is especially helpful
* to do with message splitting.
* @param <T> The type being compared to.
* @param arr The array being checked for a element.
* @param item The item to check for.
* @return True if the array contains the specified element.
*/
public static <T> boolean arrayContains(T[] arr, T item)
{
for (T t : arr)
{
if (t.equals(item))
{
return true;
}
}
return false;
}
public static <T> int arrayIndex(T[] arr, T item)
{
if (arr == null)
{
return -1;
}
for (int i = 0; i < arr.length; i ++)
{
if (arr[i].equals(item))
{
return i;
}
}
return -1;
}
public static Integer convertToInt( String input )
{
try
{
// Try and parse the integer
Integer i = Integer.parseInt( input );
return i;
}
catch(Exception e)
{
return null;
}
}
/** Determines if a String can be successfully parsed as a Integer.
* @param s The String to check
* @return True if the String can be parsed as a Integer.
*/
public static boolean isInteger(String s)
{
/*// HACK: We have to use a stack trace :(.
if (s == null)
{
return false;
}
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {return false;}*/
return s.matches("^\\d+$");
}
}
|
package edu.jhu.thrax.hadoop.paraphrasing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.features.pivot.PivotedFeature;
import edu.jhu.thrax.hadoop.features.pivot.PivotedFeatureFactory;
import edu.jhu.thrax.util.FormatUtils;
public class PivotingReducer extends
Reducer<RuleWritable, MapWritable, RuleWritable, MapWritable> {
private static final Logger logger =
Logger.getLogger(PivotingReducer.class.getName());
private static enum PivotingCounters { F_READ, EF_READ, EF_PRUNED,
EE_PRUNED, EE_WRITTEN };
private static final Text EMPTY = new Text("");
private static final DoubleWritable ZERO = new DoubleWritable(0.0);
private Text currentSource;
private Text currentLhs;
private ArrayList<String> nts;
private String lhs;
private List<ParaphrasePattern> targets;
private List<PivotedFeature> features;
private Map<Text, PruningRule> translationPruningRules;
private Map<Text, PruningRule> pivotedPruningRules;
protected void setup(Context context) throws IOException,
InterruptedException {
currentLhs = null;
currentSource = null;
lhs = null;
nts = new ArrayList<String>(2);
targets = new ArrayList<ParaphrasePattern>();
Configuration conf = context.getConfiguration();
features = PivotedFeatureFactory.getAll(conf.get("thrax.features", ""));
translationPruningRules = getTranslationPruningRules(conf.get("thrax.pruning", ""));
pivotedPruningRules = getPivotedPruningRules(conf.get("thrax.pruning", ""));
}
protected void reduce(RuleWritable key, Iterable<MapWritable> values,
Context context) throws IOException, InterruptedException {
if (currentLhs == null
|| !(key.lhs.equals(currentLhs) && key.source.equals(currentSource))) {
if (currentLhs == null) {
currentLhs = new Text();
currentSource = new Text();
} else {
pivotAll(context);
}
currentLhs.set(key.lhs);
currentSource.set(key.source);
if (currentLhs.getLength() == 0 || currentSource.getLength() == 0)
return;
try {
lhs = FormatUtils.stripNonterminal(currentLhs.toString());
nts = extractNonterminals(currentSource.toString());
} catch (Exception e) {
return;
}
targets.clear();
}
for (MapWritable value : values)
if (!prune(value, translationPruningRules)) {
try {
ParaphrasePattern pp = new ParaphrasePattern(key.target.toString(), nts, lhs, value);
targets.add(pp);
} catch (Exception e) {
context.getCounter(PivotingCounters.EF_PRUNED).increment(1);
}
} else {
context.getCounter(PivotingCounters.EF_PRUNED).increment(1);
}
}
protected void cleanup(Context context) throws IOException,
InterruptedException {
if (currentLhs != null) {
pivotAll(context);
}
}
protected void pivotAll(Context context) throws IOException,
InterruptedException {
context.getCounter(PivotingCounters.F_READ).increment(1);
context.getCounter(PivotingCounters.EF_READ).increment(targets.size());
for (int i = 0; i < targets.size(); i++) {
for (int j = i; j < targets.size(); j++) {
pivotOne(targets.get(i), targets.get(j), context);
if (i != j)
pivotOne(targets.get(j), targets.get(i), context);
}
}
}
protected void pivotOne(ParaphrasePattern src, ParaphrasePattern tgt,
Context context) throws IOException, InterruptedException {
RuleWritable pivoted_rule = new RuleWritable();
MapWritable pivoted_features = new MapWritable();
pivoted_rule.lhs = new Text(FormatUtils.markup(src.lhs));
pivoted_rule.source = new Text(src.getMonotoneForm());
pivoted_rule.target = new Text(tgt.getMatchingForm(src));
pivoted_rule.featureLabel = EMPTY;
pivoted_rule.featureScore = ZERO;
// Compute the features.
for (PivotedFeature f : features)
pivoted_features.put(f.getFeatureLabel(),
f.pivot(src.features, tgt.features));
if (!prune(pivoted_features, pivotedPruningRules)) {
context.write(pivoted_rule, pivoted_features);
context.getCounter(PivotingCounters.EE_WRITTEN).increment(1);
} else {
context.getCounter(PivotingCounters.EE_PRUNED).increment(1);
}
}
protected Map<Text, PruningRule> getPivotedPruningRules(String conf_string) {
Map<Text, PruningRule> rules = new HashMap<Text, PruningRule>();
String[] rule_strings = conf_string.split("\\s*,\\s*");
for (String rule_string : rule_strings) {
String[] f;
boolean smaller;
if (rule_string.contains("<")) {
f = rule_string.split("<");
smaller = true;
} else if (rule_string.contains(">")) {
f = rule_string.split(">");
smaller = false;
} else {
continue;
}
Text label = PivotedFeatureFactory.get(f[0]).getFeatureLabel();
rules.put(label, new PruningRule(smaller, Double.parseDouble(f[1])));
}
return rules;
}
protected Map<Text, PruningRule> getTranslationPruningRules(String conf_string) {
Map<Text, PruningRule> rules = new HashMap<Text, PruningRule>();
String[] rule_strings = conf_string.split("\\s*,\\s*");
for (String rule_string : rule_strings) {
String[] f;
boolean smaller;
if (rule_string.contains("<")) {
f = rule_string.split("<");
smaller = true;
} else if (rule_string.contains(">")) {
f = rule_string.split(">");
smaller = false;
} else {
continue;
}
Double threshold = Double.parseDouble(f[1]);
Set<Text> lower_bound_labels = PivotedFeatureFactory.get(f[0]).getLowerBoundLabels();
if (lower_bound_labels != null)
for (Text label : lower_bound_labels)
rules.put(label, new PruningRule(smaller, threshold));
Set<Text> upper_bound_labels = PivotedFeatureFactory.get(f[0]).getUpperBoundLabels();
if (upper_bound_labels != null)
for (Text label : upper_bound_labels)
rules.put(label, new PruningRule(!smaller, threshold));
}
return rules;
}
protected boolean prune(MapWritable features,
final Map<Text, PruningRule> rules) {
for (Map.Entry<Text, PruningRule> e : rules.entrySet()) {
if (features.containsKey(e.getKey())
&& e.getValue().applies((DoubleWritable) features.get(e.getKey())))
return true;
}
return false;
}
protected ArrayList<String> extractNonterminals(String source) {
ArrayList<String> nts = new ArrayList<String>();
String[] tokens = source.split("[\\s]+");
// This assumes that the source side defines NT indexing, i.e. the first
// NT encountered will have index 1 etc.
for (String token : tokens) {
if (FormatUtils.isNonterminal(token)) {
nts.add(FormatUtils.stripNonterminal(token));
}
}
return nts;
}
class ParaphrasePattern {
private String[] tokens;
private String monotone;
private String reordered;
int arity;
private String lhs;
private int[] positions;
private MapWritable features;
public ParaphrasePattern(String target,
ArrayList<String> nts,
String lhs,
MapWritable features) {
this.arity = nts.size();
this.lhs = lhs;
this.positions = new int[arity];
this.features = new MapWritable(features);
this.tokens = target.split("\\s+");
buildForms();
}
private void buildForms() {
StringBuilder m_builder = new StringBuilder();
StringBuilder r_builder = new StringBuilder();
int nt_count = 0;
for (int i = 0; i < tokens.length; i++) {
if (FormatUtils.isNonterminal(tokens[i])) {
positions[nt_count] = i;
nt_count++;
String plain_nt = FormatUtils.stripIndexedNonterminal(tokens[i]);
m_builder.append(FormatUtils.markup(plain_nt, nt_count));
if (arity == 2)
r_builder.append(FormatUtils.markup(plain_nt, 3 - nt_count));
} else {
m_builder.append(tokens[i]);
r_builder.append(tokens[i]);
}
m_builder.append(" ");
r_builder.append(" ");
}
monotone = m_builder.substring(0, m_builder.length() - 1);
reordered = (arity == 2) ? r_builder.substring(0, r_builder.length() - 1)
: monotone;
}
public String getMonotoneForm() {
return monotone;
}
public String getMatchingForm(ParaphrasePattern src) {
for (int i = 0; i < positions.length; i++) {
if (!tokens[positions[i]].equals(src.tokens[src.positions[i]]))
return reordered;
}
return monotone;
}
}
class PruningRule {
private boolean smaller;
private double threshold;
PruningRule(boolean smaller, double threshold) {
this.smaller = smaller;
this.threshold = threshold;
}
protected boolean applies(DoubleWritable value) {
return (smaller ? value.get() < threshold : value.get() > threshold);
}
}
}
|
package edu.mit.mobile.android.content;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class ForeignKeyDBHelper extends GenericDBHelper {
public static final String WILDCARD_PATH_SEGMENT = "_all";
private final String mColumn;
public ForeignKeyDBHelper(Class<? extends ContentItem> parent,
Class<? extends ContentItem> child, String column) {
super(child);
mColumn = column;
}
@Override
public Uri insertDir(SQLiteDatabase db, ContentProvider provider, Uri uri,
ContentValues values) throws SQLException {
final long parentId = Long.valueOf(ProviderUtils.getNthPathFromEnd(uri,
1));
values.put(mColumn, parentId);
return super.insertDir(db, provider, uri, values);
}
@Override
public int updateItem(SQLiteDatabase db, ContentProvider provider, Uri uri,
ContentValues values, String where, String[] whereArgs) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 2);
return super.updateItem(db, provider, uri, values,
ProviderUtils.addExtraWhere(where, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(whereArgs, parentId));
}
@Override
public int updateDir(SQLiteDatabase db, ContentProvider provider, Uri uri,
ContentValues values, String where, String[] whereArgs) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 1);
return super.updateDir(db, provider, uri, values,
ProviderUtils.addExtraWhere(where, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(whereArgs, parentId));
}
@Override
public int deleteItem(SQLiteDatabase db, ContentProvider provider, Uri uri,
String where, String[] whereArgs) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 2);
return super.deleteItem(db, provider, uri,
ProviderUtils.addExtraWhere(where, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(whereArgs, parentId));
}
@Override
public int deleteDir(SQLiteDatabase db, ContentProvider provider, Uri uri,
String where, String[] whereArgs) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 1);
return super.deleteDir(db, provider, uri,
ProviderUtils.addExtraWhere(where, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(whereArgs, parentId));
}
@Override
public Cursor queryDir(SQLiteDatabase db, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 1);
if (WILDCARD_PATH_SEGMENT.equals(parentId)) {
return super.queryDir(db, uri, projection, selection, selectionArgs, sortOrder);
} else {
return super.queryDir(db, uri, projection,
ProviderUtils.addExtraWhere(selection, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(selectionArgs, parentId), sortOrder);
}
}
@Override
public Cursor queryItem(SQLiteDatabase db, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
final String parentId = ProviderUtils.getNthPathFromEnd(uri, 2);
if (WILDCARD_PATH_SEGMENT.equals(parentId)) {
return super.queryItem(db, uri, projection, selection, selectionArgs, sortOrder);
} else {
return super.queryItem(db, uri, projection,
ProviderUtils.addExtraWhere(selection, mColumn + "=?"),
ProviderUtils.addExtraWhereArgs(selectionArgs, parentId), sortOrder);
}
}
}
|
package edu.wpi.first.wpilibj.technobots.subsystems;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.PIDSubsystem;
import edu.wpi.first.wpilibj.technobots.RobotMap;
/**
*
* @author Kim
*/
public class Elbow extends PIDSubsystem {
private static final double Kp = .2;
private static final double Ki = 0.0;
private static final double Kd = 0.0;
public static final double START = 0.57;
AnalogChannel pot;
SpeedController motor;
// Initialize your subsystem here
public Elbow() {
super("Elbow", Kp, Ki, Kd);
motor = new Victor(RobotMap.elbow);
pot = new AnalogChannel(RobotMap.pot);
setSetpoint(START);
enable();
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
protected double returnPIDInput() {
// Return your input value for the PID loop
// e.g. a sensor, like a potentiometer:
// yourPot.getAverageVoltage() / kYourMaxVoltage;
return pot.getVoltage();
}
protected void usePIDOutput(double output) {
motor.set(output);
}
}
|
package com.kii.thingif.gateway;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.text.TextUtils;
import android.util.Base64;
import com.kii.thingif.KiiApp;
import com.kii.thingif.MediaTypes;
import com.kii.thingif.exception.StoredGatewayAPIInstanceNotFoundException;
import com.kii.thingif.exception.ThingIFException;
import com.kii.thingif.internal.GsonRepository;
import com.kii.thingif.internal.http.IoTRestClient;
import com.kii.thingif.internal.http.IoTRestRequest;
import com.kii.thingif.internal.utils.Path;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GatewayAPI implements Parcelable {
private static final String SHARED_PREFERENCES_KEY_INSTANCE = "GatewayAPI_INSTANCE";
private static Context context;
private final String tag;
private final KiiApp app;
private final GatewayAddress gatewayAddress;
private String accessToken;
private final IoTRestClient restClient;
GatewayAPI(@Nullable Context context,
@NonNull KiiApp app,
@NonNull GatewayAddress gatewayAddress) {
this(context, null, app, gatewayAddress);
}
GatewayAPI(@Nullable Context context,
@Nullable String tag,
@NonNull KiiApp app,
@NonNull GatewayAddress gatewayAddress) {
if (context != null) {
GatewayAPI.context = context.getApplicationContext();
}
this.app = app;
this.tag =tag;
this.gatewayAddress = gatewayAddress;
this.restClient = new IoTRestClient();
}
protected Map<String, String> newHeader() {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer " + this.accessToken);
return headers;
}
/** Login to the Gateway.
* Local authentication for the Gateway access.
* Required prior to call other APIs access to the gateway.
* @param username Username of the Gateway.
* @param password Password of the Gateway.
* @throws ThingIFException
*/
@WorkerThread
public void login(@NonNull String username, @NonNull String password) throws ThingIFException {
if (TextUtils.isEmpty(username)) {
throw new IllegalArgumentException("username is null or empty");
}
if (TextUtils.isEmpty(password)) {
throw new IllegalArgumentException("password is null or empty");
}
String path = MessageFormat.format("/{0}/token", this.app.getSiteName());
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
String credential = this.app.getAppID() + ":" + this.app.getAppKey();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + Base64.encodeToString(credential.getBytes(), Base64.NO_WRAP));
JSONObject requestBody = new JSONObject();
try {
requestBody.put("username", username);
requestBody.put("password", password);
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = new IoTRestClient().sendRequest(request);
this.accessToken = responseBody.optString("accessToken", null);
this.saveInstance(this);
}
@NonNull
@WorkerThread
public String onboardGateway() throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
String path = MessageFormat.format("/{0}/apps/{1}/gateway/onboarding", this.app.getSiteName(), this.app.getAppID());
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
return responseBody.optString("thingID", null);
}
@WorkerThread
@NonNull
public String getGatewayID() throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
String path = MessageFormat.format("/{0}/apps/{1}/gateway/id", this.app.getSiteName(), this.app.getAppID());
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
return responseBody.optString("thingID", null);
}
@WorkerThread
@NonNull
public List<EndNode> listPendingEndNodes() throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
String path = MessageFormat.format("/{0}/apps/{1}/gateway/end-nodes/pending", this.app.getSiteName(), this.app.getAppID());
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
List<EndNode> nodes = new ArrayList<EndNode>();
JSONArray results = responseBody.optJSONArray("results");
if (results != null) {
for (int i = 0; i < results.length(); i++) {
try {
nodes.add(new EndNode(results.getJSONObject(i)));
} catch (JSONException ignore) {
}
}
}
return nodes;
}
@WorkerThread
public void notifyOnboardingCompletion(@NonNull String endNodeThingID, @NonNull String endNodeVenderThingID) throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
if (TextUtils.isEmpty(endNodeThingID)) {
throw new IllegalArgumentException("thingID is null or empty");
}
if (TextUtils.isEmpty(endNodeVenderThingID)) {
throw new IllegalArgumentException("venderThingID is null or empty");
}
String path = MessageFormat.format("/{0}/apps/{1}/gateway/end-nodes/VENDOR_THING_ID:{2}", this.app.getSiteName(), this.app.getAppID(), endNodeVenderThingID);
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
try {
requestBody.put("thingID", endNodeThingID);
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
this.restClient.sendRequest(request);
}
@WorkerThread
public void restore() throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
String path = "/gateway-app/gateway/restore";
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers);
this.restClient.sendRequest(request);
}
@WorkerThread
public void replaceEndNode(@NonNull String endNodeThingID, @NonNull String endNodeVenderThingID) throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
if (TextUtils.isEmpty(endNodeThingID)) {
throw new IllegalArgumentException("thingID is null or empty");
}
if (TextUtils.isEmpty(endNodeVenderThingID)) {
throw new IllegalArgumentException("venderThingID is null or empty");
}
String path = MessageFormat.format("/{0}/apps/{1}/gateway/end-nodes/THING_ID:{2}", this.app.getSiteName(), this.app.getAppID(), endNodeThingID);
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
try {
requestBody.put("vendorThingID", endNodeVenderThingID);
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
this.restClient.sendRequest(request);
}
@WorkerThread
@NonNull
public GatewayInformation getGatewayInformation() throws ThingIFException {
if (!isLoggedIn()) {
throw new IllegalStateException("Needs user login before execute this API");
}
String path = "/gateway-info";
String url = Path.combine(this.gatewayAddress.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
return new GatewayInformation(responseBody.optString("vendorThingID", null));
}
/** Check If user is logged in to the Gateway.
* @return true if user is logged in, false otherwise.
*/
public boolean isLoggedIn() {
return !TextUtils.isEmpty(this.accessToken);
}
/**
* Get a tag.
* @return
*/
public String getTag() {
return this.tag;
}
/** Get Kii App
* @return Kii Cloud Application.
*/
public KiiApp getApp() {
return this.app;
}
/**
* Get AppID
* @return
*/
public String getAppID() {
return this.app.getAppID();
}
/**
* Get AppKey
* @return
*/
public String getAppKey() {
return this.app.getAppKey();
}
/** Get GatewayAddress
* @return Gateway Address
*/
public GatewayAddress getGatewayAddress() {
return this.gatewayAddress;
}
/**
* Get Access Token
* @return
*/
public String getAccessToken() {
return this.accessToken;
}
void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
// Implementation of Parcelable
public static final Creator<GatewayAPI> CREATOR = new Creator<GatewayAPI>() {
@Override
public GatewayAPI createFromParcel(Parcel in) {
return new GatewayAPI(in);
}
@Override
public GatewayAPI[] newArray(int size) {
return new GatewayAPI[size];
}
};
protected GatewayAPI(Parcel in) {
this.tag = in.readString();
this.app = in.readParcelable(KiiApp.class.getClassLoader());
this.gatewayAddress = in.readParcelable(GatewayAddress.class.getClassLoader());
this.accessToken = in.readString();
this.restClient = new IoTRestClient();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.tag);
dest.writeParcelable(this.app, flags);
dest.writeParcelable(this.gatewayAddress, flags);
dest.writeString(this.accessToken);
}
/**
* Try to load the instance of GatewayAPI using stored serialized instance.
* <BR>
* Instance is automatically saved when {@link #login(String, String)} is called.
* <BR>
*
* If the GatewayAPI instance is build without the tag, all instance is saved in same place
* and overwritten when the instance is saved.
* <BR>
* <BR>
*
* If the GatewayAPI instance is build with the tag(optional), tag is used as key to distinguish
* the storage area to save the instance. This would be useful to saving multiple instance.
* You need specify tag to load the instance by the
* {@link #loadFromStoredInstance(Context, String) api}.
*
* @param context context
* @return ThingIFAPI instance.
* @throws StoredGatewayAPIInstanceNotFoundException when the instance has not stored yet.
*/
public static GatewayAPI loadFromStoredInstance(@NonNull Context context) throws StoredGatewayAPIInstanceNotFoundException {
return loadFromStoredInstance(context, null);
}
/**
* Try to load the instance of GatewayAPI using stored serialized instance.
* <BR>
* For details please refer to the {@link #loadFromStoredInstance(Context)} document.
*
* @param context context
* @param tag specified when the ThingIFAPI has been built.
* @return GatewayAPI instance.
* @throws StoredGatewayAPIInstanceNotFoundException when the instance has not stored yet.
*/
public static GatewayAPI loadFromStoredInstance(@NonNull Context context, String tag) throws StoredGatewayAPIInstanceNotFoundException {
GatewayAPI.context = context.getApplicationContext();
SharedPreferences preferences = getSharedPreferences();
String serializedJson = preferences.getString(getSharedPreferencesKey(tag), null);
if (serializedJson != null) {
return GsonRepository.gson().fromJson(serializedJson, GatewayAPI.class);
}
throw new StoredGatewayAPIInstanceNotFoundException(tag);
}
/**
* Clear all saved instances in the SharedPreferences.
*/
public static void removeAllStoredInstances() {
SharedPreferences preferences = getSharedPreferences();
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
}
/**
* Remove saved specified instance in the SharedPreferences.
*
* @param tag
*/
public static void removeStoredInstance(String tag) {
SharedPreferences preferences = getSharedPreferences();
SharedPreferences.Editor editor = preferences.edit();
editor.remove(getSharedPreferencesKey(tag));
editor.apply();
}
private static void saveInstance(GatewayAPI instance) {
SharedPreferences preferences = getSharedPreferences();
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getSharedPreferencesKey(instance.tag), GsonRepository.gson().toJson(instance));
editor.apply();
}
}
private static String getSharedPreferencesKey(String tag) {
return SHARED_PREFERENCES_KEY_INSTANCE + (tag == null ? "" : "_" +tag);
}
private static SharedPreferences getSharedPreferences() {
if (context != null) {
return context.getSharedPreferences("com.kii.thingif.preferences", Context.MODE_PRIVATE);
}
return null;
}
}
|
package org.x2a.cutter.annotation;
import org.x2a.cutter.cut.Advice;
import org.x2a.cutter.cut.JoinPoint;
import org.x2a.cutter.cut.Parameter;
import java.lang.annotation.*;
/**
* Add to a method to create a Pointcut that will intercept program execution and trigger the corresponding
* {@link Advice} methods.
* <p>
* <bold>DOES NOT SUPPORT ANONYMOUS INNER CLASSES</bold>
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface Cut {
Class<? extends Advice> value();
final class Utils { //this class exists to solve potential import problems
public static Parameter wrapParameter(final String name, final Class<?> clazz, final Object val) {
return new Parameter(name, clazz, val);
}
/**
* @param values {"name1", clazz1, val1, "name2", clazz2, val2}
*/
public static Parameter[] toParameters(Object[] values) {
Parameter[] parameters = new Parameter[values.length / 3];
for (int i = 0; i < values.length; i += 3) {
String name = (String) values[i];
Class<?> clazz = (Class<?>) values[i + 1];
Object val = values[i + 2];
parameters[i / 3] = new Parameter(name, clazz, val);
}
return parameters;
}
public static JoinPoint createJoinPoint(Class<?> clazz, String methodName) {
return new JoinPoint(clazz, methodName);
}
}
}
|
package com.exedio.cope.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.exedio.cope.Model;
/**
* A filter for starting/closing cope transactions.
*
* In order to use it, you have to deploy the filter in your <tt>web.xml</tt>,
* providing the name of the cope model via an init-parameter.
* Typically, your <tt>web.xml</tt> would contain a snippet like this:
* <pre>
* <filter>
* <filter-name>CopeFilter</filter-name>
* <filter-class>com.exedio.cope.util.CopeFilter</filter-class>
* <init-param>
* <param-name>model</param-name>
* <param-value>{@link com.exedio.cope.Model com.exedio.demoshop.Main#model}</param-value>
* </init-param>
* </filter>
* <filter-mapping>
* <filter-name>CopeFilter</filter-name>
* <url-pattern>*.do</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping>
* </pre>
*
* @author Stephan Frisch, exedio GmbH
*/
public final class CopeFilter implements Filter
{
private Model model;
public void init(final FilterConfig config) throws ServletException
{
try
{
model = ServletUtil.getConnectedModel(config);
}
catch(RuntimeException e)
{
// tomcat does not print stack trace or exception message, so we do
System.err.println("RuntimeException in CopeFilter.init");
e.printStackTrace();
throw e;
}
catch(ServletException e)
{
// tomcat does not print stack trace or exception message, so we do
System.err.println("ServletException in CopeFilter.init");
e.printStackTrace();
throw e;
}
catch(Error e)
{
// tomcat does not print stack trace or exception message, so we do
System.err.println("Error in CopeFilter.init");
e.printStackTrace();
throw e;
}
}
private volatile boolean migrated = false;
public void doFilter(
final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws IOException, ServletException
{
// This flag is just a small shortcut. No synchronization needed,
// because Model#migrate does care about synchronization.
if(!migrated)
{
// Cannot do this in init(), because filters are always initialized on startup.
// So the whole application would be useless, if the database schema is not yet created,
// including the COPE Console usually used to create the schema.
model.migrateIfSupported();
migrated = true;
}
try
{
model.startTransaction("CopeFilter");
chain.doFilter(request, response);
model.commit();
}
finally
{
model.rollbackIfNotCommitted();
}
}
public void destroy()
{
// empty implementation
}
}
|
package com.sasnee.scribo;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class DebugHelper {
private static final String TAG = "DebugHelper";
private static FileOutputStream mOutput = null;
private static OutputStreamWriter mOutputStreamWriter = null;
public static String filePath;
private static final String DEFAULT_JOURNAL_FILE = "logJournal.txt";
private static final Boolean DEFAULT_RESET_OPTION = true; // Reset file contents everytime.
private static String mLogJournalFile = filePath + DEFAULT_JOURNAL_FILE;
private File mFile;
private static Context mContext;
/* DebugHelper class is singleton */
private static DebugHelper sInstance = null;
public final static int SEVERITY_LEVEL_ERROR = 0x1;
public final static int SEVERITY_LEVEL_WARN = 0x2;
public final static int SEVERITY_LEVEL_VERBOSE = 0x4;
public final static int SEVERITY_LEVEL_INFO = 0x8;
public final static long LOG_CATEGORY_0 = 0x1;
public final static long LOG_CATEGORY_1 = 0x2;
public final static long LOG_CATEGORY_2 = 0x4;
public final static long LOG_CATEGORY_3 = 0x8;
public final static long LOG_CATEGORY_4 = 0x10;
public final static long LOG_CATEGORY_5 = 0x20;
public final static long LOG_CATEGORY_6 = 0x40;
public final static long LOG_CATEGORY_7 = 0x80;
public final static long LOG_CATEGORY_8 = 0x100;
public final static long LOG_CATEGORY_9 = 0x200;
public final static long LOG_CATEGORY_10 = 0x400;
public final static long LOG_CATEGORY_GENERAL = 0x800;
private final static boolean DEFAULT_ADB_BEHAVIOUR = true;
private final static int DEFAULT_SEVERITY_LEVEL = SEVERITY_LEVEL_VERBOSE;
private final static long DEFAULT_LOG_CATEGORY_MASK = LOG_CATEGORY_GENERAL;
private static long logCategoryMask = LOG_CATEGORY_GENERAL;
private static HashMap<Long, String>LogMaskLookupTable;
private DebugHelper(Context context) {
mContext = context;
}
public static void init(Context context) {
init(context, DEFAULT_JOURNAL_FILE, DEFAULT_RESET_OPTION);
}
public static void init(Context context, String fileName) {
init(context, fileName, DEFAULT_RESET_OPTION);
}
public static void init(Context context, Boolean resetFileContents) {
init(context, DEFAULT_JOURNAL_FILE, resetFileContents);
}
public static void init(Context context, String fileName, Boolean resetFileContents) {
if (sInstance == null) {
synchronized (DebugHelper.class) {
if (sInstance == null) {
sInstance = new DebugHelper(context);
}
}
}
if (!fileName.contains(".txt")) {
// Append .txt to the file name to make life simpler!
fileName = fileName + ".txt";
}
sInstance.setLogJournalFile(fileName);
if (resetFileContents) {
// Reset the file contents.
startFromScratch();
}
prePopulateLookupTable();
}
private void setLogJournalFile(String fileName) {
filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/AppData/" + mContext.getApplicationInfo().processName + "/";
mLogJournalFile = filePath + fileName;
mFile = new File(filePath);
mFile.mkdirs();
Log.i(TAG, "setLogJournalFile: Journal file = " + mLogJournalFile);
}
private static void prePopulateLookupTable() {
LogMaskLookupTable = new HashMap<>();
LogMaskLookupTable.put(LOG_CATEGORY_0, "Log Category 0");
LogMaskLookupTable.put(LOG_CATEGORY_1, "Log Category 1");
LogMaskLookupTable.put(LOG_CATEGORY_2, "Log Category 2");
LogMaskLookupTable.put(LOG_CATEGORY_3, "Log Category 3");
LogMaskLookupTable.put(LOG_CATEGORY_4, "Log Category 4");
LogMaskLookupTable.put(LOG_CATEGORY_5, "Log Category 5");
LogMaskLookupTable.put(LOG_CATEGORY_6, "Log Category 6");
LogMaskLookupTable.put(LOG_CATEGORY_7, "Log Category 7");
LogMaskLookupTable.put(LOG_CATEGORY_8, "Log Category 8");
LogMaskLookupTable.put(LOG_CATEGORY_9, "Log Category 9");
LogMaskLookupTable.put(LOG_CATEGORY_10, "Log Category 10");
}
public static String getFilePath() {
return mLogJournalFile;
}
private static void startFromScratch() {
// Just open close the file in non-append mode to reset the contents.
try {
PrintWriter pw = new PrintWriter(mLogJournalFile);
pw.close();
} catch (Exception e) {
Log.e(TAG, "DebugHelper : Exception: " + e.getCause() + " | " + e.getMessage());
}
}
public static boolean mapCustomLogMask(long defaultCategoryMask, String customLogMask) {
boolean result = true;
if (defaultCategoryMask >= LOG_CATEGORY_0 && defaultCategoryMask <= LOG_CATEGORY_10)
LogMaskLookupTable.put(defaultCategoryMask, customLogMask);
else
result = false;
return result;
}
private static long getLogCategoryFromCustomLogMask(String customLogMask) {
long returnVal = -1;
for (Long keyItem : LogMaskLookupTable.keySet()) {
if (LogMaskLookupTable.get(keyItem).equals(customLogMask)) {
returnVal = keyItem;
break;
}
}
return returnVal;
}
public static void enableDisableLogCategory(long category, boolean isEnable) {
if (isEnable) {
logCategoryMask = logCategoryMask | category;
} else {
logCategoryMask = logCategoryMask & ~category;
}
}
public static void enableDisableLogCategory(String customLogMask, boolean isEnable) {
long category = LOG_CATEGORY_GENERAL;
boolean customLogMaskFound = false;
for (Long keyItem : LogMaskLookupTable.keySet()) {
if (LogMaskLookupTable.get(keyItem).equals(customLogMask)) {
category = keyItem;
customLogMaskFound = true;
break;
}
}
if (customLogMaskFound) {
enableDisableLogCategory(category, isEnable);
} else {
Log.i(TAG, "enableDisableLogCategory: Unrecognized custom log mask: " + customLogMask);
}
}
private static String logFunction(int severity, String tag, String logEntry,
boolean shouldOutputToADB) {
String severityLevel = null;
switch (severity) {
case SEVERITY_LEVEL_ERROR:
severityLevel = "Error";
Log.e(tag, logEntry);
break;
case SEVERITY_LEVEL_WARN:
severityLevel = "Warning";
if (shouldOutputToADB) {
Log.w(tag, logEntry);
}
break;
case SEVERITY_LEVEL_VERBOSE:
severityLevel = "Verbose";
if (shouldOutputToADB) {
Log.v(tag, logEntry);
}
break;
case SEVERITY_LEVEL_INFO:
severityLevel = "Info";
if (shouldOutputToADB) {
Log.i(tag, logEntry);
}
break;
default:
severityLevel = "Verbose";
if (shouldOutputToADB) {
Log.v(tag, logEntry);
}
break;
}
return severityLevel;
}
synchronized private static void updateLogJournal(String tag, String logEntry,
String severityLevel) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
String currentDateTime = sdf.format(new Date());
try {
mOutput = new FileOutputStream(mLogJournalFile, true);
mOutputStreamWriter = new OutputStreamWriter(mOutput);
mOutputStreamWriter.append(currentDateTime + ": " + tag + " |"
+ severityLevel + "|" + ": ");
mOutputStreamWriter.append(logEntry);
mOutputStreamWriter.append("\n");
mOutputStreamWriter.flush();
mOutputStreamWriter.close();
mOutput.close();
} catch (Exception e) {
Log.e(TAG, "updateLogJournal : Exception: " + e.getCause() + "|" + e.getMessage());
e.printStackTrace();
}
}
synchronized private static void updateLogJournalInternal(String tag, String logEntry,
String severityLevel) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
String currentDateTime = sdf.format(new Date());
try {
mOutput = mContext.openFileOutput(DEFAULT_JOURNAL_FILE, mContext.MODE_APPEND);
mOutputStreamWriter = new OutputStreamWriter(mOutput);
mOutputStreamWriter.append(currentDateTime + ": " + tag + " |"
+ severityLevel + "|" + ": ");
mOutputStreamWriter.append(logEntry);
mOutputStreamWriter.append("\n");
mOutputStreamWriter.flush();
mOutputStreamWriter.close();
mOutput.close();
} catch (Exception e) {
Log.e(TAG, "updateLogJournal : Exception: " + e.getCause() + "|" + e.getMessage());
e.printStackTrace();
}
}
public static void logRequest(String tag, String logEntry) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, DEFAULT_SEVERITY_LEVEL,
DEFAULT_LOG_CATEGORY_MASK);
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs) {
logRequest(tag, logEntry, showOnADBLogs, DEFAULT_SEVERITY_LEVEL, DEFAULT_LOG_CATEGORY_MASK);
}
public static void logRequest(String tag, String logEntry, int severity) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, severity, DEFAULT_LOG_CATEGORY_MASK);
}
public static void logRequest(String tag, String logEntry, String customLogMask) {
long category = getLogCategoryFromCustomLogMask(customLogMask);
if (category >= 0) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, DEFAULT_SEVERITY_LEVEL, category);
} else {
Log.i(TAG, "logRequest: Unrecognized custom log mask : " + customLogMask);
}
}
public static void logRequest(String tag, String logEntry, long category) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, DEFAULT_SEVERITY_LEVEL, category);
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs,
int severity) {
logRequest(tag, logEntry, showOnADBLogs, severity, DEFAULT_LOG_CATEGORY_MASK);
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs,
String customLogMask) {
long category = getLogCategoryFromCustomLogMask(customLogMask);
if (category >= 0) {
logRequest(tag, logEntry, showOnADBLogs, DEFAULT_SEVERITY_LEVEL, category);
} else {
Log.i(TAG, "logRequest: Unrecognized custom log mask : " + customLogMask);
}
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs,
long category) {
logRequest(tag, logEntry, showOnADBLogs, DEFAULT_SEVERITY_LEVEL, category);
}
public static void logRequest(String tag, String logEntry, int severity, String customLogMask) {
long category = getLogCategoryFromCustomLogMask(customLogMask);
if (category >= 0) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, severity, category);
} else {
Log.i(TAG, "logRequest: Unrecognized custom log mask : " + customLogMask);
}
}
public static void logRequest(String tag, String logEntry, int severity, long category) {
logRequest(tag, logEntry, DEFAULT_ADB_BEHAVIOUR, severity, category);
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs,
int severity, String customLogMask) {
long category = getLogCategoryFromCustomLogMask(customLogMask);
if (category >= 0) {
logRequest(tag, logEntry, showOnADBLogs, severity, category);
} else {
Log.i(TAG, "logRequest: Unrecognized custom log mask : " + customLogMask);
}
}
public static void logRequest(String tag, String logEntry, boolean showOnADBLogs,
int severity, long category) {
String severityLevel;
boolean shouldOutputToADB = showOnADBLogs && ((category & logCategoryMask) > 0);
if (tag == null) {
tag = TAG;
}
severityLevel = logFunction(severity, tag, logEntry, shouldOutputToADB);
// Write to journal file only if the logCategoryMask allows it.
if ((category & logCategoryMask) > 0) {
String state = android.os.Environment.getExternalStorageState();
if (state.equals(android.os.Environment.MEDIA_MOUNTED))
updateLogJournal(tag, logEntry, severityLevel);
}
}
public static void sendLogFileByEmail() {
sendLogFileByEmail(null);
}
public static void sendLogFileByEmail(List<String> emailList) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String currentDateTime = sdf.format(new Date());
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_SUBJECT, "LogJournal - " + currentDateTime);
i.putExtra(Intent.EXTRA_TEXT, "Attached log file");
if (emailList != null && !emailList.isEmpty()) {
String[] emails = emailList.toArray(new String[0]);
i.putExtra(Intent.EXTRA_EMAIL, emails);
}
i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + mLogJournalFile));
i.setType("text/plain");
DebugHelper.logRequest(TAG, "sendLogFileByEmail: Emailing " + mLogJournalFile, true, DebugHelper.SEVERITY_LEVEL_INFO);
((Activity)mContext).startActivity(Intent.createChooser(i, "Send email"));
}
//Method to log the contents from the file
public static void printLogs(){
StringBuilder sb = new StringBuilder();
try {
FileInputStream fis = mContext.openFileInput(DEFAULT_JOURNAL_FILE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("TESTING", "String builder :"+ sb.toString());
}
}
|
package org.apache.jmeter.functions;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
public class MachineName extends AbstractFunction implements Serializable {
private static final List desc = new LinkedList();
private static final String KEY = "__machineName";
// Number of parameters expected - used to reject invalid calls
private static final int PARAMETER_COUNT = 1;
static {
// desc.add("Use fully qualified host name: TRUE/FALSE (Default FALSE)");
desc.add(JMeterUtils.getResString("function_name_param"));
}
private Object[] values;
public MachineName() {}
public Object clone() {
return new MachineName();
}
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
JMeterVariables vars = getVariables();
// boolean fullHostName = false;
// if ( ((CompoundFunction)values[0]).execute().toLowerCase().equals("true") )
// fullHostName = true;
String varName = ((CompoundVariable)values[values.length - 1]).execute();
String machineName = "";
try {
InetAddress Address = InetAddress.getLocalHost();
//fullHostName disabled until we move up to 1.4 as the support jre
// if ( fullHostName ) {
// machineName = Address.getCanonicalHostName();
// } else {
machineName = Address.getHostName();
} catch ( UnknownHostException e ) {
}
vars.put( varName, machineName );
return machineName;
}
public void setParameters(Collection parameters)
throws InvalidVariableException {
values = parameters.toArray();
if ( values.length != PARAMETER_COUNT ) {
throw new InvalidVariableException("Parameter Count != "+PARAMETER_COUNT);
}
}
public String getReferenceKey() {
return KEY;
}
public List getArgumentDesc() {
return desc;
}
}
|
package gov.nih.nci.ncicb.cadsr.jaas;
import java.io.*;
import javax.security.auth.callback.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Rectangle;
/**
* Simple CallbackHandler that queries the standard input. This is appropriate for console mode only.
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class SwingCallbackHandler
extends JDialog
implements CallbackHandler, ActionListener {
private JTextField usernameField = new JTextField();
private JLabel usernameLabel = new JLabel();
private JLabel passwordLabel = new JLabel();
private JPasswordField passwordField = new JPasswordField();
private JButton okButton = new JButton();
private JButton cancelButton = new JButton();
private JDialog _this = this;
public SwingCallbackHandler()
{
super((Frame)null, true);
try
{
jbInit();
this.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void jbInit() throws Exception
{
this.getContentPane().setLayout(null);
this.setSize(new Dimension(299, 201));
usernameField.setBounds(new Rectangle(130, 35, 135, 25));
usernameLabel.setText("Username");
usernameLabel.setBounds(new Rectangle(25, 35, 140, 25));
passwordLabel.setText("Password");
passwordLabel.setBounds(new Rectangle(25, 80, 150, 30));
passwordField.setBounds(new Rectangle(130, 80, 135, 30));
okButton.setText("OK");
okButton.setBounds(new Rectangle(135, 135, 55, 20));
okButton.setActionCommand("OK");
okButton.addActionListener(this);
cancelButton.setText("Cancel");
cancelButton.setBounds(new Rectangle(200, 135, 75, 20));
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(this);
this.getContentPane().add(cancelButton, null);
this.getContentPane().add(okButton, null);
this.getContentPane().add(passwordField, null);
this.getContentPane().add(passwordLabel, null);
this.getContentPane().add(usernameLabel, null);
this.getContentPane().add(usernameField, null);
this.getRootPane().setDefaultButton(okButton);
}
public void handle(Callback[] callbacks)
throws java.io.IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback)callbacks[i]).setName(usernameField.getText());
} else if (callbacks[i] instanceof PasswordCallback) {
((PasswordCallback)callbacks[i]).setPassword(passwordField.getPassword());
} else {
throw(new UnsupportedCallbackException(
callbacks[i], "Callback class not supported"));
}
}
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("OK")) {
_this.setVisible(false);
} else if(evt.getActionCommand().equals("Cancel")) {
System.exit(0);
}
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.util;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import java.util.*;
public class ObjectUpdater {
public static void updateByAltName(String altName, Concept[] oldConcepts, Concept[] newConcepts) {
ElementsLists elements = ElementsLists.getInstance();
List<DataElement> des = (List<DataElement>)elements.getElements(DomainObjectFactory.newDataElement().getClass());
for(DataElement de : des) {
// Collection<AlternateName> altNames =
// (Collection<AlternateName>)de.getAlternateNames();
// boolean found = false;
// for(AlternateName n : altNames) {
// if(n.getName().equals(altName)) {
// found = true;
// break;
// if(found) {
if(de.getDataElementConcept().getProperty().getLongName().equals(altName)) {
de.getDataElementConcept().getProperty().setPreferredName(preferredNameFromConcepts(newConcepts));
}
}
addNewConcepts(newConcepts);
removeStaleConcepts(oldConcepts);
}
public static void update(AdminComponent ac, Concept[] oldConcepts, Concept[] newConcepts) {
if(ac instanceof ObjectClass) {
ObjectClass oc = (ObjectClass)ac;
oc.setPreferredName(preferredNameFromConcepts(newConcepts));
} else if(ac instanceof DataElement) {
DataElement de = (DataElement)ac;
de.getDataElementConcept().getProperty().setPreferredName(preferredNameFromConcepts(newConcepts));
}
addNewConcepts(newConcepts);
removeStaleConcepts(oldConcepts);
}
public static String preferredNameFromConcepts(List<Concept> concepts) {
StringBuffer sb = new StringBuffer();
for(Concept con : concepts) {
if(sb.length() > 0)
sb.insert(0, ":");
sb.insert(0, con.getPreferredName());
}
return sb.toString();
}
public static String preferredNameFromConcepts(Concept[] concepts) {
StringBuffer sb = new StringBuffer();
for(Concept con : concepts) {
if(sb.length() > 0)
sb.insert(0, ":");
sb.insert(0, con.getPreferredName());
}
return sb.toString();
}
private static void removeStaleConcepts(Concept[] concepts) {
ElementsLists elements = ElementsLists.getInstance();
List<ObjectClass> ocs = (List<ObjectClass>)elements.getElements(DomainObjectFactory.newObjectClass().getClass());
List<Property> props = (List<Property>)elements.getElements(DomainObjectFactory.newProperty().getClass());
a:
for(Concept concept : concepts) {
boolean found = false;
if(StringUtil.isEmpty(concept.getPreferredName()))
continue a;
for(ObjectClass oc : ocs) {
String[] codes = oc.getPreferredName().split(":");
for(String code : codes) {
if(code.equals(concept.getPreferredName())) {
found = true;
continue a;
}
}
}
for(Property prop : props) {
String[] codes = prop.getPreferredName().split(":");
for(String code : codes) {
if(code.equals(concept.getPreferredName())) {
found = true;
continue a;
}
}
}
if(!found) {
removeFromConcepts(concept);
}
}
}
private static void addNewConcepts(Concept[] newConcepts) {
ElementsLists elements = ElementsLists.getInstance();
List<Concept> concepts = (List<Concept>)elements.getElements(DomainObjectFactory.newConcept().getClass());
for(Concept concept : newConcepts) {
boolean found = false;
for(Concept con : concepts) {
if(con.getPreferredName().equals(concept.getPreferredName())) {
found = true;
break;
}
}
if(!found) {
elements.addElement(concept);
}
}
}
private static void removeFromConcepts(Concept concept) {
ElementsLists elements = ElementsLists.getInstance();
List<Concept> concepts = (List<Concept>)elements.getElements(DomainObjectFactory.newConcept().getClass());
for(int i = 0, n = concepts.size(); i<n; i++) {
if(concepts.get(i).getPreferredName().equals(concept.getPreferredName())) {
concepts.remove(i);
return;
}
}
concepts.remove(concept);
}
}
|
// FILE: c:/projects/jetel/org/jetel/data/StringDataField.java
package org.jetel.data;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
import org.jetel.exception.BadDataFormatException;
import org.jetel.metadata.DataFieldMetadata;
/**
* A class that represents String type data field.<br>
* It can hold String of arbitrary length, however due
* to use of short value as length specifier when serializing/
* deserializing value to/from ByteBuffer, the maximum length
* is limited to 32762 characters (Short.MAX_VALUE);
*
* @author D.Pavlis
* @since March 27, 2002
* @revision $Revision$
* @created January 26, 2003
* @see org.jetel.metadata.DataFieldMetadata
*/
public class StringDataField extends DataField implements CharSequence{
private StringBuffer value;
// Attributes
/**
* An attribute that represents ...
*
* @since
*/
private final static int INITIAL_STRING_BUFFER_CAPACITY = 32;
private final static int STRING_LENGTH_INDICATOR_SIZE = 2; // sizeof(short)
// Associations
// Operations
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata) {
super(_metadata);
if (_metadata.getSize() < 1) {
value = new StringBuffer(INITIAL_STRING_BUFFER_CAPACITY);
} else {
value = new StringBuffer(_metadata.getSize());
}
}
/**
* Constructor for the StringDataField object
*
* @param _metadata Description of Parameter
* @param _value Description of Parameter
* @since April 23, 2002
*/
public StringDataField(DataFieldMetadata _metadata, String _value) {
this(_metadata);
setValue(_value);
}
/**
* Private constructor used internally when clonning
*
* @param _metadata
* @param _value
*/
private StringDataField(DataFieldMetadata _metadata, StringBuffer _value){
super(_metadata);
this.value=new StringBuffer(_value.length());
this.value.append(_value);
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copy()
*/
public DataField duplicate(){
StringDataField newField=new StringDataField(metadata,value);
newField.setNull(this.isNull());
return newField;
}
/* (non-Javadoc)
* @see org.jetel.data.DataField#copyField(org.jetel.data.DataField)
*/
public void copyFrom(DataField fieldFrom){
if (fieldFrom instanceof StringDataField ){
if (!fieldFrom.isNull){
this.value.setLength(0);
this.value.append(((StringDataField)fieldFrom).value);
}
setNull(fieldFrom.isNull);
}else{
throw new ClassCastException("Incompatible DataField type "+DataFieldMetadata.type2Str(fieldFrom.getType()));
}
}
/**
* Sets the Value attribute of the StringDataField object
*
* @param value The new value value
* @exception BadDataFormatException Description of the Exception
* @since April 23, 2002
*/
public void setValue(Object value) throws BadDataFormatException {
this.value.setLength(0);
if (value instanceof StringDataField){
this.value.append(((StringDataField)value).value);
}else if (value instanceof String){
this.value.append((String)value);
}else if (value instanceof StringBuffer){
this.value.append((StringBuffer)value);
}else if (value instanceof char[]){
this.value.append((char[])value);
}else if (value instanceof CharSequence){
CharSequence str=(CharSequence)value;
for (int i=0;i<str.length();this.value.append(str.charAt(i++)));
}else if (value==null){
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
if (this.value.length()!=0){
setNull(false);
}else{
if (this.metadata.isNullable()) {
setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
}
}
/**
* Sets the value attribute of the StringDataField object
*
* @param seq The character sequence from which to set the value (either
* String, StringBuffer or Char Buffer)
* @since October 29, 2002
*/
public void setValue(CharSequence seq) {
value.setLength(0);
if (seq != null && seq.length() > 0) {
value.append(seq);
setNull(false);
} else {
if (this.metadata.isNullable()) {
super.setNull(true);
} else {
throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", null);
}
return;
}
}
/**
* Sets the Null value indicator
*
* @param isNull The new Null value
* @since October 29, 2002
*/
public void setNull(boolean isNull) {
super.setNull(isNull);
if (isNull) {
value.setLength(0);
}
}
/**
* Gets the Null value indicator
*
* @return The Null value
* @since October 29, 2002
*/
public boolean isNull() {
return super.isNull();
}
/**
* Gets the Value attribute of the StringDataField object
*
* @return The Value value
* @since April 23, 2002
*/
public Object getValue() {
return (isNull ? null : value);
}
/**
* Gets the value of the StringDataField object as charSequence
*
* @return The charSequence value
*/
public CharSequence getCharSequence() {
return value;
}
/**
* Gets the Type attribute of the StringDataField object
*
* @return The Type value
* @since April 23, 2002
*/
public char getType() {
return DataFieldMetadata.STRING_FIELD;
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param decoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException {
fromString(decoder.decode(dataBuffer).toString());
}
/**
* Description of the Method
*
* @param dataBuffer Description of Parameter
* @param encoder Description of Parameter
* @exception CharacterCodingException Description of Exception
* @since October 31, 2002
*/
public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) throws CharacterCodingException {
dataBuffer.put(encoder.encode(CharBuffer.wrap(toString())));
}
/**
* Description of the Method
*
* @return Description of the Returned Value
* @since April 23, 2002
*/
public String toString() {
return value.toString();
}
/**
* Description of the Method
*
* @param value Description of the Parameter
* @since April 23, 2002
*/
public void fromString(String value) {
setValue(value);
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void serialize(ByteBuffer buffer) {
int length = value.length();
int chars = length;
do {
buffer.put((byte)(0x80 | (byte) length));
length = length >> 7;
} while((length >> 7) > 0);
buffer.put((byte) length);
for(int counter = 0; counter < chars; counter++) {
buffer.putChar(value.charAt(counter));
}
}
/**
* Description of the Method
*
* @param buffer Description of Parameter
* @since April 23, 2002
*/
public void deserialize(ByteBuffer buffer) {
int length;
int size;
length = size = 0;
int count = 0;
do {
size = buffer.get();
length = length | ((size & 0x7F) << (7 * count++));
} while(size < 0);
// empty value - so we can store new string
value.setLength(0);
if (length == 0) {
setNull(true);
} else {
for(int counter = 0; counter < length; counter++){
value.append(buffer.getChar());
}
setNull(false);
}
}
/**
* Description of the Method
*
* @param obj Description of Parameter
* @return Description of the Returned Value
* @since April 23, 2002
*/
public boolean equals(Object obj) {
if (isNull || obj==null ) return false;
if (this==obj) return true;
CharSequence data;
if (obj instanceof StringDataField){
if (((StringDataField)obj).isNull()) return false;
data = (CharSequence)((StringDataField) obj).getValue();
}else if (obj instanceof CharSequence){
data = (CharSequence)obj;
}else{
return false;
}
if (value.length() != data.length()) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) != data.charAt(i)) {
return false;
}
}
return true;
}
/**
* Compares this object with the specified object for order.
*
* @param obj Any object implementing CharSequence interface
* @return Description -1;0;1 based on comparison result
*/
public int compareTo(Object obj) {
CharSequence strObj;
if (isNull) return -1;
if (obj instanceof StringDataField) {
if (((StringDataField) obj).isNull())
return 1;
strObj=((StringDataField) obj).value;
}else if (obj instanceof CharSequence) {
strObj = (CharSequence) obj;
}else {
throw new ClassCastException("Can't compare StringDataField to "
+ obj.getClass().getName());
}
int valueLenght = value.length();
int strObjLenght = strObj.length();
int compLength = (valueLenght < strObjLenght ? valueLenght
: strObjLenght);
for (int i = 0; i < compLength; i++) {
if (value.charAt(i) > strObj.charAt(i)) {
return 1;
} else if (value.charAt(i) < strObj.charAt(i)) {
return -1;
}
}
// strings seem to be the same (so far), decide according to the
// length
if (valueLenght == strObjLenght) {
return 0;
} else if (valueLenght > strObjLenght) {
return 1;
} else {
return -1;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int hash=5381;
for (int i=0;i<value.length();i++){
hash = ((hash << 5) + hash) + value.charAt(i);
}
return (hash & 0x7FFFFFFF);
}
/**
* Returns how many bytes will be occupied when this field with current
* value is serialized into ByteBuffer
*
* @return The size value
* @see org.jetel.data.DataField
*/
public int getSizeSerialized() {
// lentgh in characters multiplied of 2 (each char occupies 2 bytes in UNICODE) plus
// size of length indicator (basically int variable)
int length=value.length();
int count=0;
do{
count++;
length=length>>7;
}while(length>0x7F);
return value.length()*2+count;
}
/**
* Method which implements charAt method of CharSequence interface
*
* @param position
* @return
*/
public char charAt(int position){
return value.charAt(position);
}
/**Method which implements length method of CharSequence interfaceMethod which ...
*
* @return
*/
public int length(){
return value.length();
}
/**
* Method which implements subSequence method of CharSequence interface
*
* @param start
* @param end
* @return
*/
public CharSequence subSequence(int start, int end){
return value.subSequence(start,end);
}
}
/*
* end class StringDataField
*/
|
package net.hawkengine.model;
import net.hawkengine.model.enums.JobStatus;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Job extends DbEntry {
private String jobDefinitionId;
private String pipelineId;
private String stageId;
private int executionId;
private List<EnvironmentVariable> environmentVariables;
private Set<String> resources;
private List<Task> tasks;
private JobStatus status;
private LocalDateTime startTime;
private LocalDateTime endTime;
private Duration duration;
private String assignedAgentId;
public Job() {
this.startTime = LocalDateTime.now();
this.setEnvironmentVariables(new ArrayList<>());
this.setResources(new HashSet<>());
this.setTasks(new ArrayList<>());
}
public String getJobDefinitionId() {
return this.jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getPipelineId() {
return this.pipelineId;
}
public void setPipelineId(String pipelineId) {
this.pipelineId = pipelineId;
}
public String getStageId() {
return this.stageId;
}
public void setStageId(String stageId) {
this.stageId = stageId;
}
public int getExecutionId() {
return this.executionId;
}
public void setExecutionId(int executionId) {
this.executionId = executionId;
}
public List<EnvironmentVariable> getEnvironmentVariables() {
return this.environmentVariables;
}
public void setEnvironmentVariables(List<EnvironmentVariable> environmentVariables) {
this.environmentVariables = environmentVariables;
}
public Set<String> getResources() {
return resources;
}
public void setResources(Set<String> resources) {
this.resources = resources;
}
public List<Task> getTasks() {
return this.tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public JobStatus getStatus() {
return this.status;
}
public void setStatus(JobStatus status) {
this.status = status;
}
public LocalDateTime getStartTime() {
return this.startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return this.endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public Duration getDuration() {
return this.duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public String getAssignedAgentId() {
return assignedAgentId;
}
public void setAssignedAgentId(String assignedAgentId) {
this.assignedAgentId = assignedAgentId;
}
}
|
package com.psddev.dari.util;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.imgscalr.Scalr;
@RoutingFilter.Path(application = "", value = "/_image")
public class JavaImageServlet extends HttpServlet {
private static final List<String> BASIC_COMMANDS = Arrays.asList("circle", "grayscale", "invert", "sepia", "star", "starburst", "flipH", "flipV"); //Commands that don't require a value
private static final List<String> PNG_COMMANDS = Arrays.asList("circle", "star", "starburst"); //Commands that return a PNG regardless of input
private static final String QUALITY_OPTION = "quality";
protected static final String SERVLET_PATH = "/_image/";
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String[] urlAttributes = request.getServletPath().split("/http");
String basePath = urlAttributes[0];
String imageUrl = "";
if (urlAttributes.length == 1 && request.getParameter("url") != null) {
imageUrl = request.getParameter("url");
} else if (urlAttributes.length == 2) {
imageUrl = "http" + urlAttributes[1];
if (!imageUrl.contains("://") && imageUrl.contains(":/")) {
imageUrl = imageUrl.replace(":/", ":
}
}
if (!StringUtils.isBlank(imageUrl)) {
String imageType = "png";
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg")) {
imageType = "jpg";
} else if (imageUrl.endsWith(".gif")) {
imageType = "gif";
}
JavaImageEditor javaImageEditor = ObjectUtils.to(JavaImageEditor.class, ImageEditor.Static.getInstance(ImageEditor.JAVA_IMAGE_EDITOR_NAME));
String[] parameters = null;
if (!StringUtils.isBlank(javaImageEditor.getBaseUrl())) {
Integer parameterIndex = null;
parameterIndex = basePath.indexOf(SERVLET_PATH) + SERVLET_PATH.length();
parameters = basePath.substring(parameterIndex).split("/");
} else {
parameters = basePath.substring(SERVLET_PATH.length()).split("/");
}
//Verify key
if (!StringUtils.isBlank(javaImageEditor.getSharedSecret())) {
StringBuilder commandsBuilder = new StringBuilder();
for (int i = 2; i < parameters.length; i++) {
commandsBuilder.append(StringUtils.encodeUri(parameters[i]))
.append('/');
}
Long expireTs = (long) Integer.MAX_VALUE;
String signature = expireTs + javaImageEditor.getSharedSecret() + StringUtils.decodeUri("/" + commandsBuilder.toString()) + imageUrl;
String md5Hex = StringUtils.hex(StringUtils.md5(signature));
String requestSig = md5Hex.substring(0, 7);
if (!parameters[0].equals(requestSig) || !parameters[1].equals(expireTs.toString())) {
if (!StringUtils.isBlank(javaImageEditor.getErrorImage())) {
imageUrl = javaImageEditor.getErrorImage();
response.setStatus(500);
} else {
response.sendError(404);
return;
}
}
}
BufferedImage bufferedImage;
if ((imageUrl.endsWith("tif") || imageUrl.endsWith("tiff")) && ObjectUtils.getClassByName(JavaImageEditor.TIFF_READER_CLASS) != null) {
bufferedImage = JavaImageTiffReader.readTiff(imageUrl);
} else {
bufferedImage = ImageIO.read(new URL(imageUrl));
}
if (bufferedImage == null) {
throw new IOException(String.format("Unable to process image %s", imageUrl));
}
Scalr.Method quality = null;
for (int i = 0; i < parameters.length; i = i + 2) {
String command = parameters[i];
if (command.equals(QUALITY_OPTION)) {
String value = parameters[i + 1];
try {
quality = Scalr.Method.valueOf(Scalr.Method.class, value.toUpperCase());
} catch (IllegalArgumentException ex) {
quality = javaImageEditor.findQualityByInteger(Integer.parseInt(value));
}
}
}
for (int i = 0; i < parameters.length; i = i + 2) {
String command = parameters[i];
String value = i + 1 < parameters.length ? parameters[i + 1] : "";
if (command.equals(ImageEditor.RESIZE_COMMAND)) {
String option = null;
Integer width = null;
Integer height = null;
if (value.endsWith("!")) {
option = ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO;
} else if (value.endsWith(">")) {
option = ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER;
} else if (value.endsWith("<")) {
option = ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER;
} else if (value.endsWith("^")) {
option = ImageEditor.RESIZE_OPTION_FILL_AREA;
}
if (option != null) {
value = value.substring(0, value.length() - 1);
}
String[] wh = value.split("x");
width = parseInteger(wh[0]);
if (wh.length == 2) {
height = parseInteger(wh[1]);
}
bufferedImage = javaImageEditor.reSize(bufferedImage, width, height, option, quality);
} else if (command.equals(ImageEditor.CROP_COMMAND)) {
Integer x = 0;
Integer y = 0;
Integer width = null;
Integer height = null;
String[] size;
if (value.contains("+")) {
int delimiter = value.indexOf("+");
String[] xy = value.substring(delimiter + 1).split("\\+");
x = parseInteger(xy[0]) != null ? parseInteger(xy[0]) : 0;
y = parseInteger(xy[1]) != null ? parseInteger(xy[1]) : 0;
size = value.substring(0, delimiter).split("x");
} else {
size = value.split("x");
if (size.length > 3) {
x = parseInteger(size[0]) != null ? parseInteger(size[0]) : 0;
y = parseInteger(size[1]) != null ? parseInteger(size[1]) : 0;
size[0] = size[2];
size[1] = size[3];
}
}
width = parseInteger(size[0]);
if (size.length > 1) {
height = parseInteger(size[1]);
}
bufferedImage = javaImageEditor.crop(bufferedImage, x, y, width, height);
} else if (command.equals(JavaImageEditor.THUMBNAIL_COMMAND)) {
String option = null;
if (value.endsWith("!")) {
option = ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO;
} else if (value.endsWith(">")) {
option = ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER;
} else if (value.endsWith("<")) {
option = ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER;
} else if (value.endsWith("^")) {
option = ImageEditor.RESIZE_OPTION_FILL_AREA;
}
if (option != null) {
value = value.substring(0, value.length() - 1);
}
String[] wh = value.split("x");
if (ObjectUtils.isBlank(wh) || wh.length < 2) {
continue;
}
Integer width = ObjectUtils.to(Integer.class, wh[0]);
Integer height = ObjectUtils.to(Integer.class, wh[1]);
int resizeHeight = height;
int resizeWidth = width;
if (option == null || !option.equals(ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO)) {
resizeHeight = (int) ((double) bufferedImage.getHeight() / (double) bufferedImage.getWidth() * (double) width);
resizeWidth = (int) ((double) bufferedImage.getWidth() / (double) bufferedImage.getHeight() * (double) height);
}
bufferedImage = javaImageEditor.reSize(bufferedImage, resizeWidth, resizeHeight, option, quality);
if ((width != bufferedImage.getWidth() || height != bufferedImage.getHeight())) {
//Allows for crop when reSized size is slightly off
if (width > bufferedImage.getWidth() && (width - 2) <= bufferedImage.getWidth()) {
width = bufferedImage.getWidth();
}
if (height > bufferedImage.getHeight() && (height - 2) <= bufferedImage.getHeight()) {
height = bufferedImage.getHeight();
}
int x = 0;
int y = 0;
//center automatic crop
if (bufferedImage.getWidth() > width) {
x = (bufferedImage.getWidth() - width) / 2;
}
if (bufferedImage.getHeight() > height) {
y = (bufferedImage.getHeight() - height) / 2;
}
if (width <= bufferedImage.getWidth() && height <= bufferedImage.getHeight()) {
bufferedImage = javaImageEditor.crop(bufferedImage, x, y, width, height);
}
}
} else if (command.equals("grayscale")) {
bufferedImage = javaImageEditor.grayscale(bufferedImage);
} else if (command.equals("brightness")) {
String[] wh = value.split("x");
Double brightness = Double.valueOf(wh[0]);
Double contrast = wh.length > 1 ? Double.valueOf(wh[1]) : 0.0d;
if (Math.abs(brightness) < 0) {
brightness *= 100;
}
if (Math.abs(contrast) < 0) {
contrast *= 100;
}
bufferedImage = javaImageEditor.brightness(bufferedImage, brightness.intValue(), contrast.intValue());
} else if (command.equals("contrast")) {
Double contrast = Double.valueOf(value);
if (Math.abs(contrast) < 0) {
contrast *= 100;
}
bufferedImage = javaImageEditor.brightness(bufferedImage, 0, contrast.intValue());
} else if (command.equals("flipflop")) {
if (value.equals("horizontal")) {
bufferedImage = javaImageEditor.flipHorizontal(bufferedImage);
} else if (value.equals("vertical")) {
bufferedImage = javaImageEditor.flipVertical(bufferedImage);
}
} else if (command.equals("flipH")) {
bufferedImage = javaImageEditor.flipHorizontal(bufferedImage);
} else if (command.equals("flipV")) {
bufferedImage = javaImageEditor.flipVertical(bufferedImage);
} else if (command.equals("invert")) {
bufferedImage = javaImageEditor.invert(bufferedImage);
} else if (command.equals("rotate")) {
bufferedImage = javaImageEditor.rotate(bufferedImage, Integer.valueOf(parameters[i + 1]));
} else if (command.equals("sepia")) {
bufferedImage = javaImageEditor.sepia(bufferedImage);
} else if (command.equals("format")) {
imageType = value;
} else if (command.equals("circle")) {
bufferedImage = javaImageEditor.circle(bufferedImage);
} else if (command.equals("star")) {
bufferedImage = javaImageEditor.star(bufferedImage);
} else if (command.equals("starburst")) {
int size = 5;
int count = 30;
if (value.contains("x")) {
String[] sc = value.split("x");
if (!StringUtils.isBlank(sc[0])) {
size = Integer.parseInt(sc[0]);
}
if (sc.length > 1 && !StringUtils.isBlank(sc[1])) {
count = Integer.parseInt(sc[1]);
}
}
bufferedImage = javaImageEditor.starburst(bufferedImage, size, count);
}
if (PNG_COMMANDS.contains(command)) {
imageType = "png";
}
//shift offset if basic command has no value
if (BASIC_COMMANDS.contains(command) && !StringUtils.isBlank(value) && !value.toLowerCase().equals("true")) {
i = i - 1;
}
}
response.setContentType("image/" + imageType);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bufferedImage, imageType, out);
out.close();
} else {
throw new IOException("No source image provided");
}
}
private Integer parseInteger(String integer) {
if (StringUtils.isBlank(integer) || integer.matches("null")) {
return null;
} else {
return Integer.parseInt(integer);
}
}
}
|
package net.objectlab.kit.util;
/**
* A simple helper class that is NOT SCIENTIFIC but accurate enough
* for the mere mortals, to calculate the number of milliseconds to
* be used in say a timer but setup in a easier way...
* @author Benoit Xhenseval
*
*/
public class PeriodBuilder {
private static final long MS_IN_1_SEC = 1_000L;
private static final long S_IN_1_MIN = 60L;
private static final long M_IN_1_HOUR = 60L;
private static final long H_IN_1_DAY = 24L;
private static final long D_IN_1_WEEK = 7L;
private int weeks = 0;
private int days = 0;
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
private long milliseconds = 0;
public long calculateMilliseconds() {
return milliseconds
+ seconds * MS_IN_1_SEC
+ minutes * S_IN_1_MIN * MS_IN_1_SEC
+ hours * M_IN_1_HOUR * S_IN_1_MIN * MS_IN_1_SEC
+ days * H_IN_1_DAY * M_IN_1_HOUR * S_IN_1_MIN * MS_IN_1_SEC
+ weeks * D_IN_1_WEEK * H_IN_1_DAY * M_IN_1_HOUR * S_IN_1_MIN * MS_IN_1_SEC
;
}
public PeriodBuilder weeks(final int weeks) {
this.weeks = weeks;
return this;
}
public PeriodBuilder days(final int days) {
this.days = days;
return this;
}
public PeriodBuilder hours(final int hours) {
this.hours = hours;
return this;
}
public PeriodBuilder minutes(final int minutes) {
this.minutes = minutes;
return this;
}
public PeriodBuilder seconds(final int seconds) {
this.seconds = seconds;
return this;
}
public PeriodBuilder milliseconds(final int milliseconds) {
this.milliseconds = milliseconds;
return this;
}
}
|
package net.silentchaos512.gems.core.util;
import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.block.Block;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.api.IPlaceable;
import net.silentchaos512.gems.configuration.Config;
import net.silentchaos512.gems.core.registry.SRegistry;
import net.silentchaos512.gems.enchantment.EnchantmentAOE;
import net.silentchaos512.gems.enchantment.ModEnchantments;
import net.silentchaos512.gems.item.CraftingMaterial;
import net.silentchaos512.gems.item.Gem;
import net.silentchaos512.gems.item.ModItems;
import net.silentchaos512.gems.item.tool.GemAxe;
import net.silentchaos512.gems.item.tool.GemHoe;
import net.silentchaos512.gems.item.tool.GemPickaxe;
import net.silentchaos512.gems.item.tool.GemShovel;
import net.silentchaos512.gems.item.tool.GemSickle;
import net.silentchaos512.gems.item.tool.GemSword;
import net.silentchaos512.gems.lib.EnumGem;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.gems.material.ModMaterials;
/**
* The purpose of this class is to have shared code for tools in one place, to make updating/expanding the mod easier.
*/
public class ToolHelper {
/*
* NBT constants
*/
public static final String NBT_ROOT = SilentGems.MOD_ID + "Tool";
public static final String NBT_HEAD_L = "HeadL";
public static final String NBT_HEAD_M = "HeadM";
public static final String NBT_HEAD_R = "HeadR";
public static final String NBT_ROD = "Rod";
public static final String NBT_ROD_DECO = "RodDeco";
public static final String NBT_ROD_WOOL = "RodWool";
public static final String NBT_TIP = "Tip";
public static final String NBT_STATS_MINED = "BlocksMined";
public static final String NBT_STATS_HITS = "HitsLanded";
public static final String NBT_STATS_REDECORATED = "Redecorated";
/**
* Gets the "gem ID", or base material ID for a tool. Note that the regular and supercharged gems have the same ID
* (ie, regular ruby == supercharged ruby == 0). For gems, this number is in [0, 11]. Other IDs can be found in
* ModMaterials.
*
* @param tool
* @return The material ID, or -1 if it can't be determined.
*/
public static int getToolGemId(ItemStack tool) {
if (tool == null) {
return -1;
}
Item item = tool.getItem();
if (item instanceof GemSword) {
return ((GemSword) item).gemId;
} else if (item instanceof GemPickaxe) {
return ((GemPickaxe) item).gemId;
} else if (item instanceof GemShovel) {
return ((GemShovel) item).gemId;
} else if (item instanceof GemAxe) {
return ((GemAxe) item).gemId;
} else if (item instanceof GemHoe) {
return ((GemHoe) item).gemId;
} else if (item instanceof GemSickle) {
return ((GemSickle) item).gemId;
} else {
LogHelper.debug("Called ToolHelper.getToolGemId on a non-Gems tool!");
return -1;
}
}
/**
* Determines whether the tool is "supercharged" or not.
*
* @param tool
* @return True for supercharged tools (ornate rod) or false for regular tools (wooden rod).
*/
public static boolean getToolIsSupercharged(ItemStack tool) {
if (tool == null) {
return false;
}
Item item = tool.getItem();
if (item instanceof GemSword) {
return ((GemSword) item).supercharged;
} else if (item instanceof GemPickaxe) {
return ((GemPickaxe) item).supercharged;
} else if (item instanceof GemShovel) {
return ((GemShovel) item).supercharged;
} else if (item instanceof GemAxe) {
return ((GemAxe) item).supercharged;
} else if (item instanceof GemHoe) {
return ((GemHoe) item).supercharged;
} else if (item instanceof GemSickle) {
return ((GemSickle) item).supercharged;
} else {
LogHelper.debug("Called ToolHelper.getToolIsSupercharged on a non-Gems tool!");
return false;
}
}
/**
* Gets the material ID for the given material, or -1 if it's not a recognized tool material.
*
* @param material
* @return
*/
public static int getIdFromMaterial(ItemStack material) {
Item item = material.getItem();
if (item instanceof Gem) {
return material.getItemDamage() & 0xF;
} else if (CraftingMaterial.doesStackMatch(material, Names.CHAOS_ESSENCE_PLUS_2)) {
return ModMaterials.CHAOS_GEM_ID;
} else if (item == Items.flint) {
return ModMaterials.FLINT_GEM_ID;
} else if (item == Items.fish) {
return ModMaterials.FISH_GEM_ID;
} else {
return -1;
}
}
public static ItemStack getCraftingMaterial(int gemId, boolean supercharged) {
if (gemId < EnumGem.values().length) {
return new ItemStack(ModItems.gem, 1, gemId | (supercharged ? 0x10 : 0));
}
switch (gemId) {
case ModMaterials.CHAOS_GEM_ID:
return CraftingMaterial.getStack(Names.CHAOS_ESSENCE_PLUS_2);
case ModMaterials.FLINT_GEM_ID:
return new ItemStack(Items.flint);
case ModMaterials.FISH_GEM_ID:
return new ItemStack(Items.fish);
default:
LogHelper.warning("ToolHelper.getCraftingMaterial: Unknown gem ID: " + gemId);
return null;
}
}
// Tooltip helpers
public static void addInformation(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
boolean keyControl = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)
|| Keyboard.isKeyDown(Keyboard.KEY_RCONTROL);
boolean keyShift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)
|| Keyboard.isKeyDown(Keyboard.KEY_RSHIFT);
String line;
// Old NBT warning.
if (hasOldNBT(tool)) {
addInformationOldNBT(tool, player, list, advanced);
return;
}
// Tool Upgrades
addInformationUpgrades(tool, player, list, advanced);
// Statistics
if (keyControl) {
addInformationStatistics(tool, player, list, advanced);
} else {
line = LocalizationHelper.getMiscText("PressCtrl");
list.add(EnumChatFormatting.YELLOW + line);
}
// Decoration debug
if (keyControl && keyShift) {
addInformationDecoDebug(tool, player, list, advanced);
}
// Chaos tools
int gemId = getToolGemId(tool);
if (gemId == ModMaterials.CHAOS_GEM_ID) {
// No flying penalty
line = LocalizationHelper.getMiscText("Tool.NoFlyingPenalty");
list.add(EnumChatFormatting.AQUA + line);
}
}
private static void addInformationUpgrades(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line;
// Tipped upgrades
int tip = getToolHeadTip(tool);
if (tip == 1) {
line = LocalizationHelper.getMiscText("Tool.IronTipped");
list.add(EnumChatFormatting.WHITE + line);
} else if (tip == 2) {
line = LocalizationHelper.getMiscText("Tool.DiamondTipped");
list.add(EnumChatFormatting.AQUA + line);
}
}
private static void addInformationStatistics(ItemStack tool, EntityPlayer player, List list,
boolean advanced) {
String line;
int amount;
String separator = EnumChatFormatting.DARK_GRAY
+ LocalizationHelper.getMiscText("Tool.Stats.Separator");
// Header
line = LocalizationHelper.getMiscText("Tool.Stats.Header");
list.add(EnumChatFormatting.YELLOW + line);
list.add(separator);
// Blocks mined
amount = getStatBlocksMined(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Mined");
line = String.format(line, amount);
list.add(line);
// Hits landed
amount = getStatHitsLanded(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Hits");
line = String.format(line, amount);
list.add(line);
// Redecorated count
amount = getStatRedecorated(tool);
line = LocalizationHelper.getMiscText("Tool.Stats.Redecorated");
line = String.format(line, amount);
list.add(line);
list.add(separator);
}
private static void addInformationDecoDebug(ItemStack tool, EntityPlayer player, List list, boolean advanced) {
String line = "Deco:";
line += " HL:" + getToolHeadLeft(tool);
line += " HM:" + getToolHeadMiddle(tool);
line += " HR:" + getToolHeadRight(tool);
line += " RD:" + getToolRodDeco(tool);
line += " RW:" + getToolRodWool(tool);
line += " R:" + getToolRod(tool);
line += " T:" + getToolHeadTip(tool);
list.add(EnumChatFormatting.DARK_GRAY + line);
}
private static void addInformationOldNBT(ItemStack tool, EntityPlayer player, List list, boolean advanced) {
String line;
line = LocalizationHelper.getMiscText("Tool.OldNBT1");
list.add(EnumChatFormatting.DARK_BLUE + line);
line = LocalizationHelper.getMiscText("Tool.OldNBT2");
list.add(EnumChatFormatting.DARK_BLUE + line);
}
// Mining, using, repairing, etc
/**
* Determines if a tool can be repaired with the given material in an anvil. It's not the desired why to repair tools,
* but it should be an option.
*
* @return True if the material can repair the tool, false otherwise.
*/
public static boolean getIsRepairable(ItemStack tool, ItemStack material) {
int baseMaterial = getToolGemId(tool);
boolean supercharged = getToolIsSupercharged(tool);
ItemStack correctMaterial = null;
if (baseMaterial < EnumGem.values().length) {
// Gem tools.
correctMaterial = new ItemStack(ModItems.gem, 1, baseMaterial | (supercharged ? 0x10 : 0));
} else if (baseMaterial == ModMaterials.FLINT_GEM_ID) {
// Flint tools.
correctMaterial = new ItemStack(Items.flint);
} else if (baseMaterial == ModMaterials.FISH_GEM_ID) {
// Fish tools.
correctMaterial = new ItemStack(Items.fish);
}
return correctMaterial != null && correctMaterial.getItem() == material.getItem()
&& correctMaterial.getItemDamage() == material.getItemDamage();
}
/**
* Gets the additional amount to add to the tool's max damage in getMaxDamage(ItemStack).
*
* @return The amount to add to max damage.
*/
public static int getDurabilityBoost(ItemStack tool) {
int tip = getToolHeadTip(tool);
switch (tip) {
case 2:
return Config.DURABILITY_BOOST_DIAMOND_TIP;
case 1:
return Config.DURABILITY_BOOST_IRON_TIP;
default:
return 0;
}
}
/**
* Adjusts the mining level of the tool if it has a tip upgrade.
*
* @param tool
* The tool.
* @param baseLevel
* The value returned by ItemTool.getHarvestLevel. May be -1 if the toolclasses is incorrect for the block
* being mined.
* @return The highest possible mining level, given the upgrades. Returns baseLevel if baseLevel is less than zero.
*/
public static int getAdjustedMiningLevel(ItemStack tool, int baseLevel) {
if (baseLevel < 0) {
return baseLevel;
}
int tip = getToolHeadTip(tool);
switch (tip) {
case 2:
return Math.max(baseLevel, Config.MINING_LEVEL_DIAMOND_TIP);
case 1:
return Math.max(baseLevel, Config.MINING_LEVEL_IRON_TIP);
default:
return baseLevel;
}
}
/**
* This controls the block placing ability of mining tools.
*/
public static boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y,
int z, int side, float hitX, float hitY, float hitZ) {
boolean used = false;
int toolSlot = player.inventory.currentItem;
int itemSlot = toolSlot + 1;
ItemStack nextStack = null;
if (toolSlot < 8) {
nextStack = player.inventory.getStackInSlot(itemSlot);
if (nextStack != null) {
Item item = nextStack.getItem();
if (item instanceof ItemBlock || item instanceof IPlaceable) {
ForgeDirection d = ForgeDirection.VALID_DIRECTIONS[side];
int px = x + d.offsetX;
int py = y + d.offsetY;
int pz = z + d.offsetZ;
int playerX = (int) Math.floor(player.posX);
int playerY = (int) Math.floor(player.posY);
int playerZ = (int) Math.floor(player.posZ);
// Check for overlap with player, except for torches and torch bandolier
if (Item.getIdFromItem(item) != Block.getIdFromBlock(Blocks.torch)
&& item != SRegistry.getItem(Names.TORCH_BANDOLIER) && px == playerX
&& (py == playerY || py == playerY + 1 || py == playerY - 1) && pz == playerZ) {
return false;
}
used = item.onItemUse(nextStack, player, world, x, y, z, side, hitX, hitY, hitZ);
if (nextStack.stackSize < 1) {
nextStack = null;
player.inventory.setInventorySlotContents(itemSlot, null);
}
}
}
}
return used;
}
/**
* Called by mining tools if block breaking isn't canceled.
*
* @return False in all cases, because this method is only called when Item.onBlockStartBreak returns false.
*/
public static boolean onBlockStartBreak(ItemStack stack, int x, int y, int z,
EntityPlayer player) {
// Number of blocks broken.
int amount = 1;
// Try to activate Area Miner enchantment.
if (EnchantmentHelper.getEnchantmentLevel(ModEnchantments.AOE_ID, stack) > 0) {
amount += EnchantmentAOE.tryActivate(stack, x, y, z, player);
}
// Increase number of blocks mined statistic.
ToolHelper.incrementStatBlocksMined(stack, amount);
return false;
}
public static void hitEntity(ItemStack tool) {
ToolHelper.incrementStatHitsLanded(tool, 1);
}
// NBT helper methods
private static int getTagByte(String name, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Get the requested value.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
if (!tags.hasKey(name)) {
return -1;
}
return tags.getByte(name);
}
private static void setTagByte(String name, int value, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Set the tag.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
tags.setByte(name, (byte) value);
}
private static int getTagInt(String name, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Get the requested value.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
if (!tags.hasKey(name)) {
return 0; // NOTE: This is 0, where the byte version is -1!
}
return tags.getInteger(name);
}
private static void setTagInt(String name, int value, ItemStack tool) {
// Create tag compound, if needed.
if (tool.stackTagCompound == null) {
tool.setTagCompound(new NBTTagCompound());
}
// Create root tag, if needed.
if (!tool.stackTagCompound.hasKey(NBT_ROOT)) {
tool.stackTagCompound.setTag(NBT_ROOT, new NBTTagCompound());
}
// Set the tag.
NBTTagCompound tags = (NBTTagCompound) tool.stackTagCompound.getTag(NBT_ROOT);
tags.setInteger(name, value);
}
// Tool design NBT
public static int getToolHeadLeft(ItemStack tool) {
return getTagByte(NBT_HEAD_L, tool);
}
public static void setToolHeadLeft(ItemStack tool, int id) {
setTagByte(NBT_HEAD_L, id, tool);
}
public static int getToolHeadMiddle(ItemStack tool) {
return getTagByte(NBT_HEAD_M, tool);
}
public static void setToolHeadMiddle(ItemStack tool, int id) {
setTagByte(NBT_HEAD_M, id, tool);
}
public static int getToolHeadRight(ItemStack tool) {
return getTagByte(NBT_HEAD_R, tool);
}
public static void setToolHeadRight(ItemStack tool, int id) {
setTagByte(NBT_HEAD_R, id, tool);
}
public static int getToolRodDeco(ItemStack tool) {
return getTagByte(NBT_ROD_DECO, tool);
}
public static void setToolRodDeco(ItemStack tool, int id) {
setTagByte(NBT_ROD_DECO, id, tool);
}
public static int getToolRodWool(ItemStack tool) {
return getTagByte(NBT_ROD_WOOL, tool);
}
public static void setToolRodWool(ItemStack tool, int id) {
setTagByte(NBT_ROD_WOOL, id, tool);
}
public static int getToolRod(ItemStack tool) {
return getTagByte(NBT_ROD, tool);
}
public static void setToolRod(ItemStack tool, int id) {
setTagByte(NBT_ROD, id, tool);
}
public static int getToolHeadTip(ItemStack tool) {
return getTagByte(NBT_TIP, tool);
}
public static void setToolHeadTip(ItemStack tool, int id) {
setTagByte(NBT_TIP, id, tool);
}
// Statistics NBT
public static int getStatBlocksMined(ItemStack tool) {
return getTagInt(NBT_STATS_MINED, tool);
}
public static void incrementStatBlocksMined(ItemStack tool, int amount) {
setTagInt(NBT_STATS_MINED, getStatBlocksMined(tool) + amount, tool);
}
public static int getStatHitsLanded(ItemStack tool) {
return getTagInt(NBT_STATS_HITS, tool);
}
public static void incrementStatHitsLanded(ItemStack tool, int amount) {
setTagInt(NBT_STATS_HITS, getStatHitsLanded(tool) + amount, tool);
}
public static int getStatRedecorated(ItemStack tool) {
return getTagInt(NBT_STATS_REDECORATED, tool);
}
public static void incrementStatRedecorated(ItemStack tool, int amount) {
setTagInt(NBT_STATS_REDECORATED, getStatRedecorated(tool) + amount, tool);
}
// NBT converter methods
private static int getOldTag(ItemStack tool, String name) {
if (!tool.stackTagCompound.hasKey(name)) {
return -1;
}
return tool.stackTagCompound.getByte(name);
}
private static void removeOldTag(ItemStack tool, String name) {
tool.stackTagCompound.removeTag(name);
}
public static boolean hasOldNBT(ItemStack tool) {
return convertToNewNBT(tool.copy());
}
public static boolean convertToNewNBT(ItemStack tool) {
if (tool == null || tool.stackTagCompound == null || !InventoryHelper.isGemTool(tool)) {
return false;
}
boolean updated = false;
int headL = getOldTag(tool, "HeadL");
int headM = getOldTag(tool, "HeadM");
int headR = getOldTag(tool, "HeadR");
int rodDeco = getOldTag(tool, "Deco");
int rodWool = getOldTag(tool, "Rod");
int rod = getOldTag(tool, "Handle");
int tip = getOldTag(tool, "Tip");
if (headL > -1) {
setToolHeadLeft(tool, headL);
removeOldTag(tool, "HeadL");
updated = true;
}
if (headM > -1) {
setToolHeadMiddle(tool, headM);
removeOldTag(tool, "HeadM");
updated = true;
}
if (headR > -1) {
setToolHeadRight(tool, headR);
removeOldTag(tool, "HeadR");
updated = true;
}
if (rodDeco > -1) {
setToolRodDeco(tool, rodDeco);
removeOldTag(tool, "Deco");
updated = true;
}
if (rodWool > -1) {
setToolRodWool(tool, rodWool);
removeOldTag(tool, "Rod");
updated = true;
}
if (rod > -1) {
setToolRod(tool, rod);
removeOldTag(tool, "Handle");
updated = true;
}
if (tip > -1) {
setToolHeadTip(tool, tip);
removeOldTag(tool, "Tip");
updated = true;
}
return updated;
}
}
|
package cn.com.restarter.util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileModify {
public String read(String filePath) {
BufferedReader br = null;
String line = null;
StringBuffer buf = new StringBuffer();
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
if (line.startsWith("if \"%doExitFlag%\"")) {
line=line.replace("true","false");
}
buf.append(line);
buf.append(System.getProperty("line.separator"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
}
}
}
return buf.toString();
}
public void write(String filePath, String content) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filePath));
bw.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
bw = null;
}
}
}
}
public static void modify(String filePath) {
FileModify obj = new FileModify();
obj.write(filePath, obj.read(filePath));
}
public static List<String> readFileByLines(String fileName) {
List<String> lineStr = new ArrayList<String>();
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
String[] strarray = tempString.split("=");
lineStr.add(strarray[1].replace("\\","
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return lineStr;
}
}
|
package nl.mpi.yaas.common.db;
public class TestData {
static final public String[] testData = new String[]{
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA2-6</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA2-6</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9C-7</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA2-6</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9C-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA5-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA2-6</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9C-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA5-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9F-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"CS_ChinTurk1\" ID=\"hdl:1839/00-0000-0000-0001-2AB1-4\">"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"Chinese signer (F, age 32, Ph.D. student in USA) and Turkish signer (M, age 22) first contact. Speakers were given suggested topics to discuss of the general introductory variety.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Asia\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"CS_ChinTurk1\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"References.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.References.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"Contact Signing Chinese-Turkish 1st contact\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-02-02\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"village sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2FA3-5\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA4-B</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"village sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"village sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Bali\" ID=\"hdl:1839/00-0000-0000-0001-2FA4-B\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0008-CAD1-B</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Bali\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Kata Kolok\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Bali\" ID=\"hdl:1839/00-0000-0000-0001-2FA4-B\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0008-CAD1-B</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0008-C805-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Bali\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Kata Kolok\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Vos\" ID=\"hdl:1839/00-0000-0000-0008-CAD1-B\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Vos\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Vos\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Marsaja\" ID=\"hdl:1839/00-0000-0000-0008-C805-D\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Marsaja\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Marsaja\" ID=\"hdl:1839/00-0000-0000-0008-C805-D\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Marsaja\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2ED0-D</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2ED0-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C7B-0</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2ED0-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C7B-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2D8B-3</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Germany\" ID=\"hdl:1839/00-0000-0000-0001-2C2D-F\">"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73D-9</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Germany\" ID=\"hdl:1839/00-0000-0000-0001-2C2D-F\">"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73D-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2E-1</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Germany Catalogue\" ID=\"hdl:1839/00-0000-0000-000D-B73D-9\">"
+ "<FieldGroup Label=\"Keys.Key.CorpusTreePath\">"
+ "<FieldData KeyName=\"CorpusTreePath\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(4)\" FieldValue=\"MPI corpora: Sign Language Typology: urban sign languages: Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Quality\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Quality\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Text\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Text\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Address\" FieldValue=\"Centre for Sign Linguistics and Deaf Studies\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Date\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"ContactPerson\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.ContactPerson\" FieldValue=\"Gladys Tang\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Pricing\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Pricing\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Image\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Image\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Name\" FieldValue=\"Germany Catalogue\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Title\" FieldValue=\"Germany\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Publisher\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Publisher\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Email\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Email\" FieldValue=\"gtang@arts.cuhk.edu.hk\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Video\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Video\" FieldValue=\"video/x-mpeg1, video/x-mpeg2\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"ContentType\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.ContentType\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Name\" FieldValue=\"SL TYpology -urban - DGS\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"DistributionForm\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.DistributionForm\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Applications\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Applications\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Audio\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Audio\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Date\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Author\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Author\" FieldValue=\"Gladys Tang\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Name\" FieldValue=\"Gladys Tang\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusBrowserLink\">"
+ "<FieldData KeyName=\"CorpusBrowserLink\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(2)\" FieldValue=\"http://corpus1.mpi.nl/ds/imdi_browser/?openpath=MPI76845%23\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Owner\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Owner\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Publisher\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Publisher\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Id\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Id\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Size\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Size\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Contact\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Contact\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Availability\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Availability\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Organisation\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Organisation\" FieldValue=\"The Chinese University of Hong Kong\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusImdiLink\">"
+ "<FieldData KeyName=\"CorpusImdiLink\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key\" FieldValue=\"http://corpus1.mpi.nl/qfs1/media-archive/silang_data/Corpusstructure/1-02-02.imdi\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"SmallestAnnotationUnit\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.SmallestAnnotationUnit\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusArchiveHandle\">"
+ "<FieldData KeyName=\"CorpusArchiveHandle\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(3)\" FieldValue=\"hdl:1839/00-0000-0000-0001-2C2D-F\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Id\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Id\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"contact signing\" ID=\"hdl:1839/00-0000-0000-0001-2A9B-9\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA2-6</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B73A-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9C-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB1-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9F-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAE-4</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA5-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AAB-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AA8-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"contact signing\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"1_contact_S-K\" ID=\"hdl:1839/00-0000-0000-0001-2AA2-6\">"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Date\" FieldValue=\"2004-06-23\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Name\" FieldValue=\"1_contact_S-K\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Continent\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Continent\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Actors.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Actors.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Country\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Country\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Title\" FieldValue=\"First contact S-K\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Location.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.MDGroup.Location.Address\" FieldValue=\"Unspecified\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Session.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2ED0-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2D8B-3</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C7B-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Jordan\" ID=\"hdl:1839/00-0000-0000-0004-D511-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D512-F</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B745-4</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Jordan\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Jordan\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Texts\" ID=\"hdl:1839/00-0000-0000-0004-D512-F\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Texts\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Texts\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Sign Language Typology\" ID=\"hdl:1839/00-0000-0000-0001-2A9A-4\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB4-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FA3-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2FEE-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2A9B-9</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Sign Language Typology\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"urban sign languages\" ID=\"hdl:1839/00-0000-0000-0001-2AB4-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E76-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2CB9-5</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2AB5-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0004-D511-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C32-7</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C7B-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2ED0-D</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2DA9-A</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2D8B-3</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2C2D-F</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"urban sign languages\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Brazil\" ID=\"hdl:1839/00-0000-0000-0001-2E76-0\">"
+ "<ChildIds>hdl:1839/00-0000-0000-000D-B743-0</ChildIds>"
+ "<ChildIds>hdl:1839/00-0000-0000-0001-2E77-E</ChildIds>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Brazil Catalogue\" ID=\"hdl:1839/00-0000-0000-000D-B743-0\">"
+ "<FieldGroup Label=\"Size\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Size\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusArchiveHandle\">"
+ "<FieldData KeyName=\"CorpusArchiveHandle\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(3)\" FieldValue=\"hdl:1839/00-0000-0000-0001-2E76-0\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Quality\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Quality\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Id\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Id\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Applications\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Applications\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"SmallestAnnotationUnit\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.SmallestAnnotationUnit\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Audio\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Audio\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Name\" FieldValue=\"Brazil Catalogue\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Title\" FieldValue=\"Sign Language Typology - urban sign languages - Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Owner\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Owner\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Publisher\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Publisher\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"DistributionForm\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.DistributionForm\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Email\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Email\" FieldValue=\"marmora@letras.ufrj.br\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"DocumentLanguages.Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.DocumentLanguages.Description\" FieldValue=\"The language ids listed below are set as description languages in subbranches and sessions of this corpus.\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Title\" FieldValue=\"Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"ContentType\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.ContentType\" FieldValue=\"Discourse\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Availability\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Availability\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Publisher\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Publisher\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusImdiLink\">"
+ "<FieldData KeyName=\"CorpusImdiLink\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key\" FieldValue=\"http://corpus1.mpi.nl/qfs1/media-archive/silang_data/Corpusstructure/1-02-09.imdi\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Id\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Id\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Organisation\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Organisation\" FieldValue=\"Max Planck Institute for Psycholinguistics\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Name\" FieldValue=\"Sergio Marmora de Andrade\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Text\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Text\" FieldValue=\"x-eaf+xml\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusTreePath\">"
+ "<FieldData KeyName=\"CorpusTreePath\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(4)\" FieldValue=\"MPI corpora: Sign Language Typology: urban sign languages: Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Author\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Author\" FieldValue=\"Sergio Marmora de Andrade\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Name\" FieldValue=\"SLTypology-urban-Brazil\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Date\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Video\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Video\" FieldValue=\"video/x-mpeg1, video/x-mpeg2\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Format.Image\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Format.Image\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Pricing\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Pricing\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Project.Contact.Address\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Project.Contact.Address\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Date\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Date\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Access.Contact\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.Access.Contact\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Keys.Key.CorpusBrowserLink\">"
+ "<FieldData KeyName=\"CorpusBrowserLink\" Path=\".METATRANSCRIPT.Catalogue.Keys.Key(2)\" FieldValue=\"http://corpus1.mpi.nl/ds/imdi_browser/?openpath=MPI77430%23\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"ContactPerson\">"
+ "<FieldData Path=\".METATRANSCRIPT.Catalogue.ContactPerson\" FieldValue=\"Sergio Marmora de Andrade\"/>"
+ "</FieldGroup>"
+ "</DataNode>",
"<DataNode Label=\"Texts\" ID=\"hdl:1839/00-0000-0000-0001-2E77-E\">"
+ "<FieldGroup Label=\"Name\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Name\" FieldValue=\"Texts\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Title\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Title\" FieldValue=\"Texts\"/>"
+ "</FieldGroup>"
+ "<FieldGroup Label=\"Description\">"
+ "<FieldData Path=\".METATRANSCRIPT.Corpus.Description\" FieldValue=\"\"/>"
+ "</FieldGroup>"
+ "</DataNode>"};
}
|
package com.rexsl.test;
import com.rexsl.test.client.BodyExtender;
import com.rexsl.test.client.Extender;
import com.rexsl.test.client.HeaderExtender;
import com.rexsl.test.client.Headers;
import com.ymock.util.Logger;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Test HTTP client.
*
* @author Yegor Bugayenko (yegor@rexsl.com)
* @version $Id$
* @checkstyle ClassDataAbstractionCoupling (200 lines)
*/
public final class TestClient {
/**
* Document root.
*/
private final URI home;
/**
* List of HTTP request/response extenders.
*/
private final List<Extender> extenders = new ArrayList<Extender>();
/**
* HTTP response.
*/
private HttpResponse response;
/**
* Returned body.
*/
private String body;
/**
* Public ctor.
* @param uri Home of the server
*/
public TestClient(final URI uri) {
this.home = uri;
this.response = null;
}
/**
* Set request header.
* @param name Header name
* @param value Value of the header to set
* @return This object
*/
public TestClient header(final String name, final String value) {
Logger.debug(this, "#header(%s, %s)", name, value);
this.extenders.add(new HeaderExtender(name, value));
return this;
}
/**
* Set body as a string.
* @param text The body to use for requests
* @return This object
*/
public TestClient body(final String text) {
Logger.debug(this, "#body(%s)", text);
this.extenders.add(new BodyExtender(text));
return this;
}
/**
* Execute GET request.
* @param path The URL
* @return This object
* @throws Exception If something goes wrong
*/
public TestClient get(final String path) throws Exception {
final long start = System.nanoTime();
this.response = this.execute(new HttpGet(this.uri(path)));
Logger.info(
this,
"#get(%s): completed in %.3fms [%s]",
path,
// @checkstyle MagicNumber (1 line)
(double) (System.nanoTime() - start) / (1000L * 1000),
this.response.getStatusLine()
);
return this;
}
/**
* Execute POST request.
* @param path The URL
* @return This object
* @throws Exception If something goes wrong
*/
public TestClient post(final String path) throws Exception {
final long start = System.nanoTime();
this.response = this.execute(new HttpPost(this.uri(path)));
Logger.info(
this,
"#post(%s): completed in %.3fms [%s]",
path,
// @checkstyle MagicNumber (1 line)
(double) (System.nanoTime() - start) / (1000L * 1000),
this.response.getStatusLine()
);
return this;
}
/**
* Execute PUT request.
* @param path The URL
* @return This object
* @throws Exception If something goes wrong
*/
public TestClient put(final String path) throws Exception {
final long start = System.nanoTime();
this.response = this.execute(new HttpPut(this.uri(path)));
Logger.info(
this,
"#put(%s): completed in %.3fms [%s]",
path,
// @checkstyle MagicNumber (1 line)
(double) (System.nanoTime() - start) / (1000L * 1000),
this.response.getStatusLine()
);
return this;
}
/**
* Get body as a string.
* @return The body
* @throws java.io.IOException If some IO problem inside
*/
public String getBody() throws java.io.IOException {
if (this.body == null) {
final HttpEntity entity = this.response.getEntity();
if (entity != null) {
this.body = IOUtils.toString(entity.getContent());
}
}
return this.body;
}
/**
* Get status of the response as a number.
* @return The status
*/
public Integer getStatus() {
return this.response.getStatusLine().getStatusCode();
}
/**
* Get status line of the response.
* @return The status line
*/
public String getStatusLine() {
return String.format(
"%s %s %s",
this.response.getStatusLine().getProtocolVersion(),
this.response.getStatusLine().getReasonPhrase(),
this.response.getStatusLine().getStatusCode()
);
}
/**
* Get a collection of all headers.
* @return The headers
*/
public Headers getHeaders() {
return new Headers(this.response.getAllHeaders());
}
/**
* Build URI to request.
* @param path The path to request
* @return The URI
* @throws java.net.URISyntaxException If there is some problem
*/
private URI uri(final String path) throws java.net.URISyntaxException {
return new URI(
String.format(
"%s://%s:%d%s",
this.home.getScheme(),
this.home.getHost(),
this.home.getPort(),
path
)
);
}
/**
* Execute request and return response.
* @param req The request
* @return The response
* @throws java.io.IOException If some IO problem
*/
private HttpResponse execute(final HttpRequest req)
throws java.io.IOException {
this.body = null;
for (Extender extender : this.extenders) {
extender.extend(req);
}
final HttpClient client = new DefaultHttpClient();
return client.execute((HttpUriRequest) req);
}
}
|
package endtoend.tests;
import static org.junit.Assert.assertEquals;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.api.client.filter.LoggingFilter;
/**
* This is used to perform operation on the VISION Cloud. Mainly, it can create containers and objects. Basic authentication is
* required.
*/
public class VisionHTTPClient {
private final Client client = new Client();
private final String hostURL;
private final String pass;
private final String tenant;
private final String user;
/**
* Constructor.
*
* @param hostURL
* @param tenant
* @param user
* @param pass
*/
public VisionHTTPClient(final String hostURL, final String tenant, final String user, final String pass) {
this.hostURL = hostURL;
this.tenant = tenant;
this.user = user;
this.pass = pass;
setupClient();
}
/**
* @param cont
*/
public void createContainer(final String cont) {
final ClientResponse res = containers().path(tenant).path(cont).put(ClientResponse.class);
assertEquals(ClientResponse.Status.CREATED, res.getClientResponseStatus());
}
/**
* @param cont
*/
public void deleteContainer(final String cont) {
final ClientResponse res = containers().path(tenant).path(cont).delete(ClientResponse.class);
assertEquals(ClientResponse.Status.OK, res.getClientResponseStatus());
}
/**
* @param container
* @param object
*/
public void deleteObject(final String container, final String object) {
final ClientResponse res = forObject(container, object).delete(ClientResponse.class);
assertEquals(ClientResponse.Status.NO_CONTENT, res.getClientResponseStatus());
}
/**
* @param container
* @param object
*/
public void getObject(final String container, final String object) {
final ClientResponse res = forObject(container, object).get(ClientResponse.class);
assertEquals(ClientResponse.Status.OK, res.getClientResponseStatus());
}
/**
* @param container
* @param object
* @param payload
*/
public void putObject(final String container, final String object, final String payload) {
final ClientResponse res = forObject(container, object).entity(payload).put(ClientResponse.class);
assertEquals(ClientResponse.Status.CREATED, res.getClientResponseStatus());
}
/**
* @return a resource pointing to the entry point of <code>Containers</code>.
*/
protected WebResource containers() {
return client.resource("http://" + hostURL + ":8080").path("containers");
}
/**
* @return a resource pointing to the entry point of <code>Object Service</code>.
*/
protected WebResource obs() {
return client.resource("http://" + hostURL).path("vision-cloud").path("object-service");
}
/**
* @param container
* @param object
* @return a {@link Builder}.
*/
private Builder forObject(final String container, final String object) {
return obs().path(tenant).path(container).path(object).type("application/cdmi-object").accept("application/cdmi-object")
.header("X-CDMI-Specification-Version", "1.0");
}
private void setupClient() {
client.setConnectTimeout(3);
client.setReadTimeout(3);
client.addFilter(new HTTPBasicAuthFilter(user + "@" + tenant, pass));
client.addFilter(new LoggingFilter(System.err));
client.addFilter(new ClientFilter() {
@Override
public ClientResponse handle(final ClientRequest request) throws ClientHandlerException {
final long start = System.currentTimeMillis();
final ClientResponse response = getNext().handle(request);
final long end = System.currentTimeMillis();
System.err.println("req/resp took: " + (end - start) + " ms");
return response;
}
});
}
}
|
// ImageReader.java
package loci.formats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.in.MetadataLevel;
import loci.formats.in.MetadataOptions;
import loci.formats.meta.MetadataStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageReader implements IFormatReader {
// -- Constants --
private static final Logger LOGGER =
LoggerFactory.getLogger(ImageReader.class);
// -- Static fields --
/** Default list of reader classes, for use with noargs constructor. */
private static ClassList<IFormatReader> defaultClasses;
// -- Static utility methods --
public static ClassList<IFormatReader> getDefaultReaderClasses() {
if (defaultClasses == null) {
// load built-in reader classes from readers.txt file
try {
defaultClasses =
new ClassList<IFormatReader>("readers.txt", IFormatReader.class);
}
catch (IOException exc) {
defaultClasses = new ClassList<IFormatReader>(IFormatReader.class);
LOGGER.info("Could not parse class list; using default classes", exc);
}
}
return defaultClasses;
}
// -- Fields --
/** List of supported file format readers. */
private IFormatReader[] readers;
/**
* Valid suffixes for this file format.
* Populated the first time getSuffixes() is called.
*/
private String[] suffixes;
/** Name of current file. */
private String currentId;
/** Current form index. */
private int current;
// -- Constructors --
/**
* Constructs a new ImageReader with the default
* list of reader classes from readers.txt.
*/
public ImageReader() {
this(getDefaultReaderClasses());
}
/** Constructs a new ImageReader from the given list of reader classes. */
public ImageReader(ClassList<IFormatReader> classList) {
// add readers to the list
List<IFormatReader> list = new ArrayList<IFormatReader>();
Class<? extends IFormatReader>[] c = classList.getClasses();
for (int i=0; i<c.length; i++) {
IFormatReader reader = null;
try {
reader = c[i].newInstance();
}
catch (IllegalAccessException exc) { }
catch (InstantiationException exc) { }
if (reader == null) {
LOGGER.error("{} cannot be instantiated.", c[i].getName());
continue;
}
list.add(reader);
}
readers = new IFormatReader[list.size()];
list.toArray(readers);
}
// -- ImageReader API methods --
/** Gets a string describing the file format for the given file. */
public String getFormat(String id) throws FormatException, IOException {
return getReader(id).getFormat();
}
/** Gets the reader used to open the given file. */
public IFormatReader getReader(String id)
throws FormatException, IOException
{
// HACK: skip file existence check for fake files
boolean fake = id != null && id.toLowerCase().endsWith(".fake");
// NB: Check that we can generate a valid handle for the ID;
// e.g., for files, this will throw an exception if the file is missing.
if (!fake) Location.getHandle(id).close();
if (!id.equals(currentId)) {
// initialize file
boolean success = false;
for (int i=0; i<readers.length; i++) {
if (readers[i].isThisType(id)) {
current = i;
currentId = id;
success = true;
break;
}
}
if (!success) {
throw new UnknownFormatException("Unknown file format: " + id);
}
}
return getReader();
}
/** Gets the reader used to open the current file. */
public IFormatReader getReader() {
FormatTools.assertId(currentId, true, 2);
return readers[current];
}
/** Gets the file format reader instance matching the given class. */
public IFormatReader getReader(Class<? extends IFormatReader> c) {
for (int i=0; i<readers.length; i++) {
if (readers[i].getClass().equals(c)) return readers[i];
}
return null;
}
/** Gets all constituent file format readers. */
public IFormatReader[] getReaders() {
IFormatReader[] r = new IFormatReader[readers.length];
System.arraycopy(readers, 0, r, 0, readers.length);
return r;
}
// -- IMetadataConfigurable API methods --
/* @see loci.formats.IMetadataConfigurable#getSupportedMetadataLevels() */
public Set<MetadataLevel> getSupportedMetadataLevels() {
return getReaders()[0].getSupportedMetadataLevels();
}
/* @see loci.formats.IMetadataConfigurable#getMetadataOptions() */
public MetadataOptions getMetadataOptions() {
return getReaders()[0].getMetadataOptions();
}
/**
* @see loci.formats.IMetadataConfigurable#setMetadataOptions(MetadataOptions)
*/
public void setMetadataOptions(MetadataOptions options) {
for (IFormatReader reader : readers) {
reader.setMetadataOptions(options);
}
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
for (int i=0; i<readers.length; i++) {
if (readers[i].isThisType(name, open)) return true;
}
return false;
}
/* @see IFormatReader.isThisType(byte[]) */
public boolean isThisType(byte[] block) {
for (int i=0; i<readers.length; i++) {
if (readers[i].isThisType(block)) return true;
}
return false;
}
/* @see IFormatReader.isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
for (int i=0; i<readers.length; i++) {
if (readers[i].isThisType(stream)) return true;
}
return false;
}
/* @see IFormatReader#getImageCount() */
public int getImageCount() {
return getReader().getImageCount();
}
/* @see IFormatReader#isRGB() */
public boolean isRGB() {
return getReader().isRGB();
}
/* @see IFormatReader#getSizeX() */
public int getSizeX() {
return getReader().getSizeX();
}
/* @see IFormatReader#getSizeY() */
public int getSizeY() {
return getReader().getSizeY();
}
/* @see IFormatReader#getSizeC() */
public int getSizeC() {
return getReader().getSizeC();
}
/* @see IFormatReader#getSizeZ() */
public int getSizeZ() {
return getReader().getSizeZ();
}
/* @see IFormatReader#getSizeT() */
public int getSizeT() {
return getReader().getSizeT();
}
/* @see IFormatReader#getPixelType() */
public int getPixelType() {
return getReader().getPixelType();
}
/* @see IFormatReader#getBitsPerPixel() */
public int getBitsPerPixel() {
return getReader().getBitsPerPixel();
}
/* @see IFormatReader#getEffectiveSizeC() */
public int getEffectiveSizeC() {
return getReader().getEffectiveSizeC();
}
/* @see IFormatReader#getRGBChannelCount() */
public int getRGBChannelCount() {
return getReader().getRGBChannelCount();
}
/* @see IFormatReader#isIndexed() */
public boolean isIndexed() {
return getReader().isIndexed();
}
/* @see IFormatReader#isFalseColor() */
public boolean isFalseColor() {
return getReader().isFalseColor();
}
/* @see IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
return getReader().get8BitLookupTable();
}
/* @see IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
return getReader().get16BitLookupTable();
}
/* @see IFormatReader#getChannelDimLengths() */
public int[] getChannelDimLengths() {
return getReader().getChannelDimLengths();
}
/* @see IFormatReader#getChannelDimTypes() */
public String[] getChannelDimTypes() {
return getReader().getChannelDimTypes();
}
/* @see IFormatReader#getThumbSizeX() */
public int getThumbSizeX() {
return getReader().getThumbSizeX();
}
/* @see IFormatReader#getThumbSizeY() */
public int getThumbSizeY() {
return getReader().getThumbSizeY();
}
/* @see IFormatReader#isLittleEndian() */
public boolean isLittleEndian() {
return getReader().isLittleEndian();
}
/* @see IFormatReader#getDimensionOrder() */
public String getDimensionOrder() {
return getReader().getDimensionOrder();
}
/* @see IFormatReader#isOrderCertain() */
public boolean isOrderCertain() {
return getReader().isOrderCertain();
}
/* @see IFormatReader#isThumbnailSeries() */
public boolean isThumbnailSeries() {
return getReader().isThumbnailSeries();
}
/* @see IFormatReader#isInterleaved() */
public boolean isInterleaved() {
return getReader().isInterleaved();
}
/* @see IFormatReader#isInterleaved(int) */
public boolean isInterleaved(int subC) {
return getReader().isInterleaved(subC);
}
/* @see IFormatReader#openBytes(int) */
public byte[] openBytes(int no) throws FormatException, IOException {
return getReader().openBytes(no);
}
/* @see IFormatReader#openBytes(int, int, int, int, int) */
public byte[] openBytes(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
return getReader().openBytes(no, x, y, w, h);
}
/* @see IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
return getReader().openBytes(no, buf);
}
/* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
return getReader().openBytes(no, buf, x, y, w, h);
}
/* @see IFormatReader#openPlane(int, int, int, int, int) */
public Object openPlane(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
return getReader().openPlane(no, x, y, w, h);
}
/* @see IFormatReader#openThumbBytes(int) */
public byte[] openThumbBytes(int no) throws FormatException, IOException {
return getReader().openThumbBytes(no);
}
/* @see IFormatReader#getSeriesCount() */
public int getSeriesCount() {
return getReader().getSeriesCount();
}
/* @see IFormatReader#setSeries(int) */
public void setSeries(int no) {
getReader().setSeries(no);
}
/* @see IFormatReader#getSeries() */
public int getSeries() {
return getReader().getSeries();
}
/* @see IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
return getReader().getUsedFiles();
}
/* @see IFormatReader#getUsedFiles(boolean) */
public String[] getUsedFiles(boolean noPixels) {
return getReader().getUsedFiles(noPixels);
}
/* @see IFormatReader#getSeriesUsedFiles() */
public String[] getSeriesUsedFiles() {
return getReader().getSeriesUsedFiles();
}
/* @see IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
return getReader().getSeriesUsedFiles(noPixels);
}
/* @see IFormatReader#getAdvancedUsedFiles(boolean) */
public FileInfo[] getAdvancedUsedFiles(boolean noPixels) {
return getReader().getAdvancedUsedFiles(noPixels);
}
/* @see IFormatReader#getAdvancedSeriesUsedFiles(boolean) */
public FileInfo[] getAdvancedSeriesUsedFiles(boolean noPixels) {
return getReader().getAdvancedSeriesUsedFiles(noPixels);
}
/* @see IFormatReader#getIndex(int, int, int) */
public int getIndex(int z, int c, int t) {
return getReader().getIndex(z, c, t);
}
/* @see IFormatReader#getZCTCoords(int) */
public int[] getZCTCoords(int index) {
return getReader().getZCTCoords(index);
}
/* @see IFormatReader#getMetadataValue(String) */
public Object getMetadataValue(String field) {
return getReader().getMetadataValue(field);
}
/* @see IFormatReader#getGlobalMetadata() */
public Hashtable<String, Object> getGlobalMetadata() {
return getReader().getGlobalMetadata();
}
/* @see IFormatReader#getSeriesMetadata() */
public Hashtable<String, Object> getSeriesMetadata() {
return getReader().getSeriesMetadata();
}
/** @deprecated */
public Hashtable<String, Object> getMetadata() {
return getReader().getMetadata();
}
/* @see IFormatReader#getCoreMetadata() */
public CoreMetadata[] getCoreMetadata() {
return getReader().getCoreMetadata();
}
/* @see IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
for (int i=0; i<readers.length; i++) readers[i].close(fileOnly);
if (!fileOnly) currentId = null;
}
/* @see IFormatReader#setGroupFiles(boolean) */
public void setGroupFiles(boolean group) {
FormatTools.assertId(currentId, false, 2);
for (int i=0; i<readers.length; i++) readers[i].setGroupFiles(group);
}
/* @see IFormatReader#isGroupFiles() */
public boolean isGroupFiles() {
return getReader().isGroupFiles();
}
/* @see IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return getReader(id).fileGroupOption(id);
}
/* @see IFormatReader#isMetadataComplete() */
public boolean isMetadataComplete() {
return getReader().isMetadataComplete();
}
/* @see IFormatReader#setNormalized(boolean) */
public void setNormalized(boolean normalize) {
FormatTools.assertId(currentId, false, 2);
for (int i=0; i<readers.length; i++) readers[i].setNormalized(normalize);
}
/* @see IFormatReader#isNormalized() */
public boolean isNormalized() {
// NB: all readers should have the same normalization setting
return readers[0].isNormalized();
}
/**
* @deprecated
* @see IFormatReader#setMetadataCollected(boolean)
*/
public void setMetadataCollected(boolean collect) {
FormatTools.assertId(currentId, false, 2);
for (int i=0; i<readers.length; i++) {
readers[i].setMetadataCollected(collect);
}
}
/**
* @deprecated
* @see IFormatReader#isMetadataCollected()
*/
public boolean isMetadataCollected() {
return readers[0].isMetadataCollected();
}
/* @see IFormatReader#setOriginalMetadataPopulated(boolean) */
public void setOriginalMetadataPopulated(boolean populate) {
FormatTools.assertId(currentId, false, 1);
for (int i=0; i<readers.length; i++) {
readers[i].setOriginalMetadataPopulated(populate);
}
}
/* @see IFormatReader#isOriginalMetadataPopulated() */
public boolean isOriginalMetadataPopulated() {
return readers[0].isOriginalMetadataPopulated();
}
/* @see IFormatReader#getCurrentFile() */
public String getCurrentFile() {
return getReader().getCurrentFile();
}
/* @see IFormatReader#setMetadataFiltered(boolean) */
public void setMetadataFiltered(boolean filter) {
FormatTools.assertId(currentId, false, 2);
for (int i=0; i<readers.length; i++) readers[i].setMetadataFiltered(filter);
}
/* @see IFormatReader#isMetadataFiltered() */
public boolean isMetadataFiltered() {
// NB: all readers should have the same metadata filtering setting
return readers[0].isMetadataFiltered();
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
FormatTools.assertId(currentId, false, 2);
for (int i=0; i<readers.length; i++) readers[i].setMetadataStore(store);
}
/* @see IFormatReader#getMetadataStore() */
public MetadataStore getMetadataStore() {
return getReader().getMetadataStore();
}
/* @see IFormatReader#getMetadataStoreRoot() */
public Object getMetadataStoreRoot() {
return getReader().getMetadataStoreRoot();
}
/* @see IFormatReader#getUnderlyingReaders() */
public IFormatReader[] getUnderlyingReaders() {
return getReaders();
}
/* @see IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return getReader(id).isSingleFile(id);
}
/* @see IFormatReader#hasCompanionFiles() */
public boolean hasCompanionFiles() {
return getReader().hasCompanionFiles();
}
/* @see IFormatReader#getPossibleDomains(String) */
public String[] getPossibleDomains(String id)
throws FormatException, IOException
{
return getReader(id).getPossibleDomains(id);
}
/* @see IFormatReader#getDomains() */
public String[] getDomains() {
return getReader().getDomains();
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#isThisType(String) */
public boolean isThisType(String name) {
// if necessary, open the file for further analysis
// but check isThisType(name, false) first, for efficiency
return isThisType(name, false) || isThisType(name, true);
}
/* @see IFormatHandler#getFormat() */
public String getFormat() { return getReader().getFormat(); }
/* @see IFormatHandler#getSuffixes() */
public String[] getSuffixes() {
if (suffixes == null) {
HashSet<String> suffixSet = new HashSet<String>();
for (int i=0; i<readers.length; i++) {
String[] suf = readers[i].getSuffixes();
for (int j=0; j<suf.length; j++) suffixSet.add(suf[j]);
}
suffixes = new String[suffixSet.size()];
suffixSet.toArray(suffixes);
Arrays.sort(suffixes);
}
return suffixes;
}
/* @see IFormatHandler#getNativeDataType() */
public Class<?> getNativeDataType() {
return getReader().getNativeDataType();
}
/* @see IFormatHandler#setId(String) */
public void setId(String id) throws FormatException, IOException {
getReader(id).setId(id);
}
/* @see IFormatHandler#close() */
public void close() throws IOException { close(false); }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.